fix(Cognito): OAuth/OIDC parity for RS256/JWKS, /oauth2/token, and OAuth app-client settings (#97)

* feat: add Cognito OAuth and resource server support

* chore: set FLOCI_BASE_URL for compatibility tests
This commit is contained in:
Jeffen authored and GitHub committed 2026-03-31 18:47:38 -05:00
1 parent aba95933cf
commit a4af506c15
13 files changed
+1646 -43

No files matched your search

@@ -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();
}
}
}
@@ -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<ResourceServer> 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<String, String> 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<ResourceServerScope> parseScopes(JsonNode scopesNode) {
if (scopesNode == null || !scopesNode.isArray()) {
return List.of();
}
List<ResourceServerScope> 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<String> readStringList(JsonNode node) {
if (node == null || !node.isArray()) {
return List.of();
}
List<String> 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());
@@ -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<String, String> formParams) {
return issueToken(authorization, formParams);
}
private Response issueToken(String authorization, MultivaluedMap<String, String> 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<String, Object> 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) {
}
}
@@ -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<String, UserPool> poolStore;
private final StorageBackend<String, UserPoolClient> clientStore;
private final StorageBackend<String, ResourceServer> resourceServerStore;
private final StorageBackend<String, CognitoUser> 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<Map<String, UserPool>>() {});
this.clientStore = storageFactory.create("cognito", "cognito-clients.json",
new TypeReference<Map<String, UserPoolClient>>() {});
this.resourceServerStore = storageFactory.create("cognito", "cognito-resource-servers.json",
new TypeReference<Map<String, ResourceServer>>() {});
this.userStore = storageFactory.create("cognito", "cognito-users.json",
new TypeReference<Map<String, CognitoUser>>() {});
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<UserPool> 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<String> allowedOAuthFlows,
List<String> 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<ResourceServerScope> 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<ResourceServer> 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<ResourceServerScope> 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<String, String> attributes,
@@ -311,6 +404,33 @@ public class CognitoService {
adminUpdateUserAttributes(poolId, username, attributes);
}
public Map<String, Object> 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<String, Object> 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<String, Object> authenticateWithPassword(UserPool pool, Map<String, String> 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<String> allowedScopes = normalizeStringList(client.getAllowedOAuthScopes());
if (allowedScopes.isEmpty()) {
throw new AwsException("InvalidScopeException", "Client has no allowed OAuth scopes", 400);
}
List<String> 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<String> 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<String> 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<ResourceServerScope> normalizeScopes(List<ResourceServerScope> scopes) {
if (scopes == null || scopes.isEmpty()) {
return List.of();
}
List<ResourceServerScope> normalized = new ArrayList<>();
Set<String> 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<String> normalizeStringList(List<String> values) {
if (values == null || values.isEmpty()) {
return List.of();
}
List<String> normalized = new ArrayList<>();
Set<String> 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;
}
}
@@ -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);
}
}
@@ -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<ResourceServerScope> 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<ResourceServerScope> getScopes() { return scopes; }
public void setScopes(List<ResourceServerScope> 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; }
}
@@ -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; }
}
@@ -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; }
@@ -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<String> allowedOAuthFlows = new ArrayList<>();
private List<String> 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<String> getAllowedOAuthFlows() { return allowedOAuthFlows; }
public void setAllowedOAuthFlows(List<String> allowedOAuthFlows) { this.allowedOAuthFlows = allowedOAuthFlows; }
public List<String> getAllowedOAuthScopes() { return allowedOAuthScopes; }
public void setAllowedOAuthScopes(List<String> allowedOAuthScopes) { this.allowedOAuthScopes = allowedOAuthScopes; }
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }