[pbs-devel] [RFC proxmox-backup 07/15] REST: extract and handle API tokens

Wolfgang Bumiller w.bumiller at proxmox.com
Tue Oct 20 10:34:24 CEST 2020


On Mon, Oct 19, 2020 at 09:39:11AM +0200, Fabian Grünbichler wrote:
> Signed-off-by: Fabian Grünbichler <f.gruenbichler at proxmox.com>
> ---
> 
> Notes:
>     exact format up for discussion, obviously. we probably want some sort of prefix
>     like with PVE
> 
>  src/server/rest.rs | 63 +++++++++++++++++++++++++++++++---------------
>  1 file changed, 43 insertions(+), 20 deletions(-)
> 
> diff --git a/src/server/rest.rs b/src/server/rest.rs
> index c650a3aa..a87b1e75 100644
> --- a/src/server/rest.rs
> +++ b/src/server/rest.rs
> @@ -3,6 +3,7 @@ use std::future::Future;
>  use std::hash::BuildHasher;
>  use std::path::{Path, PathBuf};
>  use std::pin::Pin;
> +use std::str::FromStr;
>  use std::sync::{Arc, Mutex};
>  use std::task::{Context, Poll};
>  
> @@ -531,7 +532,7 @@ async fn handle_static_file_download(filename: PathBuf) ->  Result<Response<Body
>      }
>  }
>  
> -fn extract_auth_data(headers: &http::HeaderMap) -> (Option<String>, Option<String>, Option<String>) {
> +fn extract_auth_data(headers: &http::HeaderMap) -> (Option<String>, Option<String>, Option<String>, Option<String>) {

Please turn this return type into a struct.

>  
>      let mut ticket = None;
>      let mut language = None;
> @@ -542,37 +543,59 @@ fn extract_auth_data(headers: &http::HeaderMap) -> (Option<String>, Option<Strin
>          }
>      }
>  
> +    let api_token = match headers.get("AUTHORIZATION").map(|v| v.to_str()) {
> +        Some(Ok(v)) => Some(v.to_owned()),
> +        _ => None,
> +    };
> +
>      let csrf_token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) {
>          Some(Ok(v)) => Some(v.to_owned()),
>          _ => None,
>      };
>  
> -    (ticket, csrf_token, language)
> +    (ticket, csrf_token, language, api_token)
>  }
>  
>  fn check_auth(
>      method: &hyper::Method,
>      ticket: &Option<String>,
>      csrf_token: &Option<String>,
> +    api_token: &Option<String>,
>      user_info: &CachedUserInfo,
>  ) -> Result<Userid, Error> {
> -    let ticket_lifetime = tools::ticket::TICKET_LIFETIME;
> +    let userid = if let Some(ticket) = ticket {
> +        let ticket_lifetime = tools::ticket::TICKET_LIFETIME;
>  
> -    let ticket = ticket.as_ref().map(String::as_str);
> -    let userid: Userid = Ticket::parse(&ticket.ok_or_else(|| format_err!("missing ticket"))?)?
> -        .verify_with_time_frame(public_auth_key(), "PBS", None, -300..ticket_lifetime)?;
> +        let ticket = ticket.as_str();
> +        let userid: Userid = Ticket::parse(ticket)?
> +            .verify_with_time_frame(public_auth_key(), "PBS", None, -300..ticket_lifetime)?;
>  
> -    if !user_info.is_active_user(&userid) {
> -        bail!("user account disabled or expired.");
> -    }
> +        if !user_info.is_active_user(&userid) {
> +            bail!("user account disabled or expired.");
> +        }
>  
> -    if method != hyper::Method::GET {
> -        if let Some(csrf_token) = csrf_token {
> -            verify_csrf_prevention_token(csrf_secret(), &userid, &csrf_token, -300, ticket_lifetime)?;
> -        } else {
> -            bail!("missing CSRF prevention token");
> +        if method != hyper::Method::GET {
> +            if let Some(csrf_token) = csrf_token {
> +                verify_csrf_prevention_token(csrf_secret(), &userid, &csrf_token, -300, ticket_lifetime)?;
> +            } else {
> +                bail!("missing CSRF prevention token");
> +            }
>          }
> -    }
> +        userid
> +    } else if let Some(api_token) = 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 = Userid::from_str(tokenid)?;
> +
> +        let tokensecret = parts.next()
> +            .ok_or_else(|| format_err!("failed to split API token header"))?;
> +        crate::config::token_shadow::verify_secret(&tokenid, &tokensecret)?;
> +
> +        tokenid
> +    } else {
> +        bail!("neither ticket nor API token provided - unauthorized");
> +    };
>  
>      Ok(userid)
>  }
> @@ -630,8 +653,8 @@ async fn handle_request(
>              }
>  
>              if auth_required {
> -                let (ticket, csrf_token, _) = extract_auth_data(&parts.headers);
> -                match check_auth(&method, &ticket, &csrf_token, &user_info) {
> +                let (ticket, csrf_token, _, api_token) = extract_auth_data(&parts.headers);
> +                match check_auth(&method, &ticket, &csrf_token, &api_token, &user_info) {
>                      Ok(userid) => rpcenv.set_user(Some(userid.to_string())),
>                      Err(err) => {
>                          // always delay unauthorized calls by 3 seconds (from start of request)
> @@ -684,9 +707,9 @@ async fn handle_request(
>          }
>  
>          if comp_len == 0 {
> -            let (ticket, csrf_token, language) = extract_auth_data(&parts.headers);
> -            if ticket != None {
> -                match check_auth(&method, &ticket, &csrf_token, &user_info) {
> +            let (ticket, csrf_token, language, api_token) = extract_auth_data(&parts.headers);
> +            if ticket != None || api_token != None {
> +                match check_auth(&method, &ticket, &csrf_token, &api_token, &user_info) {
>                      Ok(userid) => {
>                          let new_csrf_token = assemble_csrf_prevention_token(csrf_secret(), &userid);
>                          return Ok(get_index(Some(userid), Some(new_csrf_token), language, &api, parts));
> -- 
> 2.20.1





More information about the pbs-devel mailing list