feat(cognito): serve managed login for native users with PKCE (#4238)

GET /oauth2/authorize with identity_provider=COGNITO, or none, now signs
in the pool's own users through managed login instead of requiring a
federated provider. It redirects to a plain sign-in form at
/cognito-idp/login (/login on a custom domain), which checks the
password as USER_PASSWORD_AUTH does, sets a pool-scoped `cognito`
session cookie and redirects to the callback with code and state. A
browser with a live session skips the form.

/oauth2/token enforces PKCE (S256 only, as on AWS) when the
authorization request sent a code_challenge, for managed login and
federated sign-in alike, and refuses a code_verifier for a code issued
without one (RFC 9700). The ID token carries the request's nonce.

/cognito-idp/logout (/logout on a custom domain) ends the session and
redirects to a registered LogoutURL, or back to the sign-in form for
the redirect_uri form of the request. Discovery advertises
code_challenge_methods_supported.

Closes #4218
This commit is contained in:
jwoa95 authored and GitHub committed 2026-09-23 16:35:35 -04:00
1 parent 7e4d4dafae
commit eb039eb71c
18 files changed
+1832 -104

No files matched your search

@@ -47,15 +47,45 @@ class CognitoCustomDomainFilterTest {
verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp/oauth2/userInfo"));
}
@Test
void rewritesManagedLoginPathsOnACustomDomainAndPinsThePool() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
for (String path : new String[] {"/login", "/logout"}) {
ContainerRequestContext request = request("https://" + DOMAIN + path + "?client_id=c&state=a%26b", DOMAIN);
filter.filter(request);
verify(request).setProperty(CognitoCustomDomainFilter.POOL_PROPERTY, "us-east-1_abc");
verify(request).setProperty(AccountContextFilter.PINNED_ACCOUNT_PROPERTY, ACCOUNT);
verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp" + path + "?client_id=c&state=a%26b"));
}
}
@Test
void leavesOtherPathsAlone() {
ContainerRequestContext request = request("http://" + DOMAIN + "/cognito-idp/oauth2/token", DOMAIN);
for (String path : new String[] {"/cognito-idp/oauth2/token", "/login/", "/loginx", "/logout/x", "/signup"}) {
ContainerRequestContext request = request("http://" + DOMAIN + path, DOMAIN);
filter.filter(request);
filter.filter(request);
verify(request, never()).setRequestUri(any());
verify(request, never()).setProperty(any(), any());
}
verifyNoInteractions(cognitoService);
verify(request, never()).setRequestUri(any());
verify(request, never()).setProperty(any(), any());
}
/** Without a custom domain, /login is an S3 bucket path and /logout the SSO portal's. */
@Test
void leavesManagedLoginPathsOfOtherHostsAlone() {
when(cognitoService.findCustomDomain("localhost")).thenReturn(Optional.empty());
for (String path : new String[] {"/login", "/logout"}) {
ContainerRequestContext request = request("http://localhost:4566" + path, "localhost:4566");
filter.filter(request);
verify(request, never()).setRequestUri(any());
verify(request, never()).setProperty(any(), any());
}
}
@Test
@@ -137,12 +137,28 @@ class CognitoFederationServiceTest {
String redirect = federationService.beginAuthorization(
pool.getId(), "cognito-client", "https://application.example.test/callback",
List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state");
List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state", null);
CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(queryValue(redirect, "state")).orElseThrow();
assertEquals("relying-party-state", transaction.relyingPartyState());
}
@Test
void completeAuthorizationCarriesTheNonceAndCodeChallengeIntoTheCode() {
createDefaultProvider();
String challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
String redirect = federationService.beginAuthorization(
pool.getId(), "cognito-client", "https://application.example.test/callback",
List.of("openid"), "nonce-value", "ExampleOidc", null, challenge);
String authorizationCode = federationService.completeAuthorization(queryValue(redirect, "state"), "provider-code");
CognitoAuthorizationCode storedCode = stateStore.consumeAuthorizationCode(authorizationCode).orElseThrow();
assertEquals("nonce-value", storedCode.nonce());
assertEquals(challenge, storedCode.codeChallenge());
assertFalse(redirect.contains(challenge), "the challenge stays with Cognito: " + redirect);
}
@Test
void completeAuthorizationRejectsNonOidcProvider() {
createProvider("ExampleGoogle", "Google", Map.of(
@@ -389,7 +405,7 @@ class CognitoFederationServiceTest {
private String putTransaction(String providerName) {
return stateStore.putTransaction(new CognitoAuthorizationTransaction(
pool.getId(), "cognito-client", "https://application.example.test/callback",
List.of("openid"), "nonce-value", providerName, null, CLOCK.instant().plusSeconds(60)));
List.of("openid"), "nonce-value", providerName, null, null, CLOCK.instant().plusSeconds(60)));
}
private String endpoint(String path) {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
import io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
@@ -121,6 +122,53 @@ class CognitoFederationStateStoreTest {
assertTrue(store.consumeAuthorizationCode(code).isEmpty());
}
@Test
void findSession_returnsStoredUnexpiredSessionUntilDeleted() {
CognitoFederationStateStore store = storeAt(NOW);
CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60));
String sessionId = store.putSession(session);
assertEquals(Optional.of(session), store.findSession(sessionId));
assertEquals(Optional.of(session), store.findSession(sessionId));
store.deleteSession(sessionId);
assertTrue(store.findSession(sessionId).isEmpty());
}
@Test
void findSession_expiredSessionReturnsEmptyAndIsRemoved() throws ReflectiveOperationException {
MutableClock clock = new MutableClock(NOW);
CognitoFederationStateStore store = new CognitoFederationStateStore(clock);
String sessionId = store.putSession(new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60)));
clock.set(NOW.plusSeconds(60));
assertTrue(store.findSession(sessionId).isEmpty());
assertTrue(storeMap(store, "sessions").isEmpty());
}
@Test
void findSession_missingOrUnknownIdReturnsEmpty() {
CognitoFederationStateStore store = storeAt(NOW);
assertTrue(store.findSession(null).isEmpty());
assertTrue(store.findSession("unknown").isEmpty());
store.deleteSession(null);
}
@Test
void putSession_idsAreOpaqueAndDistinct() {
CognitoFederationStateStore store = storeAt(NOW);
CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60));
String first = store.putSession(session);
String second = store.putSession(session);
assertFalse(first.equals(second));
assertTrue(first.matches("[A-Za-z0-9_-]{43}"), first);
assertFalse(first.contains("user") || first.contains("pool-id"));
}
private CognitoFederationStateStore storeAt(Instant now) {
return new CognitoFederationStateStore(Clock.fixed(now, ZoneOffset.UTC));
}
@@ -128,14 +176,14 @@ class CognitoFederationStateStoreTest {
private CognitoAuthorizationTransaction transaction(Instant expiresAt) {
return new CognitoAuthorizationTransaction(
"pool-id", "client-id", "https://example.com/callback", List.of("openid", "email"),
"nonce", "ExampleOidc", null, expiresAt
"nonce", "ExampleOidc", null, null, expiresAt
);
}
private CognitoAuthorizationCode authorizationCode(Instant expiresAt) {
return new CognitoAuthorizationCode(
"pool-id", "client-id", "user-id", "https://example.com/callback", List.of("openid", "email"),
expiresAt
null, null, expiresAt
);
}
@@ -146,6 +194,13 @@ class CognitoFederationStateStoreTest {
field.set(store, replacement);
}
private ConcurrentHashMap<?, ?> storeMap(CognitoFederationStateStore store, String fieldName)
throws ReflectiveOperationException {
Field field = CognitoFederationStateStore.class.getDeclaredField(fieldName);
field.setAccessible(true);
return (ConcurrentHashMap<?, ?>) field.get(store);
}
private static final class MutableClock extends Clock {
private Instant now;
@@ -675,6 +675,87 @@ class CognitoLambdaTriggersTest {
// UserMigration
// =========================================================================
// =========================================================================
// Managed login shares USER_PASSWORD_AUTH's password check and its triggers
// =========================================================================
@Test
void managedLoginFiresPreAndPostAuthenticationButIssuesNoTokens() {
UserPool pool = createPoolWithLambdaConfig(Map.of(
"PreAuthentication", "arn:aws:lambda:::pre",
"PostAuthentication", "arn:aws:lambda:::post",
"PreTokenGeneration", "arn:aws:lambda:::pretoken"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), anyString(), any(byte[].class), any())).thenReturn(ok(Map.of()));
CognitoUser user = service.authenticateManagedLogin(client, "alice", "Perm1234!");
assertEquals("alice", user.getUsername());
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any());
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());
verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::pretoken"), any(byte[].class), any());
}
@Test
void managedLoginPreAuthenticationErrorBlocksSignIn() {
UserPool pool = createPoolWithLambdaConfig(Map.of(
"PreAuthentication", "arn:aws:lambda:::pre",
"PostAuthentication", "arn:aws:lambda:::post"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))
.thenReturn(lambdaError("Unhandled", "Email not verified"));
AwsException ex = assertThrows(AwsException.class,
() -> service.authenticateManagedLogin(client, "alice", "Perm1234!"));
assertEquals("PreAuthentication failed with error Email not verified.", ex.getMessage());
verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());
}
@Test
void managedLoginMigratesAMissingUser() {
UserPool pool = createPoolWithLambdaConfig(Map.of("UserMigration", "arn:aws:lambda:::migrate"));
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::migrate"), any(byte[].class), any()))
.thenReturn(ok(Map.of("userAttributes", Map.of("email", "newcomer@example.com"),
"finalUserStatus", "CONFIRMED")));
CognitoUser user = service.authenticateManagedLogin(client, "newcomer", "MyPassword1!");
assertEquals("newcomer", user.getUsername());
assertEquals("newcomer@example.com", service.adminGetUser(pool.getId(), "newcomer").getAttributes().get("email"));
}
/** Managed login needs neither ALLOW_USER_PASSWORD_AUTH nor a SECRET_HASH for a client with a secret. */
@Test
void managedLoginIgnoresExplicitAuthFlowsAndSecretHash() {
UserPool pool = createPoolWithLambdaConfig(Map.of());
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", true, false, List.of(), List.of(),
null, List.of(), null, List.of("ALLOW_REFRESH_TOKEN_AUTH"), null, null, List.of(), null, List.of(),
null, null, null, List.of(), null, null);
assertThrows(AwsException.class, () -> service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("alice", service.authenticateManagedLogin(client, "alice", "Perm1234!").getUsername());
}
@Test
void managedLoginRefusesAUserWhoMustSetANewPassword() {
UserPool pool = createPoolWithLambdaConfig(Map.of("PostAuthentication", "arn:aws:lambda:::post"));
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "Temp1234!");
UserPoolClient client = createClient(pool);
AwsException ex = assertThrows(AwsException.class,
() -> service.authenticateManagedLogin(client, "alice", "Temp1234!"));
assertEquals("NotAuthorizedException", ex.getErrorCode());
assertTrue(ex.getMessage().contains("must set a new password"), ex.getMessage());
verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());
}
@Test
@SuppressWarnings("unchecked")
void userMigrationCreatesAndAuthenticatesMissingUser() {
@@ -0,0 +1,621 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.jwtPayload;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Managed login for a pool's own users, driven over HTTP the way a browser drives it:
* {@code /oauth2/authorize} redirects to the sign-in form, the form posts the credentials, the
* callback receives a code, and {@code /oauth2/token} redeems it, with PKCE, the session cookie
* that skips the form, and {@code /logout}.
*/
@QuarkusTest
class CognitoManagedLoginIntegrationTest {
private static final String CALLBACK = "https://app.example.test/callback";
private static final String SIGNED_OUT = "https://app.example.test/signed-out";
private static final String PASSWORD = "Perm1234!";
/** RFC 7636 appendix B. */
private static final String VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
private static final String CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
private static final String INCORRECT_CREDENTIALS = "Incorrect username or password";
private static final Pattern HIDDEN_FIELD = Pattern.compile("<input type=\"hidden\" name=\"([^\"]*)\" value=\"([^\"]*)\">");
private static final Pattern FORM_ACTION = Pattern.compile("<form method=\"post\" action=\"([^\"]*)\">");
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void authorizeWithoutIdentityProviderRedirectsToTheLoginPageWithTheRequest() throws Exception {
Pool pool = newPool();
for (String provider : new String[] {null, "COGNITO"}) {
Map<String, String> query = authorizeRequest(pool.clientId());
if (provider != null) {
query.put("identity_provider", provider);
}
String location = browserGet(null, "/cognito-idp/oauth2/authorize", query, null)
.then().statusCode(302).extract().header("Location");
assertEquals("/cognito-idp/login", URI.create(location).getPath());
query.remove("identity_provider");
assertEquals(query, queryOf(location));
}
}
@Test
void loginPageRendersAPlainFormAndEscapesTheState() throws Exception {
Pool pool = newPool();
Map<String, String> query = authorizeRequest(pool.clientId());
query.put("state", "\"><script>alert(1)</script>");
Response page = browserGet(null, "/cognito-idp/login", query, null);
page.then().statusCode(200)
.contentType(startsWith("text/html"))
.header("Cache-Control", equalTo("no-store"))
.header("X-Content-Type-Options", equalTo("nosniff"))
.header("Content-Security-Policy", equalTo("default-src 'none'; base-uri 'none'; frame-ancestors 'none'"));
String html = page.asString();
assertTrue(html.contains("name=\"username\""), html);
assertTrue(html.contains("name=\"password\" type=\"password\""), html);
assertFalse(html.contains("<script>"), html);
assertTrue(html.contains("value=\"&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;\""), html);
assertEquals("/cognito-idp/login", formAction(html));
Map<String, String> fields = hiddenFields(html);
assertEquals(query.get("state"), fields.get("state"));
assertEquals(CHALLENGE, fields.get("code_challenge"));
String csrfCookie = setCookie(page, "XSRF-TOKEN");
assertTrue(csrfCookie.contains("; Path=/; HttpOnly; SameSite=Lax"), csrfCookie);
assertEquals(page.getCookie("XSRF-TOKEN"), fields.get("_csrf"));
}
@Test
void wrongPasswordOrUnknownUserShowsTheSameErrorWithoutACodeOrSession() throws Exception {
Pool pool = newPool();
for (String username : new String[] {pool.username(), "nobody-" + System.nanoTime()}) {
Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()));
Response failed = submit(null, page, username, "Wrong1234!");
failed.then().statusCode(400).contentType(startsWith("text/html"));
assertNull(failed.getHeader("Location"));
assertNull(setCookie(failed, "cognito"));
assertTrue(failed.asString().contains("<p role=\"alert\">" + INCORRECT_CREDENTIALS + "</p>"), failed.asString());
assertNotNull(hiddenFields(failed.asString()).get("_csrf"), "the form is shown again");
}
}
@Test
void signInWithoutTheCsrfTokenOrWithAnotherIsRejected() throws Exception {
Pool pool = newPool();
Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()));
Map<String, String> fields = hiddenFields(page.asString());
Response withoutCookie = given().redirects().follow(false)
.formParams(fields).formParam("username", pool.username()).formParam("password", PASSWORD)
.when().post("/cognito-idp/login");
Response otherToken = given().redirects().follow(false)
.cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))
.formParams(withField(fields, "_csrf", "forged-token"))
.formParam("username", pool.username()).formParam("password", PASSWORD)
.when().post("/cognito-idp/login");
Response withoutField = given().redirects().follow(false)
.cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))
.formParams(withField(fields, "_csrf", null))
.formParam("username", pool.username()).formParam("password", PASSWORD)
.when().post("/cognito-idp/login");
for (Response rejected : List.of(withoutCookie, otherToken, withoutField)) {
rejected.then().statusCode(403).body(containsString("<p role=\"alert\">"));
assertNull(rejected.getHeader("Location"));
assertNull(setCookie(rejected, "cognito"));
}
}
@Test
void signInRedirectsToTheCallbackWithACodeTheStateAndASessionCookie() throws Exception {
Pool pool = newPool();
Response signedIn = signIn(null, pool, authorizeRequest(pool.clientId()));
signedIn.then().statusCode(302);
String location = signedIn.getHeader("Location");
assertTrue(location.startsWith(CALLBACK + "?code="), location);
assertEquals("client-state", queryOf(location).get("state"));
String sessionCookie = setCookie(signedIn, "cognito");
assertTrue(sessionCookie.matches("cognito=[A-Za-z0-9_-]{43}; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"),
sessionCookie);
}
/** The client allows only refresh: USER_PASSWORD_AUTH is refused, yet managed login signs in. */
@Test
void managedLoginDoesNotDependOnTheClientsExplicitAuthFlows() throws Exception {
Pool pool = newPool();
cognitoAction("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH","AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(pool.clientId(), pool.username(), PASSWORD)).then().statusCode(400);
signIn(null, pool, authorizeRequest(pool.clientId())).then().statusCode(302);
}
@Test
void codeRedeemsWithTheVerifierForTokensOfTheSignedInUser() throws Exception {
Pool pool = newPool();
String code = code(signIn(null, pool, authorizeRequest(pool.clientId())));
Response tokens = redeem(null, pool.clientId(), code, VERIFIER);
tokens.then().statusCode(200).body("token_type", equalTo("Bearer"));
JsonNode idToken = jwtPayload(tokens.path("id_token"));
assertEquals(pool.sub(), idToken.path("sub").asText());
assertEquals(pool.username(), idToken.path("cognito:username").asText());
assertEquals("client-nonce", idToken.path("nonce").asText());
assertEquals(pool.clientId(), idToken.path("aud").asText());
JsonNode accessToken = jwtPayload(tokens.path("access_token"));
assertEquals(pool.username(), accessToken.path("username").asText());
assertFalse(accessToken.has("nonce"));
}
@Test
void codeIsRefusedWithAWrongOrMissingVerifierAndAWrongOneSpendsIt() throws Exception {
Pool pool = newPool();
Response signedIn = signIn(null, pool, authorizeRequest(pool.clientId()));
String session = signedIn.getCookie("cognito");
String wrongVerifierCode = code(signedIn);
String missingVerifierCode = code(browserGet(null, "/cognito-idp/oauth2/authorize",
authorizeRequest(pool.clientId()), session));
redeem(null, pool.clientId(), wrongVerifierCode, VERIFIER.replace('d', 'e'))
.then().statusCode(400).body("error", equalTo("invalid_grant"));
redeem(null, pool.clientId(), wrongVerifierCode, VERIFIER)
.then().statusCode(400).body("error", equalTo("invalid_grant"));
redeem(null, pool.clientId(), missingVerifierCode, null)
.then().statusCode(400).body("error", equalTo("invalid_grant"));
}
@Test
void codeCannotBeRedeemedTwice() throws Exception {
Pool pool = newPool();
String code = code(signIn(null, pool, authorizeRequest(pool.clientId())));
redeem(null, pool.clientId(), code, VERIFIER).then().statusCode(200);
redeem(null, pool.clientId(), code, VERIFIER).then().statusCode(400).body("error", equalTo("invalid_grant"));
}
@Test
void codeWithoutPkceRedeemsWithoutAVerifierButNotWithOne() throws Exception {
Pool pool = newPool();
Map<String, String> query = authorizeRequest(pool.clientId());
query.remove("code_challenge");
query.remove("code_challenge_method");
Response signedIn = signIn(null, pool, query);
String withVerifier = code(browserGet(null, "/cognito-idp/oauth2/authorize", query, signedIn.getCookie("cognito")));
redeem(null, pool.clientId(), code(signedIn), null).then().statusCode(200);
redeem(null, pool.clientId(), withVerifier, VERIFIER).then().statusCode(400).body("error", equalTo("invalid_grant"));
}
@Test
void plainOrMissingCodeChallengeMethodIsRejected() throws Exception {
Pool pool = newPool();
for (String method : new String[] {"plain", null}) {
Map<String, String> query = authorizeRequest(pool.clientId());
query.remove("code_challenge_method");
if (method != null) {
query.put("code_challenge_method", method);
}
browserGet(null, "/cognito-idp/oauth2/authorize", query, null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
}
}
@Test
void authorizeWithTheSessionCookieSkipsTheForm() throws Exception {
Pool pool = newPool();
String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito");
Map<String, String> query = authorizeRequest(pool.clientId());
query.put("state", "second-state");
Response again = browserGet(null, "/cognito-idp/oauth2/authorize", query, session);
again.then().statusCode(302);
assertEquals("second-state", queryOf(again.getHeader("Location")).get("state"));
assertTrue(again.getHeader("Location").startsWith(CALLBACK + "?code="));
JsonNode idToken = jwtPayload(redeem(null, pool.clientId(), code(again), VERIFIER)
.then().statusCode(200).extract().path("id_token"));
assertEquals(pool.username(), idToken.path("cognito:username").asText());
}
@Test
void sessionCookieOfAnotherPoolNeitherSignsInNorSignsOutThere() throws Exception {
Pool poolA = newPool();
Pool poolB = newPool();
String sessionOfA = signIn(null, poolA, authorizeRequest(poolA.clientId())).getCookie("cognito");
String location = browserGet(null, "/cognito-idp/oauth2/authorize", authorizeRequest(poolB.clientId()), sessionOfA)
.then().statusCode(302).extract().header("Location");
assertTrue(location.startsWith("/cognito-idp/login?"), location);
Response logoutOfB = browserGet(null, "/cognito-idp/logout",
Map.of("client_id", poolB.clientId(), "logout_uri", SIGNED_OUT), sessionOfA);
logoutOfB.then().statusCode(302).header("Location", equalTo(SIGNED_OUT));
assertNull(setCookie(logoutOfB, "cognito"), "the browser keeps pool A's cookie");
String stillSignedIn = browserGet(null, "/cognito-idp/oauth2/authorize", authorizeRequest(poolA.clientId()),
sessionOfA).then().statusCode(302).extract().header("Location");
assertTrue(stillSignedIn.startsWith(CALLBACK + "?code="), stillSignedIn);
}
@Test
void logoutWithAnUnregisteredLogoutUriIsRejected() throws Exception {
Pool pool = newPool();
browserGet(null, "/cognito-idp/logout",
Map.of("client_id", pool.clientId(), "logout_uri", "https://evil.example.test/"), null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
browserGet(null, "/cognito-idp/logout", Map.of("client_id", pool.clientId()), null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
}
@Test
void logoutEndsTheSessionClearsTheCookieAndRedirectsToTheLogoutUri() throws Exception {
Pool pool = newPool();
String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito");
Response logout = browserGet(null, "/cognito-idp/logout",
Map.of("client_id", pool.clientId(), "logout_uri", SIGNED_OUT), session);
logout.then().statusCode(302).header("Location", equalTo(SIGNED_OUT));
assertEquals("cognito=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax", setCookie(logout, "cognito"));
String location = browserGet(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()), session)
.then().statusCode(302).extract().header("Location");
assertTrue(location.startsWith("/cognito-idp/login?"), "the old cookie no longer signs in: " + location);
}
@Test
void logoutWithRedirectUriSendsTheUserBackToSignIn() throws Exception {
Pool pool = newPool();
String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito");
Map<String, String> query = new LinkedHashMap<>();
query.put("response_type", "code");
query.put("client_id", pool.clientId());
query.put("redirect_uri", CALLBACK);
query.put("state", "after-logout");
Response logout = browserGet(null, "/cognito-idp/logout", query, session);
logout.then().statusCode(302);
assertEquals("/cognito-idp/login", URI.create(logout.getHeader("Location")).getPath());
assertEquals(query, queryOf(logout.getHeader("Location")));
assertEquals("cognito=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax", setCookie(logout, "cognito"));
browserGet(null, "/cognito-idp/logout", withField(query, "redirect_uri", "https://evil.example.test/"), null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
}
@Test
void clientWithoutCognitoAmongItsProvidersCannotUseManagedLogin() throws Exception {
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"FederatedOnlyPool\"}").path("UserPool").path("Id").asText();
cognitoJson("CreateIdentityProvider", """
{"UserPoolId":"%s","ProviderName":"ExampleOidc","ProviderType":"OIDC",
"ProviderDetails":{"authorize_url":"https://idp.example.test/authorize","client_id":"idp-client","attributes_request_method":"GET","oidc_issuer":"https://idp.example.test"}}
""".formatted(poolId));
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"federated-only","AllowedOAuthFlowsUserPoolClient":true,
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid"],"CallbackURLs":["%s"],
"SupportedIdentityProviders":["ExampleOidc"]}
""".formatted(poolId, CALLBACK)).path("UserPoolClient").path("ClientId").asText();
Map<String, String> query = authorizeRequest(clientId);
browserGet(null, "/cognito-idp/oauth2/authorize", query, null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
browserGet(null, "/cognito-idp/login", query, null)
.then().statusCode(400).body("error", equalTo("invalid_request"));
}
@Test
void emailUsernamePoolSignsInByEmail() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"EmailUsernamePool","UsernameAttributes":["email"]}
""").path("UserPool").path("Id").asText();
String clientId = codeClient(poolId);
String email = "alias-" + System.nanoTime() + "@example.com";
Pool pool = withUser(poolId, clientId, email);
assertFalse(pool.username().equals(email), "the canonical username of an email pool is generated");
Response signedIn = signIn(null, new Pool(poolId, clientId, email, pool.sub()), authorizeRequest(clientId));
JsonNode idToken = jwtPayload(redeem(null, clientId, code(signedIn), VERIFIER)
.then().statusCode(200).extract().path("id_token"));
assertEquals(pool.username(), idToken.path("cognito:username").asText());
assertEquals(pool.sub(), idToken.path("sub").asText());
assertEquals(email, idToken.path("email").asText());
}
@Test
void userWhoMustSetANewPasswordIsToldWhy() throws Exception {
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"TemporaryPasswordPool\"}").path("UserPool").path("Id").asText();
String clientId = codeClient(poolId);
String username = "temporary-" + System.nanoTime();
cognitoAction("AdminCreateUser", """
{"UserPoolId":"%s","Username":"%s","TemporaryPassword":"Temp1234!"}
""".formatted(poolId, username)).then().statusCode(200);
Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(clientId));
Response refused = submit(null, page, username, "Temp1234!");
refused.then().statusCode(400).body(containsString("must set a new password"));
assertNull(setCookie(refused, "cognito"));
}
/** AWS's own form posts the authorization request in the query string and only the credentials in the body. */
@Test
void signInAcceptsTheRequestInTheQueryStringAsAwsFormPostsIt() throws Exception {
Pool pool = newPool();
Map<String, String> query = authorizeRequest(pool.clientId());
Response page = browserGet(null, "/cognito-idp/login", query, null);
Response signedIn = given().redirects().follow(false)
.cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))
.queryParams(query)
.formParam("_csrf", page.getCookie("XSRF-TOKEN"))
.formParam("username", pool.username())
.formParam("password", PASSWORD)
.when().post("/cognito-idp/login");
signedIn.then().statusCode(302);
redeem(null, pool.clientId(), code(signedIn), VERIFIER).then().statusCode(200);
}
@Test
void customDomainServesLoginAndLogoutAtItsRoot() throws Exception {
Pool pool = newPool();
String domain = "managed-login-" + System.nanoTime() + ".teos.localhost.floci.io";
cognitoJson("CreateUserPoolDomain", customDomain(domain, pool.poolId(), requestCertificate(domain)));
Response authorize = browserGet(domain, "/oauth2/authorize", authorizeRequest(pool.clientId()), null);
String location = authorize.then().statusCode(302).extract().header("Location");
assertEquals("/login", URI.create(location).getPath());
Response page = follow(domain, location);
page.then().statusCode(200);
assertEquals("/login", formAction(page.asString()));
Response signedIn = submit(domain, page, pool.username(), PASSWORD);
signedIn.then().statusCode(302);
redeem(domain, pool.clientId(), code(signedIn), VERIFIER).then().statusCode(200);
Response logout = browserGet(domain, "/logout",
Map.of("client_id", pool.clientId(), "logout_uri", SIGNED_OUT), signedIn.getCookie("cognito"));
logout.then().statusCode(302).header("Location", equalTo(SIGNED_OUT));
assertEquals("cognito=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax", setCookie(logout, "cognito"));
String anotherPoolsClient = newPool().clientId();
browserGet(domain, "/login", authorizeRequest(anotherPoolsClient), null)
.then().statusCode(400).body("error", equalTo("invalid_client"));
}
/** Without a custom domain Host, /login stays S3's path-style bucket route. */
@Test
void loginOnFlocisOwnHostIsNotManagedLogin() {
given().redirects().follow(false)
.when().get("/login")
.then().statusCode(404).body(containsString("NoSuchBucket"));
}
@Test
void discoveryAdvertisesS256() throws Exception {
Pool pool = newPool();
given().when().get("/" + pool.poolId() + "/.well-known/openid-configuration")
.then().statusCode(200).body("code_challenge_methods_supported", equalTo(List.of("S256")));
}
// ──────────────────────────── Fixtures ────────────────────────────
/** A pool with a confirmed user, and a public client that uses the code grant and allows only refresh. */
private record Pool(String poolId, String clientId, String username, String sub) {
}
private static Pool newPool() throws Exception {
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginPool\"}").path("UserPool").path("Id").asText();
return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime());
}
private static String codeClient(String poolId) throws Exception {
return cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true,
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],
"LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]}
""".formatted(poolId, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText();
}
private static Pool withUser(String poolId, String clientId, String username) throws Exception {
String email = username.contains("@") ? username : username + "@example.com";
cognitoAction("AdminCreateUser", """
{"UserPoolId":"%s","Username":"%s","UserAttributes":[{"Name":"email","Value":"%s"}]}
""".formatted(poolId, username, email)).then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
""".formatted(poolId, username, PASSWORD)).then().statusCode(200);
JsonNode user = cognitoJson("AdminGetUser", """
{"UserPoolId":"%s","Username":"%s"}
""".formatted(poolId, username));
String sub = null;
for (JsonNode attribute : user.path("UserAttributes")) {
if ("sub".equals(attribute.path("Name").asText())) {
sub = attribute.path("Value").asText();
}
}
return new Pool(poolId, clientId, user.path("Username").asText(), sub);
}
/** A PKCE authorization request, as a single-page app sends one. */
private static Map<String, String> authorizeRequest(String clientId) {
Map<String, String> query = new LinkedHashMap<>();
query.put("response_type", "code");
query.put("client_id", clientId);
query.put("redirect_uri", CALLBACK);
query.put("scope", "openid email");
query.put("state", "client-state");
query.put("nonce", "client-nonce");
query.put("code_challenge", CHALLENGE);
query.put("code_challenge_method", "S256");
return query;
}
// ──────────────────────────── Browser ────────────────────────────
private static Response browserGet(String host, String path, Map<String, String> query, String sessionCookie) {
RequestSpecification request = given().redirects().follow(false).queryParams(query);
if (host != null) {
request.header("Host", host);
}
if (sessionCookie != null) {
request.cookie("cognito", sessionCookie);
}
return request.when().get(path);
}
/** Follows a relative redirect, as a browser resolves it against the page's own origin. */
private static Response follow(String host, String location) {
URI uri = URI.create(location);
assertFalse(uri.isAbsolute(), location);
return browserGet(host, uri.getPath(), queryOf(location), null);
}
private static Response loginPage(String host, String authorizePath, Map<String, String> query) {
String location = browserGet(host, authorizePath, query, null).then().statusCode(302).extract().header("Location");
Response page = follow(host, location);
page.then().statusCode(200);
return page;
}
/** Submits the sign-in form the way a browser does: its hidden fields, its CSRF cookie, and the credentials. */
private static Response submit(String host, Response page, String username, String password) {
String html = page.asString();
RequestSpecification request = given().redirects().follow(false)
.cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))
.formParams(hiddenFields(html))
.formParam("username", username)
.formParam("password", password);
if (host != null) {
request.header("Host", host);
}
return request.when().post(formAction(html));
}
/** Signs a fresh browser in through the authorize endpoint and returns the redirect to the callback. */
private static Response signIn(String host, Pool pool, Map<String, String> query) {
Response page = loginPage(host, host == null ? "/cognito-idp/oauth2/authorize" : "/oauth2/authorize", query);
return submit(host, page, pool.username(), PASSWORD);
}
private static Response redeem(String host, String clientId, String code, String verifier) {
RequestSpecification request = given()
.formParam("grant_type", "authorization_code")
.formParam("client_id", clientId)
.formParam("code", code)
.formParam("redirect_uri", CALLBACK);
if (verifier != null) {
request.formParam("code_verifier", verifier);
}
if (host != null) {
request.header("Host", host);
}
return request.when().post(host == null ? "/cognito-idp/oauth2/token" : "/oauth2/token");
}
private static String code(Response callbackRedirect) {
callbackRedirect.then().statusCode(302);
String code = queryOf(callbackRedirect.getHeader("Location")).get("code");
assertNotNull(code, callbackRedirect.getHeader("Location"));
return code;
}
// ──────────────────────────── Parsing ────────────────────────────
/** The Set-Cookie header that sets {@code name}, or null. */
private static String setCookie(Response response, String name) {
for (String header : response.getHeaders().getValues("Set-Cookie")) {
if (header.startsWith(name + "=")) {
return header;
}
}
return null;
}
private static Map<String, String> hiddenFields(String html) {
Map<String, String> fields = new LinkedHashMap<>();
Matcher matcher = HIDDEN_FIELD.matcher(html);
while (matcher.find()) {
fields.put(unescapeHtml(matcher.group(1)), unescapeHtml(matcher.group(2)));
}
return fields;
}
private static String formAction(String html) {
Matcher matcher = FORM_ACTION.matcher(html);
assertTrue(matcher.find(), html);
return unescapeHtml(matcher.group(1));
}
private static String unescapeHtml(String value) {
return value.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'")
.replace("&amp;", "&");
}
private static Map<String, String> queryOf(String location) {
Map<String, String> parameters = new LinkedHashMap<>();
String query = URI.create(location).getRawQuery();
if (query == null) {
return parameters;
}
for (String pair : query.split("&")) {
String[] parts = pair.split("=", 2);
parameters.put(URLDecoder.decode(parts[0], StandardCharsets.UTF_8),
parts.length == 2 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : "");
}
return parameters;
}
/** A copy of {@code parameters} with {@code name} set to {@code value}, or removed when it is null. */
private static Map<String, String> withField(Map<String, String> parameters, String name, String value) {
Map<String, String> copy = new LinkedHashMap<>(parameters);
if (value == null) {
copy.remove(name);
} else {
copy.put(name, value);
}
return copy;
}
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode;
import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction;
import io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
@@ -13,6 +14,9 @@ import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
@@ -24,6 +28,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -36,6 +41,8 @@ class CognitoOAuthControllerTest {
private static final String POOL_ID = "us-east-1_pool";
private static final String CLIENT_ID = "cognito-client";
private static final String CALLBACK_URI = "https://application.example.test/callback";
private static final String RFC_7636_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
private static final String RFC_7636_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
private final ObjectMapper objectMapper = new ObjectMapper();
private final CognitoService cognitoService = mock(CognitoService.class);
@@ -47,7 +54,9 @@ class CognitoOAuthControllerTest {
@BeforeEach
void setUp() {
stateStore = new CognitoFederationStateStore(CLOCK);
controller = new CognitoOAuthController(cognitoService, objectMapper, federationService, stateStore);
CognitoManagedLoginService managedLoginService = new CognitoManagedLoginService(cognitoService, stateStore, CLOCK);
controller = new CognitoOAuthController(cognitoService, objectMapper, federationService, stateStore,
managedLoginService);
client = client();
when(cognitoService.findClientById(CLIENT_ID)).thenReturn(client);
}
@@ -55,11 +64,11 @@ class CognitoOAuthControllerTest {
@Test
void authorizeRedirectsToConfiguredIdentityProvider() {
when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), "nonce", "ExampleOidc",
" relying-party-state "))
" relying-party-state ", RFC_7636_CHALLENGE))
.thenReturn("https://provider.example.test/authorize?state=provider-state");
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce",
"ExampleOidc", " relying-party-state ");
"ExampleOidc", " relying-party-state ", RFC_7636_CHALLENGE, "S256", null);
assertEquals(302, response.getStatus());
assertEquals("https://provider.example.test/authorize?state=provider-state", response.getHeaderString("Location"));
@@ -71,7 +80,7 @@ class CognitoOAuthControllerTest {
.thenThrow(new AwsException("ResourceNotFoundException", "Client not found", 400));
Response response = controller.authorize(requestContext(null), "missing-client", CALLBACK_URI, "code", "openid", null,
"ExampleOidc", null);
"ExampleOidc", null, null, null, null);
assertOAuthError(response, "invalid_client");
}
@@ -79,18 +88,120 @@ class CognitoOAuthControllerTest {
@Test
void authorizeReturnsInvalidRequestForUnregisteredRedirectUri() {
Response response = controller.authorize(requestContext(null), CLIENT_ID, "https://other.example.test/callback", "code", "openid",
null, "ExampleOidc", null);
null, "ExampleOidc", null, null, null, null);
assertOAuthError(response, "invalid_request");
}
@Test
void authorizeReturnsUnsupportedResponseTypeForTokenResponse() {
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "token", "openid", null, "ExampleOidc", null);
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "token", "openid", null, "ExampleOidc",
null, null, null, null);
assertOAuthError(response, "unsupported_response_type");
}
@Test
void authorizeWithoutIdentityProviderRedirectsToTheLoginEndpointWithTheRequest() {
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid email",
"nonce", null, "state & more", RFC_7636_CHALLENGE, "S256", null);
assertEquals(302, response.getStatus());
assertEquals("/cognito-idp/login?response_type=code&client_id=" + CLIENT_ID
+ "&redirect_uri=https%3A%2F%2Fapplication.example.test%2Fcallback&scope=openid+email"
+ "&state=state+%26+more&nonce=nonce&code_challenge=" + RFC_7636_CHALLENGE
+ "&code_challenge_method=S256",
response.getHeaderString("Location"));
}
@Test
void authorizeWithCognitoProviderOnACustomDomainRedirectsToItsLoginPath() {
Response response = controller.authorize(requestContext(POOL_ID), CLIENT_ID, CALLBACK_URI, "code", null, null,
"COGNITO", null, null, null, null);
assertEquals(302, response.getStatus());
assertEquals("/login?response_type=code&client_id=" + CLIENT_ID
+ "&redirect_uri=https%3A%2F%2Fapplication.example.test%2Fcallback", response.getHeaderString("Location"));
}
@Test
void authorizeRejectsManagedLoginForAClientWithoutCognito() {
client.setSupportedIdentityProviders(List.of("ExampleOidc"));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", null,
null, null, null, null, null);
assertOAuthError(response, "invalid_request");
}
@ParameterizedTest
@CsvSource(nullValues = "null", value = {
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, plain",
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, null",
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, s256",
"null, S256",
"too-short, S256",
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-c=, S256",
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cMx, S256"})
void authorizeRejectsUnusablePkceParametersForEitherProvider(String challenge, String method) {
for (String provider : new String[] {null, "ExampleOidc"}) {
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", null,
provider, null, challenge, method, null);
assertOAuthError(response, "invalid_request");
String description = ((JsonNode) response.getEntity()).path("error_description").asText();
assertTrue(description.startsWith("code_challenge"), description);
}
}
@Test
void authorizeWithASessionOfThePoolRedirectsWithACodeCarryingTheNonceAndChallenge() {
when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user"));
String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",
CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce",
null, "relying-party-state", RFC_7636_CHALLENGE, "S256", sessionId);
assertEquals(302, response.getStatus());
String location = response.getHeaderString("Location");
assertTrue(location.startsWith(CALLBACK_URI + "?code="), location);
assertTrue(location.endsWith("&state=relying-party-state"), location);
String code = location.substring((CALLBACK_URI + "?code=").length(), location.indexOf("&state="));
CognitoAuthorizationCode storedCode = stateStore.consumeAuthorizationCode(code).orElseThrow();
assertEquals("session-user", storedCode.userId());
assertEquals("nonce", storedCode.nonce());
assertEquals(RFC_7636_CHALLENGE, storedCode.codeChallenge());
}
@Test
void authorizeIgnoresASessionOfAnotherPool() {
String sessionId = stateStore.putSession(new CognitoManagedLoginSession("us-east-1_other", "session-user",
CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
null, null, null, null, sessionId);
assertEquals(302, response.getStatus());
assertTrue(response.getHeaderString("Location").startsWith("/cognito-idp/login?"));
assertTrue(stateStore.findSession(sessionId).isPresent(), "another pool's session is left alone");
}
@Test
void authorizeEndsTheSessionOfADisabledUser() {
CognitoUser disabled = user("session-user");
disabled.setEnabled(false);
when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(disabled);
String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",
CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
null, null, null, null, sessionId);
assertTrue(response.getHeaderString("Location").startsWith("/cognito-idp/login?"));
assertTrue(stateStore.findSession(sessionId).isEmpty());
}
@Test
void idpResponseReturnsInvalidRequestForUnknownState() {
Response response = controller.idpResponse(requestContext(null), "unknown-state", "provider-code", null, null);
@@ -124,7 +235,8 @@ class CognitoOAuthControllerTest {
@Test
void tokenRedeemsAuthorizationCodeOnce() throws Exception {
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60)));
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), null, null,
CLOCK.instant().plusSeconds(60)));
when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool());
when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user());
when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null)))
@@ -148,7 +260,8 @@ class CognitoOAuthControllerTest {
@Test
void tokenRejectsAuthorizationCodeForAnotherClient() {
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
POOL_ID, "other-client", "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60)));
POOL_ID, "other-client", "federated-user", CALLBACK_URI, List.of("openid"), null, null,
CLOCK.instant().plusSeconds(60)));
Response response = controller.token(null, requestContext(null), form("grant_type", "authorization_code",
"client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI));
@@ -216,14 +329,93 @@ class CognitoOAuthControllerTest {
assertOAuthError(response, "invalid_request");
}
/** RFC 7636 appendix B: the S256 challenge of a known verifier. */
@Test
void pkceAcceptsTheRfc7636ExampleVerifierAndNothingElse() {
assertNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_VERIFIER));
assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_VERIFIER.replace('d', 'e')));
assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, null));
assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_CHALLENGE));
assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, "short"));
assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_VERIFIER + "!"));
assertNotNull(CognitoOAuthController.pkceError(null, RFC_7636_VERIFIER));
assertNull(CognitoOAuthController.pkceError(null, null));
}
/** The client has no secret: a public client proves itself with the verifier alone. */
@Test
void tokenRedeemsAPkceCodeForAPublicClientWithTheMatchingVerifier() {
String code = putAuthorizationCode(null, RFC_7636_CHALLENGE);
Response response = controller.token(null, requestContext(null),
withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER));
assertEquals(200, response.getStatus());
assertEquals("access-token", ((JsonNode) response.getEntity()).path("access_token").asText());
}
@Test
void tokenRejectsAWrongVerifierAndSpendsTheCode() {
String code = putAuthorizationCode(null, RFC_7636_CHALLENGE);
Response wrong = controller.token(null, requestContext(null),
withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER.replace('d', 'e')));
Response retry = controller.token(null, requestContext(null),
withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER));
assertOAuthError(wrong, "invalid_grant");
assertOAuthError(retry, "invalid_grant");
}
@Test
void tokenRejectsAPkceCodeWithoutAVerifier() {
String code = putAuthorizationCode(null, RFC_7636_CHALLENGE);
Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
assertOAuthError(response, "invalid_grant");
assertTrue(stateStore.findAuthorizationCode(code).isEmpty());
}
@Test
void tokenRejectsAVerifierForACodeIssuedWithoutAChallenge() {
String code = putAuthorizationCode(null, null);
Response response = controller.token(null, requestContext(null),
withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER));
assertOAuthError(response, "invalid_grant");
}
@Test
void tokenPutsTheNonceInTheIdTokenOnly() {
String code = putAuthorizationCode("request-nonce", null);
ArgumentCaptor<CognitoService.ClaimsOverride> override = ArgumentCaptor.forClass(CognitoService.ClaimsOverride.class);
when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), override.capture()))
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
assertEquals(200, response.getStatus());
assertEquals(Map.of("nonce", "request-nonce"), override.getValue().idClaimsToAddOrOverride());
assertNull(override.getValue().accessClaimsToAddOrOverride());
assertNull(override.getValue().groupsToOverride());
}
private String putTransaction(String relyingPartyState) {
return stateStore.putTransaction(new CognitoAuthorizationTransaction(POOL_ID, CLIENT_ID, CALLBACK_URI,
List.of("openid"), "nonce", "ExampleOidc", relyingPartyState, CLOCK.instant().plusSeconds(60)));
List.of("openid"), "nonce", "ExampleOidc", relyingPartyState, null, CLOCK.instant().plusSeconds(60)));
}
private String putAuthorizationCode() {
return putAuthorizationCode(null, null);
}
private String putAuthorizationCode(String nonce, String codeChallenge) {
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60)));
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), nonce, codeChallenge,
CLOCK.instant().plusSeconds(60)));
when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool());
when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user());
when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null)))
@@ -232,6 +424,12 @@ class CognitoOAuthControllerTest {
return code;
}
private static MultivaluedHashMap<String, String> withVerifier(MultivaluedHashMap<String, String> form,
String codeVerifier) {
form.add("code_verifier", codeVerifier);
return form;
}
private static MultivaluedHashMap<String, String> validAuthorizationCodeForm(String code) {
return form("grant_type", "authorization_code", "client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI);
}
@@ -247,6 +445,7 @@ class CognitoOAuthControllerTest {
result.setAllowedOAuthFlowsUserPoolClient(true);
result.setAllowedOAuthFlows(List.of("code"));
result.setCallbackURLs(List.of(CALLBACK_URI));
result.setSupportedIdentityProviders(List.of("COGNITO"));
return result;
}
@@ -257,8 +456,12 @@ class CognitoOAuthControllerTest {
}
private static CognitoUser user() {
return user("federated-user");
}
private static CognitoUser user(String username) {
CognitoUser result = new CognitoUser();
result.setUsername("federated-user");
result.setUsername(username);
result.setUserPoolId(POOL_ID);
return result;
}