proxmox-rest-server: use new ServerAdapter trait instead of callbacks

Async callbacks are a PITA, so we now pass a single trait object which
implements check_auth and get_index.
This commit is contained in:
Dietmar Maurer 2021-10-05 11:01:05 +02:00
parent 2c09017045
commit 3ffe2ebc64
3 changed files with 55 additions and 42 deletions

View File

@ -1,20 +1,24 @@
use std::sync::{Arc, Mutex}; use std::sync::Mutex;
use std::collections::HashMap; use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use anyhow::{bail, format_err, Error}; use anyhow::{bail, format_err, Error};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use hyper::{Body, Response, Method};
use http::request::Parts;
use http::HeaderMap;
use proxmox::api::{api, router::SubdirMap, Router, RpcEnvironmentType, UserInformation}; use proxmox::api::{api, router::SubdirMap, Router, RpcEnvironmentType, UserInformation};
use proxmox::list_subdirs_api_method; use proxmox::list_subdirs_api_method;
use proxmox_rest_server::{ApiAuth, ApiConfig, AuthError, RestServer, RestEnvironment}; use proxmox_rest_server::{ServerAdapter, ApiConfig, AuthError, RestServer, RestEnvironment};
// Create a Dummy User info and auth system
// Normally this would check and authenticate the user // Create a Dummy User information system
struct DummyUserInfo; struct DummyUserInfo;
impl UserInformation for DummyUserInfo { impl UserInformation for DummyUserInfo {
fn is_superuser(&self, _userid: &str) -> bool { fn is_superuser(&self, _userid: &str) -> bool {
// Always return true here, so we have access to everthing
true true
} }
fn is_group_member(&self, _userid: &str, group: &str) -> bool { fn is_group_member(&self, _userid: &str, group: &str) -> bool {
@ -25,14 +29,17 @@ impl UserInformation for DummyUserInfo {
} }
} }
struct DummyAuth; struct MinimalServer;
impl ApiAuth for DummyAuth { // implement the server adapter
fn check_auth<'a>( impl ServerAdapter for MinimalServer {
&'a self,
_headers: &'a http::HeaderMap, // normally this would check and authenticate the user
_method: &'a hyper::Method, fn check_auth(
) -> Pin<Box<dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>> + Send + 'a>> { &self,
_headers: &HeaderMap,
_method: &Method,
) -> Pin<Box<dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>> + Send>> {
Box::pin(async move { Box::pin(async move {
// get some global/cached userinfo // get some global/cached userinfo
let userinfo: Box<dyn UserInformation + Sync + Send> = Box::new(DummyUserInfo); let userinfo: Box<dyn UserInformation + Sync + Send> = Box::new(DummyUserInfo);
@ -40,21 +47,21 @@ impl ApiAuth for DummyAuth {
Ok(("User".to_string(), userinfo)) Ok(("User".to_string(), userinfo))
}) })
} }
}
// this should return the index page of the webserver // this should return the index page of the webserver
// iow. what the user browses to // iow. what the user browses to
fn get_index(
fn get_index<'a>( &self,
_env: RestEnvironment, _env: RestEnvironment,
_parts: http::request::Parts, _parts: Parts,
) -> Pin<Box<dyn Future<Output = http::Response<hyper::Body>> + Send + 'a>> { ) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> {
Box::pin(async move { Box::pin(async move {
// build an index page // build an index page
http::Response::builder() http::Response::builder()
.body("hello world".into()) .body("hello world".into())
.unwrap() .unwrap()
}) })
}
} }
// a few examples on how to do api calls with the Router // a few examples on how to do api calls with the Router
@ -190,8 +197,7 @@ async fn run() -> Result<(), Error> {
"/var/tmp/", "/var/tmp/",
&ROUTER, &ROUTER,
RpcEnvironmentType::PUBLIC, RpcEnvironmentType::PUBLIC,
Arc::new(DummyAuth {}), MinimalServer,
&get_index,
)?; )?;
let rest_server = RestServer::new(config); let rest_server = RestServer::new(config);

View File

