From 24dae0a370585bf355c77b4f2136d1a4afce356b Mon Sep 17 00:00:00 2001 From: augustuswm Date: Mon, 23 Nov 2026 09:22:04 -0600 Subject: [PATCH 1/6] Make unautheticated callers an opt in mechanic --- v-api/src/context/mod.rs | 34 +++++++++++++++++++++++++++------- v-api/src/lib.rs | 6 +++--- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/v-api/src/context/mod.rs b/v-api/src/context/mod.rs index 6481e94e..54f73f0c 100644 --- a/v-api/src/context/mod.rs +++ b/v-api/src/context/mod.rs @@ -239,7 +239,7 @@ where { fn as_ctx( &self, - ) -> impl Future, Caller), VContextCallerError>>; + ) -> impl Future, Caller), VContextCallerError>>; } #[derive(Debug, Error)] @@ -249,18 +249,24 @@ pub enum VContextError { } #[derive(Debug, Error)] -pub enum VContextCallerError { +pub enum VContextCallerError { #[error(transparent)] Auth(#[from] AuthError), #[error(transparent)] Caller(#[from] UserContextError), + 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(_) => HttpError::for_client_error( + None, + ClientErrorStatusCode::UNAUTHORIZED, + "unathentticated".to_string(), + ), } } } @@ -270,7 +276,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)) @@ -452,7 +458,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,7 +466,7 @@ where pub async fn get_caller_from_token( &self, auth: Option<&AuthToken>, - ) -> Result, VContextCallerError> { + ) -> Result, VContextCallerError> { Ok(match auth { Some(token) => { self.user @@ -755,6 +761,20 @@ where } } +pub trait UnathenticateCaller { + fn allow_unathenticated(self) -> Result, VContextCallerError>; +} + +impl UnathenticateCaller for Result, VContextCallerError> { + fn allow_unathenticated(self) -> Result, VContextCallerError> { + match self { + Ok(caller) => Ok(caller), + Err(VContextCallerError::Unauthenticated(caller)) => Ok(caller), + Err(err) => Err(err), + } + } +} + #[async_trait] impl Verify for VContext where diff --git a/v-api/src/lib.rs b/v-api/src/lib.rs index 5f35f2e6..197ceb41 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, UnathenticateCaller, + UserContext, VApiStorage, VContext, VContextBuilder, VContextBuilderError, VContextError, + VContextWithCaller, auth::SecretContext, }; pub use util::response; From a03a408d4e0f27e625713c14ea3bf2ed652bb751 Mon Sep 17 00:00:00 2001 From: augustuswm Date: Mon, 23 Nov 2026 09:50:55 -0600 Subject: [PATCH 2/6] Add calls. Differentiate between malformed header and no header --- Cargo.lock | 1 + dropshot-authorization-header/Cargo.toml | 1 + dropshot-authorization-header/src/bearer.rs | 105 ++++++++++++++------ v-api/src/authn/jwt.rs | 11 +- v-api/src/authn/mod.rs | 9 +- v-api/src/context/auth.rs | 4 +- v-api/src/context/mod.rs | 102 ++++++++++++++----- v-api/src/lib.rs | 2 +- 8 files changed, 161 insertions(+), 74 deletions(-) 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..115329ba 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::{HeaderValue, header::AUTHORIZATION}; /// A token used for bearer authentication pub struct BearerAuth(Option); @@ -25,41 +26,37 @@ 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_header(header: Option<&HeaderValue>) -> Result { + let token = header + .map(|header| { + header + .to_str() + .ok() + .and_then(|value| value.strip_prefix("Bearer ")) + .map(|token| token.to_string()) + .ok_or_else(|| { + tracing::info!("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_header(rqctx.request.headers().get(AUTHORIZATION)) } fn metadata(_body_content_type: ApiEndpointBodyContentType) -> ExtractorMetadata { @@ -69,3 +66,47 @@ impl SharedExtractor for BearerAuth { } } } + +#[cfg(test)] +mod tests { + use http::HeaderValue; + + use super::bearer_from_header; + + #[test] + fn missing_header_has_no_token() { + assert_eq!(None, bearer_from_header(None).unwrap().consume()); + } + + #[test] + fn bearer_header_yields_token() { + let header = HeaderValue::from_static("Bearer token"); + + assert_eq!( + Some("token".to_string()), + bearer_from_header(Some(&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_header(Some(&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_header(Some(&header)).is_err()); + } +} diff --git a/v-api/src/authn/jwt.rs b/v-api/src/authn/jwt.rs index 2b466fbb..72ce875f 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 + 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..c7196589 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 + 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 54f73f0c..fd29d5cd 100644 --- a/v-api/src/context/mod.rs +++ b/v-api/src/context/mod.rs @@ -254,6 +254,7 @@ pub enum VContextCallerError { Auth(#[from] AuthError), #[error(transparent)] Caller(#[from] UserContextError), + #[error("Request is unauthenticated")] Unauthenticated(Caller), } @@ -262,11 +263,9 @@ impl From> for HttpError { match value { VContextCallerError::Auth(inner) => inner.into(), VContextCallerError::Caller(inner) => inner.into(), - VContextCallerError::Unauthenticated(_) => HttpError::for_client_error( - None, - ClientErrorStatusCode::UNAUTHORIZED, - "unathentticated".to_string(), - ), + VContextCallerError::Unauthenticated(_) => { + client_error(ClientErrorStatusCode::UNAUTHORIZED, "Unauthenticated") + } } } } @@ -388,7 +387,7 @@ where self } - pub fn builtin_unauthenticated_caller(&self) -> Caller { + fn builtin_unauthenticated_caller(&self) -> Caller { self.auth.builtin_unauthenticated_caller() } @@ -467,17 +466,18 @@ where &self, auth: Option<&AuthToken>, ) -> Result, VContextCallerError> { - Ok(match auth { - Some(token) => { - self.user - .get_caller(&self.builtin_registration_user(), &self.auth, token) - .await? - } + 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))] @@ -761,17 +761,17 @@ where } } -pub trait UnathenticateCaller { - fn allow_unathenticated(self) -> Result, VContextCallerError>; +pub trait UnauthenticatedCaller { + /// Call to allow an unathenticated caller to be returned. + fn allow_unauthenticated(self) -> Result, VContextCallerError>; } -impl UnathenticateCaller for Result, VContextCallerError> { - fn allow_unathenticated(self) -> Result, VContextCallerError> { - match self { - Ok(caller) => Ok(caller), - Err(VContextCallerError::Unauthenticated(caller)) => Ok(caller), - Err(err) => Err(err), - } +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), + }) } } @@ -1272,8 +1272,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}, }; @@ -1466,6 +1468,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 197ceb41..fbc821c1 100644 --- a/v-api/src/lib.rs +++ b/v-api/src/lib.rs @@ -16,7 +16,7 @@ mod util; pub use context::{ ApiContext, BasePermissions, CallerExtension, ExtensionError, GroupContext, LinkContext, LoginContext, MagicLinkContext, MagicLinkMessage, MagicLinkTarget, MappingContext, - OAuthContext, OAuthError, PresetGroupConfig, PresetMapperConfig, UnathenticateCaller, + OAuthContext, OAuthError, PresetGroupConfig, PresetMapperConfig, UnauthenticatedCaller, UserContext, VApiStorage, VContext, VContextBuilder, VContextBuilderError, VContextError, VContextWithCaller, auth::SecretContext, }; From 2490712e3194cc255962440d57b422ca25f9fb10 Mon Sep 17 00:00:00 2001 From: augustuswm Date: Tue, 24 Nov 2026 00:25:40 -0600 Subject: [PATCH 3/6] Case insensitive check on bearer prefix --- dropshot-authorization-header/src/bearer.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/dropshot-authorization-header/src/bearer.rs b/dropshot-authorization-header/src/bearer.rs index 115329ba..d62cf1d8 100644 --- a/dropshot-authorization-header/src/bearer.rs +++ b/dropshot-authorization-header/src/bearer.rs @@ -32,7 +32,9 @@ fn bearer_from_header(header: Option<&HeaderValue>) -> Result Date: Tue, 24 Nov 2026 00:30:21 -0600 Subject: [PATCH 4/6] Update auth extract logs --- dropshot-authorization-header/src/bearer.rs | 2 +- v-api/src/authn/jwt.rs | 2 +- v-api/src/authn/mod.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dropshot-authorization-header/src/bearer.rs b/dropshot-authorization-header/src/bearer.rs index d62cf1d8..870e204c 100644 --- a/dropshot-authorization-header/src/bearer.rs +++ b/dropshot-authorization-header/src/bearer.rs @@ -37,7 +37,7 @@ fn bearer_from_header(header: Option<&HeaderValue>) -> Result Date: Tue, 24 Nov 2026 00:32:27 -0600 Subject: [PATCH 5/6] Cleanup --- v-api/src/context/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/v-api/src/context/mod.rs b/v-api/src/context/mod.rs index fd29d5cd..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, }, @@ -263,9 +263,7 @@ impl From> for HttpError { match value { VContextCallerError::Auth(inner) => inner.into(), VContextCallerError::Caller(inner) => inner.into(), - VContextCallerError::Unauthenticated(_) => { - client_error(ClientErrorStatusCode::UNAUTHORIZED, "Unauthenticated") - } + VContextCallerError::Unauthenticated(_) => unauthorized(), } } } @@ -762,7 +760,7 @@ where } pub trait UnauthenticatedCaller { - /// Call to allow an unathenticated caller to be returned. + /// Call to allow an unauthenticated caller to be returned. fn allow_unauthenticated(self) -> Result, VContextCallerError>; } From a932864866a8d173d5c4fa69956e07cfd7150032 Mon Sep 17 00:00:00 2001 From: augustuswm Date: Tue, 24 Nov 2026 00:34:06 -0600 Subject: [PATCH 6/6] Pass header map as arg --- dropshot-authorization-header/src/bearer.rs | 36 ++++++++++++++------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/dropshot-authorization-header/src/bearer.rs b/dropshot-authorization-header/src/bearer.rs index 870e204c..23a2a5e8 100644 --- a/dropshot-authorization-header/src/bearer.rs +++ b/dropshot-authorization-header/src/bearer.rs @@ -7,7 +7,7 @@ use dropshot::{ ApiEndpointBodyContentType, ClientErrorStatusCode, ExtensionMode, ExtractorMetadata, HttpError, RequestContext, ServerContext, SharedExtractor, }; -use http::{HeaderValue, header::AUTHORIZATION}; +use http::{HeaderMap, header::AUTHORIZATION}; /// A token used for bearer authentication pub struct BearerAuth(Option); @@ -26,8 +26,9 @@ impl BearerAuth { } } -fn bearer_from_header(header: Option<&HeaderValue>) -> Result { - let token = header +fn bearer_from_headers(headers: &HeaderMap) -> Result { + let token = headers + .get(AUTHORIZATION) .map(|header| { header .to_str() @@ -58,7 +59,7 @@ impl SharedExtractor for BearerAuth { async fn from_request( rqctx: &RequestContext, ) -> Result { - bearer_from_header(rqctx.request.headers().get(AUTHORIZATION)) + bearer_from_headers(rqctx.request.headers()) } fn metadata(_body_content_type: ApiEndpointBodyContentType) -> ExtractorMetadata { @@ -71,13 +72,22 @@ impl SharedExtractor for BearerAuth { #[cfg(test)] mod tests { - use http::HeaderValue; + use http::{HeaderMap, HeaderValue, header::AUTHORIZATION}; - use super::bearer_from_header; + 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_header(None).unwrap().consume()); + assert_eq!( + None, + bearer_from_headers(&HeaderMap::new()).unwrap().consume() + ); } #[test] @@ -86,7 +96,9 @@ mod tests { assert_eq!( Some("token".to_string()), - bearer_from_header(Some(&header)).unwrap().consume() + bearer_from_headers(&authorization(header)) + .unwrap() + .consume() ); } @@ -98,7 +110,9 @@ mod tests { assert_eq!( Some("token".to_string()), - bearer_from_header(Some(&header)).unwrap().consume() + bearer_from_headers(&authorization(header)) + .unwrap() + .consume() ); } } @@ -110,7 +124,7 @@ mod tests { assert_eq!( 401, - bearer_from_header(Some(&header)) + bearer_from_headers(&authorization(header)) .err() .unwrap() .status_code @@ -122,6 +136,6 @@ mod tests { fn unreadable_header_is_rejected() { let header = HeaderValue::from_bytes(b"Bearer \xff").unwrap(); - assert!(bearer_from_header(Some(&header)).is_err()); + assert!(bearer_from_headers(&authorization(header)).is_err()); } }