mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cognito): scope OAuth tokens to the requested scopes (#4771)
* fix(cognito): scope OAuth tokens to the requested scopes * fix(cognito): require the admin scope on access-token operations * fix(cognito): bind an authorization code to the scopes granted at authorize * fix(cognito): keep the provider's requested scopes apart from Cognito's grant
This commit is contained in:
1 parent
c60da16c54
commit
f1d718cae2
11 files changed
+642
-115
No files matched your search
+2
-2
@@ -137,7 +137,7 @@ class CognitoFederationServiceTest {
|
||||
|
||||
String redirect = federationService.beginAuthorization(
|
||||
pool.getId(), "cognito-client", "https://application.example.test/callback",
|
||||
List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state", null);
|
||||
List.of("openid"), List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state", null);
|
||||
|
||||
CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(queryValue(redirect, "state")).orElseThrow();
|
||||
assertEquals("relying-party-state", transaction.relyingPartyState());
|
||||
@@ -149,7 +149,7 @@ class CognitoFederationServiceTest {
|
||||
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);
|
||||
List.of("openid"), List.of("openid"), "nonce-value", "ExampleOidc", null, challenge);
|
||||
|
||||
String authorizationCode = federationService.completeAuthorization(queryValue(redirect, "state"), "provider-code");
|
||||
|
||||
|
||||
+127
-5
@@ -34,6 +34,7 @@ import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
@@ -854,9 +855,9 @@ class CognitoLambdaTriggersTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Nothing checks an authorization request's scopes against the client's AllowedOAuthScopes when the
|
||||
* code is issued, so the stored code can name a scope the client may not use. A V2 trigger may grant
|
||||
* claims or scopes from what it is told was requested, so it must never be told about one.
|
||||
* The authorize endpoint refuses a scope the client may not use, but a client's AllowedOAuthScopes
|
||||
* can change before its code is redeemed. A V2 trigger may grant claims or scopes from what it is
|
||||
* told was requested, so it must never be told about one the client no longer allows.
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -914,7 +915,7 @@ class CognitoLambdaTriggersTest {
|
||||
void redemptionKeepsTheRequestNonceOverATriggerThatTriesToChangeIt() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createClient(pool);
|
||||
UserPoolClient client = createOAuthClient(pool, List.of("openid"));
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("claimsOverrideDetails", Map.of(
|
||||
@@ -940,7 +941,7 @@ class CognitoLambdaTriggersTest {
|
||||
void redemptionMintsTokensWhenNoPreTokenGenerationTriggerIsConfigured() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of());
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createClient(pool);
|
||||
UserPoolClient client = createOAuthClient(pool, List.of("openid"));
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
|
||||
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client,
|
||||
@@ -960,6 +961,127 @@ class CognitoLambdaTriggersTest {
|
||||
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS grants every scope the client allows to a request that names none, and that grant is what
|
||||
* the trigger is told and what the access token carries.
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void aRequestWithoutScopesIsGrantedEveryAllowedScope() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email", "aws.cognito.signin.user.admin"));
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
ArgumentCaptor<byte[]> payloadCap = ArgumentCaptor.forClass(byte[].class);
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any()))
|
||||
.thenReturn(ok(Map.of()));
|
||||
|
||||
List<String> granted = CognitoService.grantedScopes(client, List.of());
|
||||
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, granted);
|
||||
|
||||
assertEquals(List.of("openid", "email", "aws.cognito.signin.user.admin"), granted);
|
||||
Map<String, Object> event;
|
||||
Map<String, Object> accessClaims;
|
||||
try {
|
||||
event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {});
|
||||
accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
assertEquals(granted, ((Map<String, Object>) event.get("request")).get("scopes"));
|
||||
assertEquals(Set.copyOf(granted), Set.of(((String) accessClaims.get("scope")).split(" ")));
|
||||
assertNotNull(auth.get("IdToken"));
|
||||
}
|
||||
|
||||
/** Redemption issues the code's grant and never widens it, even when that grant is empty. */
|
||||
@Test
|
||||
void redemptionNeverWidensTheCodesGrant() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of());
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email"));
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
|
||||
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of());
|
||||
|
||||
Map<String, Object> accessClaims;
|
||||
try {
|
||||
accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
assertFalse(accessClaims.containsKey("scope"), "an empty grant stays empty: " + accessClaims);
|
||||
assertFalse(auth.containsKey("IdToken"));
|
||||
}
|
||||
|
||||
/** A V2 trigger that suppresses every scope of the grant leaves no scope claim. */
|
||||
@Test
|
||||
void preTokenGenerationV2SuppressingTheWholeCodeGrantRemovesTheScopeClaim() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email"));
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of(
|
||||
"accessTokenGeneration", Map.of("scopesToSuppress", List.of("email"))))));
|
||||
|
||||
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"));
|
||||
|
||||
Map<String, Object> accessClaims;
|
||||
try {
|
||||
accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
assertFalse(accessClaims.containsKey("scope"), "suppressing the only granted scope leaves none: " + accessClaims);
|
||||
}
|
||||
|
||||
/** Only a grant with {@code openid} gets an ID token, and the access token carries just the grant. */
|
||||
@Test
|
||||
void redemptionWithoutOpenidMintsNoIdToken() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of());
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email"));
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
|
||||
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("email"));
|
||||
|
||||
Map<String, Object> accessClaims;
|
||||
try {
|
||||
accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
assertEquals("email", accessClaims.get("scope"));
|
||||
assertFalse(auth.containsKey("IdToken"), "no openid, no ID token: " + auth.keySet());
|
||||
assertNotNull(auth.get("RefreshToken"));
|
||||
}
|
||||
|
||||
/** V2 scope changes apply on top of the grant, not on top of a fixed default scope. */
|
||||
@Test
|
||||
void preTokenGenerationV2ScopeChangesApplyOnTopOfTheCodeGrant() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email", "profile"));
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of(
|
||||
"accessTokenGeneration", Map.of(
|
||||
"scopesToSuppress", List.of("email"),
|
||||
"scopesToAdd", List.of("aws.cognito.signin.user.admin"))))));
|
||||
|
||||
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null,
|
||||
List.of("openid", "email"));
|
||||
|
||||
Map<String, Object> accessClaims;
|
||||
try {
|
||||
accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
assertEquals(Set.of("openid", "aws.cognito.signin.user.admin"),
|
||||
Set.of(((String) accessClaims.get("scope")).split(" ")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void managedLoginPreAuthenticationErrorBlocksSignIn() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of(
|
||||
|
||||
+239
-45
@@ -16,9 +16,11 @@ import org.mockito.ArgumentCaptor;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -39,6 +41,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -60,6 +64,7 @@ class CognitoManagedLoginIntegrationTest {
|
||||
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=\"([^\"]*)\">");
|
||||
private static final String PRE_TOKEN_GENERATION_ARN = "arn:aws:lambda:::pre-token-generation";
|
||||
private static final String ADMIN_SCOPE = "aws.cognito.signin.user.admin";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** Only the PreTokenGeneration trigger is configured on any pool here, so nothing else invokes it. */
|
||||
@@ -236,52 +241,196 @@ class CognitoManagedLoginIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* The authorize endpoint stores the scopes the request named without checking them against the
|
||||
* client's AllowedOAuthScopes, so a request can carry one the client may not use. A V2 trigger can
|
||||
* grant claims or scopes from what it is told was requested, so an unallowed scope must not reach it.
|
||||
* AWS refuses a scope outside the client's AllowedOAuthScopes at the authorize endpoint, before
|
||||
* the sign-in form and even for a browser that is already signed in, by redirecting to the
|
||||
* callback with {@code error=invalid_request} and {@code error_description=invalid_scope}. No
|
||||
* code is issued, so a V2 trigger never hears of the scope.
|
||||
*/
|
||||
@Test
|
||||
void aScopeTheClientIsNotAllowedDoesNotReachTheTrigger() throws Exception {
|
||||
Pool pool = newPoolWithPreTokenGenerationTrigger();
|
||||
Map<String, String> query = authorizeRequest(pool.clientId());
|
||||
query.put("scope", "openid email admin/superuser");
|
||||
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
|
||||
when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), event.capture(), any()))
|
||||
.thenReturn(triggerResponse(Map.of()));
|
||||
void aScopeTheClientIsNotAllowedIsRedirectedToTheCallbackAsInvalidScope() throws Exception {
|
||||
Pool withoutAdmin = newPoolWithPreTokenGenerationTrigger();
|
||||
Pool withAdmin = newPool(List.of("openid", "email", ADMIN_SCOPE));
|
||||
String session = signIn(null, withoutAdmin, authorizeRequest(withoutAdmin.clientId())).getCookie("cognito");
|
||||
Map<String, Pool> requests = new LinkedHashMap<>();
|
||||
requests.put("openid " + ADMIN_SCOPE, withoutAdmin);
|
||||
requests.put("openid email admin/superuser", withoutAdmin);
|
||||
requests.put("openid phone", withAdmin);
|
||||
|
||||
Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER);
|
||||
for (Map.Entry<String, Pool> request : requests.entrySet()) {
|
||||
Map<String, String> query = withField(authorizeRequest(request.getValue().clientId()), "scope",
|
||||
request.getKey());
|
||||
for (String sessionCookie : new String[] {null, session}) {
|
||||
String location = browserGet(null, "/cognito-idp/oauth2/authorize", query, sessionCookie)
|
||||
.then().statusCode(302).extract().header("Location");
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
assertEquals(List.of("openid", "email"),
|
||||
MAPPER.convertValue(MAPPER.readTree(event.getValue()).path("request").path("scopes"), List.class),
|
||||
"admin/superuser is not in the client's AllowedOAuthScopes, so the trigger never sees it");
|
||||
assertTrue(location.startsWith(CALLBACK + "?"), location);
|
||||
assertEquals(Map.of("error", "invalid_request", "error_description", "invalid_scope",
|
||||
"state", "client-state"), queryOf(location), "scope=" + request.getKey());
|
||||
}
|
||||
}
|
||||
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
|
||||
}
|
||||
|
||||
/** AWS: the requested scopes, or every scope the client allows when the request names none. */
|
||||
@Test
|
||||
void theAccessTokenCarriesTheRequestedScopesOrEveryAllowedScopeWhenNoneAreRequested() throws Exception {
|
||||
Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));
|
||||
Map<String, Set<String>> expected = new LinkedHashMap<>();
|
||||
expected.put("openid email", Set.of("openid", "email"));
|
||||
expected.put("openid email " + ADMIN_SCOPE, Set.of("openid", "email", ADMIN_SCOPE));
|
||||
expected.put(null, Set.of("openid", "email", ADMIN_SCOPE));
|
||||
|
||||
for (Map.Entry<String, Set<String>> request : expected.entrySet()) {
|
||||
Map<String, String> query = withField(authorizeRequest(pool.clientId()), "scope", request.getKey());
|
||||
|
||||
Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER);
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
assertEquals(request.getValue(), scopes(tokens.path("access_token")), "scope=" + request.getKey());
|
||||
assertEquals(Set.of("access_token", "id_token", "refresh_token", "expires_in", "token_type"),
|
||||
fieldNames(tokens), "scope=" + request.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
/** AWS issues an ID token only for a request with {@code openid}. */
|
||||
@Test
|
||||
void withoutOpenidTheTokenEndpointIssuesNoIdToken() throws Exception {
|
||||
Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));
|
||||
|
||||
for (String requested : new String[] {"email", ADMIN_SCOPE}) {
|
||||
Map<String, String> query = withField(authorizeRequest(pool.clientId()), "scope", requested);
|
||||
|
||||
Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER);
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
assertEquals(Set.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(tokens),
|
||||
"scope=" + requested);
|
||||
assertEquals(Set.of(requested), scopes(tokens.path("access_token")));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GetUserAuthFactors needs {@code aws.cognito.signin.user.admin} in the access token's scope.
|
||||
* Floci stamps that scope on every code-grant access token whatever the request asked for, so a
|
||||
* V2 trigger reshapes this token's scope to the {@code openid email} the request named.
|
||||
* A code carries the scopes granted when it was issued. A request without a scope is granted
|
||||
* every scope the client allows then, so a scope the client is allowed only afterwards is not
|
||||
* added when the code is redeemed.
|
||||
*/
|
||||
@Test
|
||||
void codeGrantAccessTokenWithoutTheAdminScopeCannotReadAuthFactors() throws Exception {
|
||||
String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of(
|
||||
"scopesToAdd", List.of("openid", "email"),
|
||||
"scopesToSuppress", List.of("aws.cognito.signin.user.admin")));
|
||||
assertEquals("openid email", jwtPayload(accessToken).path("scope").asText());
|
||||
void aScopeTheClientIsAllowedAfterTheCodeWasIssuedIsNotAdded() throws Exception {
|
||||
Pool pool = newPool();
|
||||
String code = code(signIn(null, pool, withField(authorizeRequest(pool.clientId()), "scope", null)));
|
||||
allowScopes(pool, List.of("openid", "email", ADMIN_SCOPE));
|
||||
|
||||
cognitoAction("GetUserAuthFactors", """
|
||||
{"AccessToken":"%s"}
|
||||
""".formatted(accessToken))
|
||||
Response tokens = redeem(null, pool.clientId(), code, VERIFIER);
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
assertEquals(Set.of("openid", "email"), scopes(tokens.path("access_token")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A scope the client no longer allows is dropped from a code issued before the change, here
|
||||
* one issued to a browser that was already signed in.
|
||||
*/
|
||||
@Test
|
||||
void aScopeTheClientNoLongerAllowsIsDroppedFromAnIssuedCode() throws Exception {
|
||||
Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));
|
||||
String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito");
|
||||
String code = code(browserGet(null, "/cognito-idp/oauth2/authorize",
|
||||
withField(authorizeRequest(pool.clientId()), "scope", null), session));
|
||||
allowScopes(pool, List.of("openid", ADMIN_SCOPE));
|
||||
|
||||
Response tokens = redeem(null, pool.clientId(), code, VERIFIER);
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
assertEquals(Set.of("openid", ADMIN_SCOPE), scopes(tokens.path("access_token")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Floci lets an OAuth client allow no scopes. Its code grant has no scope claim and no ID token,
|
||||
* and none of the user's own operations accepts a token without a scope.
|
||||
*/
|
||||
@Test
|
||||
void aCodeGrantOfAClientThatAllowsNoScopesCannotCallTheUsersOwnOperations() throws Exception {
|
||||
Pool pool = newPool(List.of());
|
||||
|
||||
Response tokens = redeem(null, pool.clientId(),
|
||||
code(signIn(null, pool, withField(authorizeRequest(pool.clientId()), "scope", null))), VERIFIER);
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
assertEquals(Set.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(tokens));
|
||||
String accessToken = tokens.path("access_token");
|
||||
assertFalse(jwtPayload(accessToken).has("scope"));
|
||||
cognitoAction("GetUser", "{\"AccessToken\":\"%s\"}".formatted(accessToken))
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Access Token does not have required scopes"));
|
||||
}
|
||||
|
||||
/** A trigger that suppresses the token's only scope leaves no scope claim, which grants nothing. */
|
||||
/**
|
||||
* {@code aws.cognito.signin.user.admin} is what lets an access token call the user's own API
|
||||
* operations. A code-grant token requested without it is refused with AWS's message, and the
|
||||
* refused calls change nothing.
|
||||
*/
|
||||
@Test
|
||||
void aCodeGrantTokenWithoutTheAdminScopeCannotCallTheUsersOwnOperations() throws Exception {
|
||||
Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));
|
||||
String withoutAdmin = accessToken(pool, "openid email");
|
||||
String withAdmin = accessToken(pool, "openid email " + ADMIN_SCOPE);
|
||||
Map<String, String> requests = new LinkedHashMap<>();
|
||||
requests.put("GetUser", "{\"AccessToken\":\"%s\"}");
|
||||
requests.put("GetUserAuthFactors", "{\"AccessToken\":\"%s\"}");
|
||||
requests.put("UpdateUserAttributes",
|
||||
"{\"AccessToken\":\"%s\",\"UserAttributes\":[{\"Name\":\"given_name\",\"Value\":\"Changed\"}]}");
|
||||
requests.put("DeleteUserAttributes", "{\"AccessToken\":\"%s\",\"UserAttributeNames\":[\"email\"]}");
|
||||
requests.put("ChangePassword",
|
||||
"{\"AccessToken\":\"%s\",\"PreviousPassword\":\"" + PASSWORD + "\",\"ProposedPassword\":\"Other1234!\"}");
|
||||
requests.put("GetUserAttributeVerificationCode", "{\"AccessToken\":\"%s\",\"AttributeName\":\"email\"}");
|
||||
requests.put("VerifyUserAttribute", "{\"AccessToken\":\"%s\",\"AttributeName\":\"email\",\"Code\":\"123456\"}");
|
||||
requests.put("SetUserMFAPreference", "{\"AccessToken\":\"%s\",\"EmailMfaSettings\":{\"Enabled\":true}}");
|
||||
requests.put("AssociateSoftwareToken", "{\"AccessToken\":\"%s\"}");
|
||||
requests.put("VerifySoftwareToken", "{\"AccessToken\":\"%s\",\"UserCode\":\"123456\"}");
|
||||
requests.put("GlobalSignOut", "{\"AccessToken\":\"%s\"}");
|
||||
|
||||
for (Map.Entry<String, String> request : requests.entrySet()) {
|
||||
cognitoAction(request.getKey(), request.getValue().formatted(withoutAdmin))
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Access Token does not have required scopes"));
|
||||
}
|
||||
|
||||
JsonNode user = cognitoJson("GetUser", "{\"AccessToken\":\"%s\"}".formatted(withAdmin));
|
||||
assertEquals(pool.username(), user.path("Username").asText(), "the user was not signed out");
|
||||
assertTrue(user.path("UserAttributes").toString().contains("\"email\""), user.toString());
|
||||
assertFalse(user.path("UserAttributes").toString().contains("given_name"), user.toString());
|
||||
code(signIn(null, pool, authorizeRequest(pool.clientId())));
|
||||
}
|
||||
|
||||
/**
|
||||
* A V2 trigger's {@code scopesToAdd} and {@code scopesToSuppress} apply on top of the scopes the
|
||||
* request was granted, so a trigger can still give a token the scope that API calls need.
|
||||
*/
|
||||
@Test
|
||||
void preTokenGenerationV2ScopeChangesApplyOnTopOfTheGrantedScopes() throws Exception {
|
||||
Pool pool = newPoolWithPreTokenGenerationTrigger();
|
||||
when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), any(byte[].class), any()))
|
||||
.thenReturn(triggerResponse(Map.of("claimsAndScopeOverrideDetails", Map.of(
|
||||
"accessTokenGeneration", Map.of(
|
||||
"scopesToSuppress", List.of("email"),
|
||||
"scopesToAdd", List.of(ADMIN_SCOPE))))));
|
||||
|
||||
Response tokens = redeem(null, pool.clientId(),
|
||||
code(signIn(null, pool, authorizeRequest(pool.clientId()))), VERIFIER);
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
String accessToken = tokens.path("access_token");
|
||||
assertEquals(Set.of("openid", ADMIN_SCOPE), scopes(accessToken));
|
||||
cognitoAction("GetUser", "{\"AccessToken\":\"%s\"}".formatted(accessToken)).then().statusCode(200);
|
||||
}
|
||||
|
||||
/** A trigger that suppresses every scope the request was granted leaves no scope claim, which grants nothing. */
|
||||
@Test
|
||||
void codeGrantAccessTokenWithEveryScopeSuppressedCannotReadAuthFactors() throws Exception {
|
||||
String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of(
|
||||
"scopesToSuppress", List.of("aws.cognito.signin.user.admin")));
|
||||
"scopesToSuppress", List.of("openid", "email")));
|
||||
assertFalse(jwtPayload(accessToken).has("scope"));
|
||||
|
||||
cognitoAction("GetUserAuthFactors", """
|
||||
@@ -295,7 +444,7 @@ class CognitoManagedLoginIntegrationTest {
|
||||
@Test
|
||||
void codeGrantAccessTokenWithEveryScopeSuppressedCannotVerifyAnAttribute() throws Exception {
|
||||
String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of(
|
||||
"scopesToSuppress", List.of("aws.cognito.signin.user.admin")));
|
||||
"scopesToSuppress", List.of("openid", "email")));
|
||||
assertFalse(jwtPayload(accessToken).has("scope"));
|
||||
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
@@ -308,15 +457,8 @@ class CognitoManagedLoginIntegrationTest {
|
||||
|
||||
@Test
|
||||
void codeGrantAccessTokenWithTheAdminScopeReadsAuthFactors() throws Exception {
|
||||
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginAdminScopePool\"}")
|
||||
.path("UserPool").path("Id").asText();
|
||||
Pool pool = withUser(poolId,
|
||||
codeClient(poolId, "\"openid\",\"email\",\"aws.cognito.signin.user.admin\""),
|
||||
"user-" + System.nanoTime());
|
||||
Map<String, String> query = authorizeRequest(pool.clientId());
|
||||
query.put("scope", "openid email aws.cognito.signin.user.admin");
|
||||
String accessToken = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER)
|
||||
.path("access_token");
|
||||
Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));
|
||||
String accessToken = accessToken(pool, "openid email " + ADMIN_SCOPE);
|
||||
|
||||
cognitoAction("GetUserAuthFactors", """
|
||||
{"AccessToken":"%s"}
|
||||
@@ -471,7 +613,7 @@ class CognitoManagedLoginIntegrationTest {
|
||||
""".formatted(poolId));
|
||||
String clientId = cognitoJson("CreateUserPoolClient", """
|
||||
{"UserPoolId":"%s","ClientName":"federated-only","AllowedOAuthFlowsUserPoolClient":true,
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid"],"CallbackURLs":["%s"],
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],
|
||||
"SupportedIdentityProviders":["ExampleOidc"]}
|
||||
""".formatted(poolId, CALLBACK)).path("UserPoolClient").path("ClientId").asText();
|
||||
Map<String, String> query = authorizeRequest(clientId);
|
||||
@@ -562,6 +704,26 @@ class CognitoManagedLoginIntegrationTest {
|
||||
.then().statusCode(400).body("error", equalTo("invalid_client"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void customDomainScopesTheCodeGrantTheSameWay() throws Exception {
|
||||
Pool pool = newPool(List.of("openid", "email", ADMIN_SCOPE));
|
||||
String domain = "managed-login-scope-" + System.nanoTime() + ".teos.localhost.floci.io";
|
||||
cognitoJson("CreateUserPoolDomain", customDomain(domain, pool.poolId(), requestCertificate(domain)));
|
||||
|
||||
Response tokens = redeem(domain, pool.clientId(),
|
||||
code(signIn(domain, pool, withField(authorizeRequest(pool.clientId()), "scope", "email"))), VERIFIER);
|
||||
|
||||
tokens.then().statusCode(200);
|
||||
assertEquals(Set.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(tokens));
|
||||
assertEquals(Set.of("email"), scopes(tokens.path("access_token")));
|
||||
String refused = browserGet(domain, "/oauth2/authorize",
|
||||
withField(authorizeRequest(pool.clientId()), "scope", "openid phone"), null)
|
||||
.then().statusCode(302).extract().header("Location");
|
||||
assertTrue(refused.startsWith(CALLBACK + "?"), refused);
|
||||
assertEquals(Map.of("error", "invalid_request", "error_description", "invalid_scope", "state", "client-state"),
|
||||
queryOf(refused));
|
||||
}
|
||||
|
||||
/** Without a custom domain Host, /login stays S3's path-style bucket route. */
|
||||
@Test
|
||||
void loginOnFlocisOwnHostIsNotManagedLogin() {
|
||||
@@ -585,8 +747,12 @@ class CognitoManagedLoginIntegrationTest {
|
||||
}
|
||||
|
||||
private static Pool newPool() throws Exception {
|
||||
return newPool(List.of("openid", "email"));
|
||||
}
|
||||
|
||||
private static Pool newPool(List<String> allowedScopes) throws Exception {
|
||||
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginPool\"}").path("UserPool").path("Id").asText();
|
||||
return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime());
|
||||
return withUser(poolId, codeClient(poolId, allowedScopes), "user-" + System.nanoTime());
|
||||
}
|
||||
|
||||
private static Pool newPoolWithPreTokenGenerationTrigger() throws Exception {
|
||||
@@ -615,16 +781,26 @@ class CognitoManagedLoginIntegrationTest {
|
||||
}
|
||||
|
||||
private static String codeClient(String poolId) throws Exception {
|
||||
return codeClient(poolId, "\"openid\",\"email\"");
|
||||
return codeClient(poolId, List.of("openid", "email"));
|
||||
}
|
||||
|
||||
/** {@code allowedScopes} is the body of the AllowedOAuthScopes JSON array. */
|
||||
private static String codeClient(String poolId, String allowedScopes) throws Exception {
|
||||
private static String codeClient(String poolId, List<String> allowedScopes) throws Exception {
|
||||
return cognitoJson("CreateUserPoolClient", """
|
||||
{"UserPoolId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true,
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":[%s],"CallbackURLs":["%s"],
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":%s,"CallbackURLs":["%s"],
|
||||
"LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]}
|
||||
""".formatted(poolId, allowedScopes, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText();
|
||||
""".formatted(poolId, MAPPER.writeValueAsString(allowedScopes), CALLBACK, SIGNED_OUT))
|
||||
.path("UserPoolClient").path("ClientId").asText();
|
||||
}
|
||||
|
||||
/** Replaces the client's AllowedOAuthScopes, sending the rest of its OAuth configuration unchanged. */
|
||||
private static void allowScopes(Pool pool, List<String> allowedScopes) throws Exception {
|
||||
cognitoJson("UpdateUserPoolClient", """
|
||||
{"UserPoolId":"%s","ClientId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true,
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":%s,"CallbackURLs":["%s"],
|
||||
"LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]}
|
||||
""".formatted(pool.poolId(), pool.clientId(), MAPPER.writeValueAsString(allowedScopes), CALLBACK,
|
||||
SIGNED_OUT));
|
||||
}
|
||||
|
||||
private static Pool withUser(String poolId, String clientId, String username) throws Exception {
|
||||
@@ -723,6 +899,13 @@ class CognitoManagedLoginIntegrationTest {
|
||||
return request.when().post(host == null ? "/cognito-idp/oauth2/token" : "/oauth2/token");
|
||||
}
|
||||
|
||||
/** An access token for the pool's user from a fresh sign-in that requested {@code scope}. */
|
||||
private static String accessToken(Pool pool, String scope) {
|
||||
Map<String, String> query = withField(authorizeRequest(pool.clientId()), "scope", scope);
|
||||
return redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER)
|
||||
.then().statusCode(200).extract().path("access_token");
|
||||
}
|
||||
|
||||
private static String code(Response callbackRedirect) {
|
||||
callbackRedirect.then().statusCode(302);
|
||||
String code = queryOf(callbackRedirect.getHeader("Location")).get("code");
|
||||
@@ -732,6 +915,17 @@ class CognitoManagedLoginIntegrationTest {
|
||||
|
||||
// ──────────────────────────── Parsing ────────────────────────────
|
||||
|
||||
/** The access token's scopes, as a set: AWS does not promise their order. */
|
||||
private static Set<String> scopes(String accessToken) throws Exception {
|
||||
return Set.of(jwtPayload(accessToken).path("scope").asText().split(" "));
|
||||
}
|
||||
|
||||
private static Set<String> fieldNames(Response tokens) throws Exception {
|
||||
Set<String> names = new HashSet<>();
|
||||
MAPPER.readTree(tokens.asString()).fieldNames().forEachRemaining(names::add);
|
||||
return names;
|
||||
}
|
||||
|
||||
/** 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")) {
|
||||
|
||||
+117
-3
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCod
|
||||
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.IdentityProvider;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
@@ -18,10 +19,13 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -65,8 +69,8 @@ class CognitoOAuthControllerTest {
|
||||
|
||||
@Test
|
||||
void authorizeRedirectsToConfiguredIdentityProvider() {
|
||||
when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), "nonce", "ExampleOidc",
|
||||
" relying-party-state ", RFC_7636_CHALLENGE))
|
||||
when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), List.of("openid"),
|
||||
"nonce", "ExampleOidc", " 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",
|
||||
@@ -156,6 +160,77 @@ class CognitoOAuthControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** AWS redirects an unallowed scope to the callback, in this parameter order, before any provider is involved. */
|
||||
@Test
|
||||
void authorizeRedirectsAScopeTheClientIsNotAllowedToTheCallbackForEitherProvider() {
|
||||
for (String provider : new String[] {null, "COGNITO", "ExampleOidc"}) {
|
||||
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid phone",
|
||||
null, provider, "s1", null, null, null);
|
||||
|
||||
assertEquals(302, response.getStatus());
|
||||
assertEquals(CALLBACK_URI + "?error_description=invalid_scope&state=s1&error=invalid_request",
|
||||
response.getHeaderString("Location"));
|
||||
}
|
||||
Response withoutState = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code",
|
||||
"aws.cognito.signin.user.admin", null, null, null, null, null, null);
|
||||
assertEquals(CALLBACK_URI + "?error_description=invalid_scope&error=invalid_request",
|
||||
withoutState.getHeaderString("Location"));
|
||||
verify(federationService, never()).beginAuthorization(any(), any(), any(), any(), any(), any(), any(), any(),
|
||||
any());
|
||||
}
|
||||
|
||||
/**
|
||||
* Federation asks the provider for what the request named, its {@code authorize_scopes} aside, as
|
||||
* before; the grant governs only Cognito's own code. A request without a scope therefore asks the
|
||||
* provider for none, while its code is granted every scope the client allows.
|
||||
*/
|
||||
@Test
|
||||
void authorizeWithoutAScopeAsksTheProviderForNoneWhileTheCodeGetsEveryAllowedScope() throws Exception {
|
||||
IdentityProvider provider = new IdentityProvider();
|
||||
provider.setUserPoolId(POOL_ID);
|
||||
provider.setProviderName("ExampleOidc");
|
||||
provider.setProviderType("OIDC");
|
||||
provider.setProviderDetails(Map.of("authorize_url", "https://provider.example.test/authorize",
|
||||
"client_id", "provider-client"));
|
||||
when(cognitoService.describeIdentityProvider(POOL_ID, "ExampleOidc")).thenReturn(provider);
|
||||
when(cognitoService.getIdentityProviderCallbackEndpoint(POOL_ID))
|
||||
.thenReturn("http://localhost:4566/cognito-idp/oauth2/idpresponse");
|
||||
when(cognitoService.provisionFederatedUser(eq(POOL_ID), eq(provider), eq("provider-subject"), any(), any()))
|
||||
.thenReturn(user());
|
||||
CognitoOidcClient oidcClient = mock(CognitoOidcClient.class);
|
||||
when(oidcClient.exchangeCode(eq(provider), eq("provider-code"), any()))
|
||||
.thenReturn(objectMapper.readTree("{\"access_token\":\"provider-access-token\"}"));
|
||||
when(oidcClient.fetchClaims(provider, "provider-access-token"))
|
||||
.thenReturn(objectMapper.readTree("{\"sub\":\"provider-subject\"}"));
|
||||
CognitoOAuthController federating = new CognitoOAuthController(cognitoService, objectMapper,
|
||||
new CognitoFederationService(cognitoService, stateStore, oidcClient, CLOCK), stateStore,
|
||||
new CognitoManagedLoginService(cognitoService, stateStore, CLOCK));
|
||||
|
||||
String toProvider = federating.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
|
||||
"ExampleOidc", "s1", null, null, null).getHeaderString("Location");
|
||||
String toCallback = federating.idpResponse(requestContext(null), queryParameter(toProvider, "state"),
|
||||
"provider-code", null, null).getHeaderString("Location");
|
||||
|
||||
assertTrue(toProvider.startsWith("https://provider.example.test/authorize?"), toProvider);
|
||||
assertEquals("", queryParameter(toProvider, "scope"));
|
||||
assertEquals(List.of("openid", "email"), storedCode(toCallback).scopes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeWithASessionBindsTheCodeToTheScopesGrantedThen() {
|
||||
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)));
|
||||
|
||||
String withoutScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
|
||||
null, null, null, null, sessionId).getHeaderString("Location");
|
||||
String withScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "email email",
|
||||
null, null, null, null, null, sessionId).getHeaderString("Location");
|
||||
|
||||
assertEquals(List.of("openid", "email"), storedCode(withoutScope).scopes());
|
||||
assertEquals(List.of("email"), storedCode(withScope).scopes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeWithASessionOfThePoolRedirectsWithACodeCarryingTheNonceAndChallenge() {
|
||||
when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user"));
|
||||
@@ -259,6 +334,21 @@ class CognitoOAuthControllerTest {
|
||||
assertOAuthError(replay, "invalid_grant");
|
||||
}
|
||||
|
||||
/** AWS leaves {@code id_token} out of the response, rather than sending it as null, without openid. */
|
||||
@Test
|
||||
void tokenLeavesTheIdTokenOutWhenNoneWasMinted() {
|
||||
String code = putAuthorizationCode();
|
||||
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any()))
|
||||
.thenReturn(Map.of("AccessToken", "access-token", "RefreshToken", "refresh-token",
|
||||
"ExpiresIn", 3600, "TokenType", "Bearer"));
|
||||
|
||||
Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
JsonNode body = (JsonNode) response.getEntity();
|
||||
assertEquals(List.of("access_token", "refresh_token", "expires_in", "token_type"), fieldNames(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenRejectsAuthorizationCodeForAnotherClient() {
|
||||
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
|
||||
@@ -421,7 +511,7 @@ class CognitoOAuthControllerTest {
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(cognitoService).generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client),
|
||||
any(), scopes.capture());
|
||||
assertEquals(List.of("openid"), scopes.getValue(), "the code's requested scopes reach the trigger");
|
||||
assertEquals(List.of("openid"), scopes.getValue(), "the code's granted scopes reach the trigger");
|
||||
verify(cognitoService, never()).generateAuthResult(any(CognitoUser.class), any(UserPool.class), any(), any());
|
||||
}
|
||||
|
||||
@@ -466,6 +556,7 @@ class CognitoOAuthControllerTest {
|
||||
result.setUserPoolId(POOL_ID);
|
||||
result.setAllowedOAuthFlowsUserPoolClient(true);
|
||||
result.setAllowedOAuthFlows(List.of("code"));
|
||||
result.setAllowedOAuthScopes(List.of("openid", "email"));
|
||||
result.setCallbackURLs(List.of(CALLBACK_URI));
|
||||
result.setSupportedIdentityProviders(List.of("COGNITO"));
|
||||
return result;
|
||||
@@ -507,6 +598,29 @@ class CognitoOAuthControllerTest {
|
||||
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** The code a redirect to the callback carries, as the state store holds it. */
|
||||
private CognitoAuthorizationCode storedCode(String location) {
|
||||
assertTrue(location.startsWith(CALLBACK_URI + "?code="), location);
|
||||
return stateStore.findAuthorizationCode(queryParameter(location, "code")).orElseThrow();
|
||||
}
|
||||
|
||||
/** A query parameter of {@code location}, decoded, or null when it has none of that name. */
|
||||
private static String queryParameter(String location, String name) {
|
||||
for (String pair : URI.create(location).getRawQuery().split("&")) {
|
||||
String[] parts = pair.split("=", 2);
|
||||
if (parts[0].equals(name)) {
|
||||
return parts.length == 2 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : "";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<String> fieldNames(JsonNode body) {
|
||||
List<String> names = new ArrayList<>();
|
||||
body.fieldNames().forEachRemaining(names::add);
|
||||
return names;
|
||||
}
|
||||
|
||||
private void assertOAuthError(Response response, String error) {
|
||||
assertEquals(400, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
|
||||
Reference in new issue
Block a user