diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index 690465a02c..6601f0f7c9 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -96,6 +96,7 @@ jobs: -p 4566:4566 \ -v /var/run/docker.sock:/var/run/docker.sock \ --group-add "$DOCKER_GID" \ + -e FLOCI_BASE_URL=http://floci:4566 \ -e FLOCI_SERVICES_DOCKER_NETWORK=compat-net \ -e FLOCI_HOSTNAME=floci \ floci:test diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 356d5b1229..827769e432 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -3,7 +3,7 @@ **Protocol:** JSON 1.1 (`X-Amz-Target: AWSCognitoIdentityProviderService.*`) **Endpoint:** `POST http://localhost:4566/` -Floci also serves OIDC well-known endpoints, making it compatible with JWT validation libraries. +Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth token endpoint, so local clients can mint and validate Cognito-like access tokens against RS256 signing keys. ## Supported Actions @@ -11,17 +11,30 @@ Floci also serves OIDC well-known endpoints, making it compatible with JWT valid |---|---| | **User Pools** | CreateUserPool, DescribeUserPool, ListUserPools, DeleteUserPool | | **User Pool Clients** | CreateUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, DeleteUserPoolClient | +| **Resource Servers** | CreateResourceServer, DescribeResourceServer, ListResourceServers, DeleteResourceServer | | **Admin User Management** | AdminCreateUser, AdminGetUser, AdminDeleteUser, AdminSetUserPassword, AdminUpdateUserAttributes | | **User Operations** | SignUp, ConfirmSignUp, GetUser, UpdateUserAttributes, ChangePassword, ForgotPassword, ConfirmForgotPassword | | **Authentication** | InitiateAuth, AdminInitiateAuth, RespondToAuthChallenge | | **User Listing** | ListUsers | -## OIDC Well-Known Endpoints +## Well-Known And OAuth Endpoints | Endpoint | Description | |---|---| -| `GET /.well-known/openid-configuration` | OIDC discovery document | -| `GET /.well-known/jwks.json` | JSON Web Key Set for JWT validation | +| `GET /{userPoolId}/.well-known/openid-configuration` | OpenID discovery document | +| `GET /{userPoolId}/.well-known/jwks.json` | JSON Web Key Set for JWT validation | +| `POST /cognito-idp/oauth2/token` | Relaxed OAuth token endpoint for `grant_type=client_credentials` | + +`POST /cognito-idp/oauth2/token` is intentionally emulator-friendly rather than full Cognito parity: + +- It requires an existing `client_id`. +- It accepts `client_id` and `client_secret` from the form body or Basic auth. +- It requires a confidential app client created with `GenerateSecret=true`. +- It requires `AllowedOAuthFlowsUserPoolClient=true` and `AllowedOAuthFlows=["client_credentials"]`. +- It doesn't require a Cognito domain. +- It returns only `access_token`, `token_type`, and `expires_in`. +- It validates requested OAuth scopes against the app client's `AllowedOAuthScopes` and the pool's registered resource-server scopes. +- It advertises the prefixed token endpoint in `/{userPoolId}/.well-known/openid-configuration`. ## Examples @@ -38,10 +51,28 @@ POOL_ID=$(aws cognito-idp create-user-pool \ CLIENT_ID=$(aws cognito-idp create-user-pool-client \ --user-pool-id $POOL_ID \ --client-name my-client \ - --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \ + --generate-secret \ + --allowed-o-auth-flows-user-pool-client \ + --allowed-o-auth-flows client_credentials \ + --allowed-o-auth-scopes notes/read notes/write \ --query UserPoolClient.ClientId --output text \ --endpoint-url $AWS_ENDPOINT) +# Retrieve the generated client secret +CLIENT_SECRET=$(aws cognito-idp describe-user-pool-client \ + --user-pool-id $POOL_ID \ + --client-id $CLIENT_ID \ + --query UserPoolClient.ClientSecret --output text \ + --endpoint-url $AWS_ENDPOINT) + +# Register a resource server and scopes +aws cognito-idp create-resource-server \ + --user-pool-id $POOL_ID \ + --identifier notes \ + --name "Notes API" \ + --scopes ScopeName=read,ScopeDescription="Read notes" ScopeName=write,ScopeDescription="Write notes" \ + --endpoint-url $AWS_ENDPOINT + # Create a user aws cognito-idp admin-create-user \ --user-pool-id $POOL_ID \ @@ -63,20 +94,35 @@ aws cognito-idp initiate-auth \ --client-id $CLIENT_ID \ --auth-parameters USERNAME=alice@example.com,PASSWORD=Perm1234! \ --endpoint-url $AWS_ENDPOINT + +# Fetch the pool discovery document +curl -s "$AWS_ENDPOINT/$POOL_ID/.well-known/openid-configuration" + +# Get a machine access token from the OAuth endpoint +curl -s \ + -X POST "$AWS_ENDPOINT/cognito-idp/oauth2/token" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -u "$CLIENT_ID:$CLIENT_SECRET" \ + --data-urlencode "grant_type=client_credentials" \ + --data-urlencode "scope=notes/read notes/write" ``` ## JWT Validation -Tokens issued by Floci can be validated using the JWKS endpoint: +Tokens issued by Floci can be validated using the discovery and JWKS endpoints: ``` -http://localhost:4566/.well-known/jwks.json +http://localhost:4566/$POOL_ID/.well-known/openid-configuration ``` -The OIDC discovery endpoint returns: - ``` -http://localhost:4566/.well-known/openid-configuration +http://localhost:4566/$POOL_ID/.well-known/jwks.json ``` -This allows libraries like `jsonwebtoken`, `jose`, or Spring Security to validate tokens against Floci the same way they would against real Cognito. \ No newline at end of file +Tokens issued by Cognito auth flows and the OAuth token endpoint use the emulator base URL plus the pool id: + +``` +http://localhost:4566/$POOL_ID +``` + +This keeps the issuer, discovery document, JWKS URL, and token endpoint internally consistent for local JWT validation while supporting LocalStack-style confidential clients and resource-server-backed scopes. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java index f6c054f833..1e63af3d18 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java @@ -1,8 +1,12 @@ package io.github.hectorvent.floci.core.common; +import io.github.hectorvent.floci.services.cognito.CognitoOAuthController; +import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.ResourceInfo; +import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.Provider; @@ -16,6 +20,9 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { private static final Pattern AUTH_SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/"); + @Context + ResourceInfo resourceInfo; + private final ServiceRegistry serviceRegistry; @Inject @@ -48,7 +55,7 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { } } - return null; + return serviceKeyFromMatchedResource(); } private String serviceKeyFromTarget(String target) { @@ -75,12 +82,25 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { }; } + private String serviceKeyFromMatchedResource() { + Class resourceClass = resourceInfo != null ? resourceInfo.getResourceClass() : null; + if (resourceClass == null) { + return null; + } + if (CognitoOAuthController.class.equals(resourceClass) + || CognitoWellKnownController.class.equals(resourceClass)) { + return "cognito-idp"; + } + return null; + } + private Response disabledResponse(ContainerRequestContext ctx, String serviceKey) { String message = "Service " + serviceKey + " is not enabled."; String target = ctx.getHeaderString("X-Amz-Target"); String contentType = ctx.getMediaType() != null ? ctx.getMediaType().toString() : ""; + boolean jsonEndpoint = serviceKeyFromMatchedResource() != null; - if (target != null || contentType.contains("json")) { + if (target != null || contentType.contains("json") || jsonEndpoint) { return Response.status(400) .type(MediaType.APPLICATION_JSON) .entity(new AwsErrorResponse("ServiceNotAvailableException", message)) @@ -99,4 +119,4 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { .build(); return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build(); } -} \ No newline at end of file +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java index 6e7acd7493..abbc5aa483 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java @@ -6,6 +6,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.ResourceServer; +import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; import jakarta.enterprise.context.ApplicationScoped; @@ -38,6 +40,11 @@ public class CognitoJsonHandler { case "DescribeUserPoolClient" -> handleDescribeUserPoolClient(request); case "ListUserPoolClients" -> handleListUserPoolClients(request); case "DeleteUserPoolClient" -> handleDeleteUserPoolClient(request); + case "CreateResourceServer" -> handleCreateResourceServer(request); + case "DescribeResourceServer" -> handleDescribeResourceServer(request); + case "ListResourceServers" -> handleListResourceServers(request); + case "UpdateResourceServer" -> handleUpdateResourceServer(request); + case "DeleteResourceServer" -> handleDeleteResourceServer(request); case "AdminCreateUser" -> handleAdminCreateUser(request); case "AdminGetUser" -> handleAdminGetUser(request); case "AdminDeleteUser" -> handleAdminDeleteUser(request); @@ -91,7 +98,11 @@ public class CognitoJsonHandler { private Response handleCreateUserPoolClient(JsonNode request) { UserPoolClient client = service.createUserPoolClient( request.path("UserPoolId").asText(), - request.path("ClientName").asText() + request.path("ClientName").asText(), + request.path("GenerateSecret").asBoolean(false), + request.path("AllowedOAuthFlowsUserPoolClient").asBoolean(false), + readStringList(request.path("AllowedOAuthFlows")), + readStringList(request.path("AllowedOAuthScopes")) ); ObjectNode response = objectMapper.createObjectNode(); response.set("UserPoolClient", clientToNode(client)); @@ -124,6 +135,56 @@ public class CognitoJsonHandler { return Response.ok(objectMapper.createObjectNode()).build(); } + private Response handleCreateResourceServer(JsonNode request) { + ResourceServer server = service.createResourceServer( + request.path("UserPoolId").asText(), + request.path("Identifier").asText(), + request.path("Name").asText(), + parseScopes(request.path("Scopes")) + ); + ObjectNode response = objectMapper.createObjectNode(); + response.set("ResourceServer", resourceServerToNode(server)); + return Response.ok(response).build(); + } + + private Response handleDescribeResourceServer(JsonNode request) { + ResourceServer server = service.describeResourceServer( + request.path("UserPoolId").asText(), + request.path("Identifier").asText() + ); + ObjectNode response = objectMapper.createObjectNode(); + response.set("ResourceServer", resourceServerToNode(server)); + return Response.ok(response).build(); + } + + private Response handleListResourceServers(JsonNode request) { + List servers = service.listResourceServers(request.path("UserPoolId").asText()); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode items = response.putArray("ResourceServers"); + servers.forEach(server -> items.add(resourceServerToNode(server))); + return Response.ok(response).build(); + } + + private Response handleUpdateResourceServer(JsonNode request) { + ResourceServer server = service.updateResourceServer( + request.path("UserPoolId").asText(), + request.path("Identifier").asText(), + request.path("Name").asText(), + parseScopes(request.path("Scopes")) + ); + ObjectNode response = objectMapper.createObjectNode(); + response.set("ResourceServer", resourceServerToNode(server)); + return Response.ok(response).build(); + } + + private Response handleDeleteResourceServer(JsonNode request) { + service.deleteResourceServer( + request.path("UserPoolId").asText(), + request.path("Identifier").asText() + ); + return Response.ok(objectMapper.createObjectNode()).build(); + } + private Response handleAdminCreateUser(JsonNode request) { Map attrs = new HashMap<>(); request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText())); @@ -321,11 +382,63 @@ public class CognitoJsonHandler { node.put("ClientId", c.getClientId()); node.put("UserPoolId", c.getUserPoolId()); node.put("ClientName", c.getClientName()); + if (c.getClientSecret() != null) { + node.put("ClientSecret", c.getClientSecret()); + } + node.put("GenerateSecret", c.isGenerateSecret()); + node.put("AllowedOAuthFlowsUserPoolClient", c.isAllowedOAuthFlowsUserPoolClient()); + ArrayNode flows = node.putArray("AllowedOAuthFlows"); + c.getAllowedOAuthFlows().forEach(flows::add); + ArrayNode scopes = node.putArray("AllowedOAuthScopes"); + c.getAllowedOAuthScopes().forEach(scopes::add); node.put("CreationDate", c.getCreationDate()); node.put("LastModifiedDate", c.getLastModifiedDate()); return node; } + private ObjectNode resourceServerToNode(ResourceServer server) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("UserPoolId", server.getUserPoolId()); + node.put("Identifier", server.getIdentifier()); + node.put("Name", server.getName()); + node.put("CreationDate", server.getCreationDate()); + node.put("LastModifiedDate", server.getLastModifiedDate()); + ArrayNode scopes = node.putArray("Scopes"); + for (ResourceServerScope scope : server.getScopes()) { + ObjectNode item = scopes.addObject(); + item.put("ScopeName", scope.getScopeName()); + if (scope.getScopeDescription() != null) { + item.put("ScopeDescription", scope.getScopeDescription()); + } + } + return node; + } + + private List parseScopes(JsonNode scopesNode) { + if (scopesNode == null || !scopesNode.isArray()) { + return List.of(); + } + + List scopes = new java.util.ArrayList<>(); + scopesNode.forEach(item -> { + ResourceServerScope scope = new ResourceServerScope(); + scope.setScopeName(item.path("ScopeName").asText()); + scope.setScopeDescription(item.path("ScopeDescription").asText(null)); + scopes.add(scope); + }); + return scopes; + } + + private List readStringList(JsonNode node) { + if (node == null || !node.isArray()) { + return List.of(); + } + + List values = new java.util.ArrayList<>(); + node.forEach(item -> values.add(item.asText())); + return values; + } + private ObjectNode userToNode(CognitoUser u) { ObjectNode node = objectMapper.createObjectNode(); node.put("Username", u.getUsername()); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java new file mode 100644 index 0000000000..f131f71b39 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java @@ -0,0 +1,158 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.HeaderParam; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; + +@ApplicationScoped +@Path("/") +@Produces(MediaType.APPLICATION_JSON) +public class CognitoOAuthController { + + private static final Logger LOG = Logger.getLogger(CognitoOAuthController.class); + + private final CognitoService cognitoService; + private final ObjectMapper objectMapper; + + @Inject + public CognitoOAuthController(CognitoService cognitoService, ObjectMapper objectMapper) { + this.cognitoService = cognitoService; + this.objectMapper = objectMapper; + } + + @POST + @Path("/cognito-idp/oauth2/token") + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + public Response token(@HeaderParam("Authorization") String authorization, + MultivaluedMap formParams) { + return issueToken(authorization, formParams); + } + + private Response issueToken(String authorization, MultivaluedMap formParams) { + String grantType = trimToNull(formParams.getFirst("grant_type")); + if (grantType == null) { + return oauthError("invalid_request", "grant_type is required"); + } + if (!"client_credentials".equals(grantType)) { + return oauthError("unsupported_grant_type", "Only client_credentials is supported"); + } + + BasicCredentials basicCredentials; + try { + basicCredentials = parseBasicCredentials(authorization); + } catch (IllegalArgumentException e) { + return oauthError("invalid_request", e.getMessage()); + } + + String bodyClientId = trimToNull(formParams.getFirst("client_id")); + String bodyClientSecret = trimToNull(formParams.getFirst("client_secret")); + String basicClientId = basicCredentials != null ? basicCredentials.clientId() : null; + String basicClientSecret = basicCredentials != null ? basicCredentials.clientSecret() : null; + + if (bodyClientSecret != null && basicClientSecret != null && !bodyClientSecret.equals(basicClientSecret)) { + return oauthError("invalid_request", "client_secret does not match Authorization header"); + } + + if (bodyClientId != null && basicClientId != null && !bodyClientId.equals(basicClientId)) { + return oauthError("invalid_request", "client_id does not match Authorization header"); + } + + String clientId = bodyClientId != null ? bodyClientId : basicClientId; + if (clientId == null) { + return oauthError("invalid_request", "client_id is required"); + } + + String clientSecret = bodyClientSecret != null ? bodyClientSecret : basicClientSecret; + String scope = trimToNull(formParams.getFirst("scope")); + + try { + Map result = cognitoService.issueClientCredentialsToken(clientId, clientSecret, scope); + return Response.ok(objectMapper.valueToTree(result)) + .type(MediaType.APPLICATION_JSON) + .header("Cache-Control", "no-store") + .header("Pragma", "no-cache") + .build(); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + return oauthError("invalid_client", "Client not found"); + } + if ("InvalidClientException".equals(e.getErrorCode())) { + return oauthError("invalid_client", e.getMessage()); + } + if ("UnauthorizedClientException".equals(e.getErrorCode())) { + return oauthError("unauthorized_client", e.getMessage()); + } + if ("InvalidScopeException".equals(e.getErrorCode())) { + return oauthError("invalid_scope", e.getMessage()); + } + LOG.error("Failed to issue Cognito OAuth token", e); + return oauthError("invalid_request", e.getMessage()); + } + } + + private Response oauthError(String error, String description) { + ObjectNode body = objectMapper.createObjectNode(); + body.put("error", error); + body.put("error_description", description); + return Response.status(400) + .type(MediaType.APPLICATION_JSON) + .header("Cache-Control", "no-store") + .header("Pragma", "no-cache") + .entity(body) + .build(); + } + + private BasicCredentials parseBasicCredentials(String authorization) { + if (authorization == null || authorization.isBlank()) { + return null; + } + if (!authorization.regionMatches(true, 0, "Basic ", 0, 6)) { + return null; + } + + String encoded = authorization.substring(6).trim(); + if (encoded.isEmpty()) { + throw new IllegalArgumentException("Basic Authorization header is malformed"); + } + + try { + String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); + int separator = decoded.indexOf(':'); + if (separator < 0) { + throw new IllegalArgumentException("Basic Authorization header is malformed"); + } + return new BasicCredentials( + trimToNull(decoded.substring(0, separator)), + trimToNull(decoded.substring(separator + 1)) + ); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Basic Authorization header is malformed"); + } + } + + private String trimToNull(String value) { + if (value == null) { + return null; + } + String trimmed = value.trim(); + return trimmed.isEmpty() ? null : trimmed; + } + + private record BasicCredentials(String clientId, String clientSecret) { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 95e8f4cd0f..21a3e07ce1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -1,20 +1,30 @@ package io.github.hectorvent.floci.services.cognito; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.ResourceServer; +import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; import java.util.*; @ApplicationScoped @@ -24,16 +34,21 @@ public class CognitoService { private final StorageBackend poolStore; private final StorageBackend clientStore; + private final StorageBackend resourceServerStore; private final StorageBackend userStore; + private final String baseUrl; @Inject - public CognitoService(StorageFactory storageFactory) { + public CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig) { this.poolStore = storageFactory.create("cognito", "cognito-pools.json", new TypeReference>() {}); this.clientStore = storageFactory.create("cognito", "cognito-clients.json", new TypeReference>() {}); + this.resourceServerStore = storageFactory.create("cognito", "cognito-resource-servers.json", + new TypeReference>() {}); this.userStore = storageFactory.create("cognito", "cognito-users.json", new TypeReference>() {}); + this.baseUrl = trimTrailingSlash(emulatorConfig.baseUrl()); } // ──────────────────────────── User Pools ──────────────────────────── @@ -43,14 +58,19 @@ public class CognitoService { UserPool pool = new UserPool(); pool.setId(id); pool.setName(name); + ensureJwtSigningKeys(pool); poolStore.put(id, pool); LOG.infov("Created User Pool: {0}", id); return pool; } public UserPool describeUserPool(String id) { - return poolStore.get(id) + UserPool pool = poolStore.get(id) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 404)); + if (ensureJwtSigningKeys(pool)) { + poolStore.put(id, pool); + } + return pool; } public List listUserPools() { @@ -63,13 +83,23 @@ public class CognitoService { // ──────────────────────────── User Pool Clients ──────────────────────────── - public UserPoolClient createUserPoolClient(String userPoolId, String clientName) { + public UserPoolClient createUserPoolClient(String userPoolId, String clientName, boolean generateSecret, + boolean allowedOAuthFlowsUserPoolClient, + List allowedOAuthFlows, + List allowedOAuthScopes) { describeUserPool(userPoolId); String clientId = UUID.randomUUID().toString().replace("-", "").substring(0, 26); UserPoolClient client = new UserPoolClient(); client.setClientId(clientId); client.setUserPoolId(userPoolId); client.setClientName(clientName); + client.setGenerateSecret(generateSecret); + client.setAllowedOAuthFlowsUserPoolClient(allowedOAuthFlowsUserPoolClient); + client.setAllowedOAuthFlows(normalizeStringList(allowedOAuthFlows)); + client.setAllowedOAuthScopes(normalizeStringList(allowedOAuthScopes)); + if (generateSecret) { + client.setClientSecret(generateSecretValue()); + } clientStore.put(clientId, client); LOG.infov("Created User Pool Client: {0} for pool {1}", clientId, userPoolId); return client; @@ -93,6 +123,69 @@ public class CognitoService { clientStore.delete(clientId); } + // ──────────────────────────── Resource Servers ──────────────────────────── + + public ResourceServer createResourceServer(String userPoolId, String identifier, String name, + List scopes) { + describeUserPool(userPoolId); + if (identifier == null || identifier.isBlank()) { + throw new AwsException("InvalidParameterException", "Identifier is required", 400); + } + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterException", "Name is required", 400); + } + + String key = resourceServerKey(userPoolId, identifier); + if (resourceServerStore.get(key).isPresent()) { + throw new AwsException("ResourceConflictException", "Resource server already exists", 400); + } + + ResourceServer server = new ResourceServer(); + server.setUserPoolId(userPoolId); + server.setIdentifier(identifier); + server.setName(name); + server.setScopes(normalizeScopes(scopes)); + resourceServerStore.put(key, server); + return server; + } + + public ResourceServer describeResourceServer(String userPoolId, String identifier) { + describeUserPool(userPoolId); + return resourceServerStore.get(resourceServerKey(userPoolId, identifier)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Resource server not found", 404)); + } + + public List listResourceServers(String userPoolId) { + describeUserPool(userPoolId); + String prefix = userPoolId + "::"; + return resourceServerStore.scan(k -> k.startsWith(prefix)); + } + + public ResourceServer updateResourceServer(String userPoolId, String identifier, String name, + List scopes) { + if (userPoolId == null || userPoolId.isBlank()) { + throw new AwsException("InvalidParameterException", "UserPoolId is required", 400); + } + if (identifier == null || identifier.isBlank()) { + throw new AwsException("InvalidParameterException", "Identifier is required", 400); + } + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterException", "Name is required", 400); + } + + ResourceServer server = describeResourceServer(userPoolId, identifier); + server.setName(name); + server.setScopes(normalizeScopes(scopes)); + server.setLastModifiedDate(System.currentTimeMillis() / 1000L); + resourceServerStore.put(resourceServerKey(userPoolId, identifier), server); + return server; + } + + public void deleteResourceServer(String userPoolId, String identifier) { + describeResourceServer(userPoolId, identifier); + resourceServerStore.delete(resourceServerKey(userPoolId, identifier)); + } + // ──────────────────────────── Users ──────────────────────────── public CognitoUser adminCreateUser(String userPoolId, String username, Map attributes, @@ -311,6 +404,33 @@ public class CognitoService { adminUpdateUserAttributes(poolId, username, attributes); } + public Map issueClientCredentialsToken(String clientId, String clientSecret, String scope) { + UserPoolClient client = clientStore.get(clientId) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404)); + UserPool pool = describeUserPool(client.getUserPoolId()); + validateClientAllowsClientCredentials(client); + validateClientSecret(client, clientSecret); + String normalizedScope = resolveAuthorizedScopes(client, pool.getId(), scope); + + Map response = new LinkedHashMap<>(); + response.put("access_token", generateClientAccessToken(client, pool, normalizedScope)); + response.put("token_type", "Bearer"); + response.put("expires_in", 3600); + return response; + } + + public String getIssuer(String poolId) { + return baseUrl + "/" + poolId; + } + + public String getJwksUri(String poolId) { + return getIssuer(poolId) + "/.well-known/jwks.json"; + } + + public String getTokenEndpoint() { + return baseUrl + "/cognito-idp/oauth2/token"; + } + // ──────────────────────────── Private helpers ──────────────────────────── private Map authenticateWithPassword(UserPool pool, Map params, String clientId) { @@ -385,7 +505,9 @@ public class CognitoService { } private String generateSignedJwt(CognitoUser user, UserPool pool, String type) { - String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}"; + String headerJson = String.format( + "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}", + escapeJson(getSigningKeyId(pool))); String header = Base64.getUrlEncoder().withoutPadding() .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8)); @@ -393,48 +515,265 @@ public class CognitoService { String email = user.getAttributes().getOrDefault("email", user.getUsername()); String payloadJson = String.format( "{\"sub\":\"%s\",\"event_id\":\"%s\",\"token_use\":\"%s\",\"auth_time\":%d," + - "\"iss\":\"https://cognito-idp.local/%s\",\"exp\":%d,\"iat\":%d," + + "\"iss\":\"%s\",\"exp\":%d,\"iat\":%d," + "\"username\":\"%s\",\"email\":\"%s\",\"cognito:username\":\"%s\"}", UUID.randomUUID(), UUID.randomUUID(), type, now, - pool.getId(), now + 3600, now, + escapeJson(getIssuer(pool.getId())), now + 3600, now, user.getUsername(), email, user.getUsername() ); String payload = Base64.getUrlEncoder().withoutPadding() .encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8)); - - String signingInput = header + "." + payload; - String signature = hmacSha256(signingInput, pool.getSigningSecret()); - return signingInput + "." + signature; + return signJwt(header, payload, getSigningPrivateKey(pool)); } private String generateTokenString(String type, String username, UserPool pool) { long now = System.currentTimeMillis() / 1000L; - String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}"; + String headerJson = String.format( + "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}", + escapeJson(getSigningKeyId(pool))); String header = Base64.getUrlEncoder().withoutPadding() .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8)); String payloadJson = String.format( - "{\"sub\":\"%s\",\"token_use\":\"%s\",\"iss\":\"https://cognito-idp.local/%s\"," + + "{\"sub\":\"%s\",\"token_use\":\"%s\",\"iss\":\"%s\"," + "\"exp\":%d,\"iat\":%d,\"username\":\"%s\"}", - UUID.randomUUID(), type, pool.getId(), now + 3600, now, username + UUID.randomUUID(), type, escapeJson(getIssuer(pool.getId())), now + 3600, now, username ); String payload = Base64.getUrlEncoder().withoutPadding() .encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8)); + return signJwt(header, payload, getSigningPrivateKey(pool)); + } + + private String generateClientAccessToken(UserPoolClient client, UserPool pool, String scope) { + String headerJson = String.format( + "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"%s\"}", + escapeJson(getSigningKeyId(pool))); + String header = Base64.getUrlEncoder().withoutPadding() + .encodeToString(headerJson.getBytes(StandardCharsets.UTF_8)); + + long now = System.currentTimeMillis() / 1000L; + StringBuilder payloadJson = new StringBuilder(); + payloadJson.append("{") + .append("\"iss\":\"").append(escapeJson(getIssuer(pool.getId()))).append("\",") + .append("\"version\":2,") + .append("\"sub\":\"").append(escapeJson(client.getClientId())).append("\",") + .append("\"client_id\":\"").append(escapeJson(client.getClientId())).append("\",") + .append("\"token_use\":\"access\",") + .append("\"exp\":").append(now + 3600).append(",") + .append("\"iat\":").append(now).append(",") + .append("\"jti\":\"").append(UUID.randomUUID()).append("\""); + if (scope != null && !scope.isBlank()) { + payloadJson.append(",\"scope\":\"").append(escapeJson(scope)).append("\""); + } + payloadJson.append("}"); + + String payload = Base64.getUrlEncoder().withoutPadding() + .encodeToString(payloadJson.toString().getBytes(StandardCharsets.UTF_8)); + return signJwt(header, payload, getSigningPrivateKey(pool)); + } + + private void validateClientSecret(UserPoolClient client, String clientSecret) { + String expectedSecret = client.getClientSecret(); + if (expectedSecret == null || expectedSecret.isBlank() || !client.isGenerateSecret()) { + throw new AwsException("InvalidClientException", "Client must have a secret for client_credentials", 400); + } + if (clientSecret == null || clientSecret.isBlank()) { + throw new AwsException("InvalidClientException", "Client secret is required", 400); + } + if (!expectedSecret.equals(clientSecret)) { + throw new AwsException("InvalidClientException", "Client secret is invalid", 400); + } + } + + private void validateClientAllowsClientCredentials(UserPoolClient client) { + if (!client.isAllowedOAuthFlowsUserPoolClient()) { + throw new AwsException("UnauthorizedClientException", "Client is not enabled for OAuth flows", 400); + } + if (!client.getAllowedOAuthFlows().contains("client_credentials")) { + throw new AwsException("UnauthorizedClientException", "Client is not allowed to use client_credentials", 400); + } + } + + private String resolveAuthorizedScopes(UserPoolClient client, String userPoolId, String requestedScope) { + List allowedScopes = normalizeStringList(client.getAllowedOAuthScopes()); + if (allowedScopes.isEmpty()) { + throw new AwsException("InvalidScopeException", "Client has no allowed OAuth scopes", 400); + } + + List effectiveScopes; + if (requestedScope == null || requestedScope.isBlank()) { + effectiveScopes = allowedScopes; + } else { + effectiveScopes = Arrays.asList(normalizeRequestedScope(requestedScope).split(" ")); + for (String scope : effectiveScopes) { + if (!allowedScopes.contains(scope)) { + throw new AwsException("InvalidScopeException", "Scope is not allowed for this client: " + scope, 400); + } + } + } + + Set validCustomScopes = new HashSet<>(); + for (ResourceServer server : listResourceServers(userPoolId)) { + for (ResourceServerScope serverScope : server.getScopes()) { + validCustomScopes.add(server.getIdentifier() + "/" + serverScope.getScopeName()); + } + } + + for (String scope : effectiveScopes) { + if (isBuiltInScope(scope)) { + continue; + } + if (!validCustomScopes.contains(scope)) { + throw new AwsException("InvalidScopeException", "Scope is invalid: " + scope, 400); + } + } + + return String.join(" ", effectiveScopes); + } + + private String normalizeRequestedScope(String scope) { + if (scope == null || scope.isBlank()) { + return null; + } + + List normalized = new ArrayList<>(); + for (String part : scope.trim().split("\\s+")) { + if (!part.isBlank()) { + normalized.add(part); + } + } + return normalized.isEmpty() ? null : String.join(" ", normalized); + } + + private List normalizeScopes(List scopes) { + if (scopes == null || scopes.isEmpty()) { + return List.of(); + } + + List normalized = new ArrayList<>(); + Set scopeNames = new HashSet<>(); + for (ResourceServerScope scope : scopes) { + if (scope == null || scope.getScopeName() == null || scope.getScopeName().isBlank()) { + throw new AwsException("InvalidParameterException", "ScopeName is required", 400); + } + if (!scopeNames.add(scope.getScopeName())) { + throw new AwsException("InvalidParameterException", "Duplicate scope name: " + scope.getScopeName(), 400); + } + ResourceServerScope normalizedScope = new ResourceServerScope(); + normalizedScope.setScopeName(scope.getScopeName()); + normalizedScope.setScopeDescription(scope.getScopeDescription()); + normalized.add(normalizedScope); + } + return normalized; + } + + private List normalizeStringList(List values) { + if (values == null || values.isEmpty()) { + return List.of(); + } + + List normalized = new ArrayList<>(); + Set seen = new LinkedHashSet<>(); + for (String value : values) { + if (value == null) { + continue; + } + String trimmed = value.trim(); + if (!trimmed.isEmpty() && seen.add(trimmed)) { + normalized.add(trimmed); + } + } + return normalized; + } + + private boolean isBuiltInScope(String scope) { + return switch (scope) { + case "phone", "email", "openid", "profile", "aws.cognito.signin.user.admin" -> true; + default -> false; + }; + } + + private String signJwt(String header, String payload, PrivateKey signingKey) { String signingInput = header + "." + payload; - String signature = hmacSha256(signingInput, pool.getSigningSecret()); + String signature = rsaSha256(signingInput, signingKey); return signingInput + "." + signature; } - private String hmacSha256(String data, String key) { + private String rsaSha256(String data, PrivateKey signingKey) { try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); - byte[] sig = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(signingKey); + signature.update(data.getBytes(StandardCharsets.UTF_8)); + byte[] sig = signature.sign(); return Base64.getUrlEncoder().withoutPadding().encodeToString(sig); } catch (Exception e) { throw new RuntimeException("JWT signing failed", e); } } + String getSigningKeyId(UserPool pool) { + ensureJwtSigningKeys(pool); + return pool.getSigningKeyId(); + } + + RSAPublicKey getSigningPublicKey(UserPool pool) { + ensureJwtSigningKeys(pool); + + try { + byte[] encoded = Base64.getDecoder().decode(pool.getSigningPublicKey()); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded); + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec); + return (RSAPublicKey) publicKey; + } catch (Exception e) { + throw new RuntimeException("Failed to load Cognito RSA public key", e); + } + } + + private PrivateKey getSigningPrivateKey(UserPool pool) { + ensureJwtSigningKeys(pool); + + try { + byte[] encoded = Base64.getDecoder().decode(pool.getSigningPrivateKey()); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); + return KeyFactory.getInstance("RSA").generatePrivate(keySpec); + } catch (Exception e) { + throw new RuntimeException("Failed to load Cognito RSA private key", e); + } + } + + private boolean ensureJwtSigningKeys(UserPool pool) { + synchronized (pool) { + boolean changed = false; + + if (pool.getSigningKeyId() == null || pool.getSigningKeyId().isBlank()) { + pool.setSigningKeyId(pool.getId()); + changed = true; + } + + if (pool.getSigningPrivateKey() == null || pool.getSigningPrivateKey().isBlank() + || pool.getSigningPublicKey() == null || pool.getSigningPublicKey().isBlank()) { + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + + pool.setSigningPrivateKey( + Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); + pool.setSigningPublicKey( + Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); + changed = true; + } catch (Exception e) { + throw new RuntimeException("Failed to generate Cognito RSA signing keypair", e); + } + } + + if (changed && pool.getId() != null) { + pool.setLastModifiedDate(System.currentTimeMillis() / 1000L); + } + + return changed; + } + } + String hashPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); @@ -473,7 +812,6 @@ public class CognitoService { String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); String iss = extractJsonField(payloadJson, "iss"); if (iss == null) return null; - // iss = "https://cognito-idp.local/POOL_ID" int lastSlash = iss.lastIndexOf('/'); return lastSlash >= 0 ? iss.substring(lastSlash + 1) : null; } catch (Exception e) { @@ -494,4 +832,26 @@ public class CognitoService { private String userKey(String poolId, String username) { return poolId + "::" + username; } + + private String resourceServerKey(String userPoolId, String identifier) { + return userPoolId + "::" + identifier; + } + + private String escapeJson(String value) { + return value + .replace("\\", "\\\\") + .replace("\"", "\\\""); + } + + private String generateSecretValue() { + return UUID.randomUUID().toString().replace("-", "") + + UUID.randomUUID().toString().replace("-", ""); + } + + private String trimTrailingSlash(String value) { + if (value.endsWith("/")) { + return value.substring(0, value.length() - 1); + } + return value; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java index d8eacb0c9e..9f60676b02 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java @@ -9,7 +9,7 @@ import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -import java.nio.charset.StandardCharsets; +import java.math.BigInteger; import java.util.Base64; /** @@ -32,14 +32,36 @@ public class CognitoWellKnownController { @Path("/{poolId}/.well-known/jwks.json") public Response getJwks(@PathParam("poolId") String poolId) { UserPool pool = cognitoService.describeUserPool(poolId); - String kid = pool.getId(); - // Encode signing secret bytes as Base64URL (no padding) for the JWK "k" parameter - byte[] secretBytes = pool.getSigningSecret().getBytes(StandardCharsets.UTF_8); - String k = Base64.getUrlEncoder().withoutPadding().encodeToString(secretBytes); + String kid = cognitoService.getSigningKeyId(pool); + var publicKey = cognitoService.getSigningPublicKey(pool); + String modulus = base64UrlEncodeUnsigned(publicKey.getModulus()); + String exponent = base64UrlEncodeUnsigned(publicKey.getPublicExponent()); String body = """ - {"keys":[{"kty":"oct","kid":"%s","alg":"HS256","k":"%s","use":"sig"}]} - """.formatted(kid, k).strip(); + {"keys":[{"kty":"RSA","kid":"%s","alg":"RS256","n":"%s","e":"%s","use":"sig"}]} + """.formatted(kid, modulus, exponent).strip(); return Response.ok(body).build(); } + + @GET + @Path("/{poolId}/.well-known/openid-configuration") + public Response getOpenIdConfiguration(@PathParam("poolId") String poolId) { + UserPool pool = cognitoService.describeUserPool(poolId); + String issuer = cognitoService.getIssuer(pool.getId()); + String jwksUri = cognitoService.getJwksUri(pool.getId()); + String tokenEndpoint = cognitoService.getTokenEndpoint(); + + String body = """ + {"issuer":"%s","jwks_uri":"%s","token_endpoint":"%s","subject_types_supported":["public"],"response_types_supported":[],"grant_types_supported":["client_credentials"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"id_token_signing_alg_values_supported":["RS256"]} + """.formatted(issuer, jwksUri, tokenEndpoint).strip(); + return Response.ok(body).build(); + } + + private String base64UrlEncodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes.length > 1 && bytes[0] == 0) { + bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + } + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/ResourceServer.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/ResourceServer.java new file mode 100644 index 0000000000..0e61f7c25c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/ResourceServer.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.services.cognito.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.List; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResourceServer { + private String userPoolId; + private String identifier; + private String name; + private List scopes = new ArrayList<>(); + private long creationDate; + private long lastModifiedDate; + + public ResourceServer() { + long now = System.currentTimeMillis() / 1000L; + this.creationDate = now; + this.lastModifiedDate = now; + } + + public String getUserPoolId() { return userPoolId; } + public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; } + + public String getIdentifier() { return identifier; } + public void setIdentifier(String identifier) { this.identifier = identifier; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public List getScopes() { return scopes; } + public void setScopes(List scopes) { this.scopes = scopes; } + + public long getCreationDate() { return creationDate; } + public void setCreationDate(long creationDate) { this.creationDate = creationDate; } + + public long getLastModifiedDate() { return lastModifiedDate; } + public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/ResourceServerScope.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/ResourceServerScope.java new file mode 100644 index 0000000000..28aa94c92a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/ResourceServerScope.java @@ -0,0 +1,17 @@ +package io.github.hectorvent.floci.services.cognito.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ResourceServerScope { + private String scopeName; + private String scopeDescription; + + public String getScopeName() { return scopeName; } + public void setScopeName(String scopeName) { this.scopeName = scopeName; } + + public String getScopeDescription() { return scopeDescription; } + public void setScopeDescription(String scopeDescription) { this.scopeDescription = scopeDescription; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java index b8e9db29e5..2518f59a75 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java @@ -9,6 +9,9 @@ public class UserPool { private String id; private String name; private String signingSecret; + private String signingKeyId; + private String signingPublicKey; + private String signingPrivateKey; private long creationDate; private long lastModifiedDate; @@ -28,6 +31,15 @@ public class UserPool { public String getSigningSecret() { return signingSecret; } public void setSigningSecret(String signingSecret) { this.signingSecret = signingSecret; } + public String getSigningKeyId() { return signingKeyId; } + public void setSigningKeyId(String signingKeyId) { this.signingKeyId = signingKeyId; } + + public String getSigningPublicKey() { return signingPublicKey; } + public void setSigningPublicKey(String signingPublicKey) { this.signingPublicKey = signingPublicKey; } + + public String getSigningPrivateKey() { return signingPrivateKey; } + public void setSigningPrivateKey(String signingPrivateKey) { this.signingPrivateKey = signingPrivateKey; } + public long getCreationDate() { return creationDate; } public void setCreationDate(long creationDate) { this.creationDate = creationDate; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java index 32e8b7bb19..dee2bf8883 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolClient.java @@ -3,12 +3,20 @@ package io.github.hectorvent.floci.services.cognito.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.ArrayList; +import java.util.List; + @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) public class UserPoolClient { private String clientId; private String userPoolId; private String clientName; + private String clientSecret; + private boolean generateSecret; + private boolean allowedOAuthFlowsUserPoolClient; + private List allowedOAuthFlows = new ArrayList<>(); + private List allowedOAuthScopes = new ArrayList<>(); private long creationDate; private long lastModifiedDate; @@ -27,6 +35,23 @@ public class UserPoolClient { public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } + public String getClientSecret() { return clientSecret; } + public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } + + public boolean isGenerateSecret() { return generateSecret; } + public void setGenerateSecret(boolean generateSecret) { this.generateSecret = generateSecret; } + + public boolean isAllowedOAuthFlowsUserPoolClient() { return allowedOAuthFlowsUserPoolClient; } + public void setAllowedOAuthFlowsUserPoolClient(boolean allowedOAuthFlowsUserPoolClient) { + this.allowedOAuthFlowsUserPoolClient = allowedOAuthFlowsUserPoolClient; + } + + public List getAllowedOAuthFlows() { return allowedOAuthFlows; } + public void setAllowedOAuthFlows(List allowedOAuthFlows) { this.allowedOAuthFlows = allowedOAuthFlows; } + + public List getAllowedOAuthScopes() { return allowedOAuthScopes; } + public void setAllowedOAuthScopes(List allowedOAuthScopes) { this.allowedOAuthScopes = allowedOAuthScopes; } + public long getCreationDate() { return creationDate; } public void setCreationDate(long creationDate) { this.creationDate = creationDate; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java new file mode 100644 index 0000000000..53f8ce590a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java @@ -0,0 +1,230 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.config.EncoderConfig; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.RSAPublicKeySpec; +import java.util.Base64; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoIntegrationTest { + + private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private static String poolId; + private static String clientId; + private static final String username = "alice+" + UUID.randomUUID() + "@example.com"; + private static final String password = "Perm1234!"; + + @BeforeAll + static void configureRestAssured() { + RestAssured.config = RestAssured.config().encoderConfig( + EncoderConfig.encoderConfig() + .encodeContentTypeAs(COGNITO_CONTENT_TYPE, ContentType.TEXT)); + } + + @Test + @Order(1) + void createPoolClientAndUser() throws Exception { + JsonNode poolResponse = cognitoJson("CreateUserPool", """ + { + "PoolName": "JwtPool" + } + """); + poolId = poolResponse.path("UserPool").path("Id").asText(); + + JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "jwt-client" + } + """.formatted(poolId)); + clientId = clientResponse.path("UserPoolClient").path("ClientId").asText(); + + cognitoAction("AdminCreateUser", """ + { + "UserPoolId": "%s", + "Username": "%s", + "UserAttributes": [ + { "Name": "email", "Value": "%s" } + ] + } + """.formatted(poolId, username, username)) + .then() + .statusCode(200); + + cognitoAction("AdminSetUserPassword", """ + { + "UserPoolId": "%s", + "Username": "%s", + "Password": "%s", + "Permanent": true + } + """.formatted(poolId, username, password)) + .then() + .statusCode(200); + } + + @Test + @Order(2) + void initiateAuthReturnsAuthenticationResult() { + cognitoAction("InitiateAuth", """ + { + "ClientId": "%s", + "AuthFlow": "USER_PASSWORD_AUTH", + "AuthParameters": { + "USERNAME": "%s", + "PASSWORD": "%s" + } + } + """.formatted(clientId, username, password)) + .then() + .statusCode(200) + .body("AuthenticationResult.AccessToken", org.hamcrest.Matchers.notNullValue()) + .body("AuthenticationResult.IdToken", org.hamcrest.Matchers.notNullValue()) + .body("AuthenticationResult.RefreshToken", org.hamcrest.Matchers.notNullValue()); + } + + @Test + @Order(3) + void authTokensAreSignedWithPublishedRsaJwksKey() throws Exception { + Response authResponse = cognitoAction("InitiateAuth", """ + { + "ClientId": "%s", + "AuthFlow": "USER_PASSWORD_AUTH", + "AuthParameters": { + "USERNAME": "%s", + "PASSWORD": "%s" + } + } + """.formatted(clientId, username, password)); + + authResponse.then().statusCode(200); + + String accessToken = authResponse.jsonPath().getString("AuthenticationResult.AccessToken"); + JsonNode header = decodeJwtHeader(accessToken); + JsonNode payload = decodeJwtPayload(accessToken); + assertEquals("RS256", header.path("alg").asText()); + assertEquals(poolId, header.path("kid").asText()); + assertEquals("http://localhost:4566/" + poolId, payload.path("iss").asText()); + assertEquals(username, payload.path("username").asText()); + assertEquals("access", payload.path("token_use").asText()); + + String jwksResponse = given() + .when() + .get("/" + poolId + "/.well-known/jwks.json") + .then() + .statusCode(200) + .extract() + .asString(); + + JsonNode jwks = OBJECT_MAPPER.readTree(jwksResponse); + JsonNode key = jwks.path("keys").get(0); + assertNotNull(key); + assertEquals("RSA", key.path("kty").asText()); + assertEquals("RS256", key.path("alg").asText()); + assertEquals("sig", key.path("use").asText()); + assertEquals(poolId, key.path("kid").asText()); + assertTrue(key.hasNonNull("n")); + assertTrue(key.hasNonNull("e")); + assertTrue(verifyJwtSignature(accessToken, key)); + } + + @Test + @Order(4) + void openIdConfigurationPublishesIssuerAndJwksUri() throws Exception { + String openIdResponse = given() + .when() + .get("/" + poolId + "/.well-known/openid-configuration") + .then() + .statusCode(200) + .extract() + .asString(); + + JsonNode document = OBJECT_MAPPER.readTree(openIdResponse); + assertEquals("http://localhost:4566/" + poolId, document.path("issuer").asText()); + assertEquals( + "http://localhost:4566/" + poolId + "/.well-known/jwks.json", + document.path("jwks_uri").asText()); + assertEquals("public", document.path("subject_types_supported").get(0).asText()); + assertEquals("RS256", document.path("id_token_signing_alg_values_supported").get(0).asText()); + } + + private static Response cognitoAction(String action, String body) { + return given() + .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action) + .contentType(COGNITO_CONTENT_TYPE) + .body(body) + .when() + .post("/"); + } + + private static JsonNode cognitoJson(String action, String body) throws Exception { + String response = cognitoAction(action, body) + .then() + .statusCode(200) + .extract() + .asString(); + return OBJECT_MAPPER.readTree(response); + } + + private static JsonNode decodeJwtPayload(String token) throws Exception { + return decodeJwtPart(token, 1); + } + + private static JsonNode decodeJwtHeader(String token) throws Exception { + return decodeJwtPart(token, 0); + } + + private static JsonNode decodeJwtPart(String token, int partIndex) throws Exception { + String[] parts = token.split("\\."); + assertEquals(3, parts.length); + return OBJECT_MAPPER.readTree(Base64.getUrlDecoder().decode(padBase64(parts[partIndex]))); + } + + private static boolean verifyJwtSignature(String token, JsonNode jwk) throws Exception { + String[] parts = token.split("\\."); + assertEquals(3, parts.length); + + BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(jwk.path("n").asText()))); + BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(jwk.path("e").asText()))); + RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent); + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec); + + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initVerify(publicKey); + signature.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8)); + return signature.verify(Base64.getUrlDecoder().decode(padBase64(parts[2]))); + } + + private static String padBase64(String value) { + int remainder = value.length() % 4; + if (remainder == 0) { + return value; + } + return value + "=".repeat(4 - remainder); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java new file mode 100644 index 0000000000..795ee045a4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthTokenIntegrationTest.java @@ -0,0 +1,557 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.config.EncoderConfig; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.RSAPublicKeySpec; +import java.util.Base64; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoOAuthTokenIntegrationTest { + + private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private static String poolId; + private static String clientId; + private static String limitedClientId; + private static String confidentialClientId; + private static String confidentialClientSecret; + + @BeforeAll + static void configureRestAssured() { + RestAssured.config = RestAssured.config().encoderConfig( + EncoderConfig.encoderConfig() + .encodeContentTypeAs(COGNITO_CONTENT_TYPE, ContentType.TEXT)); + } + + @Test + @Order(1) + void createPoolAndClients() throws Exception { + JsonNode poolResponse = cognitoJson("CreateUserPool", """ + { + "PoolName": "OAuthPool" + } + """); + poolId = poolResponse.path("UserPool").path("Id").asText(); + + JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "oauth-client" + } + """.formatted(poolId)); + clientId = clientResponse.path("UserPoolClient").path("ClientId").asText(); + + JsonNode confidentialClientResponse = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "confidential-oauth-client", + "GenerateSecret": true, + "AllowedOAuthFlowsUserPoolClient": true, + "AllowedOAuthFlows": ["client_credentials"], + "AllowedOAuthScopes": ["notes/read", "notes/write"] + } + """.formatted(poolId)); + confidentialClientId = confidentialClientResponse.path("UserPoolClient").path("ClientId").asText(); + confidentialClientSecret = confidentialClientResponse.path("UserPoolClient").path("ClientSecret").asText(); + + JsonNode limitedClientResponse = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "limited-oauth-client", + "GenerateSecret": true, + "AllowedOAuthFlowsUserPoolClient": true, + "AllowedOAuthFlows": ["client_credentials"], + "AllowedOAuthScopes": ["notes/read"] + } + """.formatted(poolId)); + limitedClientId = limitedClientResponse.path("UserPoolClient").path("ClientId").asText(); + + JsonNode resourceServerResponse = cognitoJson("CreateResourceServer", """ + { + "UserPoolId": "%s", + "Identifier": "notes", + "Name": "Notes API", + "Scopes": [ + { + "ScopeName": "read", + "ScopeDescription": "Read notes" + }, + { + "ScopeName": "write", + "ScopeDescription": "Write notes" + } + ] + } + """.formatted(poolId)); + assertTrue(resourceServerResponse.path("ResourceServer").path("CreationDate").asLong() > 0); + assertTrue(resourceServerResponse.path("ResourceServer").path("LastModifiedDate").asLong() > 0); + } + + @Test + @Order(2) + void describeUserPoolClientReturnsGeneratedSecret() throws Exception { + JsonNode response = cognitoJson("DescribeUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientId": "%s" + } + """.formatted(poolId, confidentialClientId)); + + assertEquals(confidentialClientId, response.path("UserPoolClient").path("ClientId").asText()); + assertEquals(confidentialClientSecret, response.path("UserPoolClient").path("ClientSecret").asText()); + assertTrue(response.path("UserPoolClient").path("GenerateSecret").asBoolean()); + assertTrue(response.path("UserPoolClient").path("AllowedOAuthFlowsUserPoolClient").asBoolean()); + assertEquals("client_credentials", + response.path("UserPoolClient").path("AllowedOAuthFlows").get(0).asText()); + } + + @Test + @Order(3) + void updateResourceServerReplacesNameAndScopes() throws Exception { + JsonNode before = cognitoJson("DescribeResourceServer", """ + { + "UserPoolId": "%s", + "Identifier": "notes" + } + """.formatted(poolId)); + long creationDate = before.path("ResourceServer").path("CreationDate").asLong(); + long previousLastModifiedDate = before.path("ResourceServer").path("LastModifiedDate").asLong(); + + JsonNode updateResponse = cognitoJson("UpdateResourceServer", """ + { + "UserPoolId": "%s", + "Identifier": "notes", + "Name": "Notes API v2", + "Scopes": [ + { + "ScopeName": "read", + "ScopeDescription": "Read notes v2" + }, + { + "ScopeName": "write", + "ScopeDescription": "Write notes v2" + } + ] + } + """.formatted(poolId)); + + JsonNode resourceServer = updateResponse.path("ResourceServer"); + assertEquals("notes", resourceServer.path("Identifier").asText()); + assertEquals("Notes API v2", resourceServer.path("Name").asText()); + assertEquals(creationDate, resourceServer.path("CreationDate").asLong()); + assertTrue(resourceServer.path("LastModifiedDate").asLong() >= previousLastModifiedDate); + assertEquals("read", resourceServer.path("Scopes").get(0).path("ScopeName").asText()); + assertEquals("Read notes v2", resourceServer.path("Scopes").get(0).path("ScopeDescription").asText()); + assertEquals("write", resourceServer.path("Scopes").get(1).path("ScopeName").asText()); + assertEquals("Write notes v2", resourceServer.path("Scopes").get(1).path("ScopeDescription").asText()); + + JsonNode described = cognitoJson("DescribeResourceServer", """ + { + "UserPoolId": "%s", + "Identifier": "notes" + } + """.formatted(poolId)); + assertEquals("Notes API v2", described.path("ResourceServer").path("Name").asText()); + assertEquals("write", described.path("ResourceServer").path("Scopes").get(1).path("ScopeName").asText()); + } + + @Test + @Order(4) + void updateResourceServerRequiresUserPoolId() { + cognitoAction("UpdateResourceServer", """ + { + "Identifier": "notes", + "Name": "Missing pool" + } + """) + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")) + .body("message", equalTo("UserPoolId is required")); + } + + @Test + @Order(5) + void updateResourceServerRequiresIdentifier() { + cognitoAction("UpdateResourceServer", """ + { + "UserPoolId": "%s", + "Name": "Missing identifier" + } + """.formatted(poolId)) + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")) + .body("message", equalTo("Identifier is required")); + } + + @Test + @Order(6) + void publicClientCannotUseClientCredentialsGrant() { + given() + .formParam("grant_type", "client_credentials") + .formParam("client_id", clientId) + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("unauthorized_client")); + } + + @Test + @Order(7) + void tokenEndpointReturnsAccessTokenFromBasicAuth() throws Exception { + String basic = Base64.getEncoder() + .encodeToString((confidentialClientId + ":" + confidentialClientSecret).getBytes(StandardCharsets.UTF_8)); + + Response response = given() + .header("Authorization", "Basic " + basic) + .formParam("grant_type", "client_credentials") + .when() + .post("/cognito-idp/oauth2/token"); + + response.then() + .statusCode(200) + .body("token_type", equalTo("Bearer")); + + JsonNode payload = decodeJwtPayload(response.jsonPath().getString("access_token")); + assertEquals(confidentialClientId, payload.path("client_id").asText()); + assertEquals("http://localhost:4566/" + poolId, payload.path("iss").asText()); + } + + @Test + @Order(8) + void tokenEndpointReturnsScopedAccessTokenForConfidentialClient() throws Exception { + String basic = Base64.getEncoder() + .encodeToString((confidentialClientId + ":" + confidentialClientSecret).getBytes(StandardCharsets.UTF_8)); + + Response response = given() + .header("Authorization", "Basic " + basic) + .formParam("grant_type", "client_credentials") + .formParam("scope", "notes/read notes/write") + .when() + .post("/cognito-idp/oauth2/token"); + + response.then().statusCode(200); + + JsonNode payload = decodeJwtPayload(response.jsonPath().getString("access_token")); + assertEquals("notes/read notes/write", payload.path("scope").asText()); + assertEquals(confidentialClientId, payload.path("client_id").asText()); + } + + @Test + @Order(9) + void tokenEndpointReturnsAllAllowedScopesWhenScopeOmitted() throws Exception { + String basic = Base64.getEncoder() + .encodeToString((confidentialClientId + ":" + confidentialClientSecret).getBytes(StandardCharsets.UTF_8)); + + Response response = given() + .header("Authorization", "Basic " + basic) + .formParam("grant_type", "client_credentials") + .when() + .post("/cognito-idp/oauth2/token"); + + response.then().statusCode(200); + + JsonNode payload = decodeJwtPayload(response.jsonPath().getString("access_token")); + assertEquals("notes/read notes/write", payload.path("scope").asText()); + } + + @Test + @Order(10) + void tokenEndpointAllowsClientSecretPostForConfidentialClient() { + given() + .formParam("grant_type", "client_credentials") + .formParam("client_id", confidentialClientId) + .formParam("client_secret", confidentialClientSecret) + .formParam("scope", "notes/read") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(200) + .body("token_type", equalTo("Bearer")); + } + + @Test + @Order(11) + void missingSecretForConfidentialClientReturnsInvalidClient() { + given() + .formParam("grant_type", "client_credentials") + .formParam("client_id", confidentialClientId) + .formParam("scope", "notes/read") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_client")); + } + + @Test + @Order(12) + void invalidSecretForConfidentialClientReturnsInvalidClient() { + String basic = Base64.getEncoder() + .encodeToString((confidentialClientId + ":wrong-secret").getBytes(StandardCharsets.UTF_8)); + + given() + .header("Authorization", "Basic " + basic) + .formParam("grant_type", "client_credentials") + .formParam("scope", "notes/read") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_client")); + } + + @Test + @Order(13) + void unknownScopeReturnsInvalidScope() { + String basic = Base64.getEncoder() + .encodeToString((confidentialClientId + ":" + confidentialClientSecret).getBytes(StandardCharsets.UTF_8)); + + given() + .header("Authorization", "Basic " + basic) + .formParam("grant_type", "client_credentials") + .formParam("scope", "notes/delete") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_scope")); + } + + @Test + @Order(14) + void clientCannotRequestScopeThatIsNotAllowedForIt() { + String limitedClientSecret = cognitoDescribeClientSecret(limitedClientId); + String basic = Base64.getEncoder() + .encodeToString((limitedClientId + ":" + limitedClientSecret).getBytes(StandardCharsets.UTF_8)); + + given() + .header("Authorization", "Basic " + basic) + .formParam("grant_type", "client_credentials") + .formParam("scope", "notes/write") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_scope")); + } + + @Test + @Order(15) + void missingGrantTypeReturnsInvalidRequest() { + given() + .formParam("client_id", clientId) + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")); + } + + @Test + @Order(16) + void unsupportedGrantTypeReturnsUnsupportedGrantType() { + given() + .formParam("grant_type", "refresh_token") + .formParam("client_id", clientId) + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("unsupported_grant_type")); + } + + @Test + @Order(17) + void missingClientIdReturnsInvalidRequest() { + given() + .formParam("grant_type", "client_credentials") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")); + } + + @Test + @Order(18) + void unknownClientIdReturnsInvalidClient() { + given() + .formParam("grant_type", "client_credentials") + .formParam("client_id", "missing-client") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_client")); + } + + @Test + @Order(19) + void mismatchedClientIdsReturnInvalidRequest() { + String basic = Base64.getEncoder() + .encodeToString((clientId + ":ignored-secret").getBytes(StandardCharsets.UTF_8)); + + given() + .header("Authorization", "Basic " + basic) + .formParam("grant_type", "client_credentials") + .formParam("client_id", "different-client-id") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")); + } + + @Test + @Order(20) + void oauthTokensAreSignedWithPublishedRsaJwksKey() throws Exception { + Response tokenResponse = given() + .header("Authorization", "Basic " + Base64.getEncoder() + .encodeToString((confidentialClientId + ":" + confidentialClientSecret) + .getBytes(StandardCharsets.UTF_8))) + .formParam("grant_type", "client_credentials") + .when() + .post("/cognito-idp/oauth2/token"); + + tokenResponse.then().statusCode(200); + + String accessToken = tokenResponse.jsonPath().getString("access_token"); + JsonNode header = decodeJwtHeader(accessToken); + assertEquals("RS256", header.path("alg").asText()); + assertEquals(poolId, header.path("kid").asText()); + + String jwksResponse = given() + .when() + .get("/" + poolId + "/.well-known/jwks.json") + .then() + .statusCode(200) + .extract() + .asString(); + + JsonNode jwks = OBJECT_MAPPER.readTree(jwksResponse); + JsonNode key = jwks.path("keys").get(0); + assertNotNull(key); + assertEquals("RSA", key.path("kty").asText()); + assertEquals("RS256", key.path("alg").asText()); + assertEquals("sig", key.path("use").asText()); + assertEquals(poolId, key.path("kid").asText()); + assertTrue(key.hasNonNull("n")); + assertTrue(key.hasNonNull("e")); + assertTrue(verifyJwtSignature(accessToken, key)); + } + + @Test + @Order(21) + void openIdConfigurationIncludesTokenEndpointMetadata() throws Exception { + String openIdResponse = given() + .when() + .get("/" + poolId + "/.well-known/openid-configuration") + .then() + .statusCode(200) + .extract() + .asString(); + + JsonNode document = OBJECT_MAPPER.readTree(openIdResponse); + assertEquals( + "http://localhost:4566/cognito-idp/oauth2/token", + document.path("token_endpoint").asText()); + assertEquals("client_credentials", document.path("grant_types_supported").get(0).asText()); + assertEquals("client_secret_basic", document.path("token_endpoint_auth_methods_supported").get(0).asText()); + } + + private static Response cognitoAction(String action, String body) { + return given() + .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action) + .contentType(COGNITO_CONTENT_TYPE) + .body(body) + .when() + .post("/"); + } + + private static JsonNode cognitoJson(String action, String body) throws Exception { + String response = cognitoAction(action, body) + .then() + .statusCode(200) + .extract() + .asString(); + return OBJECT_MAPPER.readTree(response); + } + + private static String cognitoDescribeClientSecret(String clientId) { + return cognitoAction("DescribeUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientId": "%s" + } + """.formatted(poolId, clientId)) + .then() + .statusCode(200) + .extract() + .jsonPath() + .getString("UserPoolClient.ClientSecret"); + } + + private static JsonNode decodeJwtPayload(String token) throws Exception { + return decodeJwtPart(token, 1); + } + + private static JsonNode decodeJwtHeader(String token) throws Exception { + return decodeJwtPart(token, 0); + } + + private static JsonNode decodeJwtPart(String token, int partIndex) throws Exception { + String[] parts = token.split("\\."); + assertEquals(3, parts.length); + return OBJECT_MAPPER.readTree(Base64.getUrlDecoder().decode(padBase64(parts[partIndex]))); + } + + private static boolean verifyJwtSignature(String token, JsonNode jwk) throws Exception { + String[] parts = token.split("\\."); + assertEquals(3, parts.length); + + BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(jwk.path("n").asText()))); + BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(jwk.path("e").asText()))); + RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent); + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec); + + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initVerify(publicKey); + signature.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8)); + return signature.verify(Base64.getUrlDecoder().decode(padBase64(parts[2]))); + } + + private static String padBase64(String value) { + int remainder = value.length() % 4; + if (remainder == 0) { + return value; + } + return value + "=".repeat(4 - remainder); + } +}