Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dropshot-authorization-header/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ publish.workspace = true
async-trait = { workspace = true }
base64 = { workspace = true }
dropshot = { workspace = true }
http = { workspace = true }
tracing = { workspace = true }
134 changes: 102 additions & 32 deletions dropshot-authorization-header/src/bearer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>);
Expand All @@ -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<BearerAuth, HttpError> {
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<Context: ServerContext>(
rqctx: &RequestContext<Context>,
) -> Result<BearerAuth, HttpError> {
// 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 {
Expand All @@ -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());
}
}
13 changes: 5 additions & 8 deletions v-api/src/authn/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down Expand Up @@ -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
}
Expand Down
11 changes: 3 additions & 8 deletions v-api/src/authn/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
4 changes: 2 additions & 2 deletions v-api/src/context/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@ where
})
}

pub fn builtin_unauthenticated_caller(&self) -> Caller<T> {
pub(super) fn builtin_unauthenticated_caller(&self) -> Caller<T> {
self.unauthenticated_caller.clone()
}

pub fn builtin_unauthenticated_caller_mut(&mut self) -> &mut Caller<T> {
pub(super) fn builtin_unauthenticated_caller_mut(&mut self) -> &mut Caller<T> {
&mut self.unauthenticated_caller
}

Expand Down
Loading
Loading