@ -3,7 +3,6 @@ use std::path::PathBuf;
use std::time::SystemTime; use std::time::SystemTime;
use std::fs::metadata; use std::fs::metadata;
use std::sync::{Arc, Mutex, RwLock}; use std::sync::{Arc, Mutex, RwLock};
use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use anyhow::{bail, Error, format_err}; use anyhow::{bail, Error, format_err};
@ -16,9 +15,8 @@ use serde::Serialize;
use proxmox::api::{ApiMethod, Router, RpcEnvironmentType, UserInformation}; use proxmox::api::{ApiMethod, Router, RpcEnvironmentType, UserInformation};
use proxmox::tools::fs::{create_path, CreateOptions}; use proxmox::tools::fs::{create_path, CreateOptions};
use crate::{ApiAuth, AuthError, FileLogger, FileLogOptions, CommandSocket, RestEnvironment}; use crate::{ServerAdapter, AuthError, FileLogger, FileLogOptions, CommandSocket, RestEnvironment};
pub type GetIndexFn = &'static (dyn Fn(RestEnvironment, Parts) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> + Send + Sync);
/// REST server configuration /// REST server configuration
pub struct ApiConfig { pub struct ApiConfig {
@ -30,8 +28,7 @@ pub struct ApiConfig {
template_files: RwLock<HashMap<String, (SystemTime, PathBuf)>>, template_files: RwLock<HashMap<String, (SystemTime, PathBuf)>>,
request_log: Option<Arc<Mutex<FileLogger>>>, request_log: Option<Arc<Mutex<FileLogger>>>,
auth_log: Option<Arc<Mutex<FileLogger>>>, auth_log: Option<Arc<Mutex<FileLogger>>>,
api_auth: Arc<dyn ApiAuth + Send + Sync>, adapter: Pin<Box<dyn ServerAdapter + Send + Sync>>,
get_index_fn: GetIndexFn,
} }
impl ApiConfig { impl ApiConfig {
@ -53,8 +50,7 @@ impl ApiConfig {
basedir: B, basedir: B,
router: &'static Router, router: &'static Router,
env_type: RpcEnvironmentType, env_type: RpcEnvironmentType,
api_auth: Arc<dyn ApiAuth + Send + Sync>, adapter: impl ServerAdapter + 'static,
get_index_fn: GetIndexFn,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
Ok(Self { Ok(Self {
basedir: basedir.into(), basedir: basedir.into(),
@ -65,8 +61,7 @@ impl ApiConfig {
template_files: RwLock::new(HashMap::new()), template_files: RwLock::new(HashMap::new()),
request_log: None, request_log: None,
auth_log: None, auth_log: None,
api_auth, adapter: Box::pin(adapter),
get_index_fn,
}) })
} }
@ -75,7 +70,7 @@ impl ApiConfig {
rest_env: RestEnvironment, rest_env: RestEnvironment,
parts: Parts, parts: Parts,
) -> Response<Body> { ) -> Response<Body> {
(self.get_index_fn)(rest_env, parts).await self.adapter.get_index(rest_env, parts).await
} }
pub(crate) async fn check_auth( pub(crate) async fn check_auth(
@ -83,7 +78,7 @@ impl ApiConfig {
headers: &http::HeaderMap, headers: &http::HeaderMap,
method: &hyper::Method, method: &hyper::Method,
) -> Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError> { ) -> Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError> {
self.api_auth.check_auth(headers, method).await self.adapter.check_auth(headers, method).await
} }
pub(crate) fn find_method( pub(crate) fn find_method(

View File

@ -21,6 +21,9 @@ use std::pin::Pin;
use anyhow::{bail, format_err, Error}; use anyhow::{bail, format_err, Error};
use nix::unistd::Pid; use nix::unistd::Pid;
use hyper::{Body, Response, Method};
use http::request::Parts;
use http::HeaderMap;
use proxmox::tools::fd::Fd; use proxmox::tools::fd::Fd;
use proxmox::sys::linux::procfs::PidStat; use proxmox::sys::linux::procfs::PidStat;
@ -70,17 +73,26 @@ impl From<Error> for AuthError {
} }
} }
/// User Authentication trait /// User Authentication and index/root page generation methods
pub trait ApiAuth { pub trait ServerAdapter: Send + Sync {
/// Returns the index/root page
fn get_index(
&self,
rest_env: RestEnvironment,
parts: Parts,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>>;
/// Extract user credentials from headers and check them. /// Extract user credentials from headers and check them.
/// ///
/// If credenthials are valid, returns the username and a /// If credenthials are valid, returns the username and a
/// [UserInformation] object to query additional user data. /// [UserInformation] object to query additional user data.
fn check_auth<'a>( fn check_auth<'a>(
&'a self, &'a self,
headers: &'a http::HeaderMap, headers: &'a HeaderMap,
method: &'a hyper::Method, method: &'a Method,
) -> Pin<Box<dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>> + Send + 'a>>; ) -> Pin<Box<dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>> + Send + 'a>>;
} }
lazy_static::lazy_static!{ lazy_static::lazy_static!{