mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cognito): implement federated sign-in (#3748)
* feat(cognito): add federation transaction stores * fix(cognito): atomically consume federation state * feat(cognito): support OIDC provider exchange * fix(cognito): validate OIDC federation providers * fix(cognito): validate OIDC endpoint schemes * feat(cognito): add federated oauth routes * fix(cognito): preserve oauth state and codes * feat(cognito): implement federated sign-in coverage * chore: remove internal task report * fix(cognito): use Cognito IdP callback for federation * fix(cognito): use provider callback for token exchange
This commit is contained in:
1 parent
d0d787d8a3
commit
f004aeaad5
17 files changed
+1952
-27
No files matched your search
+31
-7
@@ -98,7 +98,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void unsupportedGrantTypeIsRefused() {
|
||||
void authorizationCodeGrantRequiresItsMandatoryParameters() {
|
||||
given()
|
||||
.header("Host", DOMAIN)
|
||||
.header("Authorization", basic(clientA, secretA))
|
||||
@@ -108,7 +108,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
|
||||
.post("/oauth2/token")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("error", equalTo("unsupported_grant_type"));
|
||||
.body("error", equalTo("invalid_request"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -175,11 +175,35 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
|
||||
.header("WWW-Authenticate", startsWith("Bearer error=\"invalid_token\""));
|
||||
}
|
||||
|
||||
/** Floci has no hosted UI: the other endpoints AWS serves on a domain are absent, not stubbed. */
|
||||
/** Floci has no hosted UI revoke endpoint. */
|
||||
@Test
|
||||
@Order(9)
|
||||
void otherHostedUiPathsAreNotServed() {
|
||||
for (String path : List.of("/oauth2/authorize", "/oauth2/revoke", "/oauth2/idpresponse")) {
|
||||
void authorizeRouteIsServedOnCustomDomain() {
|
||||
given()
|
||||
.header("Host", DOMAIN)
|
||||
.when()
|
||||
.get("/oauth2/authorize")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("error", equalTo("unsupported_response_type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void idpResponseRouteIsServedOnCustomDomain() {
|
||||
given()
|
||||
.header("Host", DOMAIN)
|
||||
.when()
|
||||
.get("/oauth2/idpresponse")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("error", equalTo("invalid_request"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void revokeEndpointIsNotServed() {
|
||||
for (String path : List.of("/oauth2/revoke")) {
|
||||
given()
|
||||
.header("Host", DOMAIN)
|
||||
.when()
|
||||
@@ -191,7 +215,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
|
||||
|
||||
/** A prefix domain's hostname resolves to AWS, so Floci never routes by it. */
|
||||
@Test
|
||||
@Order(10)
|
||||
@Order(12)
|
||||
void prefixDomainHostIsNotRouted() throws Exception {
|
||||
String prefix = "routing-prefix-" + System.nanoTime();
|
||||
cognitoJson("CreateUserPoolDomain", """
|
||||
@@ -211,7 +235,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
|
||||
* requests on many threads must never let one request's pin decide another's answer.
|
||||
*/
|
||||
@Test
|
||||
@Order(11)
|
||||
@Order(13)
|
||||
void concurrentRequestsKeepTheirOwnPinnedPool() throws Exception {
|
||||
ExecutorService pool = Executors.newFixedThreadPool(8);
|
||||
try {
|
||||
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain;
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate;
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
@QuarkusTest
|
||||
class CognitoFederatedSignInIntegrationTest {
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
private static final String DOMAIN = "federated-" + System.nanoTime() + ".teos.localhost.floci.io";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void oidcProviderReceivesAuthorizationRequestAndDiscoveryAdvertisesCodeFlow() throws Exception {
|
||||
try (MockOidcProvider provider = new MockOidcProvider()) {
|
||||
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"FederatedPool\"}")
|
||||
.path("UserPool").path("Id").asText();
|
||||
JsonNode client = cognitoJson("CreateUserPoolClient", """
|
||||
{"UserPoolId":"%s","ClientName":"federated-client","AllowedOAuthFlowsUserPoolClient":true,
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid"],"CallbackURLs":["https://client.example/callback"]}
|
||||
""".formatted(poolId)).path("UserPoolClient");
|
||||
String clientId = client.path("ClientId").asText();
|
||||
cognitoJson("CreateIdentityProvider", """
|
||||
{"UserPoolId":"%s","ProviderName":"LocalOidc","ProviderType":"OIDC",
|
||||
"ProviderDetails":{"authorize_url":"%s/authorize","token_url":"%s/token","attributes_url":"%s/userinfo","client_id":"provider-client","client_secret":"provider-secret"},
|
||||
"AttributeMapping":{"email":"email","username":"sub"}}
|
||||
""".formatted(poolId, provider.baseUrl(), provider.baseUrl(), provider.baseUrl()));
|
||||
cognitoJson("CreateUserPoolDomain", customDomain(DOMAIN, poolId, requestCertificate(DOMAIN)));
|
||||
|
||||
Response authorizeResponse = given()
|
||||
.redirects().follow(false)
|
||||
.header("Host", DOMAIN)
|
||||
.queryParam("client_id", clientId)
|
||||
.queryParam("redirect_uri", "https://client.example/callback")
|
||||
.queryParam("response_type", "code")
|
||||
.queryParam("scope", "openid")
|
||||
.queryParam("identity_provider", "LocalOidc")
|
||||
.queryParam("state", "client-state")
|
||||
.when()
|
||||
.get("/oauth2/authorize")
|
||||
.then().statusCode(302).extract().response();
|
||||
String location = authorizeResponse.getHeader("Location");
|
||||
assertNotNull(location, authorizeResponse.getHeaders().toString());
|
||||
|
||||
assertEquals(provider.baseUrl() + "/authorize", URI.create(location).resolve("/authorize").toString());
|
||||
String providerState = queryParameter(location, "state");
|
||||
assertNotNull(providerState);
|
||||
assertFalse(providerState.equals("client-state"));
|
||||
assertEquals("code", queryParameter(location, "response_type"));
|
||||
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
HttpResponse<Void> providerAuthorizeResponse = httpClient.send(
|
||||
HttpRequest.newBuilder(URI.create(location)).GET().build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
assertEquals(302, providerAuthorizeResponse.statusCode());
|
||||
Map<String, String> providerParameters = provider.authorizationParameters();
|
||||
assertEquals("provider-client", providerParameters.get("client_id"));
|
||||
assertEquals("code", providerParameters.get("response_type"));
|
||||
assertEquals("https://" + DOMAIN + "/oauth2/idpresponse", providerParameters.get("redirect_uri"));
|
||||
assertEquals("openid", providerParameters.get("scope"));
|
||||
|
||||
Response callbackResponse = given()
|
||||
.redirects().follow(false)
|
||||
.header("Host", DOMAIN)
|
||||
.queryParam("state", providerState)
|
||||
.queryParam("code", "provider-code")
|
||||
.when()
|
||||
.get("/oauth2/idpresponse")
|
||||
.then().statusCode(302).extract().response();
|
||||
String callbackLocation = callbackResponse.getHeader("Location");
|
||||
assertEquals("client-state", queryParameter(callbackLocation, "state"));
|
||||
String authorizationCode = queryParameter(callbackLocation, "code");
|
||||
|
||||
Response tokenResponse = given()
|
||||
.header("Host", DOMAIN)
|
||||
.formParam("grant_type", "authorization_code")
|
||||
.formParam("client_id", clientId)
|
||||
.formParam("code", authorizationCode)
|
||||
.formParam("redirect_uri", "https://client.example/callback")
|
||||
.when()
|
||||
.post("/oauth2/token")
|
||||
.then().statusCode(200)
|
||||
.body("token_type", equalTo("Bearer"))
|
||||
.extract().response();
|
||||
assertEquals("authorization_code", formValue(provider.tokenRequestBody(), "grant_type"));
|
||||
assertEquals("Bearer provider-access-token", provider.userInfoAuthorization());
|
||||
|
||||
JsonNode users = cognitoJson("ListUsers", "{\"UserPoolId\":\"%s\",\"Filter\":\"email = \\\"federated@example.com\\\"\"}".formatted(poolId));
|
||||
JsonNode attributes = users.path("Users").get(0).path("Attributes");
|
||||
assertEquals("federated@example.com", attributeValue(attributes, "email"));
|
||||
JsonNode identities = OBJECT_MAPPER.readTree(attributeValue(attributes, "identities")).get(0);
|
||||
assertEquals("LocalOidc", identities.path("providerName").asText());
|
||||
assertEquals("provider-subject", identities.path("userId").asText());
|
||||
assertFalse(identities.path("primary").asBoolean());
|
||||
String accessToken = tokenResponse.path("access_token").toString();
|
||||
assertFalse(accessToken.isBlank());
|
||||
|
||||
given()
|
||||
.get("/" + poolId + "/.well-known/openid-configuration")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("response_types_supported[0]", equalTo("code"))
|
||||
.body("authorization_endpoint", equalTo("https://" + DOMAIN + "/oauth2/authorize"))
|
||||
.body("grant_types_supported[1]", equalTo("authorization_code"));
|
||||
}
|
||||
}
|
||||
|
||||
private String queryParameter(String location, String name) {
|
||||
for (String parameter : URI.create(location).getRawQuery().split("&")) {
|
||||
String[] pair = parameter.split("=", 2);
|
||||
if (pair[0].equals(name)) {
|
||||
return URLDecoder.decode(pair[1], StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String formValue(String form, String name) {
|
||||
return queryParameter("http://localhost/?" + form, name);
|
||||
}
|
||||
|
||||
private String attributeValue(JsonNode attributes, String name) {
|
||||
for (JsonNode attribute : attributes) {
|
||||
if (name.equals(attribute.path("Name").asText())) {
|
||||
return attribute.path("Value").asText();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.acm.AcmService;
|
||||
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.CognitoGroup;
|
||||
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.ResourceServer;
|
||||
import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
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.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class CognitoFederationServiceTest {
|
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-09-16T00:00:00Z"), ZoneOffset.UTC);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private HttpServer oidcServer;
|
||||
private CognitoService cognitoService;
|
||||
private CognitoFederationStateStore stateStore;
|
||||
private CognitoFederationService federationService;
|
||||
private UserPool pool;
|
||||
private final AtomicReference<Request> tokenRequest = new AtomicReference<>();
|
||||
private final AtomicReference<Request> claimsRequest = new AtomicReference<>();
|
||||
private volatile int tokenStatus;
|
||||
private volatile String tokenResponse;
|
||||
private volatile int claimsStatus;
|
||||
private volatile String claimsResponse;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
oidcServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
oidcServer.createContext("/token", this::handleToken);
|
||||
oidcServer.createContext("/userinfo", this::handleClaims);
|
||||
oidcServer.start();
|
||||
|
||||
cognitoService = new CognitoService(
|
||||
new InMemoryStorage<String, UserPool>(),
|
||||
new InMemoryStorage<String, UserPoolClient>(),
|
||||
new InMemoryStorage<String, ResourceServer>(),
|
||||
new InMemoryStorage<String, UserPoolDomain>(),
|
||||
new InMemoryStorage<String, IdentityProvider>(),
|
||||
new InMemoryStorage<String, CognitoUser>(),
|
||||
new InMemoryStorage<String, CognitoGroup>(),
|
||||
new InMemoryStorage<String, RevokedTokenInfo>(),
|
||||
"http://localhost:4566",
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
null,
|
||||
mock(AcmService.class),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
stateStore = new CognitoFederationStateStore(CLOCK);
|
||||
federationService = new CognitoFederationService(
|
||||
cognitoService, stateStore, new CognitoOidcClient(MAPPER), CLOCK);
|
||||
pool = cognitoService.createUserPool(Map.of("PoolName", "FederationPool"), "us-east-1");
|
||||
tokenStatus = 200;
|
||||
tokenResponse = "{\"access_token\":\"provider-access-token\"}";
|
||||
claimsStatus = 200;
|
||||
claimsResponse = "{\"sub\":\"provider-subject\",\"iss\":\"https://issuer.example.test\","
|
||||
+ "\"email\":\"alice@example.test\",\"name\":\"Alice Provider\"}";
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
oidcServer.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void beginAuthorizationRejectsProviderWithoutAuthorizeEndpoint() {
|
||||
createProvider(Map.of(
|
||||
"client_id", "provider-client",
|
||||
"token_url", endpoint("/token"),
|
||||
"attributes_url", endpoint("/userinfo")), Map.of());
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class, () -> federationService.beginAuthorization(
|
||||
pool.getId(), "cognito-client", "https://application.example.test/callback",
|
||||
List.of("openid"), "nonce-value", "ExampleOidc"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void beginAuthorizationRejectsNonOidcProviderBeforeStoringState() {
|
||||
createProvider("ExampleGoogle", "Google", Map.of(
|
||||
"client_id", "provider-client",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"token_url", endpoint("/token"),
|
||||
"attributes_url", endpoint("/userinfo")), Map.of());
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class, () -> federationService.beginAuthorization(
|
||||
pool.getId(), "cognito-client", "https://application.example.test/callback",
|
||||
List.of("openid"), "nonce-value", "ExampleGoogle"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
assertNull(tokenRequest.get());
|
||||
assertNull(claimsRequest.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void beginAuthorizationStoresRelyingPartyStateInTransaction() {
|
||||
createDefaultProvider();
|
||||
|
||||
String redirect = federationService.beginAuthorization(
|
||||
pool.getId(), "cognito-client", "https://application.example.test/callback",
|
||||
List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state");
|
||||
|
||||
CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(queryValue(redirect, "state")).orElseThrow();
|
||||
assertEquals("relying-party-state", transaction.relyingPartyState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsNonOidcProvider() {
|
||||
createProvider("ExampleGoogle", "Google", Map.of(
|
||||
"client_id", "provider-client",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"token_url", endpoint("/token"),
|
||||
"attributes_url", endpoint("/userinfo")), Map.of());
|
||||
String state = putTransaction("ExampleGoogle");
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
assertNull(tokenRequest.get());
|
||||
assertNull(claimsRequest.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsProviderWithoutTokenEndpoint() {
|
||||
createProvider(Map.of(
|
||||
"client_id", "provider-client",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"attributes_url", endpoint("/userinfo")), Map.of());
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsProviderWithoutClaimsEndpoint() {
|
||||
createProvider(Map.of(
|
||||
"client_id", "provider-client",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"token_url", endpoint("/token")), Map.of());
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationConvertsInvalidTokenEndpointUriToAwsException() {
|
||||
createProvider(Map.of(
|
||||
"client_id", "provider-client",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"token_url", "http://[invalid",
|
||||
"attributes_url", endpoint("/userinfo")), Map.of());
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsUnsupportedTokenEndpointScheme() {
|
||||
createProvider(Map.of(
|
||||
"client_id", "provider-client",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"token_url", "ftp://provider.example.test/token",
|
||||
"attributes_url", endpoint("/userinfo")), Map.of());
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsUnsupportedClaimsEndpointScheme() {
|
||||
createProvider(Map.of(
|
||||
"client_id", "provider-client",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"token_url", endpoint("/token"),
|
||||
"attributes_url", "ftp://provider.example.test/userinfo"), Map.of());
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsFailedTokenExchange() {
|
||||
createDefaultProvider();
|
||||
tokenStatus = 400;
|
||||
tokenResponse = "{\"error\":\"invalid_grant\"}";
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("NotAuthorizedException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsFailedClaimsRequest() {
|
||||
createDefaultProvider();
|
||||
claimsStatus = 503;
|
||||
claimsResponse = "{\"error\":\"temporarily_unavailable\"}";
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("NotAuthorizedException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationRejectsClaimsWithoutSubject() {
|
||||
createDefaultProvider();
|
||||
claimsResponse = "{\"email\":\"alice@example.test\"}";
|
||||
String state = beginAuthorization();
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> federationService.completeAuthorization(state, "provider-code"));
|
||||
|
||||
assertEquals("InvalidParameterException", exception.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationMapsClaimsAndUsesOidcRequests() {
|
||||
createDefaultProvider();
|
||||
String state = beginAuthorization();
|
||||
|
||||
String authorizationCode = federationService.completeAuthorization(state, "provider code");
|
||||
|
||||
CognitoAuthorizationCode storedCode = stateStore.consumeAuthorizationCode(authorizationCode).orElseThrow();
|
||||
CognitoUser user = cognitoService.adminGetUser(pool.getId(), storedCode.userId());
|
||||
assertEquals("alice@example.test", user.getAttributes().get("email"));
|
||||
assertEquals("Alice Provider", user.getAttributes().get("name"));
|
||||
assertEquals("ExampleOidc", user.getFederatedProviderName());
|
||||
assertEquals("provider-subject", user.getFederatedSubject());
|
||||
|
||||
Request observedTokenRequest = tokenRequest.get();
|
||||
assertNotNull(observedTokenRequest);
|
||||
assertEquals("POST", observedTokenRequest.method());
|
||||
assertEquals("authorization_code", formValue(observedTokenRequest.body(), "grant_type"));
|
||||
assertEquals("provider-client", formValue(observedTokenRequest.body(), "client_id"));
|
||||
assertEquals("provider-secret", formValue(observedTokenRequest.body(), "client_secret"));
|
||||
assertEquals("provider code", formValue(observedTokenRequest.body(), "code"));
|
||||
assertEquals(cognitoService.getIdentityProviderCallbackEndpoint(pool.getId()),
|
||||
formValue(observedTokenRequest.body(), "redirect_uri"));
|
||||
|
||||
Request observedClaimsRequest = claimsRequest.get();
|
||||
assertNotNull(observedClaimsRequest);
|
||||
assertEquals("GET", observedClaimsRequest.method());
|
||||
assertEquals("Bearer provider-access-token", observedClaimsRequest.authorization());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationProvisionsNewFederatedUser() {
|
||||
createDefaultProvider();
|
||||
|
||||
CognitoAuthorizationCode storedCode = completeAndConsumeAuthorizationCode();
|
||||
CognitoUser user = cognitoService.adminGetUser(pool.getId(), storedCode.userId());
|
||||
|
||||
assertEquals(pool.getId(), user.getUserPoolId());
|
||||
assertEquals("CONFIRMED", user.getUserStatus());
|
||||
assertTrue(user.isEnabled());
|
||||
assertFalse(user.getUsername().isBlank());
|
||||
assertNotNull(user.getAttributes().get("sub"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationReconcilesExistingFederatedUserWithoutLosingOtherAttributes() {
|
||||
createDefaultProvider();
|
||||
CognitoAuthorizationCode firstCode = completeAndConsumeAuthorizationCode();
|
||||
CognitoUser firstUser = cognitoService.adminGetUser(pool.getId(), firstCode.userId());
|
||||
cognitoService.adminUpdateUserAttributes(pool.getId(), firstUser.getUsername(),
|
||||
Map.of("custom:note", "preserve-me", "email", "old@example.test"));
|
||||
claimsResponse = "{\"sub\":\"provider-subject\",\"iss\":\"https://issuer.example.test\","
|
||||
+ "\"email\":\"new@example.test\",\"name\":\"Updated Provider\"}";
|
||||
|
||||
CognitoAuthorizationCode secondCode = completeAndConsumeAuthorizationCode();
|
||||
CognitoUser reconciledUser = cognitoService.adminGetUser(pool.getId(), secondCode.userId());
|
||||
|
||||
assertEquals(firstUser.getUsername(), reconciledUser.getUsername());
|
||||
assertEquals("new@example.test", reconciledUser.getAttributes().get("email"));
|
||||
assertEquals("Updated Provider", reconciledUser.getAttributes().get("name"));
|
||||
assertEquals("preserve-me", reconciledUser.getAttributes().get("custom:note"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void completeAuthorizationStoresAwsCompatibleIdentityFields() throws Exception {
|
||||
createDefaultProvider();
|
||||
|
||||
CognitoAuthorizationCode storedCode = completeAndConsumeAuthorizationCode();
|
||||
CognitoUser user = cognitoService.adminGetUser(pool.getId(), storedCode.userId());
|
||||
JsonNode identity = MAPPER.readTree(user.getAttributes().get("identities")).get(0);
|
||||
List<String> fieldNames = new ArrayList<>();
|
||||
identity.fieldNames().forEachRemaining(fieldNames::add);
|
||||
|
||||
assertEquals(List.of("userId", "providerName", "providerType", "issuer", "primary", "dateCreated"),
|
||||
fieldNames);
|
||||
assertEquals("provider-subject", identity.path("userId").asText());
|
||||
assertEquals("ExampleOidc", identity.path("providerName").asText());
|
||||
assertEquals("OIDC", identity.path("providerType").asText());
|
||||
assertEquals("https://issuer.example.test", identity.path("issuer").asText());
|
||||
assertFalse(identity.path("primary").asBoolean());
|
||||
assertTrue(identity.path("dateCreated").asLong() > 0L);
|
||||
}
|
||||
|
||||
private IdentityProvider createDefaultProvider() {
|
||||
return createProvider(Map.of(
|
||||
"client_id", "provider-client",
|
||||
"client_secret", "provider-secret",
|
||||
"authorize_url", "https://provider.example.test/authorize",
|
||||
"token_url", endpoint("/token"),
|
||||
"attributes_url", endpoint("/userinfo")),
|
||||
Map.of("email", "email", "name", "name"));
|
||||
}
|
||||
|
||||
private IdentityProvider createProvider(Map<String, String> details, Map<String, String> attributeMapping) {
|
||||
return createProvider("ExampleOidc", "OIDC", details, attributeMapping);
|
||||
}
|
||||
|
||||
private IdentityProvider createProvider(String providerName, String providerType, Map<String, String> details,
|
||||
Map<String, String> attributeMapping) {
|
||||
return cognitoService.createIdentityProvider(pool.getId(), providerName, providerType, details,
|
||||
attributeMapping, List.of());
|
||||
}
|
||||
|
||||
private CognitoAuthorizationCode completeAndConsumeAuthorizationCode() {
|
||||
String authorizationCode = federationService.completeAuthorization(beginAuthorization(), "provider-code");
|
||||
return stateStore.consumeAuthorizationCode(authorizationCode).orElseThrow();
|
||||
}
|
||||
|
||||
private String beginAuthorization() {
|
||||
String redirect = federationService.beginAuthorization(
|
||||
pool.getId(), "cognito-client", "https://application.example.test/callback",
|
||||
List.of("openid"), "nonce-value", "ExampleOidc");
|
||||
return queryValue(redirect, "state");
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
|
||||
private String endpoint(String path) {
|
||||
return "http://127.0.0.1:" + oidcServer.getAddress().getPort() + path;
|
||||
}
|
||||
|
||||
private void handleToken(HttpExchange exchange) throws IOException {
|
||||
tokenRequest.set(new Request(exchange.getRequestMethod(),
|
||||
new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8),
|
||||
exchange.getRequestHeaders().getFirst("Authorization")));
|
||||
writeResponse(exchange, tokenStatus, tokenResponse);
|
||||
}
|
||||
|
||||
private void handleClaims(HttpExchange exchange) throws IOException {
|
||||
claimsRequest.set(new Request(exchange.getRequestMethod(),
|
||||
new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8),
|
||||
exchange.getRequestHeaders().getFirst("Authorization")));
|
||||
writeResponse(exchange, claimsStatus, claimsResponse);
|
||||
}
|
||||
|
||||
private void writeResponse(HttpExchange exchange, int status, String response) throws IOException {
|
||||
byte[] body = response.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(status, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private String queryValue(String uri, String name) {
|
||||
String query = URI.create(uri).getRawQuery();
|
||||
for (String pair : query.split("&")) {
|
||||
String[] parts = pair.split("=", 2);
|
||||
if (parts.length == 2 && name.equals(URLDecoder.decode(parts[0], StandardCharsets.UTF_8))) {
|
||||
return URLDecoder.decode(parts[1], StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
throw new AssertionError("Query parameter " + name + " was absent from " + uri);
|
||||
}
|
||||
|
||||
private String formValue(String form, String name) {
|
||||
return queryValue("https://form.example.test/?" + form, name);
|
||||
}
|
||||
|
||||
private record Request(String method, String body, String authorization) {
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class CognitoFederationStateStoreTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-09-16T12:00:00Z");
|
||||
|
||||
@Test
|
||||
void consumeTransaction_returnsStoredUnexpiredTransaction() {
|
||||
CognitoFederationStateStore store = storeAt(NOW);
|
||||
CognitoAuthorizationTransaction transaction = transaction(NOW.plusSeconds(60));
|
||||
|
||||
String state = store.putTransaction(transaction);
|
||||
|
||||
assertEquals(Optional.of(transaction), store.consumeTransaction(state));
|
||||
}
|
||||
|
||||
@Test
|
||||
void consumeTransaction_expiredTransactionReturnsEmpty() {
|
||||
CognitoFederationStateStore store = storeAt(NOW);
|
||||
String state = store.putTransaction(transaction(NOW));
|
||||
|
||||
assertTrue(store.consumeTransaction(state).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void consumeTransaction_expiringAtMapMutationReturnsEmpty() throws ReflectiveOperationException {
|
||||
Instant expiresAt = NOW.plusSeconds(1);
|
||||
MutableClock clock = new MutableClock(NOW);
|
||||
CognitoFederationStateStore store = new CognitoFederationStateStore(clock);
|
||||
replaceStoreMap(store, "transactions", new ExpiringAtMutationMap<>(clock, expiresAt));
|
||||
String state = store.putTransaction(transaction(expiresAt));
|
||||
|
||||
assertTrue(store.consumeTransaction(state).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void consumeTransaction_concurrentRequestsReturnTransactionOnlyOnce() throws Exception {
|
||||
CognitoFederationStateStore store = storeAt(NOW);
|
||||
String state = store.putTransaction(transaction(NOW.plusSeconds(60)));
|
||||
int consumers = 16;
|
||||
CountDownLatch ready = new CountDownLatch(consumers);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
ExecutorService executor = Executors.newFixedThreadPool(consumers);
|
||||
|
||||
try {
|
||||
List<Future<Optional<CognitoAuthorizationTransaction>>> results = IntStream.range(0, consumers)
|
||||
.mapToObj(ignored -> executor.submit(() -> {
|
||||
ready.countDown();
|
||||
start.await();
|
||||
return store.consumeTransaction(state);
|
||||
}))
|
||||
.toList();
|
||||
assertTrue(ready.await(5, TimeUnit.SECONDS));
|
||||
|
||||
start.countDown();
|
||||
|
||||
long successfulConsumptions = 0;
|
||||
for (Future<Optional<CognitoAuthorizationTransaction>> result : results) {
|
||||
if (result.get(5, TimeUnit.SECONDS).isPresent()) {
|
||||
successfulConsumptions++;
|
||||
}
|
||||
}
|
||||
assertEquals(1, successfulConsumptions);
|
||||
} finally {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void consumeAuthorizationCode_returnsStoredUnexpiredCode() {
|
||||
CognitoFederationStateStore store = storeAt(NOW);
|
||||
CognitoAuthorizationCode authorizationCode = authorizationCode(NOW.plusSeconds(60));
|
||||
|
||||
String code = store.putAuthorizationCode(authorizationCode);
|
||||
|
||||
assertEquals(Optional.of(authorizationCode), store.consumeAuthorizationCode(code));
|
||||
}
|
||||
|
||||
@Test
|
||||
void consumeAuthorizationCode_replayedCodeReturnsEmpty() {
|
||||
CognitoFederationStateStore store = storeAt(NOW);
|
||||
CognitoAuthorizationCode authorizationCode = authorizationCode(NOW.plusSeconds(60));
|
||||
String code = store.putAuthorizationCode(authorizationCode);
|
||||
|
||||
assertEquals(Optional.of(authorizationCode), store.consumeAuthorizationCode(code));
|
||||
assertFalse(store.consumeAuthorizationCode(code).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void consumeAuthorizationCode_expiringAtMapMutationReturnsEmpty() throws ReflectiveOperationException {
|
||||
Instant expiresAt = NOW.plusSeconds(1);
|
||||
MutableClock clock = new MutableClock(NOW);
|
||||
CognitoFederationStateStore store = new CognitoFederationStateStore(clock);
|
||||
replaceStoreMap(store, "authorizationCodes", new ExpiringAtMutationMap<>(clock, expiresAt));
|
||||
String code = store.putAuthorizationCode(authorizationCode(expiresAt));
|
||||
|
||||
assertTrue(store.consumeAuthorizationCode(code).isEmpty());
|
||||
}
|
||||
|
||||
private CognitoFederationStateStore storeAt(Instant now) {
|
||||
return new CognitoFederationStateStore(Clock.fixed(now, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
private CognitoAuthorizationTransaction transaction(Instant expiresAt) {
|
||||
return new CognitoAuthorizationTransaction(
|
||||
"pool-id", "client-id", "https://example.com/callback", List.of("openid", "email"),
|
||||
"nonce", "ExampleOidc", 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
|
||||
);
|
||||
}
|
||||
|
||||
private void replaceStoreMap(CognitoFederationStateStore store, String fieldName,
|
||||
ConcurrentHashMap<?, ?> replacement) throws ReflectiveOperationException {
|
||||
Field field = CognitoFederationStateStore.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(store, replacement);
|
||||
}
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant now;
|
||||
|
||||
private MutableClock(Instant now) {
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
void set(Instant now) {
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZoneOffset getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return now;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ExpiringAtMutationMap<V> extends ConcurrentHashMap<String, V> {
|
||||
private final MutableClock clock;
|
||||
private final Instant expiresAt;
|
||||
|
||||
private ExpiringAtMutationMap(MutableClock clock, Instant expiresAt) {
|
||||
this.clock = clock;
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object key, Object value) {
|
||||
clock.set(expiresAt);
|
||||
return super.remove(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public V computeIfPresent(String key,
|
||||
BiFunction<? super String, ? super V, ? extends V> remappingFunction) {
|
||||
clock.set(expiresAt);
|
||||
return super.computeIfPresent(key, remappingFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.CognitoUser;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
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 java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
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.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class CognitoOAuthControllerTest {
|
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-09-16T00:00:00Z"), ZoneOffset.UTC);
|
||||
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 final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final CognitoService cognitoService = mock(CognitoService.class);
|
||||
private final CognitoFederationService federationService = mock(CognitoFederationService.class);
|
||||
private CognitoFederationStateStore stateStore;
|
||||
private CognitoOAuthController controller;
|
||||
private UserPoolClient client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
stateStore = new CognitoFederationStateStore(CLOCK);
|
||||
controller = new CognitoOAuthController(cognitoService, objectMapper, federationService, stateStore);
|
||||
client = client();
|
||||
when(cognitoService.findClientById(CLIENT_ID)).thenReturn(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeRedirectsToConfiguredIdentityProvider() {
|
||||
when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), "nonce", "ExampleOidc",
|
||||
" relying-party-state "))
|
||||
.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 ");
|
||||
|
||||
assertEquals(302, response.getStatus());
|
||||
assertEquals("https://provider.example.test/authorize?state=provider-state", response.getHeaderString("Location"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeReturnsInvalidClientForUnknownClient() {
|
||||
when(cognitoService.findClientById("missing-client"))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
|
||||
Response response = controller.authorize(requestContext(null), "missing-client", CALLBACK_URI, "code", "openid", null,
|
||||
"ExampleOidc", null);
|
||||
|
||||
assertOAuthError(response, "invalid_client");
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeReturnsInvalidRequestForUnregisteredRedirectUri() {
|
||||
Response response = controller.authorize(requestContext(null), CLIENT_ID, "https://other.example.test/callback", "code", "openid",
|
||||
null, "ExampleOidc", null);
|
||||
|
||||
assertOAuthError(response, "invalid_request");
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeReturnsUnsupportedResponseTypeForTokenResponse() {
|
||||
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "token", "openid", null, "ExampleOidc", null);
|
||||
|
||||
assertOAuthError(response, "unsupported_response_type");
|
||||
}
|
||||
|
||||
@Test
|
||||
void idpResponseReturnsInvalidRequestForUnknownState() {
|
||||
Response response = controller.idpResponse(requestContext(null), "unknown-state", "provider-code", null, null);
|
||||
|
||||
assertOAuthError(response, "invalid_request");
|
||||
}
|
||||
|
||||
@Test
|
||||
void idpResponseRedirectsProviderErrorToApplication() {
|
||||
String state = putTransaction("relying-party-state");
|
||||
|
||||
Response response = controller.idpResponse(requestContext(null), state, null, "access_denied", "The provider refused access");
|
||||
|
||||
assertEquals(302, response.getStatus());
|
||||
assertEquals(CALLBACK_URI + "?error=access_denied&error_description=The+provider+refused+access&state=relying-party-state",
|
||||
response.getHeaderString("Location"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void idpResponseRedirectsAuthorizationCodeToApplication() {
|
||||
String state = putTransaction("relying-party-state");
|
||||
when(federationService.completeAuthorization(any(CognitoAuthorizationTransaction.class), eq("provider-code")))
|
||||
.thenReturn("authorization-code");
|
||||
|
||||
Response response = controller.idpResponse(requestContext(null), state, "provider-code", null, null);
|
||||
|
||||
assertEquals(302, response.getStatus());
|
||||
assertEquals(CALLBACK_URI + "?code=authorization-code&state=relying-party-state", response.getHeaderString("Location"));
|
||||
}
|
||||
|
||||
@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)));
|
||||
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)))
|
||||
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
|
||||
"ExpiresIn", 3600, "TokenType", "Bearer"));
|
||||
|
||||
MultivaluedHashMap<String, String> form = form("grant_type", "authorization_code", "client_id", CLIENT_ID,
|
||||
"code", code, "redirect_uri", CALLBACK_URI);
|
||||
Response first = controller.token(null, requestContext(null), form);
|
||||
Response replay = controller.token(null, requestContext(null), form);
|
||||
|
||||
assertEquals(200, first.getStatus());
|
||||
JsonNode body = (JsonNode) first.getEntity();
|
||||
assertEquals("access-token", body.path("access_token").asText());
|
||||
assertEquals("id-token", body.path("id_token").asText());
|
||||
assertEquals("refresh-token", body.path("refresh_token").asText());
|
||||
assertEquals(3600, body.path("expires_in").asInt());
|
||||
assertOAuthError(replay, "invalid_grant");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenRejectsAuthorizationCodeForAnotherClient() {
|
||||
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
|
||||
POOL_ID, "other-client", "federated-user", CALLBACK_URI, List.of("openid"), 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));
|
||||
|
||||
assertOAuthError(response, "invalid_grant");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenDoesNotConsumeAuthorizationCodeWhenRedirectUriIsInvalid() {
|
||||
String code = putAuthorizationCode();
|
||||
|
||||
Response invalid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", CLIENT_ID,
|
||||
"code", code, "redirect_uri", "https://application.example.test/other"));
|
||||
Response valid = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
|
||||
|
||||
assertOAuthError(invalid, "invalid_grant");
|
||||
assertEquals(200, valid.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenDoesNotConsumeAuthorizationCodeWhenClientDoesNotMatch() {
|
||||
UserPoolClient otherClient = client("other-client");
|
||||
when(cognitoService.findClientById("other-client")).thenReturn(otherClient);
|
||||
String code = putAuthorizationCode();
|
||||
|
||||
Response invalid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", "other-client",
|
||||
"code", code, "redirect_uri", CALLBACK_URI));
|
||||
Response valid = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
|
||||
|
||||
assertOAuthError(invalid, "invalid_grant");
|
||||
assertEquals(200, valid.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenDoesNotConsumeAuthorizationCodeWhenClientSecretIsInvalid() {
|
||||
client.setClientSecret("correct-secret");
|
||||
String code = putAuthorizationCode();
|
||||
|
||||
Response invalid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", CLIENT_ID,
|
||||
"client_secret", "wrong-secret", "code", code, "redirect_uri", CALLBACK_URI));
|
||||
Response valid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", CLIENT_ID,
|
||||
"client_secret", "correct-secret", "code", code, "redirect_uri", CALLBACK_URI));
|
||||
|
||||
assertOAuthError(invalid, "invalid_client");
|
||||
assertEquals(200, valid.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenDoesNotConsumeAuthorizationCodeWhenDomainDoesNotMatch() {
|
||||
String code = putAuthorizationCode();
|
||||
|
||||
Response invalid = controller.token(null, requestContext("other-pool"), validAuthorizationCodeForm(code));
|
||||
Response valid = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
|
||||
|
||||
assertOAuthError(invalid, "invalid_grant");
|
||||
assertEquals(200, valid.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenRejectsMismatchedBasicAndFormClientAuthentication() {
|
||||
Response response = controller.token(basicAuthorization(CLIENT_ID, "header-secret"), requestContext(null),
|
||||
form("grant_type", "authorization_code", "client_id", CLIENT_ID, "client_secret", "form-secret",
|
||||
"code", "authorization-code", "redirect_uri", CALLBACK_URI));
|
||||
|
||||
assertOAuthError(response, "invalid_request");
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
|
||||
private String putAuthorizationCode() {
|
||||
String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(
|
||||
POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), 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)))
|
||||
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
|
||||
"ExpiresIn", 3600, "TokenType", "Bearer"));
|
||||
return code;
|
||||
}
|
||||
|
||||
private static MultivaluedHashMap<String, String> validAuthorizationCodeForm(String code) {
|
||||
return form("grant_type", "authorization_code", "client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI);
|
||||
}
|
||||
|
||||
private static UserPoolClient client() {
|
||||
return client(CLIENT_ID);
|
||||
}
|
||||
|
||||
private static UserPoolClient client(String clientId) {
|
||||
UserPoolClient result = new UserPoolClient();
|
||||
result.setClientId(clientId);
|
||||
result.setUserPoolId(POOL_ID);
|
||||
result.setAllowedOAuthFlowsUserPoolClient(true);
|
||||
result.setAllowedOAuthFlows(List.of("code"));
|
||||
result.setCallbackURLs(List.of(CALLBACK_URI));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static UserPool pool() {
|
||||
UserPool result = new UserPool();
|
||||
result.setId(POOL_ID);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static CognitoUser user() {
|
||||
CognitoUser result = new CognitoUser();
|
||||
result.setUsername("federated-user");
|
||||
result.setUserPoolId(POOL_ID);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ContainerRequestContext requestContext(String poolId) {
|
||||
ContainerRequestContext result = mock(ContainerRequestContext.class);
|
||||
when(result.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY)).thenReturn(poolId);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static MultivaluedHashMap<String, String> form(String... values) {
|
||||
MultivaluedHashMap<String, String> result = new MultivaluedHashMap<>();
|
||||
for (int index = 0; index < values.length; index += 2) {
|
||||
result.add(values[index], values[index + 1]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String basicAuthorization(String clientId, String clientSecret) {
|
||||
String credentials = clientId + ":" + clientSecret;
|
||||
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private void assertOAuthError(Response response, String error) {
|
||||
assertEquals(400, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
JsonNode body = (JsonNode) response.getEntity();
|
||||
assertEquals(error, body.path("error").asText());
|
||||
assertTrue(body.hasNonNull("error_description"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
final class MockOidcProvider implements AutoCloseable {
|
||||
|
||||
private final HttpServer server;
|
||||
private final Map<String, String> authorizationParameters = new ConcurrentHashMap<>();
|
||||
private volatile String tokenRequestBody;
|
||||
private volatile String userInfoAuthorization;
|
||||
|
||||
MockOidcProvider() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/authorize", exchange -> {
|
||||
authorizationParameters.putAll(queryParameters(exchange.getRequestURI().getRawQuery()));
|
||||
respond(exchange, 302, "");
|
||||
});
|
||||
server.createContext("/token", exchange -> {
|
||||
tokenRequestBody = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
|
||||
respond(exchange, 200, "{\"access_token\":\"provider-access-token\",\"token_type\":\"Bearer\"}");
|
||||
});
|
||||
server.createContext("/userinfo", exchange -> {
|
||||
userInfoAuthorization = exchange.getRequestHeaders().getFirst("Authorization");
|
||||
respond(exchange, 200, "{\"sub\":\"provider-subject\",\"email\":\"federated@example.com\"}");
|
||||
});
|
||||
server.start();
|
||||
}
|
||||
|
||||
String baseUrl() {
|
||||
return "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
}
|
||||
|
||||
Map<String, String> authorizationParameters() {
|
||||
return new LinkedHashMap<>(authorizationParameters);
|
||||
}
|
||||
|
||||
String tokenRequestBody() {
|
||||
return tokenRequestBody;
|
||||
}
|
||||
|
||||
String userInfoAuthorization() {
|
||||
return userInfoAuthorization;
|
||||
}
|
||||
|
||||
private Map<String, String> queryParameters(String query) {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
if (query == null || query.isBlank()) {
|
||||
return parameters;
|
||||
}
|
||||
for (String parameter : query.split("&")) {
|
||||
String[] pair = parameter.split("=", 2);
|
||||
if (pair.length == 2) {
|
||||
parameters.put(URLDecoder.decode(pair[0], StandardCharsets.UTF_8),
|
||||
URLDecoder.decode(pair[1], StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private void respond(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream output = exchange.getResponseBody()) {
|
||||
output.write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user