diff --git a/Cargo.lock b/Cargo.lock index 620d6055..c948a1a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -998,6 +998,7 @@ dependencies = [ "async-trait", "base64 0.23.1", "dropshot", + "http", "tracing", ] diff --git a/dropshot-authorization-header/Cargo.toml b/dropshot-authorization-header/Cargo.toml index a7eabca0..27ea71ea 100644 --- a/dropshot-authorization-header/Cargo.toml +++ b/dropshot-authorization-header/Cargo.toml @@ -10,4 +10,5 @@ publish.workspace = true async-trait = { workspace = true } base64 = { workspace = true } dropshot = { workspace = true } +http = { workspace = true } tracing = { workspace = true } diff --git a/dropshot-authorization-header/src/bearer.rs b/dropshot-authorization-header/src/bearer.rs index 5473d0f9..23a2a5e8 100644 --- a/dropshot-authorization-header/src/bearer.rs +++ b/dropshot-authorization-header/src/bearer.rs @@ -4,9 +4,10 @@ use async_trait::async_trait; use dropshot::{ - ApiEndpointBodyContentType, ExtensionMode, ExtractorMetadata, HttpError, RequestContext, - ServerContext, SharedExtractor, + ApiEndpointBodyContentType, ClientErrorStatusCode, ExtensionMode, ExtractorMetadata, HttpError, + RequestContext, ServerContext, SharedExtractor, }; +use http::{HeaderMap, header::AUTHORIZATION}; /// A token used for bearer authentication pub struct BearerAuth(Option); @@ -25,41 +26,40 @@ impl BearerAuth { } } -/// Extracting a bearer token should never fail, it should always return `Ok(BearerAuth(Some(token))))` -/// or `Ok(BearerAuth(None))`. `None` will be returned in any of the cases that a valid string can not -/// be extracted. This extractor is not responsible for checking the value of the token. +fn bearer_from_headers(headers: &HeaderMap) -> Result { + let token = headers + .get(AUTHORIZATION) + .map(|header| { + header + .to_str() + .ok() + .and_then(|value| value.split_once(' ')) + .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Bearer")) + .map(|(_, token)| token) + .map(|token| token.to_string()) + .ok_or_else(|| { + tracing::debug!("Authorization header is not a bearer token"); + HttpError::for_client_error( + None, + ClientErrorStatusCode::UNAUTHORIZED, + "Authorization header is not a bearer token".to_string(), + ) + }) + }) + .transpose()?; + + Ok(BearerAuth(token)) +} + +/// A request without an Authorization header extracts as `BearerAuth(None)`. A request whose +/// Authorization header is not a readable bearer token is rejected as unauthorized. This extractor +/// is not responsible for checking the value of the token. #[async_trait] impl SharedExtractor for BearerAuth { async fn from_request( rqctx: &RequestContext, ) -> Result { - // Similarly we only care about the presence of the Authorization header - let header_value = rqctx - .request - .headers() - .get("Authorization") - .and_then(|header| { - // If the value provided is not a readable string we will throw it out - header - .to_str() - .map(|s| s.to_string()) - .inspect_err(|err| { - tracing::info!(?err, "Failed to turn Authorization header into string"); - }) - .ok() - }); - - // Finally ensure that the value we found is properly formed - let contents = header_value.and_then(|value| { - let parts = value.split_once(' '); - - match parts { - Some(("Bearer", token)) => Some(token.to_string()), - _ => None, - } - }); - - Ok(BearerAuth(contents)) + bearer_from_headers(rqctx.request.headers()) } fn metadata(_body_content_type: ApiEndpointBodyContentType) -> ExtractorMetadata { @@ -69,3 +69,73 @@ impl SharedExtractor for BearerAuth { } } } + +#[cfg(test)] +mod tests { + use http::{HeaderMap, HeaderValue, header::AUTHORIZATION}; + + use super::bearer_from_headers; + + fn authorization(value: HeaderValue) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, value); + headers + } + + #[test] + fn missing_header_has_no_token() { + assert_eq!( + None, + bearer_from_headers(&HeaderMap::new()).unwrap().consume() + ); + } + + #[test] + fn bearer_header_yields_token() { + let header = HeaderValue::from_static("Bearer token"); + + assert_eq!( + Some("token".to_string()), + bearer_from_headers(&authorization(header)) + .unwrap() + .consume() + ); + } + + /// The authentication scheme name is case insensitive + #[test] + fn scheme_is_case_insensitive() { + for value in ["bearer token", "BEARER token", "BeArEr token"] { + let header = HeaderValue::from_static(value); + + assert_eq!( + Some("token".to_string()), + bearer_from_headers(&authorization(header)) + .unwrap() + .consume() + ); + } + } + + /// A header that is present but is not a bearer token must not be mistaken for a missing one + #[test] + fn other_schemes_are_rejected() { + let header = HeaderValue::from_static("Basic dXNlcjpwYXNz"); + + assert_eq!( + 401, + bearer_from_headers(&authorization(header)) + .err() + .unwrap() + .status_code + .as_u16() + ); + } + + #[test] + fn unreadable_header_is_rejected() { + let header = HeaderValue::from_bytes(b"Bearer \xff").unwrap(); + + assert!(bearer_from_headers(&authorization(header)).is_err()); + } +} diff --git a/v-api/src/authn/jwt.rs b/v-api/src/authn/jwt.rs index 2b466fbb..0223de43 100644 --- a/v-api/src/authn/jwt.rs +++ b/v-api/src/authn/jwt.rs @@ -37,6 +37,8 @@ pub enum JwtError { NoMatchingKey, #[error("No token found")] NoToken, + #[error("Authorization header is not a bearer token")] + NotBearer, #[error("Unsupported algorithm")] UnsupportedAlgorithm, } @@ -177,17 +179,12 @@ where where T: VAppPermission, { - // Ensure there is a bearer, without it there is nothing else to do let bearer = BearerAuth::from_request(rqctx).await.map_err(|err| { - tracing::info!(?err, "Failed to extract bearer auth"); - JwtError::NoToken + tracing::info!(?err, "Failed to extract bearer auth for jwt"); + JwtError::NotBearer })?; - // Check that the extracted token actually contains a value - let token = bearer.consume().ok_or_else(|| { - tracing::debug!("Bearer auth is empty"); - JwtError::NoToken - })?; + let token = bearer.consume().ok_or(JwtError::NoToken)?; Self::new(rqctx.v_ctx(), &token).await } diff --git a/v-api/src/authn/mod.rs b/v-api/src/authn/mod.rs index ec490e82..247e13b7 100644 --- a/v-api/src/authn/mod.rs +++ b/v-api/src/authn/mod.rs @@ -66,17 +66,12 @@ impl AuthToken { where T: VAppPermission + PermissionStorage, { - // Ensure there is a bearer, without it there is nothing else to do let bearer = BearerAuth::from_request(rqctx).await.map_err(|err| { - tracing::info!(?err, "Failed to extract bearer auth"); - AuthError::NoToken + tracing::info!(?err, "Failed to extract bearer auth for auth token"); + AuthError::FailedToExtract })?; - // Check that the extracted token actually contains a value - let token = bearer.consume().ok_or_else(|| { - tracing::debug!("Bearer auth is empty"); - AuthError::NoToken - })?; + let token = bearer.consume().ok_or(AuthError::NoToken)?; let ctx = rqctx.context(); diff --git a/v-api/src/context/auth.rs b/v-api/src/context/auth.rs index 676e21cf..d01f02e9 100644 --- a/v-api/src/context/auth.rs +++ b/v-api/src/context/auth.rs @@ -89,11 +89,11 @@ where }) } - pub fn builtin_unauthenticated_caller(&self) -> Caller { + pub(super) fn builtin_unauthenticated_caller(&self) -> Caller { self.unauthenticated_caller.clone() } - pub fn builtin_unauthenticated_caller_mut(&mut self) -> &mut Caller { + pub(super) fn builtin_unauthenticated_caller_mut(&mut self) -> &mut Caller { &mut self.unauthenticated_caller } diff --git a/v-api/src/context/mod.rs b/v-api/src/context/mod.rs index 6481e94e..9cd83f02 100644 --- a/v-api/src/context/mod.rs +++ b/v-api/src/context/mod.rs @@ -53,7 +53,7 @@ use crate::{ error::ApiError, mapper::DefaultMappingEngine, permissions::{VAppPermission, VPermission}, - response::{OptionalResource, ResourceErrorInner}, + response::{OptionalResource, ResourceErrorInner, unauthorized}, util::response::{ ResourceResult, client_error, internal_error, resource_error, resource_restricted, }, @@ -239,7 +239,7 @@ where { fn as_ctx( &self, - ) -> impl Future, Caller), VContextCallerError>>; + ) -> impl Future, Caller), VContextCallerError>>; } #[derive(Debug, Error)] @@ -249,18 +249,21 @@ pub enum VContextError { } #[derive(Debug, Error)] -pub enum VContextCallerError { +pub enum VContextCallerError { #[error(transparent)] Auth(#[from] AuthError), #[error(transparent)] Caller(#[from] UserContextError), + #[error("Request is unauthenticated")] + Unauthenticated(Caller), } -impl From for HttpError { - fn from(value: VContextCallerError) -> Self { +impl From> for HttpError { + fn from(value: VContextCallerError) -> Self { match value { VContextCallerError::Auth(inner) => inner.into(), VContextCallerError::Caller(inner) => inner.into(), + VContextCallerError::Unauthenticated(_) => unauthorized(), } } } @@ -270,7 +273,7 @@ where T: VAppPermission, U: ApiContext, { - async fn as_ctx(&self) -> Result<(&VContext, Caller), VContextCallerError> { + async fn as_ctx(&self) -> Result<(&VContext, Caller), VContextCallerError> { let ctx = self.v_ctx(); let caller = ctx.get_caller(self).await?; Ok((ctx, caller)) @@ -382,7 +385,7 @@ where self } - pub fn builtin_unauthenticated_caller(&self) -> Caller { + fn builtin_unauthenticated_caller(&self) -> Caller { self.auth.builtin_unauthenticated_caller() } @@ -452,7 +455,7 @@ where pub async fn get_caller( &self, rqctx: &RequestContext>, - ) -> Result, VContextCallerError> { + ) -> Result, VContextCallerError> { self.get_caller_from_token(self.auth.authn_token(rqctx).await?.as_ref()) .await } @@ -460,18 +463,19 @@ where pub async fn get_caller_from_token( &self, auth: Option<&AuthToken>, - ) -> Result, VContextCallerError> { - Ok(match auth { - Some(token) => { - self.user - .get_caller(&self.builtin_registration_user(), &self.auth, token) - .await? - } + ) -> Result, VContextCallerError> { + match auth { + Some(token) => Ok(self + .user + .get_caller(&self.builtin_registration_user(), &self.auth, token) + .await?), None => { - tracing::debug!("No token found in request. Falling back to unauthenticated user"); - self.builtin_unauthenticated_caller() + tracing::debug!("No token found in request"); + Err(VContextCallerError::Unauthenticated( + self.builtin_unauthenticated_caller(), + )) } - }) + } } #[instrument(skip(self, info), fields(info.external_id))] @@ -755,6 +759,20 @@ where } } +pub trait UnauthenticatedCaller { + /// Call to allow an unauthenticated caller to be returned. + fn allow_unauthenticated(self) -> Result, VContextCallerError>; +} + +impl UnauthenticatedCaller for Result, VContextCallerError> { + fn allow_unauthenticated(self) -> Result, VContextCallerError> { + self.or_else(|err| match err { + VContextCallerError::Unauthenticated(caller) => Ok(caller), + err => Err(err), + }) + } +} + #[async_trait] impl Verify for VContext where @@ -1252,8 +1270,10 @@ mod tests { util::tests::{MockKey, mock_key}, }; + use dropshot::HttpError; + use super::{ - PresetGroupConfig, VContext, VContextCallerError, + PresetGroupConfig, UnauthenticatedCaller, VContext, VContextCallerError, test_mocks::{MockStorage, build_ctx_with_groups, mock_context, mock_context_with_groups}, }; @@ -1446,6 +1466,56 @@ mod tests { } } + #[tokio::test] + async fn test_missing_token_is_rejected_as_unauthenticated() { + let ctx = mock_context(Arc::new(MockStorage::new())).await; + + let err = ctx.get_caller_from_token(None).await.unwrap_err(); + match &err { + VContextCallerError::Unauthenticated(caller) => { + assert_eq!(ctx.builtin_unauthenticated_caller().id, caller.id) + } + other => panic!( + "Expected an unauthenticated error. Instead found {:?}", + other + ), + } + + assert_eq!(401, HttpError::from(err).status_code.as_u16()); + } + + #[tokio::test] + async fn test_allow_unauthenticated_opts_in_to_the_unauthenticated_caller() { + let ctx = mock_context(Arc::new(MockStorage::new())).await; + + let caller = ctx + .get_caller_from_token(None) + .await + .allow_unauthenticated() + .unwrap(); + + assert_eq!(ctx.builtin_unauthenticated_caller().id, caller.id); + assert_eq!( + ctx.builtin_unauthenticated_caller().permissions, + caller.permissions + ); + } + + /// Opting in to unauthenticated callers must not hide a token that failed to verify + #[test] + fn test_allow_unauthenticated_keeps_other_errors() { + let result: Result, VContextCallerError> = + Err(VContextCallerError::Caller(UserContextError::InvalidToken)); + + match result.allow_unauthenticated() { + Err(VContextCallerError::Caller(UserContextError::InvalidToken)) => (), + other => panic!( + "Expected the token error to be kept. Instead found {:?}", + other + ), + } + } + #[tokio::test] async fn test_preset_group_membership_grants_permissions() { let mut storage = MockStorage::new(); diff --git a/v-api/src/lib.rs b/v-api/src/lib.rs index 5f35f2e6..fbc821c1 100644 --- a/v-api/src/lib.rs +++ b/v-api/src/lib.rs @@ -16,9 +16,9 @@ mod util; pub use context::{ ApiContext, BasePermissions, CallerExtension, ExtensionError, GroupContext, LinkContext, LoginContext, MagicLinkContext, MagicLinkMessage, MagicLinkTarget, MappingContext, - OAuthContext, OAuthError, PresetGroupConfig, PresetMapperConfig, UserContext, VApiStorage, - VContext, VContextBuilder, VContextBuilderError, VContextError, VContextWithCaller, - auth::SecretContext, + OAuthContext, OAuthError, PresetGroupConfig, PresetMapperConfig, UnauthenticatedCaller, + UserContext, VApiStorage, VContext, VContextBuilder, VContextBuilderError, VContextError, + VContextWithCaller, auth::SecretContext, }; pub use util::response;