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

@@ -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
// =========================================================================