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 48176b0a77
commit 608806e884
9 changed files with 238 additions and 209 deletions

View File

@ -5,16 +5,17 @@ use anyhow::{bail, Error};
use futures::*;
use http::request::Parts;
use http::Response;
use hyper::{Body, StatusCode};
use hyper::header;
use hyper::{Body, Method, StatusCode};
use http::HeaderMap;
use proxmox::try_block;
use proxmox::api::RpcEnvironmentType;
use proxmox::tools::fs::CreateOptions;
use proxmox::api::UserInformation;
use proxmox_rest_server::{daemon, ApiConfig, RestServer, RestEnvironment};
use proxmox_rest_server::{daemon, AuthError, ApiConfig, RestServer, RestEnvironment, ServerAdapter};
use proxmox_backup::server::auth::default_api_auth;
use proxmox_backup::server::auth::check_pbs_auth;
use proxmox_backup::auth_helpers::*;
use proxmox_backup::config;
@ -27,20 +28,36 @@ fn main() {
}
}
fn get_index<'a>(
_env: RestEnvironment,
_parts: Parts,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'a>> {
Box::pin(async move {
struct ProxmoxBackupApiAdapter;
let index = "<center><h1>Proxmox Backup API Server</h1></center>";
impl ServerAdapter for ProxmoxBackupApiAdapter {
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "text/html")
.body(index.into())
.unwrap()
})
fn get_index(
&self,
_env: RestEnvironment,
_parts: Parts,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> {
Box::pin(async move {
let index = "<center><h1>Proxmox Backup API Server</h1></center>";
Response::builder()
.status(StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "text/html")
.body(index.into())
.unwrap()
})
}
fn check_auth<'a>(
&'a self,
headers: &'a HeaderMap,
method: &'a Method,
) -> Pin<Box<dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>> + Send + 'a>> {
Box::pin(async move {
check_pbs_auth(headers, method).await
})
}
}
async fn run() -> Result<(), Error> {
@ -78,8 +95,7 @@ async fn run() -> Result<(), Error> {
pbs_buildcfg::JS_DIR,
&proxmox_backup::api2::ROUTER,
RpcEnvironmentType::PRIVILEGED,
default_api_auth(),
&get_index,
ProxmoxBackupApiAdapter,
)?;
let backup_user = pbs_config::backup_user()?;

View File

@ -15,21 +15,23 @@ use url::form_urlencoded;
use openssl::ssl::{SslMethod, SslAcceptor, SslFiletype};
use tokio_stream::wrappers::ReceiverStream;
use serde_json::{json, Value};
use http::{Method, HeaderMap};
use proxmox::try_block;
use proxmox::api::{RpcEnvironment, RpcEnvironmentType};
use proxmox::api::{RpcEnvironment, RpcEnvironmentType, UserInformation};
use proxmox::sys::linux::socket::set_tcp_keepalive;
use proxmox::tools::fs::CreateOptions;
use pbs_tools::task_log;
use pbs_datastore::DataStore;
use proxmox_rest_server::{
rotate_task_log_archive, extract_cookie , ApiConfig, RestServer, RestEnvironment, WorkerTask,
rotate_task_log_archive, extract_cookie , AuthError, ApiConfig, RestServer, RestEnvironment,
ServerAdapter, WorkerTask,
};
use proxmox_backup::{
server::{
auth::default_api_auth,
auth::check_pbs_auth,
jobstate::{
self,
Job,
@ -81,6 +83,29 @@ fn main() -> Result<(), Error> {
}
struct ProxmoxBackupProxyAdapter;
impl ServerAdapter for ProxmoxBackupProxyAdapter {
fn get_index(
&self,
env: RestEnvironment,
parts: Parts,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> {
Box::pin(get_index_future(env, parts))
}
fn check_auth<'a>(
&'a self,
headers: &'a HeaderMap,
method: &'a Method,
) -> Pin<Box<dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>> + Send + 'a>> {
Box::pin(async move {
check_pbs_auth(headers, method).await
})
}
}
fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
return extract_cookie(cookie, "PBSLangCookie");
@ -88,13 +113,6 @@ fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
None
}
fn get_index<'a>(
env: RestEnvironment,
parts: Parts,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'a>> {
Box::pin(get_index_future(env, parts))
}
async fn get_index_future(
env: RestEnvironment,
parts: Parts,
@ -191,8 +209,7 @@ async fn run() -> Result<(), Error> {
pbs_buildcfg::JS_DIR,
&proxmox_backup::api2::ROUTER,
RpcEnvironmentType::PUBLIC,
default_api_auth(),
&get_index,
ProxmoxBackupProxyAdapter,
)?;
config.add_alias("novnc", "/usr/share/novnc-pve");

View File

@ -1,9 +1,5 @@
//! Provides authentication primitives for the HTTP server
use std::sync::Arc;
use std::future::Future;
use std::pin::Pin;
use anyhow::format_err;
use proxmox::api::UserInformation;
@ -11,7 +7,7 @@ use proxmox::api::UserInformation;
use pbs_tools::ticket::{self, Ticket};
use pbs_config::{token_shadow, CachedUserInfo};
use pbs_api_types::{Authid, Userid};
use proxmox_rest_server::{ApiAuth, AuthError, extract_cookie};
use proxmox_rest_server::{AuthError, extract_cookie};
use crate::auth_helpers::*;
@ -28,111 +24,93 @@ enum AuthData {
ApiToken(String),
}
pub struct UserApiAuth {}
pub fn default_api_auth() -> Arc<UserApiAuth> {
Arc::new(UserApiAuth {})
}
impl UserApiAuth {
fn extract_auth_data(headers: &http::HeaderMap) -> Option<AuthData> {
if let Some(raw_cookie) = headers.get(header::COOKIE) {
if let Ok(cookie) = raw_cookie.to_str() {
if let Some(ticket) = extract_cookie(cookie, "PBSAuthCookie") {
let csrf_token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) {
Some(Ok(v)) => Some(v.to_owned()),
_ => None,
};
return Some(AuthData::User(UserAuthData { ticket, csrf_token }));
}
fn extract_auth_data(headers: &http::HeaderMap) -> Option<AuthData> {
if let Some(raw_cookie) = headers.get(header::COOKIE) {
if let Ok(cookie) = raw_cookie.to_str() {
if let Some(ticket) = extract_cookie(cookie, "PBSAuthCookie") {
let csrf_token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) {
Some(Ok(v)) => Some(v.to_owned()),
_ => None,
};
return Some(AuthData::User(UserAuthData { ticket, csrf_token }));
}
}
}
match headers.get(header::AUTHORIZATION).map(|v| v.to_str()) {
Some(Ok(v)) => {
if v.starts_with("PBSAPIToken ") || v.starts_with("PBSAPIToken=") {
Some(AuthData::ApiToken(v["PBSAPIToken ".len()..].to_owned()))
match headers.get(header::AUTHORIZATION).map(|v| v.to_str()) {
Some(Ok(v)) => {
if v.starts_with("PBSAPIToken ") || v.starts_with("PBSAPIToken=") {
Some(AuthData::ApiToken(v["PBSAPIToken ".len()..].to_owned()))
} else {
None
}
}
_ => None,
}
}
pub async fn check_pbs_auth(
headers: &http::HeaderMap,
method: &hyper::Method,
) -> Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError> {
// fixme: make all IO async
let user_info = CachedUserInfo::new()?;
let auth_data = extract_auth_data(headers);
match auth_data {
Some(AuthData::User(user_auth_data)) => {
let ticket = user_auth_data.ticket.clone();
let ticket_lifetime = ticket::TICKET_LIFETIME;
let userid: Userid = Ticket::<super::ticket::ApiTicket>::parse(&ticket)?
.verify_with_time_frame(public_auth_key(), "PBS", None, -300..ticket_lifetime)?
.require_full()?;
let auth_id = Authid::from(userid.clone());
if !user_info.is_active_auth_id(&auth_id) {
return Err(format_err!("user account disabled or expired.").into());
}
if method != hyper::Method::GET {
if let Some(csrf_token) = &user_auth_data.csrf_token {
verify_csrf_prevention_token(
csrf_secret(),
&userid,
&csrf_token,
-300,
ticket_lifetime,
)?;
} else {
None
return Err(format_err!("missing CSRF prevention token").into());
}
}
_ => None,
Ok((auth_id.to_string(), Box::new(user_info)))
}
}
Some(AuthData::ApiToken(api_token)) => {
let mut parts = api_token.splitn(2, ':');
let tokenid = parts
.next()
.ok_or_else(|| format_err!("failed to split API token header"))?;
let tokenid: Authid = tokenid.parse()?;
async fn check_auth_async(
&self,
headers: &http::HeaderMap,
method: &hyper::Method,
) -> Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError> {
// fixme: make all IO async
let user_info = CachedUserInfo::new()?;
let auth_data = Self::extract_auth_data(headers);
match auth_data {
Some(AuthData::User(user_auth_data)) => {
let ticket = user_auth_data.ticket.clone();
let ticket_lifetime = ticket::TICKET_LIFETIME;
let userid: Userid = Ticket::<super::ticket::ApiTicket>::parse(&ticket)?
.verify_with_time_frame(public_auth_key(), "PBS", None, -300..ticket_lifetime)?
.require_full()?;
let auth_id = Authid::from(userid.clone());
if !user_info.is_active_auth_id(&auth_id) {
return Err(format_err!("user account disabled or expired.").into());
}
if method != hyper::Method::GET {
if let Some(csrf_token) = &user_auth_data.csrf_token {
verify_csrf_prevention_token(
csrf_secret(),
&userid,
&csrf_token,
-300,
ticket_lifetime,
)?;
} else {
return Err(format_err!("missing CSRF prevention token").into());
}
}
Ok((auth_id.to_string(), Box::new(user_info)))
if !user_info.is_active_auth_id(&tokenid) {
return Err(format_err!("user account or token disabled or expired.").into());
}
Some(AuthData::ApiToken(api_token)) => {
let mut parts = api_token.splitn(2, ':');
let tokenid = parts
.next()
.ok_or_else(|| format_err!("failed to split API token header"))?;
let tokenid: Authid = tokenid.parse()?;
if !user_info.is_active_auth_id(&tokenid) {
return Err(format_err!("user account or token disabled or expired.").into());
}
let tokensecret = parts
.next()
.ok_or_else(|| format_err!("failed to split API token header"))?;
let tokensecret = percent_decode_str(tokensecret)
.decode_utf8()
.map_err(|_| format_err!("failed to decode API token header"))?;
let tokensecret = parts
.next()
.ok_or_else(|| format_err!("failed to split API token header"))?;
let tokensecret = percent_decode_str(tokensecret)
.decode_utf8()
.map_err(|_| format_err!("failed to decode API token header"))?;
token_shadow::verify_secret(&tokenid, &tokensecret)?;
token_shadow::verify_secret(&tokenid, &tokensecret)?;
Ok((tokenid.to_string(), Box::new(user_info)))
}
None => Err(AuthError::NoData),
Ok((tokenid.to_string(), Box::new(user_info)))
}
}
}
impl ApiAuth for UserApiAuth {
fn check_auth<'a>(
&'a self,
headers: &'a http::HeaderMap,
method: &'a hyper::Method,
) -> Pin<Box<dyn Future<Output = Result<(String, Box<dyn UserInformation + Sync + Send>), AuthError>> + Send + 'a>> {
Box::pin(self.check_auth_async(headers, method))
None => Err(AuthError::NoData),
}
}