Skip to content

Commit

Permalink
Expose RequestContext::authorizer() for Api Gateway requests.
Browse files Browse the repository at this point in the history
Signed-off-by :David Calavera <[email protected]>
  • Loading branch information
calavera committed Feb 21, 2024
1 parent e606126 commit 7a3ab97
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lambda-http/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use crate::ext::extensions::{PathParameters, StageVariables};
use crate::ext::extensions::{QueryStringParameters, RawHttpPath};
#[cfg(feature = "alb")]
use aws_lambda_events::alb::{AlbTargetGroupRequest, AlbTargetGroupRequestContext};
#[cfg(any(feature = "apigw_rest", feature = "apigw_http", feature = "apigw_websockets"))]
use aws_lambda_events::apigw::ApiGatewayRequestAuthorizer;
#[cfg(feature = "apigw_rest")]
use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyRequestContext};
#[cfg(feature = "apigw_http")]
Expand Down Expand Up @@ -425,6 +427,22 @@ impl From<LambdaRequest> for http::Request<Body> {
}
}

impl RequestContext {
/// Returns the Api Gateway Authorizer information for a request.
#[cfg(any(feature = "apigw_rest", feature = "apigw_http", feature = "apigw_websockets"))]
pub fn authorizer(&self) -> Option<&ApiGatewayRequestAuthorizer> {
match self {
#[cfg(feature = "apigw_rest")]
Self::ApiGatewayV1(ag) => Some(&ag.authorizer),
#[cfg(feature = "apigw_http")]
Self::ApiGatewayV2(ag) => ag.authorizer.as_ref(),
#[cfg(feature = "apigw_websockets")]
Self::WebSocket(ag) => Some(&ag.authorizer),
_ => None,
}
}
}

/// Deserializes a `Request` from a `Read` impl providing JSON events.
///
/// # Example
Expand Down Expand Up @@ -920,4 +938,20 @@ mod tests {
assert_eq!(vec!["val1", "val2"], query.0.my_key);
assert_eq!(vec!["val3", "val4"], query.0.my_other_key);
}

#[test]
#[cfg(feature = "apigw_rest")]
fn deserializes_request_authorizer() {
let input = include_str!("../../lambda-events/src/fixtures/example-apigw-request.json");
let result = from_str(input);
assert!(
result.is_ok(),
"event was not parsed as expected {result:?} given {input}"
);
let req = result.expect("failed to parse request");

let req_context = req.request_context_ref().expect("Request is missing RequestContext");
let authorizer = req_context.authorizer().expect("authorizer is missing");
assert_eq!(Some("admin"), authorizer.fields.get("principalId").unwrap().as_str());
}
}

0 comments on commit 7a3ab97

Please sign in to comment.