mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 01:43:02 -05:00
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:
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");
|
||||
|
||||
+32
-11
@@ -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);
|
||||
|
||||
+63
-42
@@ -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) {
|
||||
|
||||
+83
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user