Skip to content

Commit

Permalink
update allow_anonymous logic
Browse files Browse the repository at this point in the history
The presence of an Authorization header implies intent to be identified and authenticated
  • Loading branch information
calebbourg committed Nov 7, 2024
1 parent 71063ce commit 6926d4c
Showing 1 changed file with 45 additions and 12 deletions.
57 changes: 45 additions & 12 deletions rama-http/src/layer/auth/require_authorization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,13 +214,12 @@ where
) -> Result<(Context<S>, Request<B>), Response<Self::ResponseBody>> {
match request.headers().get(header::AUTHORIZATION) {
Some(actual) if actual == self.credential.header_value => Ok((ctx, request)),
None if self.allow_anonymous => {
let mut ctx = ctx;
ctx.insert(UserId::Anonymous);
Ok((ctx, request))
}
_ => {
if self.allow_anonymous {
let mut ctx = ctx;
ctx.insert(UserId::Anonymous);

return Ok((ctx, request));
}
let mut res = Response::new(ResBody::default());
*res.status_mut() = StatusCode::UNAUTHORIZED;
Err(res)
Expand Down Expand Up @@ -283,13 +282,12 @@ where
) -> Result<(Context<S>, Request<B>), Response<Self::ResponseBody>> {
match request.headers().get(header::AUTHORIZATION) {
Some(actual) if actual == self.credential.header_value => Ok((ctx, request)),
None if self.allow_anonymous => {
let mut ctx = ctx;
ctx.insert(UserId::Anonymous);
Ok((ctx, request))
}
_ => {
if self.allow_anonymous {
let mut ctx = ctx;
ctx.insert(UserId::Anonymous);

return Ok((ctx, request));
}
let mut res = Response::new(ResBody::default());
*res.status_mut() = StatusCode::UNAUTHORIZED;
res.headers_mut()
Expand Down Expand Up @@ -487,6 +485,25 @@ mod tests {
assert_eq!(res.status(), StatusCode::OK);
}

#[tokio::test]
async fn basic_fails_if_allow_anonymous_and_credentials_are_invalid() {
let service = ValidateRequestHeaderLayer::basic("foo", "bar")
.with_allow_anonymous(true)
.layer(service_fn(echo));

let request = Request::get("/")
.header(
header::AUTHORIZATION,
format!("Basic {}", BASE64.encode("wrong:credentials")),
)
.body(Body::empty())
.unwrap();

let res = service.serve(Context::default(), request).await.unwrap();

assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn bearer_allows_anonymous_if_header_is_missing() {
let service = ValidateRequestHeaderLayer::bearer("foobar")
Expand All @@ -499,4 +516,20 @@ mod tests {

assert_eq!(res.status(), StatusCode::OK);
}

#[tokio::test]
async fn bearer_fails_if_allow_anonymous_and_credentials_are_invalid() {
let service = ValidateRequestHeaderLayer::bearer("foobar")
.with_allow_anonymous(true)
.layer(service_fn(echo));

let request = Request::get("/")
.header(header::AUTHORIZATION, "Bearer wrong")
.body(Body::empty())
.unwrap();

let res = service.serve(Context::default(), request).await.unwrap();

assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
}

0 comments on commit 6926d4c

Please sign in to comment.