feat(apigateway): enforce Cognito user pool authorizers (#4323)

* feat(apigateway): enforce Cognito user pool authorizers

* fix(apigateway): honor Cognito authorizer configuration

* fix(cognito): reject signed-out REST authorizer tokens

* style(apigateway): order imports

* style(apigateway): explain authorizer type clash

* chore(ci): rerun PR test workflow

* refactor(apigateway): isolate Cognito user pool authorization

---------

Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
This commit is contained in:
vamsiakandVamsi Akavarapu authored and GitHub committed 2026-09-25 07:11:07 -04:00
1 parent 6cd1bb3794
commit 1a009300dd
20 files changed
+486 -100

No files matched your search

@@ -2176,6 +2176,9 @@ public class ApiGatewayController {
node.put("authorizationType", m.getAuthorizationType());
node.put("apiKeyRequired", m.isApiKeyRequired());
if (m.getAuthorizerId() != null) node.put("authorizerId", m.getAuthorizerId());
if (m.getAuthorizationScopes() != null && !m.getAuthorizationScopes().isEmpty()) {
node.set("authorizationScopes", objectMapper.valueToTree(m.getAuthorizationScopes()));
}
if (m.getRequestValidatorId() != null) node.put("requestValidatorId", m.getRequestValidatorId());
if (m.getRequestParameters() != null && !m.getRequestParameters().isEmpty()) {
ObjectNode params = node.putObject("requestParameters");
@@ -96,6 +96,7 @@ public class ApiGatewayExecuteController {
"application/graphql");
private final ApiGatewayService apiGatewayService;
private final CognitoUserPoolAuthorizer cognitoAuthorizer;
private final ApiGatewayV2Service apiGatewayV2Service;
private final LambdaService lambdaService;
private final RegionResolver regionResolver;
@@ -111,7 +112,8 @@ public class ApiGatewayExecuteController {
private final ExecuteApiSigV4Authorizer sigV4Authorizer;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer,
ApiGatewayV2Service apiGatewayV2Service,
LambdaService lambdaService, RegionResolver regionResolver,
ObjectMapper objectMapper, VtlTemplateEngine vtlEngine,
AwsServiceRouter serviceRouter,
@@ -123,6 +125,7 @@ public class ApiGatewayExecuteController {
RequestContext requestContext,
ExecuteApiSigV4Authorizer sigV4Authorizer) {
this.apiGatewayService = apiGatewayService;
this.cognitoAuthorizer = cognitoAuthorizer;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
this.regionResolver = regionResolver;
@@ -964,6 +967,18 @@ public class ApiGatewayExecuteController {
Stage stage,
MethodConfig method,
HttpHeaders headers, UriInfo uriInfo, ResolvedApiKey resolvedApiKey) {
if ("COGNITO_USER_POOLS".equalsIgnoreCase(method.getAuthorizationType())) {
CognitoUserPoolAuthorizer.Result result = cognitoAuthorizer.authorize(region, apiId, method, headers);
if (result.failure() == CognitoUserPoolAuthorizer.Failure.UNAUTHORIZED) {
return new AuthorizerResult(gatewayResponse(scope, GatewayResponseType.UNAUTHORIZED, 401,
"Unauthorized"), null, null);
}
if (result.failure() == CognitoUserPoolAuthorizer.Failure.ACCESS_DENIED) {
return new AuthorizerResult(gatewayResponse(scope, GatewayResponseType.ACCESS_DENIED, 403,
"User is not authorized to access this resource"), null, null);
}
return new AuthorizerResult(null, result.principalId(), result.context());
}
if ("CUSTOM".equals(method.getAuthorizationType())) {
String authorizerId = method.getAuthorizerId();
if (authorizerId == null) {
@@ -1331,7 +1346,9 @@ public class ApiGatewayExecuteController {
}
if (authorizerContext != null) {
authorizerContext.forEach((key, value) -> {
if (value != null) {
if (value instanceof Map<?, ?>) {
authorizerNode.set(key, objectMapper.valueToTree(value));
} else if (value != null) {
authorizerNode.put(key, value.toString());
}
});
@@ -1503,7 +1520,7 @@ public class ApiGatewayExecuteController {
if (authorizerContext != null) {
authorizerContext.forEach((key, value) -> {
if (value != null) {
result.put(key, value.toString());
result.put(key, value instanceof Map<?, ?> ? value : value.toString());
}
});
}
@@ -2522,12 +2539,18 @@ public class ApiGatewayExecuteController {
}
}
private Optional<Authorizer> findV2Authorizer(String region, String apiId, String authorizerId) {
try {
return Optional.of(apiGatewayV2Service.getAuthorizer(region, apiId, authorizerId));
} catch (AwsException e) {
return Optional.empty();
}
}
private JwtAuthorizerResult enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers,
UriInfo uriInfo) {
Authorizer authorizer;
try {
authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, route.getAuthorizerId());
} catch (AwsException e) {
Authorizer authorizer = findV2Authorizer(region, apiId, route.getAuthorizerId()).orElse(null);
if (authorizer == null) {
return new JwtAuthorizerResult(Response.status(500)
.entity(jsonMessage("Authorizer not found"))
.type(MediaType.APPLICATION_JSON).build(), null);
@@ -2692,10 +2715,8 @@ public class ApiGatewayExecuteController {
private RequestAuthorizerResult enforceRequestAuthorizerV2(String region, String apiId, String stageName,
Route route, String httpMethod, String path,
HttpHeaders headers, UriInfo uriInfo) {
Authorizer authorizer;
try {
authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, route.getAuthorizerId());
} catch (AwsException e) {
Authorizer authorizer = findV2Authorizer(region, apiId, route.getAuthorizerId()).orElse(null);
if (authorizer == null) {
return new RequestAuthorizerResult(Response.status(500)
.entity(jsonMessage("Authorizer not found"))
.type(MediaType.APPLICATION_JSON).build(), null);
@@ -1,5 +1,46 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.Account;
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
import io.github.hectorvent.floci.services.apigateway.model.EndpointType;
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponseType;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
import io.github.hectorvent.floci.services.apigateway.model.MethodResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
import io.github.hectorvent.floci.services.apigateway.model.Model;
import io.github.hectorvent.floci.services.apigateway.model.RequestValidator;
import io.github.hectorvent.floci.services.apigateway.model.RestApi;
import io.github.hectorvent.floci.services.apigateway.model.Stage;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.apigateway.model.VpcLink;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
@@ -16,51 +57,11 @@ import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
import io.github.hectorvent.floci.services.apigateway.model.EndpointType;
import org.jboss.logging.Logger;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.Account;
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.MethodSetting;
import io.github.hectorvent.floci.services.apigateway.model.VpcLink;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import io.github.hectorvent.floci.services.apigateway.model.Deployment;
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponse;
import io.github.hectorvent.floci.services.apigateway.model.GatewayResponseType;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
import io.github.hectorvent.floci.services.apigateway.model.MethodResponse;
import io.github.hectorvent.floci.services.apigateway.model.Model;
import io.github.hectorvent.floci.services.apigateway.model.RequestValidator;
import io.github.hectorvent.floci.services.apigateway.model.RestApi;
import io.github.hectorvent.floci.services.apigateway.model.Stage;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
public class ApiGatewayService {
private static final ObjectMapper JSON = new ObjectMapper();
/** Documented default page size for GetUsage. */
private static final int DEFAULT_USAGE_LIMIT = 25;
/**
@@ -463,6 +464,10 @@ public class ApiGatewayService {
method.setHttpMethod(httpMethod.toUpperCase());
method.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
method.setAuthorizerId((String) request.get("authorizerId"));
Object authorizationScopes = request.get("authorizationScopes");
if (authorizationScopes instanceof List<?> scopes) {
method.setAuthorizationScopes(scopes.stream().map(String::valueOf).toList());
}
method.setRequestValidatorId((String) request.get("requestValidatorId"));
method.setApiKeyRequired(Boolean.TRUE.equals(request.get("apiKeyRequired")));
@@ -2485,6 +2490,14 @@ public class ApiGatewayService {
if (!"replace".equals(opType)) continue;
if ("/authorizationType".equals(path)) method.setAuthorizationType(value);
else if ("/authorizerId".equals(path)) method.setAuthorizerId(value);
else if ("/authorizationScopes".equals(path)) {
try {
method.setAuthorizationScopes(value == null || value.isBlank()
? List.of() : JSON.readValue(value, new TypeReference<List<String>>() {}));
} catch (Exception e) {
throw new AwsException("BadRequestException", "Invalid authorizationScopes", 400);
}
}
else if ("/apiKeyRequired".equals(path)) method.setApiKeyRequired(Boolean.parseBoolean(value));
else if ("/requestValidatorId".equals(path)) {
method.setRequestValidatorId(value == null || value.isEmpty() ? null : value);
@@ -3032,6 +3045,7 @@ public class ApiGatewayService {
? operation.getSecurity() : openAPI.getSecurity();
String authType = "NONE";
String authorizerId = null;
List<String> authorizationScopes = List.of();
if (secReqs != null) {
// AWS resolves the OR-list of security requirements to the first declared
// authorizer scheme (a method has exactly one authorizer), so stop at the first match.
@@ -3044,6 +3058,10 @@ public class ApiGatewayService {
}
authType = mapped;
authorizerId = schemeToAuthorizerId.get(schemeName);
List<String> requestedScopes = secReq.get(schemeName);
if (requestedScopes != null) {
authorizationScopes = requestedScopes;
}
break resolveAuth;
}
}
@@ -3052,6 +3070,9 @@ public class ApiGatewayService {
if (authorizerId != null) {
methodRequest.put("authorizerId", authorizerId);
}
if (!authorizationScopes.isEmpty()) {
methodRequest.put("authorizationScopes", authorizationScopes);
}
// Link request models from operation requestBody
if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
@@ -0,0 +1,83 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.apigateway.model.Authorizer;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.HttpHeaders;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Verifies Cognito user-pool tokens for REST execute-api methods. */
@ApplicationScoped
public class CognitoUserPoolAuthorizer {
public enum Failure {
UNAUTHORIZED,
ACCESS_DENIED
}
public record Result(Failure failure, String principalId, Map<String, Object> context) {}
private final ApiGatewayService apiGatewayService;
private final CognitoService cognitoService;
@Inject
public CognitoUserPoolAuthorizer(ApiGatewayService apiGatewayService, CognitoService cognitoService) {
this.apiGatewayService = apiGatewayService;
this.cognitoService = cognitoService;
}
public Result authorize(String region, String apiId, MethodConfig method, HttpHeaders headers) {
if (method.getAuthorizerId() == null) {
return new Result(Failure.UNAUTHORIZED, null, null);
}
try {
Authorizer authorizer = apiGatewayService.getAuthorizer(region, apiId, method.getAuthorizerId());
List<String> providerArns = authorizer.getProviderARNs();
if (providerArns == null || providerArns.isEmpty()) {
return new Result(Failure.UNAUTHORIZED, null, null);
}
String identitySource = authorizer.getIdentitySource();
if (identitySource == null || !identitySource.startsWith("method.request.header.")) {
return new Result(Failure.UNAUTHORIZED, null, null);
}
String headerName = identitySource.substring("method.request.header.".length());
String authorization = headers.getHeaderString(headerName);
if (authorization == null || authorization.isBlank()) {
return new Result(Failure.UNAUTHORIZED, null, null);
}
String token = authorization.regionMatches(true, 0, "Bearer ", 0, 7)
? authorization.substring(7).trim() : authorization.trim();
CognitoService.VerifiedApiGatewayToken verified = cognitoService.verifyApiGatewayToken(token);
String verifiedPoolArn = cognitoService.describeUserPool(verified.poolId()).getArn();
if (!providerArns.contains(verifiedPoolArn)) {
return new Result(Failure.UNAUTHORIZED, null, null);
}
List<String> requiredScopes = method.getAuthorizationScopes();
if (requiredScopes != null && !requiredScopes.isEmpty()) {
if (!"access".equals(verified.tokenUse())) {
return new Result(Failure.ACCESS_DENIED, null, null);
}
Set<String> granted = new HashSet<>();
Object scopeClaim = verified.claims().get("scope");
if (scopeClaim instanceof String value) {
granted.addAll(Arrays.asList(value.trim().split("\\s+")));
}
if (requiredScopes.stream().noneMatch(granted::contains)) {
return new Result(Failure.ACCESS_DENIED, null, null);
}
}
String principalId = String.valueOf(verified.claims().getOrDefault("sub", "unknown"));
return new Result(null, principalId, Map.of("claims", verified.claims()));
} catch (AwsException e) {
return new Result(Failure.UNAUTHORIZED, null, null);
}
}
}
@@ -4,7 +4,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -14,6 +16,7 @@ public class MethodConfig {
private String httpMethod;
private String authorizationType;
private String authorizerId;
private List<String> authorizationScopes = new ArrayList<>();
private String requestValidatorId;
private boolean apiKeyRequired;
private Map<String, Boolean> requestParameters = new HashMap<>();
@@ -30,6 +33,11 @@ public class MethodConfig {
public String getAuthorizerId() { return authorizerId; }
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
public List<String> getAuthorizationScopes() { return authorizationScopes; }
public void setAuthorizationScopes(List<String> authorizationScopes) {
this.authorizationScopes = authorizationScopes != null ? new ArrayList<>(authorizationScopes) : new ArrayList<>();
}
public String getRequestValidatorId() { return requestValidatorId; }
public void setRequestValidatorId(String requestValidatorId) { this.requestValidatorId = requestValidatorId; }
@@ -4020,6 +4020,55 @@ public class CognitoService implements ResourceProvider {
record VerifiedAccessToken(String username, String poolId, String subject) {}
/** Verified JWT details for services that enforce Cognito user-pool authorizers. */
public record VerifiedApiGatewayToken(String poolId, String tokenUse, Map<String, Object> claims) {}
private record VerifiedJwt(String poolId, JsonNode claims) {}
/**
* Verifies an access or ID token using the persisted user-pool signing key. This deliberately
* does not fetch keys over the network because the emulator owns the pool and its key pair.
*/
public VerifiedApiGatewayToken verifyApiGatewayToken(String token) {
try {
VerifiedJwt verified = verifyJwtSignatureAndIssuer(token);
JsonNode claims = verified.claims();
String poolId = verified.poolId();
String tokenUse = textClaim(claims, "token_use");
long expiresAt = requiredNumericClaim(claims, "exp");
String subject = textClaim(claims, "sub");
if (!("access".equals(tokenUse) || "id".equals(tokenUse))
|| subject == null || expiresAt <= System.currentTimeMillis() / 1000L) {
throw new IllegalArgumentException("invalid token claims");
}
String clientId = "access".equals(tokenUse)
? textClaim(claims, "client_id") : textClaim(claims, "aud");
if (clientId == null || clientStore.get(clientId)
.filter(c -> poolId.equals(c.getUserPoolId())).isEmpty()) {
throw new IllegalArgumentException("invalid client");
}
String jti = textClaim(claims, "jti");
validateTokenNotRevoked(jti, poolId, tokenUse);
String originJti = textClaim(claims, "origin_jti");
if (originJti != null) {
validateTokenNotRevoked(originJti, poolId, tokenUse);
}
String username = "access".equals(tokenUse)
? textClaim(claims, "username") : textClaim(claims, "cognito:username");
if (username != null) {
validateUserNotGloballySignedOut(username, poolId, tokenUse,
requiredNumericClaim(claims, "iat"));
}
Map<String, Object> mapped = MAPPER.convertValue(claims, new TypeReference<Map<String, Object>>() {});
return new VerifiedApiGatewayToken(poolId, tokenUse, Map.copyOf(mapped));
} catch (AwsException e) {
throw e;
} catch (Exception e) {
LOG.debug("API Gateway Cognito token verification failed", e);
throw new AwsException("NotAuthorizedException", INVALID_ACCESS_TOKEN_MESSAGE, 400);
}
}
/**
* Verifies the Cognito access-token contract before any self-service operation uses its claims.
* The pool's persisted public key is the trust anchor; claims are never trusted before the
@@ -4027,38 +4076,9 @@ public class CognitoService implements ResourceProvider {
*/
VerifiedAccessToken verifyAccessToken(String token) {
try {
if (token == null || token.isBlank()) {
throw new IllegalArgumentException("missing token");
}
String[] parts = token.split("\\.", -1);
if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) {
throw new IllegalArgumentException("malformed JWT");
}
JsonNode header = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[0]));
JsonNode claims = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[1]));
if (!"RS256".equals(header.path("alg").asText())
|| !"JWT".equalsIgnoreCase(header.path("typ").asText())) {
throw new IllegalArgumentException("unsupported JWT algorithm");
}
String issuer = textClaim(claims, "iss");
String poolId = null;
if (issuer != null && issuer.startsWith(baseUrl + "/")) {
poolId = issuer.substring((baseUrl + "/").length());
}
UserPool pool = poolId == null ? null : poolStore.get(poolId).orElse(null);
if (pool == null || !getIssuer(poolId).equals(issuer)
|| !getSigningKeyId(pool).equals(textClaim(header, "kid"))) {
throw new IllegalArgumentException("invalid issuer or key");
}
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(getSigningPublicKey(pool));
verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8));
if (!verifier.verify(Base64.getUrlDecoder().decode(parts[2]))) {
throw new IllegalArgumentException("invalid signature");
}
VerifiedJwt verified = verifyJwtSignatureAndIssuer(token);
JsonNode claims = verified.claims();
String poolId = verified.poolId();
String verifiedPoolId = poolId;
String username = textClaim(claims, "username");
@@ -4089,6 +4109,37 @@ public class CognitoService implements ResourceProvider {
}
}
private VerifiedJwt verifyJwtSignatureAndIssuer(String token) throws Exception {
if (token == null || token.isBlank()) {
throw new IllegalArgumentException("missing token");
}
String[] parts = token.split("\\.", -1);
if (parts.length != 3 || Arrays.stream(parts).anyMatch(String::isEmpty)) {
throw new IllegalArgumentException("malformed JWT");
}
JsonNode header = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[0]));
JsonNode claims = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[1]));
if (!"RS256".equals(header.path("alg").asText())
|| !"JWT".equalsIgnoreCase(header.path("typ").asText())) {
throw new IllegalArgumentException("unsupported JWT algorithm");
}
String issuer = textClaim(claims, "iss");
String poolId = issuer != null && issuer.startsWith(baseUrl + "/")
? issuer.substring((baseUrl + "/").length()) : null;
UserPool pool = poolId == null ? null : poolStore.get(poolId).orElse(null);
if (pool == null || !getIssuer(poolId).equals(issuer)
|| !getSigningKeyId(pool).equals(textClaim(header, "kid"))) {
throw new IllegalArgumentException("invalid issuer or key");
}
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(getSigningPublicKey(pool));
verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8));
if (!verifier.verify(Base64.getUrlDecoder().decode(parts[2]))) {
throw new IllegalArgumentException("invalid signature");
}
return new VerifiedJwt(poolId, claims);
}
private static String textClaim(JsonNode claims, String name) {
JsonNode value = claims.path(name);
return value.isTextual() && !value.asText().isBlank() ? value.asText() : null;
@@ -0,0 +1,151 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class ApiGatewayCognitoAuthorizerIntegrationTest {
@Inject CognitoService cognitoService;
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
@SuppressWarnings("unchecked")
void enforcesPoolHeaderAndScopesAndExposesClaims() throws Exception {
UserPool allowedPool = cognitoService.createUserPool(Map.of("PoolName", "allowed-pool"), "us-east-1");
UserPool otherPool = cognitoService.createUserPool(Map.of("PoolName", "other-pool"), "us-east-1");
Map<String, Object> allowed = issueTokens(allowedPool);
Map<String, Object> other = issueTokens(otherPool);
String accessToken = (String) allowed.get("AccessToken");
String idToken = (String) allowed.get("IdToken");
String otherToken = (String) other.get("AccessToken");
String apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"cognito-authorizer-test\"}")
.when().post("/restapis").then().statusCode(201).extract().path("id");
try {
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String securedId = createResource(apiId, rootId, "secured");
String unscopedId = createResource(apiId, rootId, "unscoped");
String missingScopeId = createResource(apiId, rootId, "missing-scope");
String noPoolId = createResource(apiId, rootId, "no-pool");
String openId = createResource(apiId, rootId, "open");
String authorizerId = createAuthorizer(apiId, "pool-auth", allowedPool.getArn());
String emptyAuthorizerId = createAuthorizer(apiId, "empty-auth", null);
configureMethod(apiId, securedId, authorizerId, "COGNITO_USER_POOLS",
List.of("aws.cognito.signin.user.admin"));
configureMethod(apiId, unscopedId, authorizerId, "COGNITO_USER_POOLS", List.of());
configureMethod(apiId, missingScopeId, authorizerId, "COGNITO_USER_POOLS",
List.of("orders/read"));
configureMethod(apiId, noPoolId, emptyAuthorizerId, "COGNITO_USER_POOLS", List.of());
configureMethod(apiId, openId, null, "NONE", List.of());
String deploymentId = given().contentType(ContentType.JSON).body("{}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages").then().statusCode(201);
String base = "/execute-api/" + apiId + "/test/";
given().when().get(base + "secured").then().statusCode(401);
given().header("X-Id-Token", "Bearer " + otherToken)
.when().get(base + "secured").then().statusCode(401);
given().header("Authorization", "Bearer " + accessToken)
.when().get(base + "secured").then().statusCode(401);
given().header("X-Id-Token", "Bearer " + idToken)
.when().get(base + "secured").then().statusCode(403);
given().header("X-Id-Token", "Bearer " + accessToken)
.when().get(base + "missing-scope").then().statusCode(403);
given().header("X-Id-Token", "not-a-jwt")
.when().get(base + "secured").then().statusCode(401);
given().header("X-Id-Token", "Bearer " + accessToken)
.when().get(base + "no-pool").then().statusCode(401);
given().header("X-Id-Token", "Bearer " + accessToken)
.when().get(base + "open").then().statusCode(200);
String securedResponse = given().header("X-Id-Token", "Bearer " + accessToken)
.when().get(base + "secured").then().statusCode(200).extract().asString();
String unscopedResponse = given().header("X-Id-Token", "Bearer " + idToken)
.when().get(base + "unscoped").then().statusCode(200).extract().asString();
JsonNode accessClaims = MAPPER.readTree(securedResponse);
JsonNode idClaims = MAPPER.readTree(unscopedResponse);
assertEquals("access", accessClaims.path("tokenUse").asText());
assertEquals("id", idClaims.path("tokenUse").asText());
assertEquals(accessClaims.path("sub").asText(), idClaims.path("sub").asText());
cognitoService.globalSignOut(accessToken);
given().header("X-Id-Token", "Bearer " + accessToken)
.when().get(base + "secured").then().statusCode(401);
given().header("X-Id-Token", "Bearer " + idToken)
.when().get(base + "unscoped").then().statusCode(401);
} finally {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
}
private Map<String, Object> issueTokens(UserPool pool) {
String username = "user-" + UUID.randomUUID();
cognitoService.adminCreateUser(pool.getId(), username,
Map.of("email", username + "@example.com"), "TempPass1!");
cognitoService.adminSetUserPassword(pool.getId(), username, "Perm1234!", true);
UserPoolClient client = cognitoService.createUserPoolClient(pool.getId(), "test-client", false, false,
List.of(), List.of(), null, List.of(), null,
List.of("ALLOW_USER_PASSWORD_AUTH"), null, null, List.of(), null, List.of(), null,
null, null, List.of(), null, null);
Map<String, Object> response = cognitoService.initiateAuth(client.getClientId(),
"USER_PASSWORD_AUTH", Map.of("USERNAME", username, "PASSWORD", "Perm1234!"));
return (Map<String, Object>) response.get("AuthenticationResult");
}
private String createResource(String apiId, String rootId, String name) {
return given().contentType(ContentType.JSON).body("{\"pathPart\":\"" + name + "\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
}
private String createAuthorizer(String apiId, String name, String poolArn) {
String body = poolArn == null
? "{\"name\":\"" + name + "\",\"type\":\"COGNITO_USER_POOLS\","
+ "\"identitySource\":\"method.request.header.X-Id-Token\"}"
: "{\"name\":\"" + name + "\",\"type\":\"COGNITO_USER_POOLS\","
+ "\"identitySource\":\"method.request.header.X-Id-Token\","
+ "\"providerARNs\":[\"" + poolArn + "\"]}";
return given().contentType(ContentType.JSON).body(body)
.when().post("/restapis/" + apiId + "/authorizers")
.then().statusCode(201).extract().path("id");
}
private void configureMethod(String apiId, String resourceId, String authorizerId,
String authType, List<String> scopes) throws Exception {
String methodPath = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
Map<String, Object> method = authorizerId == null
? Map.of("authorizationType", authType)
: Map.of("authorizationType", authType, "authorizerId", authorizerId,
"authorizationScopes", scopes);
given().contentType(ContentType.JSON).body(MAPPER.writeValueAsString(method))
.when().put(methodPath).then().statusCode(201);
given().contentType(ContentType.JSON).body("""
{"type":"MOCK","requestTemplates":{"application/json":"{\\"statusCode\\":200}"}}
""").when().put(methodPath + "/integration").then().statusCode(201);
given().contentType(ContentType.JSON).body("""
{"responseTemplates":{"application/json":"{\\"sub\\":\\"$context.authorizer.claims.sub\\",\\"tokenUse\\":\\"$context.authorizer.claims.token_use\\"}"}}
""").when().put(methodPath + "/integration/responses/200").then().statusCode(201);
}
}
@@ -35,7 +35,7 @@ class ApiGatewayExecuteControllerTest {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
return new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, objectMapper, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
}
@@ -352,7 +352,7 @@ class ApiGatewayExecuteControllerTest {
.thenReturn(null);
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
@@ -382,7 +382,7 @@ class ApiGatewayExecuteControllerTest {
.thenReturn(null);
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
@@ -416,7 +416,7 @@ class ApiGatewayExecuteControllerTest {
new AwsException("NotFoundException", "Invalid API id specified", 404));
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, apiGatewayV2Service, null,
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
@@ -1463,7 +1463,7 @@ class ApiGatewayOpenApiImportTest {
"paths": {
"/cog": {
"get": {
"security": [{"CognitoAuth": []}],
"security": [{"CognitoAuth": ["orders/read"]}],
"x-amazon-apigateway-integration": {
"type": "MOCK",
"requestTemplates": {"application/json": "{\\"statusCode\\": 200}"},
@@ -1503,6 +1503,19 @@ class ApiGatewayOpenApiImportTest {
.body("item.find { it.name == 'BearerAuth' }.identitySource",
equalTo("method.request.header.Authorization"));
String resources = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().body().asString();
String cogResourceId = null;
for (JsonNode resource : mapper.readTree(resources).get("item")) {
if ("/cog".equals(resource.path("path").asText())) {
cogResourceId = resource.path("id").asText();
}
}
assertNotNull(cogResourceId);
given().when().get("/restapis/" + apiId + "/resources/" + cogResourceId + "/methods/GET")
.then().statusCode(200)
.body("authorizationScopes", hasItem("orders/read"));
given().delete("/restapis/" + apiId);
}
@@ -33,7 +33,7 @@ class ApiGatewayProxyMatchTest {
@BeforeEach
void setUp() {
ctrl = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, lambdaService,
ctrl = new ApiGatewayExecuteController(apiGatewayService, null, apiGatewayV2Service, lambdaService,
new RegionResolver("us-east-1", "000000000000"),
new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null,
new ApiGatewayExecuteRouteContext(), null, null, null);
@@ -44,7 +44,7 @@ class BuildV2AuthorizerEventTrailingSlashTest {
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
@@ -48,7 +48,7 @@ class BuildV2ProxyEventBodyEncodingTest {
objectMapper = new ObjectMapper();
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, objectMapper, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
@@ -44,7 +44,7 @@ class BuildV2ProxyEventJwtClaimsTest {
when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/api/stage/v1/things"));
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
@@ -48,7 +48,7 @@ class BuildV2ProxyEventLambdaAuthorizerTest {
when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/api/stage/v1/things"));
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
@@ -39,7 +39,7 @@ class BuildV2ProxyEventPathParametersTest {
when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/api/stage/trpc/health"));
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
);
@@ -43,7 +43,7 @@ class BuildV2ProxyEventTrailingSlashTest {
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
@@ -26,7 +26,7 @@ class JwtClaimsWireFormatTest {
@BeforeEach
void setUp() {
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
null, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
@@ -48,7 +48,7 @@ class ProxyEventIamIdentityTest {
when(uriInfo.getRequestUri()).thenReturn(new URI("http://localhost:4566/execute-api/api1/test/iam"));
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
}
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
@@ -47,7 +48,7 @@ class ProxyEventPathParametersTest {
new URI("http://localhost:4566/execute-api/api1/v1/datasets/abc123"));
controller = new ApiGatewayExecuteController(
null, null, null,
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
}
@@ -66,6 +67,18 @@ class ProxyEventPathParametersTest {
return keys;
}
@Test
void cognitoClaimsRemainNestedInProxyRequestContext() throws Exception {
JsonNode event = MAPPER.readTree(controller.buildProxyEvent(
"us-east-1", "api1", "GET", "/datasets/abc123", "/datasets/{datasetId}",
"res1", "v1", null, headers, uriInfo, null, "req-1", "subject-1",
Map.of("claims", Map.of("sub", "subject-1", "token_use", "access")), null, null));
JsonNode authorizer = event.path("requestContext").path("authorizer");
assertEquals("subject-1", authorizer.path("claims").path("sub").asText());
assertEquals("access", authorizer.path("claims").path("token_use").asText());
}
@Test
void nonGreedyResourceEmitsOnlyItsDeclaredPathParameters() throws Exception {
JsonNode pp = pathParametersFor("/datasets/abc123", "/datasets/{datasetId}");
@@ -2928,6 +2928,28 @@ class CognitoServiceTest {
"IdToken should not contain client_id claim");
}
@Test
@SuppressWarnings("unchecked")
void verifyApiGatewayTokenAcceptsAccessAndIdTokens() {
UserPool pool = createPoolAndUser();
UserPoolClient client = openClient(service, pool.getId(), "c", false);
Map<String, Object> authResult = service.initiateAuth(
client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
Map<String, Object> auth = (Map<String, Object>) authResult.get("AuthenticationResult");
CognitoService.VerifiedApiGatewayToken access =
service.verifyApiGatewayToken((String) auth.get("AccessToken"));
CognitoService.VerifiedApiGatewayToken id =
service.verifyApiGatewayToken((String) auth.get("IdToken"));
assertEquals(pool.getId(), access.poolId());
assertEquals("access", access.tokenUse());
assertEquals("id", id.tokenUse());
assertEquals(client.getClientId(), access.claims().get("client_id"));
assertEquals(client.getClientId(), id.claims().get("aud"));
}
// =========================================================================
// AdminGetUser resolves configured identifiers
// =========================================================================