Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cognito): add OAuth2 /oauth2/userInfo endpoint (#1062)

aprox25b3c9821faf6
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 fc8adc7499..1a0787acba 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
@@ -984,6 +984,10 @@ public class CognitoService {
return baseUrl + "/cognito-idp/oauth2/token";
}
+ public String getUserInfoEndpoint() {
+ return baseUrl + "/cognito-idp/oauth2/userInfo";
+ }
+
// ──────────────────────────── Private helpers ────────────────────────────
UserPoolClient findClientById(String clientId) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java
new file mode 100644
index 0000000000..ac56379123
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java
@@ -0,0 +1,173 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Implements the Cognito hosted-UI {@code /oauth2/userInfo} endpoint. Real
+ * Cognito serves this route but the SDK API does not expose it, so SDK-based
+ * mocks alone are insufficient for OIDC clients that resolve a user's profile
+ * via this endpoint.
+ *
+ * <p>Floci is a local emulator, not a security boundary: the bearer token is
+ * parsed but not signature-verified. The {@code iss} claim determines which
+ * pool to look the user up in and {@code sub} identifies the user. Attributes
+ * are returned with their raw Cognito names (including the {@code custom:*}
+ * prefix) so downstream Jackson mappings such as
+ * {@code @JsonProperty("custom:my_attribute")} resolve correctly.
+ *
+ * <p>The response shape mirrors real AWS Cognito: snake_case keys for OIDC
+ * standard claims and string-valued {@code email_verified} /
+ * {@code phone_number_verified}. Error responses follow the OAuth 2.0
+ * Bearer-token error convention — status code plus a {@code WWW-Authenticate}
+ * header with {@code error} / {@code error_description} parameters and no
+ * response body — matching the behaviour documented for Cognito.
+ */
+@ApplicationScoped
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+public class CognitoUserInfoController {
+
+ private static final Logger LOG = Logger.getLogger(CognitoUserInfoController.class);
+ private static final TypeReference<Map<String, Object>> CLAIM_MAP_TYPE = new TypeReference<>() {};
+
+ private final CognitoService cognitoService;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public CognitoUserInfoController(CognitoService cognitoService, ObjectMapper objectMapper) {
+ this.cognitoService = cognitoService;
+ this.objectMapper = objectMapper;
+ }
+
+ @GET
+ @Path("/cognito-idp/oauth2/userInfo")
+ public Response userInfo(@HeaderParam("Authorization") String authorization) {
+ if (authorization == null || authorization.isBlank()
+ || !authorization.regionMatches(true, 0, "Bearer ", 0, 7)) {
+ return bearerError(401, "invalid_token", "Bearer token required");
+ }
+ String token = authorization.substring(7).trim();
+ String[] parts = token.split("\\.");
+ if (parts.length < 2) {
+ return bearerError(401, "invalid_token", "Malformed JWT");
+ }
+
+ Map<String, Object> claims;
+ try {
+ byte[] payload = Base64.getUrlDecoder().decode(parts[1]);
+ claims = objectMapper.readValue(payload, CLAIM_MAP_TYPE);
+ } catch (Exception e) {
+ LOG.debug("Failed to decode JWT payload", e);
+ return bearerError(401, "invalid_token", "Cannot decode JWT payload");
+ }
+
+ String sub = asString(claims.get("sub"));
+ String iss = asString(claims.get("iss"));
+ if (sub == null || iss == null) {
+ return bearerError(401, "invalid_token", "Missing sub or iss claim");
+ }
+
+ String poolId = poolIdFromIssuer(iss);
+ if (poolId == null) {
+ return bearerError(401, "invalid_token", "Cannot derive user pool from iss: " + iss);
+ }
+
+ CognitoUser user;
+ try {
+ List<CognitoUser> matches = cognitoService.listUsers(poolId, "sub=\"" + sub + "\"");
+ if (matches.isEmpty()) {
+ return bearerError(401, "invalid_token", "Token subject does not resolve to a user in pool " + poolId);
+ }
+ user = matches.getFirst();
+ } catch (AwsException e) {
+ return bearerError(e.getHttpStatus() == 404 ? 401 : e.getHttpStatus(),
+ "invalid_token", e.getMessage());
+ }
+
+ ObjectNode body = objectMapper.createObjectNode();
+ Map<String, String> attrs = user.getAttributes();
+ body.put("sub", attrs.getOrDefault("sub", sub));
+ body.put("username", user.getUsername());
+ putIfPresent(body, "email", attrs.get("email"));
+ putVerifiedFlag(body, "email_verified", attrs.get("email_verified"));
+ putIfPresent(body, "phone_number", attrs.get("phone_number"));
+ putVerifiedFlag(body, "phone_number_verified", attrs.get("phone_number_verified"));
+ for (String standardClaim : OIDC_PROFILE_CLAIMS) {
+ putIfPresent(body, standardClaim, attrs.get(standardClaim));
+ }
+ for (Map.Entry<String, String> e : attrs.entrySet()) {
+ if (e.getKey().startsWith("custom:") && e.getValue() != null) {
+ body.put(e.getKey(), e.getValue());
+ }
+ }
+ return Response.ok(body)
+ .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
+ .header("Pragma", "no-cache")
+ .build();
+ }
+
+ private static final List<String> OIDC_PROFILE_CLAIMS = List.of(
+ "name", "family_name", "given_name", "middle_name", "nickname",
+ "preferred_username", "profile", "picture", "website", "gender",
+ "birthdate", "zoneinfo", "locale", "updated_at", "address");
+
+ private static String poolIdFromIssuer(String iss) {
+ // iss looks like http://localhost:4566/eu-central-1_abc123 (or, in real AWS,
+ // https://cognito-idp.<region>.amazonaws.com/<pool-id>) — the pool id is the
+ // last path segment.
+ int slash = iss.lastIndexOf('/');
+ if (slash < 0 || slash == iss.length() - 1) {
+ return null;
+ }
+ String candidate = iss.substring(slash + 1);
+ return candidate.contains("_") ? candidate : null;
+ }
+
+ private static String asString(Object value) {
+ if (value == null) {
+ return null;
+ }
+ String s = value.toString().trim();
+ return s.isEmpty() ? null : s;
+ }
+
+ private static void putIfPresent(ObjectNode body, String key, String value) {
+ if (value != null && !value.isEmpty()) {
+ body.put(key, value);
+ }
+ }
+
+ private static void putVerifiedFlag(ObjectNode body, String key, String value) {
+ if (value == null || value.isEmpty()) {
+ return;
+ }
+ body.put(key, "true".equalsIgnoreCase(value) ? "true" : "false");
+ }
+
+ private Response bearerError(int status, String code, String description) {
+ String sanitized = description == null ? "" : description.replace("\"", "'");
+ return Response.status(status)
+ .header("WWW-Authenticate",
+ "Bearer error=\"" + code + "\", error_description=\"" + sanitized + "\"")
+ .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
+ .header("Pragma", "no-cache")
+ .build();
+ }
+}
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 a56352abea..17f1d4e4ae 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
@@ -60,10 +60,11 @@ public class CognitoWellKnownController {
String issuer = cognitoService.getIssuer(pool.getId());
String jwksUri = cognitoService.getJwksUri(pool.getId());
String tokenEndpoint = cognitoService.getTokenEndpoint();
+ String userInfoEndpoint = cognitoService.getUserInfoEndpoint();
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();
+ {"issuer":"%s","jwks_uri":"%s","token_endpoint":"%s","userinfo_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, userInfoEndpoint).strip();
return Response.ok(body).build();
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java
new file mode 100644
index 0000000000..01f2412e06
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoIntegrationTest.java
@@ -0,0 +1,363 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+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.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class CognitoUserInfoIntegrationTest {
+
+ 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 accessToken;
+ private static final String username = "carol+" + UUID.randomUUID() + "@example.com";
+ private static final String password = "Perm1234!";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ @Order(1)
+ void createPoolClientAndUser() throws Exception {
+ JsonNode poolResponse = cognitoJson("CreateUserPool", """
+ {
+ "PoolName": "UserInfoPool"
+ }
+ """);
+ poolId = poolResponse.path("UserPool").path("Id").asText();
+
+ JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """
+ {
+ "UserPoolId": "%s",
+ "ClientName": "userinfo-client"
+ }
+ """.formatted(poolId));
+ clientId = clientResponse.path("UserPoolClient").path("ClientId").asText();
+
+ cognitoAction("AdminCreateUser", """
+ {
+ "UserPoolId": "%s",
+ "Username": "%s",
+ "UserAttributes": [
+ { "Name": "email", "Value": "%s" },
+ { "Name": "email_verified", "Value": "true" },
+ { "Name": "phone_number", "Value": "+12065550100" },
+ { "Name": "phone_number_verified", "Value": "false" },
+ { "Name": "given_name", "Value": "Carol" },
+ { "Name": "family_name", "Value": "Example" },
+ { "Name": "preferred_username", "Value": "carol-pref" },
+ { "Name": "custom:tenant_id", "Value": "tenant-42" }
+ ]
+ }
+ """.formatted(poolId, username, username))
+ .then()
+ .statusCode(200);
+
+ cognitoAction("AdminSetUserPassword", """
+ {
+ "UserPoolId": "%s",
+ "Username": "%s",
+ "Password": "%s",
+ "Permanent": true
+ }
+ """.formatted(poolId, username, password))
+ .then()
+ .statusCode(200);
+
+ JsonNode authResp = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "USER_PASSWORD_AUTH",
+ "AuthParameters": {
+ "USERNAME": "%s",
+ "PASSWORD": "%s"
+ }
+ }
+ """.formatted(clientId, username, password));
+ accessToken = authResp.path("AuthenticationResult").path("AccessToken").asText();
+ assertNotNull(accessToken);
+ assertFalse(accessToken.isBlank());
+ }
+
+ @Test
+ @Order(2)
+ void userInfoReturnsClaimsInCognitoShape() throws Exception {
+ Response response = given()
+ .header("Authorization", "Bearer " + accessToken)
+ .when()
+ .get("/cognito-idp/oauth2/userInfo");
+
+ response.then()
+ .statusCode(200)
+ .contentType(containsString("application/json"))
+ .header("Cache-Control", containsString("no-store"));
+
+ JsonNode body = OBJECT_MAPPER.readTree(response.asString());
+
+ assertEquals(username, body.path("username").asText());
+ assertTrue(body.hasNonNull("sub"));
+ assertEquals(username, body.path("email").asText());
+ // email_verified / phone_number_verified must be JSON strings, not booleans.
+ assertTrue(body.path("email_verified").isTextual(),
+ "email_verified must be a string per AWS Cognito spec");
+ assertEquals("true", body.path("email_verified").asText());
+ assertTrue(body.path("phone_number_verified").isTextual(),
+ "phone_number_verified must be a string per AWS Cognito spec");
+ assertEquals("false", body.path("phone_number_verified").asText());
+ assertEquals("+12065550100", body.path("phone_number").asText());
+ assertEquals("Carol", body.path("given_name").asText());
+ assertEquals("Example", body.path("family_name").asText());
+ assertEquals("carol-pref", body.path("preferred_username").asText());
+ assertEquals("tenant-42", body.path("custom:tenant_id").asText());
+ }
+
+ @Test
+ @Order(3)
+ void userInfoDoesNotEmitNonOidcCamelCaseAliases() throws Exception {
+ Response response = given()
+ .header("Authorization", "Bearer " + accessToken)
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(200)
+ .extract().response();
+
+ JsonNode body = OBJECT_MAPPER.readTree(response.asString());
+ // Real AWS Cognito only returns snake_case OIDC claims.
+ assertFalse(body.has("givenName"), "givenName is not part of the AWS userInfo response");
+ assertFalse(body.has("familyName"), "familyName is not part of the AWS userInfo response");
+ assertFalse(body.has("preferredUsername"), "preferredUsername is not part of the AWS userInfo response");
+ assertFalse(body.has("enabled"), "enabled is not part of the AWS userInfo response");
+ }
+
+ @Test
+ @Order(4)
+ void missingAuthorizationHeaderReturns401WithBearerChallenge() {
+ given()
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("error=\"invalid_token\""));
+ }
+
+ @Test
+ @Order(5)
+ void nonBearerAuthorizationReturns401() {
+ given()
+ .header("Authorization", "Basic dXNlcjpwYXNz")
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("invalid_token"));
+ }
+
+ @Test
+ @Order(6)
+ void malformedJwtReturns401InvalidToken() {
+ given()
+ .header("Authorization", "Bearer not-a-real-jwt")
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("invalid_token"));
+ }
+
+ @Test
+ @Order(7)
+ void undecodablePayloadReturns401InvalidToken() {
+ given()
+ .header("Authorization", "Bearer header.notbase64!!!.sig")
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("invalid_token"));
+ }
+
+ @Test
+ @Order(8)
+ void tokenWithUnknownSubReturns401() {
+ // Forge a JWT payload with a sub that does not exist in this pool.
+ String header = base64Url("{\"alg\":\"none\",\"typ\":\"JWT\"}");
+ String payload = base64Url(("{\"sub\":\"00000000-0000-0000-0000-000000000000\","
+ + "\"iss\":\"http://localhost:4566/" + poolId + "\","
+ + "\"token_use\":\"access\"}"));
+ String forged = header + "." + payload + ".sig";
+
+ given()
+ .header("Authorization", "Bearer " + forged)
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("invalid_token"));
+ }
+
+ @Test
+ @Order(9)
+ void tokenWithoutIssuerOrSubReturns401() {
+ String header = base64Url("{\"alg\":\"none\"}");
+ String payload = base64Url("{\"foo\":\"bar\"}");
+ String forged = header + "." + payload + ".sig";
+
+ given()
+ .header("Authorization", "Bearer " + forged)
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("invalid_token"));
+ }
+
+ @Test
+ @Order(10)
+ void openIdConfigurationAdvertisesUserInfoEndpoint() 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/userInfo",
+ document.path("userinfo_endpoint").asText());
+ }
+
+ @Test
+ @Order(11)
+ void userInfoFromRefreshedAccessToken() throws Exception {
+ JsonNode initialAuth = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "USER_PASSWORD_AUTH",
+ "AuthParameters": {
+ "USERNAME": "%s",
+ "PASSWORD": "%s"
+ }
+ }
+ """.formatted(clientId, username, password));
+ String refreshToken = initialAuth.path("AuthenticationResult").path("RefreshToken").asText();
+ assertNotNull(refreshToken);
+
+ JsonNode refreshed = cognitoJson("InitiateAuth", """
+ {
+ "ClientId": "%s",
+ "AuthFlow": "REFRESH_TOKEN_AUTH",
+ "AuthParameters": { "REFRESH_TOKEN": "%s" }
+ }
+ """.formatted(clientId, refreshToken));
+ String refreshedAccess = refreshed.path("AuthenticationResult").path("AccessToken").asText();
+ assertNotNull(refreshedAccess);
+
+ String refreshedResponse = given()
+ .header("Authorization", "Bearer " + refreshedAccess)
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(200)
+ .extract()
+ .asString();
+ JsonNode refreshedBody = OBJECT_MAPPER.readTree(refreshedResponse);
+ assertEquals(username, refreshedBody.path("username").asText());
+ assertEquals("true", refreshedBody.path("email_verified").asText());
+ assertEquals("tenant-42", refreshedBody.path("custom:tenant_id").asText());
+ }
+
+ @Test
+ @Order(12)
+ void issuerFromOtherPoolReturns401() {
+ // Create a second pool with no users, forge a token claiming to come from it.
+ String secondPoolId;
+ try {
+ JsonNode secondPool = cognitoJson("CreateUserPool", """
+ { "PoolName": "OtherPool" }
+ """);
+ secondPoolId = secondPool.path("UserPool").path("Id").asText();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ String header = base64Url("{\"alg\":\"none\"}");
+ String payload = base64Url(("{\"sub\":\"unknown\","
+ + "\"iss\":\"http://localhost:4566/" + secondPoolId + "\"}"));
+ String forged = header + "." + payload + ".sig";
+
+ given()
+ .header("Authorization", "Bearer " + forged)
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("invalid_token"));
+ // Touch the pool id so the variable is meaningful in the assertion message.
+ assertNotNull(secondPoolId);
+ }
+
+ @Test
+ @Order(13)
+ void issuerWithoutPoolIdSegmentReturns401() {
+ String header = base64Url("{\"alg\":\"none\"}");
+ // iss ends in a segment without `_` — must not be parsed as a pool id.
+ String payload = base64Url("{\"sub\":\"x\",\"iss\":\"http://localhost:4566/no-pool-here\"}");
+ String forged = header + "." + payload + ".sig";
+
+ given()
+ .header("Authorization", "Bearer " + forged)
+ .when()
+ .get("/cognito-idp/oauth2/userInfo")
+ .then()
+ .statusCode(401)
+ .header("WWW-Authenticate", containsString("invalid_token"));
+ }
+
+ 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 base64Url(String raw) {
+ return java.util.Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ }
+}