diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 24ad1d36b1..e421f13968 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -101,6 +101,24 @@ always returns it. | UpdateUserPoolDomain | Replaces a custom domain's certificate or changes the managed login version in place. The domain keeps its `CloudFrontDistribution`, and its `InUseBy` entry moves to the new certificate. | | DeleteUserPoolDomain | Deletes a domain from its user pool. | +#### Custom domains + +A domain created with `CustomDomainConfig` answers the OAuth endpoints on that host, as on AWS: + +``` +POST https://auth.example.localhost.floci.io/oauth2/token +GET https://auth.example.localhost.floci.io/oauth2/userInfo +``` + +Requests are matched on the `Host` header, so the name must resolve to Floci (any +`*.localhost.floci.io` does) and, for `https`, TLS must be enabled. The domain pins its user pool and +the account that created it, since these requests carry no AWS credential: a `client_id` from +another pool is refused with `invalid_client`, and an access token issued by another pool with +`invalid_token`. Domain names are unique across all accounts, as on AWS. The pool's `openid-configuration` advertises the custom-domain +URLs when one exists. Prefix domains (`.auth..amazoncognito.com`) are stored but not +routed, since that hostname never reaches Floci. `/oauth2/authorize`, `/login` and `/logout` are not +served on any host. + ### Log Delivery | Action | Description | @@ -239,7 +257,8 @@ and returned rather than rendered. Two divergences follow from that: - It doesn't require a Cognito domain. - It returns only `access_token`, `token_type`, and `expires_in`. - It validates requested OAuth scopes against the app client's `AllowedOAuthScopes` and the pool's registered resource-server scopes. -- It advertises the prefixed token endpoint in `/{userPoolId}/.well-known/openid-configuration`. +- It advertises the prefixed token endpoint in `/{userPoolId}/.well-known/openid-configuration`, or + `https:///oauth2/token` when the pool has a custom domain (see Custom domains above). ## Sign-in Identifiers (`UsernameAttributes`) diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java index 53f96a8d0b..6a439d3841 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java @@ -26,6 +26,13 @@ import java.util.Optional; @Priority(Priorities.AUTHENTICATION - 100) public class AccountContextFilter implements ContainerRequestFilter { + /** + * Set by a {@code @PreMatching} Host filter that resolved the request to a resource owned by + * one account (a Cognito custom domain). Such requests carry no AWS credential, so the + * owner's account is used instead of the default one. + */ + public static final String PINNED_ACCOUNT_PROPERTY = AccountContextFilter.class.getName() + ".accountId"; + private final AccountResolver accountResolver; private final RegionResolver regionResolver; private final RequestContext requestContext; @@ -44,6 +51,12 @@ public class AccountContextFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext ctx) { + Object pinnedAccount = ctx.getProperty(PINNED_ACCOUNT_PROPERTY); + if (pinnedAccount != null) { + requestContext.setAccountId(pinnedAccount.toString()); + requestContext.setRegion(regionResolver.resolveRegionFromAuth(null)); + return; + } String auth = ctx.getHeaderString("Authorization"); if (auth != null && !auth.isEmpty()) { String akid = accountResolver.extractAccessKeyId(auth); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java new file mode 100644 index 0000000000..ad38831d9b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java @@ -0,0 +1,85 @@ +package io.github.hectorvent.floci.services.cognito; + +import io.github.hectorvent.floci.core.common.AccountContextFilter; +import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain; +import jakarta.annotation.Priority; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.PreMatching; +import jakarta.ws.rs.core.UriBuilder; +import jakarta.ws.rs.ext.Provider; +import org.jboss.logging.Logger; + +import java.net.URI; +import java.util.Optional; + +/** + * Routes Cognito custom-domain requests by Host. On AWS a custom domain serves + * {@code https:///oauth2/token} and {@code /oauth2/userInfo}; Floci maps those onto + * the {@code /cognito-idp/oauth2/...} handlers and pins the pool and the account that own the + * domain, since the request itself carries no AWS credential. + */ +@Provider +@PreMatching +@Priority(12) // after ApiGatewayCustomDomainFilter (10), before CloudFrontDistributionFilter (15) +public class CognitoCustomDomainFilter implements ContainerRequestFilter { + + /** + * The id of the pool whose custom domain the request arrived on. A request property, not a + * header, so a caller cannot supply it, and resolved once here so the controllers never + * fail open if the domain is deleted between the filter and the handler. + */ + public static final String POOL_PROPERTY = CognitoCustomDomainFilter.class.getName() + ".poolId"; + + private static final Logger LOG = Logger.getLogger(CognitoCustomDomainFilter.class); + private static final String OAUTH_PREFIX = "/oauth2/"; + private static final String TARGET_PREFIX = "/cognito-idp/oauth2/"; + + private final CognitoService cognitoService; + + @Inject + public CognitoCustomDomainFilter(CognitoService cognitoService) { + this.cognitoService = cognitoService; + } + + @Override + public void filter(ContainerRequestContext requestContext) { + URI originalUri = requestContext.getUriInfo().getRequestUri(); + String path = originalUri.getRawPath(); + if (path == null || !path.startsWith(OAUTH_PREFIX)) { + return; + } + // HTTP/2 has no Host header; its :authority arrives as the request URI authority. + String host = requestContext.getHeaderString("Host"); + if (host == null) { + host = originalUri.getAuthority(); + } + if (host == null) { + return; + } + Optional domain = cognitoService.findCustomDomain(stripPort(host)); + if (domain.isEmpty()) { + return; + } + + URI newUri = UriBuilder.fromUri(originalUri) + .replacePath(TARGET_PREFIX + path.substring(OAUTH_PREFIX.length())) + .build(); + LOG.debugv("Cognito custom domain routing: {0}{1} -> {2}", host, path, newUri.getPath()); + requestContext.setProperty(POOL_PROPERTY, domain.get().getUserPoolId()); + requestContext.setProperty(AccountContextFilter.PINNED_ACCOUNT_PROPERTY, domain.get().getAwsAccountId()); + requestContext.setRequestUri(newUri); + } + + private static String stripPort(String host) { + int colonIndex = host.lastIndexOf(':'); + if (colonIndex > 0) { + String maybePort = host.substring(colonIndex + 1); + if (!maybePort.isEmpty() && maybePort.chars().allMatch(Character::isDigit)) { + return host.substring(0, colonIndex); + } + } + return host; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java index f131f71b39..20c0aface3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java @@ -10,6 +10,8 @@ import jakarta.ws.rs.HeaderParam; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; @@ -39,11 +41,14 @@ public class CognitoOAuthController { @Path("/cognito-idp/oauth2/token") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response token(@HeaderParam("Authorization") String authorization, + @Context ContainerRequestContext requestContext, MultivaluedMap formParams) { - return issueToken(authorization, formParams); + String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY); + return issueToken(authorization, formParams, domainPoolId); } - private Response issueToken(String authorization, MultivaluedMap formParams) { + private Response issueToken(String authorization, MultivaluedMap formParams, + String domainPoolId) { String grantType = trimToNull(formParams.getFirst("grant_type")); if (grantType == null) { return oauthError("invalid_request", "grant_type is required"); @@ -81,7 +86,8 @@ public class CognitoOAuthController { String scope = trimToNull(formParams.getFirst("scope")); try { - Map result = cognitoService.issueClientCredentialsToken(clientId, clientSecret, scope); + Map result = cognitoService.issueClientCredentialsToken( + clientId, clientSecret, scope, domainPoolId); return Response.ok(objectMapper.valueToTree(result)) .type(MediaType.APPLICATION_JSON) .header("Cache-Control", "no-store") diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index b932ec573f..504ca1e8a9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.ReservedTags; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; @@ -1096,7 +1097,7 @@ public class CognitoService implements ResourceProvider { if (domain == null || domain.isBlank()) { throw new AwsException("InvalidParameterException", "Domain is required", 400); } - if (domainStore.get(domain).isPresent()) { + if (!findDomains(domain).isEmpty()) { throw new AwsException("InvalidParameterException", "Domain " + domain + " already associated with another user pool", 400); } @@ -1123,10 +1124,19 @@ public class CognitoService implements ResourceProvider { userPoolDomain.setCloudFrontDistribution(generateCloudFrontDomain()); } - if (userPoolDomain.isCustomDomain()) { - registerCertificateUse(userPoolDomain.getCertificateArn(), userPoolDomain); + // Check and write as one step: two accounts racing for one name write to different + // account-prefixed keys, so without the lock both would succeed and the name would be + // ambiguous for routing. + synchronized (domainLock) { + if (!findDomains(domain).isEmpty()) { + throw new AwsException("InvalidParameterException", + "Domain " + domain + " already associated with another user pool", 400); + } + if (userPoolDomain.isCustomDomain()) { + registerCertificateUse(userPoolDomain.getCertificateArn(), userPoolDomain); + } + domainStore.put(domain, userPoolDomain); } - domainStore.put(domain, userPoolDomain); LOG.infov("Created User Pool Domain: {0} for pool {1}", domain, userPoolId); return userPoolDomain; } @@ -1139,6 +1149,48 @@ public class CognitoService implements ResourceProvider { .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Domain does not exist", 404)); } + /** + * Resolves a request {@code Host} to the custom domain it names. An OAuth call carries no + * SigV4 account, so the lookup spans every account rather than the request's default one. + */ + public Optional findCustomDomain(String hostname) { + List matches = findDomains(hostname).stream() + .filter(UserPoolDomain::isCustomDomain) + .toList(); + if (matches.size() > 1) { + LOG.warnv("Custom domain {0} exists in {1} accounts and is not routed; delete the duplicates", + hostname, matches.size()); + return Optional.empty(); + } + return matches.stream().findFirst(); + } + + /** + * Domain names are one namespace across every account on AWS, so this is also the + * uniqueness check {@link #createUserPoolDomain} runs. More than one match can only come + * from data persisted before that check spanned accounts. + */ + private List findDomains(String name) { + if (name == null || name.isBlank()) { + return List.of(); + } + return allDomains().stream() + .filter(d -> name.equalsIgnoreCase(d.getDomain())) + .toList(); + } + + public Optional findCustomDomainForPool(String poolId) { + return allDomains().stream() + .filter(d -> d.isCustomDomain() && poolId.equals(d.getUserPoolId())) + .findFirst(); + } + + private List allDomains() { + return domainStore instanceof AccountAwareStorageBackend aware + ? aware.scanAllAccounts() + : domainStore.scan(key -> true); + } + /** * Changes a domain in place: the certificate behind a custom domain ({@code CustomDomainConfig}) * or the managed login version. As on AWS the domain keeps its CloudFront distribution, so a @@ -1715,6 +1767,9 @@ public class CognitoService implements ResourceProvider { // every mutating path with one lock reproduces that. private final Object identityProviderLock = new Object(); + // Domain creation is check-then-act across every account's keys; see createUserPoolDomain. + private final Object domainLock = new Object(); + public void adminLinkProviderForUser(String userPoolId, String destinationUsername, String sourceProviderName, String sourceUserId) { if (destinationUsername == null || destinationUsername.isEmpty()) { @@ -2543,8 +2598,15 @@ public class CognitoService implements ResourceProvider { adminDeleteUserAttributes(poolId, username, attributeNames); } - public Map issueClientCredentialsToken(String clientId, String clientSecret, String scope) { + /** + * @param requiredPoolId the pool owning the custom domain the request arrived on, or + * {@code null} on Floci's own host. As on AWS, a client of another pool + * does not exist on that domain. + */ + public Map issueClientCredentialsToken(String clientId, String clientSecret, String scope, + String requiredPoolId) { UserPoolClient client = clientStore.get(clientId) + .filter(c -> requiredPoolId == null || requiredPoolId.equals(c.getUserPoolId())) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400)); UserPool pool = describeUserPool(client.getUserPoolId()); validateClientAllowsClientCredentials(client); @@ -2574,12 +2636,22 @@ public class CognitoService implements ResourceProvider { return getIssuer(poolId) + "/.well-known/jwks.json"; } - public String getTokenEndpoint() { - return baseUrl + "/cognito-idp/oauth2/token"; + /** + * A custom domain is HTTPS-only on AWS, so its endpoints are advertised as {@code https} + * regardless of Floci's own base URL. + */ + public String getTokenEndpoint(String poolId) { + return oauthEndpoint(poolId, "token"); } - public String getUserInfoEndpoint() { - return baseUrl + "/cognito-idp/oauth2/userInfo"; + public String getUserInfoEndpoint(String poolId) { + return oauthEndpoint(poolId, "userInfo"); + } + + private String oauthEndpoint(String poolId, String operation) { + return findCustomDomainForPool(poolId) + .map(d -> "https://" + d.getDomain() + "/oauth2/" + operation) + .orElse(baseUrl + "/cognito-idp/oauth2/" + operation); } // ──────────────────────────── Private helpers ──────────────────────────── diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java index ac56379123..a0b13a00c8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java @@ -11,6 +11,8 @@ import jakarta.ws.rs.GET; import jakarta.ws.rs.HeaderParam; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; @@ -58,7 +60,8 @@ public class CognitoUserInfoController { @GET @Path("/cognito-idp/oauth2/userInfo") - public Response userInfo(@HeaderParam("Authorization") String authorization) { + public Response userInfo(@HeaderParam("Authorization") String authorization, + @Context ContainerRequestContext requestContext) { if (authorization == null || authorization.isBlank() || !authorization.regionMatches(true, 0, "Bearer ", 0, 7)) { return bearerError(401, "invalid_token", "Bearer token required"); @@ -88,6 +91,10 @@ public class CognitoUserInfoController { if (poolId == null) { return bearerError(401, "invalid_token", "Cannot derive user pool from iss: " + iss); } + String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY); + if (domainPoolId != null && !domainPoolId.equals(poolId)) { + return bearerError(401, "invalid_token", "Token was not issued by the user pool of this domain"); + } CognitoUser user; try { diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java index 17f1d4e4ae..d184b6f4b0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java @@ -59,8 +59,8 @@ public class CognitoWellKnownController { UserPool pool = cognitoService.describeUserPool(poolId); String issuer = cognitoService.getIssuer(pool.getId()); String jwksUri = cognitoService.getJwksUri(pool.getId()); - String tokenEndpoint = cognitoService.getTokenEndpoint(); - String userInfoEndpoint = cognitoService.getUserInfoEndpoint(); + String tokenEndpoint = cognitoService.getTokenEndpoint(pool.getId()); + String userInfoEndpoint = cognitoService.getUserInfoEndpoint(pool.getId()); String body = """ {"issuer":"%s","jwks_uri":"%s","token_endpoint":"%s","userinfo_endpoint":"%s","subject_types_supported":["public"],"response_types_supported":[],"grant_types_supported":["client_credentials"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"id_token_signing_alg_values_supported":["RS256"]} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java index e8120cf6b2..1dbb7e20fb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.core.common.docker.ContainerDetector; import io.github.hectorvent.floci.services.cloudfront.CloudFrontDistributionFilter; +import io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFilter; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; @@ -128,9 +129,11 @@ public class S3VirtualHostFilter implements ContainerRequestFilter { return; } - // A higher-priority CloudFront distribution filter may have already routed this request. - // Use its server-side marker rather than trusting a user-controlled path prefix. - if (Boolean.TRUE.equals(requestContext.getProperty(CloudFrontDistributionFilter.ROUTED_PROPERTY))) { + // A higher-priority Host filter (CloudFront, Cognito custom domain) may have already + // routed this request. Use its server-side marker rather than trusting a + // user-controlled path prefix. + if (Boolean.TRUE.equals(requestContext.getProperty(CloudFrontDistributionFilter.ROUTED_PROPERTY)) + || requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY) != null) { return; } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java index e2b1fbf976..1cd14a272c 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/AccountContextFilterTest.java @@ -160,6 +160,26 @@ class AccountContextFilterTest { assertEquals("eu-west-1", requestContext.getRegion()); } + @Test + void pinnedAccountWinsOverTheAuthorizationHeader() { + ContainerRequestContext ctx = mockContext( + "AWS4-HMAC-SHA256 Credential=000000000001/20260617/us-west-2/s3/aws4_request, SignedHeaders=host, Signature=abc", + null + ); + when(ctx.getProperty(AccountContextFilter.PINNED_ACCOUNT_PROPERTY)).thenReturn("111122223333"); + filter.filter(ctx); + assertEquals("111122223333", requestContext.getAccountId()); + assertEquals(DEFAULT_REGION, requestContext.getRegion()); + } + + @Test + void pinnedAccountAppliesToAnUnsignedRequest() { + ContainerRequestContext ctx = mockContext("Basic Y2xpZW50OnNlY3JldA==", null); + when(ctx.getProperty(AccountContextFilter.PINNED_ACCOUNT_PROPERTY)).thenReturn("111122223333"); + filter.filter(ctx); + assertEquals("111122223333", requestContext.getAccountId()); + } + private ContainerRequestContext mockContext(String authHeader, String xAmzCredential) { ContainerRequestContext ctx = mock(ContainerRequestContext.class); when(ctx.getHeaderString("Authorization")).thenReturn(authHeader); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilterTest.java new file mode 100644 index 0000000000..d5a59d7902 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilterTest.java @@ -0,0 +1,89 @@ +package io.github.hectorvent.floci.services.cognito; + +import io.github.hectorvent.floci.core.common.AccountContextFilter; +import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.UriInfo; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class CognitoCustomDomainFilterTest { + + private static final String DOMAIN = "auth.example.localhost.floci.io"; + private static final String ACCOUNT = "111122223333"; + + private final CognitoService cognitoService = mock(CognitoService.class); + private final CognitoCustomDomainFilter filter = new CognitoCustomDomainFilter(cognitoService); + + @Test + void rewritesAnOauthPathOnACustomDomainAndPinsThePool() { + ContainerRequestContext request = request("http://" + DOMAIN + ":4566/oauth2/token?x=1", DOMAIN + ":4566"); + when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc"))); + + filter.filter(request); + + verify(request).setProperty(CognitoCustomDomainFilter.POOL_PROPERTY, "us-east-1_abc"); + verify(request).setProperty(AccountContextFilter.PINNED_ACCOUNT_PROPERTY, ACCOUNT); + verify(request).setRequestUri(URI.create("http://" + DOMAIN + ":4566/cognito-idp/oauth2/token?x=1")); + } + + /** HTTP/2 carries no Host header; the authority is on the request URI. */ + @Test + void fallsBackToTheRequestAuthorityWithoutAHostHeader() { + ContainerRequestContext request = request("https://" + DOMAIN + "/oauth2/userInfo", null); + when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc"))); + + filter.filter(request); + + verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp/oauth2/userInfo")); + } + + @Test + void leavesOtherPathsAlone() { + ContainerRequestContext request = request("http://" + DOMAIN + "/cognito-idp/oauth2/token", DOMAIN); + + filter.filter(request); + + verifyNoInteractions(cognitoService); + verify(request, never()).setRequestUri(any()); + verify(request, never()).setProperty(any(), any()); + } + + @Test + void leavesUnknownHostsAlone() { + ContainerRequestContext request = request("http://nobody.localhost.floci.io/oauth2/token", "nobody.localhost.floci.io"); + when(cognitoService.findCustomDomain("nobody.localhost.floci.io")).thenReturn(Optional.empty()); + + filter.filter(request); + + verify(request, never()).setRequestUri(any()); + verify(request, never()).setProperty(any(), any()); + } + + private static ContainerRequestContext request(String uri, String hostHeader) { + ContainerRequestContext request = mock(ContainerRequestContext.class); + UriInfo uriInfo = mock(UriInfo.class); + when(uriInfo.getRequestUri()).thenReturn(URI.create(uri)); + when(request.getUriInfo()).thenReturn(uriInfo); + when(request.getHeaderString("Host")).thenReturn(hostHeader); + return request; + } + + private static UserPoolDomain domain(String poolId) { + UserPoolDomain domain = new UserPoolDomain(); + domain.setDomain(DOMAIN); + domain.setUserPoolId(poolId); + domain.setAwsAccountId(ACCOUNT); + domain.setCertificateArn("arn:aws:acm:us-east-1:000000000000:certificate/abc"); + return domain; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFixtures.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFixtures.java new file mode 100644 index 0000000000..c84420dbac --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFixtures.java @@ -0,0 +1,142 @@ +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.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.restassured.RestAssured.given; + +/** Shared setup for the custom-domain integration tests: pools, clients, certificates and token calls. */ +final class CognitoCustomDomainFixtures { + + static final String FLOCI_URL = "http://localhost:4566"; + static final String COGNITO = "AWSCognitoIdentityProviderService"; + static final String PASSWORD = "Perm1234!"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private CognitoCustomDomainFixtures() { + } + + static String createPool(String name) throws Exception { + return cognitoJson("CreateUserPool", "{\"PoolName\": \"" + name + "\"}").path("UserPool").path("Id").asText(); + } + + static String confidentialClient(String poolId) { + return """ + { + "UserPoolId": "%s", + "ClientName": "routing-client", + "GenerateSecret": true, + "AllowedOAuthFlowsUserPoolClient": true, + "AllowedOAuthFlows": ["client_credentials"], + "AllowedOAuthScopes": ["aws.cognito.signin.user.admin"] + } + """.formatted(poolId); + } + + static String customDomain(String domain, String poolId, String certificateArn) { + return """ + { + "Domain": "%s", + "UserPoolId": "%s", + "CustomDomainConfig": {"CertificateArn": "%s"} + } + """.formatted(domain, poolId, certificateArn); + } + + static String requestCertificate(String domainName) throws Exception { + return RestAssuredJsonUtils.awsActionJson("CertificateManager", "RequestCertificate", + certificateRequest(domainName)).path("CertificateArn").asText(); + } + + static String requestCertificateAs(String accountId, String domainName) throws Exception { + return awsJsonAs(accountId, "CertificateManager", "RequestCertificate", certificateRequest(domainName)) + .path("CertificateArn").asText(); + } + + private static String certificateRequest(String domainName) { + return "{\"DomainName\": \"" + domainName + "\", \"ValidationMethod\": \"DNS\"}"; + } + + static JsonNode awsJsonAs(String accountId, String target, String action, String body) throws Exception { + String response = awsActionAs(accountId, target, action, body).then().statusCode(200).extract().asString(); + return OBJECT_MAPPER.readTree(response); + } + + /** A management call signed for {@code accountId}: the account comes from the credential scope. */ + static Response awsActionAs(String accountId, String target, String action, String body) { + return given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accountId + + "/20260905/us-east-1/cognito-idp/aws4_request") + .header("X-Amz-Target", target + "." + action) + .contentType("application/x-amz-json-1.1") + .body(body) + .when() + .post("/"); + } + + /** A public client, a confirmed user and the access token USER_PASSWORD_AUTH issues for it. */ + static String signInNewUser(String poolId) throws Exception { + String publicClient = cognitoJson("CreateUserPoolClient", """ + {"UserPoolId": "%s", "ClientName": "routing-user-client"} + """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText(); + String username = "user-" + System.nanoTime() + "@example.com"; + cognitoAction("AdminCreateUser", """ + { + "UserPoolId": "%s", + "Username": "%s", + "UserAttributes": [ + {"Name": "email", "Value": "%s"}, + {"Name": "email_verified", "Value": "true"} + ] + } + """.formatted(poolId, username, username)).then().statusCode(200); + cognitoAction("AdminSetUserPassword", """ + {"UserPoolId": "%s", "Username": "%s", "Password": "%s", "Permanent": true} + """.formatted(poolId, username, PASSWORD)).then().statusCode(200); + return cognitoJson("InitiateAuth", """ + { + "ClientId": "%s", + "AuthFlow": "USER_PASSWORD_AUTH", + "AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"} + } + """.formatted(publicClient, username, PASSWORD)) + .path("AuthenticationResult").path("AccessToken").asText(); + } + + /** A client-credentials request with Basic authentication, on {@code host} when one is given. */ + static Response tokenRequest(String host, String clientId, String secret, String path) { + RequestSpecification request = given() + .header("Authorization", basic(clientId, secret)) + .formParam("grant_type", "client_credentials"); + if (host != null) { + request.header("Host", host); + } + return request.when().post(path); + } + + /** Runs one token request and returns null on the expected status, otherwise a description. */ + static String expect(int status, String host, String clientId, String secret, String path) { + Response response = tokenRequest(host, clientId, secret, path); + if (response.statusCode() != status) { + return "expected " + status + " for " + clientId + " on " + host + path + + " but got " + response.statusCode() + ": " + response.asString(); + } + return null; + } + + static String basic(String clientId, String secret) { + return "Basic " + Base64.getEncoder().encodeToString((clientId + ":" + secret).getBytes(StandardCharsets.UTF_8)); + } + + static JsonNode jwtPayload(String token) throws Exception { + return OBJECT_MAPPER.readTree(Base64.getUrlDecoder().decode(token.split("\\.")[1])); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java new file mode 100644 index 0000000000..84a11b3708 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java @@ -0,0 +1,239 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.FLOCI_URL; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.basic; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.confidentialClient; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.createPool; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.expect; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.jwtPayload; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.tokenRequest; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The OAuth contract of the token and userInfo endpoints when reached on a custom domain: the + * same answers AWS gives on {@code https:///oauth2/...}. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoCustomDomainOAuthContractIntegrationTest { + + private static final String DOMAIN = "auth-c-" + System.nanoTime() + ".teos.localhost.floci.io"; + + private static String poolA; + private static String clientA; + private static String secretA; + private static String clientB; + private static String secretB; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void setUpTwoPoolsAndOneCustomDomain() throws Exception { + poolA = createPool("ContractPoolA"); + String poolB = createPool("ContractPoolB"); + + JsonNode a = cognitoJson("CreateUserPoolClient", confidentialClient(poolA)).path("UserPoolClient"); + clientA = a.path("ClientId").asText(); + secretA = a.path("ClientSecret").asText(); + JsonNode b = cognitoJson("CreateUserPoolClient", confidentialClient(poolB)).path("UserPoolClient"); + clientB = b.path("ClientId").asText(); + secretB = b.path("ClientSecret").asText(); + + cognitoJson("CreateUserPoolDomain", customDomain(DOMAIN, poolA, requestCertificate(DOMAIN))); + } + + @Test + @Order(2) + void clientSecretPostIsAccepted() { + given() + .header("Host", DOMAIN) + .formParam("grant_type", "client_credentials") + .formParam("client_id", clientA) + .formParam("client_secret", secretA) + .when() + .post("/oauth2/token") + .then() + .statusCode(200) + .body("token_type", equalTo("Bearer")) + .body("expires_in", equalTo(3600)); + } + + @Test + @Order(3) + void wrongSecretIsInvalidClient() { + tokenRequest(DOMAIN, clientA, "not-the-secret", "/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_client")); + } + + @Test + @Order(4) + void unsupportedGrantTypeIsRefused() { + given() + .header("Host", DOMAIN) + .header("Authorization", basic(clientA, secretA)) + .formParam("grant_type", "authorization_code") + .formParam("code", "abc") + .when() + .post("/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("unsupported_grant_type")); + } + + @Test + @Order(5) + void scopeNotAllowedForTheClientIsInvalidScope() { + given() + .header("Host", DOMAIN) + .header("Authorization", basic(clientA, secretA)) + .formParam("grant_type", "client_credentials") + .formParam("scope", "openid") + .when() + .post("/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_scope")); + } + + /** The issuer stays the pool's, as on AWS where iss names cognito-idp, never the custom domain. */ + @Test + @Order(6) + void tokenNamesThePoolIssuerAndTheClient() throws Exception { + Response response = tokenRequest(DOMAIN, clientA, secretA, "/oauth2/token"); + + response.then() + .statusCode(200) + .contentType(containsString("application/json")) + .header("Cache-Control", equalTo("no-store")) + .header("Pragma", equalTo("no-cache")); + + JsonNode claims = jwtPayload(response.path("access_token")); + assertEquals(FLOCI_URL + "/" + poolA, claims.path("iss").asText()); + assertEquals(clientA, claims.path("client_id").asText()); + assertEquals("access", claims.path("token_use").asText()); + assertEquals("aws.cognito.signin.user.admin", claims.path("scope").asText()); + } + + /** A client-credentials token carries no user, so userInfo cannot serve it. */ + @Test + @Order(7) + void userInfoRefusesAMachineToken() { + String machineToken = tokenRequest(DOMAIN, clientA, secretA, "/oauth2/token") + .then().statusCode(200).extract().path("access_token"); + + given() + .header("Host", DOMAIN) + .header("Authorization", "Bearer " + machineToken) + .when() + .get("/oauth2/userInfo") + .then() + .statusCode(401) + .header("WWW-Authenticate", startsWith("Bearer error=\"invalid_token\"")); + } + + @Test + @Order(8) + void userInfoRefusesAMalformedBearerToken() { + given() + .header("Host", DOMAIN) + .header("Authorization", "Bearer not-a-jwt") + .when() + .get("/oauth2/userInfo") + .then() + .statusCode(401) + .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. */ + @Test + @Order(9) + void otherHostedUiPathsAreNotServed() { + for (String path : List.of("/oauth2/authorize", "/oauth2/revoke", "/oauth2/idpresponse")) { + given() + .header("Host", DOMAIN) + .when() + .get(path) + .then() + .statusCode(404); + } + } + + /** A prefix domain's hostname resolves to AWS, so Floci never routes by it. */ + @Test + @Order(10) + void prefixDomainHostIsNotRouted() throws Exception { + String prefix = "routing-prefix-" + System.nanoTime(); + cognitoJson("CreateUserPoolDomain", """ + {"Domain": "%s", "UserPoolId": "%s"} + """.formatted(prefix, poolA)); + + for (String host : List.of(prefix, prefix + ".auth.us-east-1.amazoncognito.com")) { + tokenRequest(host, clientA, secretA, "/oauth2/token") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + } + } + + /** + * The pinned pool and account live on one request. Interleaving custom-domain and generic + * requests on many threads must never let one request's pin decide another's answer. + */ + @Test + @Order(11) + void concurrentRequestsKeepTheirOwnPinnedPool() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(8); + try { + List> outcomes = new ArrayList<>(); + for (int i = 0; i < 60; i++) { + int kind = i % 3; + outcomes.add(pool.submit(() -> switch (kind) { + case 0 -> expect(200, DOMAIN, clientA, secretA, "/oauth2/token"); + case 1 -> expect(200, null, clientB, secretB, "/cognito-idp/oauth2/token"); + default -> expect(400, DOMAIN, clientB, secretB, "/oauth2/token"); + })); + } + List failures = new ArrayList<>(); + for (Future outcome : outcomes) { + String failure = outcome.get(30, TimeUnit.SECONDS); + if (failure != null) { + failures.add(failure); + } + } + assertTrue(failures.isEmpty(), () -> String.join("\n", failures)); + } finally { + pool.shutdownNow(); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainRoutingIntegrationTest.java new file mode 100644 index 0000000000..17e10738fa --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainRoutingIntegrationTest.java @@ -0,0 +1,359 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.COGNITO; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.FLOCI_URL; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.awsActionAs; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.awsJsonAs; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.basic; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.confidentialClient; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.createPool; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.expect; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificateAs; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.signInNewUser; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A Cognito custom domain serves {@code https:///oauth2/token} and + * {@code /oauth2/userInfo} on AWS. Floci resolves the request Host against the domain store and + * routes those paths to the handlers behind {@code /cognito-idp/oauth2/...}, pinned to the pool + * and the account that own the domain. The OAuth contract on the routed endpoints is covered by + * {@link CognitoCustomDomainOAuthContractIntegrationTest}. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoCustomDomainRoutingIntegrationTest { + + private static final String DOMAIN = "auth-" + System.nanoTime() + ".teos.localhost.floci.io"; + private static final String DOMAIN_B = "auth-b-" + System.nanoTime() + ".teos.localhost.floci.io"; + private static final String ACCOUNT_B = "111122223333"; + + private static String poolA; + private static String poolB; + private static String clientA; + private static String secretA; + private static String clientB; + private static String secretB; + private static String userTokenA; + private static String userTokenB; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void setUpTwoPoolsAndOneCustomDomain() throws Exception { + poolA = createPool("RoutingPoolA"); + poolB = createPool("RoutingPoolB"); + + JsonNode a = cognitoJson("CreateUserPoolClient", confidentialClient(poolA)).path("UserPoolClient"); + clientA = a.path("ClientId").asText(); + secretA = a.path("ClientSecret").asText(); + JsonNode b = cognitoJson("CreateUserPoolClient", confidentialClient(poolB)).path("UserPoolClient"); + clientB = b.path("ClientId").asText(); + secretB = b.path("ClientSecret").asText(); + + userTokenA = signInNewUser(poolA); + userTokenB = signInNewUser(poolB); + + cognitoJson("CreateUserPoolDomain", customDomain(DOMAIN, poolA, requestCertificate(DOMAIN))); + } + + @Test + @Order(2) + void tokenRequestOnTheCustomDomainReachesTheTokenHandler() { + given() + .header("Host", DOMAIN) + .header("Authorization", basic(clientA, secretA)) + .formParam("grant_type", "client_credentials") + .when() + .post("/oauth2/token") + .then() + .statusCode(200) + .body("token_type", equalTo("Bearer")); + } + + @Test + @Order(3) + void hostWithPortAndMixedCaseStillMatches() { + assertNull(expect(200, DOMAIN.toUpperCase() + ":4566", clientA, secretA, "/oauth2/token")); + } + + @Test + @Order(4) + void clientOfAnotherPoolIsRefusedOnThisDomain() { + given() + .header("Host", DOMAIN) + .header("Authorization", basic(clientB, secretB)) + .formParam("grant_type", "client_credentials") + .when() + .post("/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_client")); + } + + @Test + @Order(5) + void sameClientStillWorksOnTheGenericPath() { + assertNull(expect(200, null, clientB, secretB, "/cognito-idp/oauth2/token")); + } + + @Test + @Order(6) + void emptyPostOnTheCustomDomainAnswersInvalidRequest() { + given() + .header("Host", DOMAIN) + .contentType("application/x-www-form-urlencoded") + .when() + .post("/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")); + } + + /** Without a matching Host nothing is rewritten: /oauth2/token is S3's /{bucket}/{key}. */ + @Test + @Order(7) + void unknownHostIsLeftUntouched() { + given() + .header("Host", "nobody-" + System.nanoTime() + ".example.com") + .formParam("grant_type", "client_credentials") + .when() + .post("/oauth2/token") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + } + + @Test + @Order(8) + void userInfoWithoutBearerTokenIsRoutedToo() { + given() + .header("Host", DOMAIN) + .when() + .get("/oauth2/userInfo") + .then() + .statusCode(401) + .header("WWW-Authenticate", startsWith("Bearer error=\"invalid_token\"")); + } + + @Test + @Order(9) + void userInfoOnTheCustomDomainServesThePoolsOwnUsers() { + given() + .header("Host", DOMAIN) + .header("Authorization", "Bearer " + userTokenA) + .when() + .get("/oauth2/userInfo") + .then() + .statusCode(200) + .contentType(containsString("application/json")) + .header("Cache-Control", containsString("no-store")) + .header("Pragma", equalTo("no-cache")) + .body("email_verified", equalTo("true")); + } + + @Test + @Order(10) + void userInfoOnTheCustomDomainRefusesATokenOfAnotherPool() { + given() + .header("Host", DOMAIN) + .header("Authorization", "Bearer " + userTokenB) + .when() + .get("/oauth2/userInfo") + .then() + .statusCode(401) + .header("WWW-Authenticate", startsWith("Bearer error=\"invalid_token\"")); + + given() + .header("Authorization", "Bearer " + userTokenB) + .when() + .get("/cognito-idp/oauth2/userInfo") + .then() + .statusCode(200); + } + + @Test + @Order(11) + void openIdConfigurationAdvertisesTheCustomDomain() { + given() + .when() + .get("/" + poolA + "/.well-known/openid-configuration") + .then() + .statusCode(200) + .body("issuer", equalTo(FLOCI_URL + "/" + poolA)) + .body("jwks_uri", equalTo(FLOCI_URL + "/" + poolA + "/.well-known/jwks.json")) + .body("token_endpoint", equalTo("https://" + DOMAIN + "/oauth2/token")) + .body("userinfo_endpoint", equalTo("https://" + DOMAIN + "/oauth2/userInfo")); + + given() + .when() + .get("/" + poolB + "/.well-known/openid-configuration") + .then() + .statusCode(200) + .body("token_endpoint", equalTo(FLOCI_URL + "/cognito-idp/oauth2/token")) + .body("userinfo_endpoint", equalTo(FLOCI_URL + "/cognito-idp/oauth2/userInfo")); + } + + /** Domain names are one global namespace on AWS, whichever account asks. */ + @Test + @Order(12) + void anotherAccountCannotReuseTheDomainName() throws Exception { + String poolInB = awsJsonAs(ACCOUNT_B, COGNITO, "CreateUserPool", "{\"PoolName\": \"RoutingPoolB2\"}") + .path("UserPool").path("Id").asText(); + + awsActionAs(ACCOUNT_B, COGNITO, "CreateUserPoolDomain", + customDomain(DOMAIN, poolInB, requestCertificateAs(ACCOUNT_B, DOMAIN))) + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + /** The domain's account, not the default one, serves a request on that domain. */ + @Test + @Order(13) + void tokenOnAnotherAccountsDomainRunsInThatAccount() throws Exception { + String poolInB = awsJsonAs(ACCOUNT_B, COGNITO, "CreateUserPool", "{\"PoolName\": \"RoutingPoolB3\"}") + .path("UserPool").path("Id").asText(); + JsonNode client = awsJsonAs(ACCOUNT_B, COGNITO, "CreateUserPoolClient", confidentialClient(poolInB)) + .path("UserPoolClient"); + String clientInB = client.path("ClientId").asText(); + String secretInB = client.path("ClientSecret").asText(); + awsJsonAs(ACCOUNT_B, COGNITO, "CreateUserPoolDomain", + customDomain(DOMAIN_B, poolInB, requestCertificateAs(ACCOUNT_B, DOMAIN_B))); + + assertNull(expect(200, DOMAIN_B, clientInB, secretInB, "/oauth2/token")); + + given() + .header("Authorization", basic(clientInB, secretInB)) + .formParam("grant_type", "client_credentials") + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_client")); + } + + @Test + @Order(14) + void replacingTheCertificateKeepsTheDomainRouted() throws Exception { + cognitoJson("UpdateUserPoolDomain", customDomain(DOMAIN, poolA, requestCertificate(DOMAIN))); + + assertNull(expect(200, DOMAIN, clientA, secretA, "/oauth2/token")); + } + + @Test + @Order(15) + void deletedDomainIsNoLongerRouted() throws Exception { + cognitoJson("DeleteUserPoolDomain", """ + {"Domain": "%s", "UserPoolId": "%s"} + """.formatted(DOMAIN, poolA)); + + given() + .header("Host", DOMAIN) + .header("Authorization", basic(clientA, secretA)) + .formParam("grant_type", "client_credentials") + .when() + .post("/oauth2/token") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + + given() + .when() + .get("/" + poolA + "/.well-known/openid-configuration") + .then() + .statusCode(200) + .body("token_endpoint", equalTo(FLOCI_URL + "/cognito-idp/oauth2/token")); + } + + /** After a delete the name is free again, and it follows its new pool. */ + @Test + @Order(16) + void domainNameFollowsItsNewPoolAfterReassignment() throws Exception { + cognitoJson("CreateUserPoolDomain", customDomain(DOMAIN, poolB, requestCertificate(DOMAIN))); + + assertNull(expect(200, DOMAIN, clientB, secretB, "/oauth2/token")); + assertNull(expect(400, DOMAIN, clientA, secretA, "/oauth2/token")); + + given() + .when() + .get("/" + poolB + "/.well-known/openid-configuration") + .then() + .statusCode(200) + .body("token_endpoint", equalTo("https://" + DOMAIN + "/oauth2/token")); + } + + /** Two accounts racing for one name: exactly one create succeeds, so the name never turns ambiguous. */ + @Test + @Order(17) + void concurrentCreatesAcrossAccountsLeaveOneOwner() throws Exception { + String contested = "auth-race-" + System.nanoTime() + ".teos.localhost.floci.io"; + String defaultAccount = "000000000000"; + String poolInA = createPool("RacePoolA"); + String poolInB = awsJsonAs(ACCOUNT_B, COGNITO, "CreateUserPool", "{\"PoolName\": \"RacePoolB\"}") + .path("UserPool").path("Id").asText(); + String certificateA = requestCertificate(contested); + String certificateB = requestCertificateAs(ACCOUNT_B, contested); + + ExecutorService executor = Executors.newFixedThreadPool(8); + try { + List> outcomes = new ArrayList<>(); + for (int i = 0; i < 16; i++) { + boolean inA = i % 2 == 0; + outcomes.add(executor.submit(() -> awsActionAs(inA ? defaultAccount : ACCOUNT_B, COGNITO, + "CreateUserPoolDomain", + customDomain(contested, inA ? poolInA : poolInB, inA ? certificateA : certificateB)) + .statusCode())); + } + int created = 0; + for (Future outcome : outcomes) { + int status = outcome.get(30, TimeUnit.SECONDS); + assertTrue(status == 200 || status == 400, "unexpected status " + status); + if (status == 200) { + created++; + } + } + assertEquals(1, created); + } finally { + executor.shutdownNow(); + } + + assertNull(expect(400, contested, clientA, secretA, "/oauth2/token")); + given() + .header("Host", contested) + .header("Authorization", basic(clientA, secretA)) + .formParam("grant_type", "client_credentials") + .when() + .post("/oauth2/token") + .then() + .body("error", equalTo("invalid_client")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index 717dae4cc8..ae763ae448 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.acm.model.CertificateStatus; 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.ResourceServerScope; 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; @@ -32,6 +33,11 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +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.Function; import static org.junit.jupiter.api.Assertions.*; @@ -3440,6 +3446,139 @@ class CognitoServiceTest { verify(acmService, never()).removeInUseBy(any(), any(), any()); } + @Test + void findCustomDomainMatchesOnlyCustomDomains() { + String poolId = createPoolWithCustomDomain("auth.teos.localhost.floci.io").getId(); + service.createUserPoolDomain("teos-prefix", poolId, null, null); + + assertEquals(poolId, service.findCustomDomain("auth.teos.localhost.floci.io").orElseThrow().getUserPoolId()); + assertEquals(poolId, service.findCustomDomain("AUTH.teos.localhost.floci.io").orElseThrow().getUserPoolId()); + assertTrue(service.findCustomDomain("teos-prefix").isEmpty()); + assertTrue(service.findCustomDomain("nobody.localhost.floci.io").isEmpty()); + assertTrue(service.findCustomDomain(null).isEmpty()); + assertEquals("auth.teos.localhost.floci.io", + service.findCustomDomainForPool(poolId).orElseThrow().getDomain()); + } + + /** The uniqueness check and the write are one step, so a burst of creates leaves one owner. */ + @Test + void concurrentCreatesOfTheSameDomainLetExactlyOneWin() throws Exception { + int threads = 16; + List pools = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + pools.add(service.createUserPool(Map.of("PoolName", "race-" + i), "us-east-1").getId()); + } + ExecutorService executor = Executors.newFixedThreadPool(threads); + CountDownLatch start = new CountDownLatch(1); + try { + List> outcomes = new ArrayList<>(); + for (String poolId : pools) { + outcomes.add(executor.submit(() -> { + start.await(); + try { + service.createUserPoolDomain("auth.race.localhost.floci.io", poolId, + Map.of("CertificateArn", CERTIFICATE_ARN), null); + return true; + } catch (AwsException e) { + assertEquals("InvalidParameterException", e.getErrorCode()); + return false; + } + })); + } + start.countDown(); + int winners = 0; + for (Future outcome : outcomes) { + if (outcome.get(10, TimeUnit.SECONDS)) { + winners++; + } + } + assertEquals(1, winners); + verify(acmService, times(1)).addInUseBy(eq(CERTIFICATE_ARN), any(), eq("us-east-1")); + } finally { + executor.shutdownNow(); + } + } + + /** Two accounts holding the same name can only come from data persisted before names were global. */ + @Test + void ambiguousCustomDomainIsNotRouted() { + InMemoryStorage domains = new InMemoryStorage<>(); + domains.put("111111111111/auth.dup.localhost.floci.io", customDomain("auth.dup.localhost.floci.io", "us-east-1_a")); + domains.put("222222222222/auth.dup.localhost.floci.io", customDomain("auth.dup.localhost.floci.io", "us-east-1_b")); + CognitoService ambiguous = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), domains, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566", regionResolver, null, + acmService, null, null); + + assertTrue(ambiguous.findCustomDomain("auth.dup.localhost.floci.io").isEmpty()); + } + + private static UserPoolDomain customDomain(String name, String poolId) { + UserPoolDomain domain = new UserPoolDomain(); + domain.setDomain(name); + domain.setUserPoolId(poolId); + domain.setCertificateArn(CERTIFICATE_ARN); + return domain; + } + + @Test + void findCustomDomainForPoolIgnoresPrefixDomainsAndOtherPools() { + String prefixOnly = service.createUserPool(Map.of("PoolName", "prefix-only"), "us-east-1").getId(); + service.createUserPoolDomain("prefix-only", prefixOnly, null, null); + createPoolWithCustomDomain("auth.other.localhost.floci.io"); + + assertTrue(service.findCustomDomainForPool(prefixOnly).isEmpty()); + } + + @Test + void clientCredentialsTokenIsRefusedWhenTheClientBelongsToAnotherPool() { + String poolA = service.createUserPool(Map.of("PoolName", "pool-a"), "us-east-1").getId(); + String poolB = service.createUserPool(Map.of("PoolName", "pool-b"), "us-east-1").getId(); + ResourceServerScope read = new ResourceServerScope(); + read.setScopeName("read"); + service.createResourceServer(poolB, "notes", "Notes", List.of(read)); + UserPoolClient clientB = service.createUserPoolClient(poolB, "b", true, true, + List.of("client_credentials"), List.of("notes/read")); + + AwsException failure = assertThrows(AwsException.class, () -> service.issueClientCredentialsToken( + clientB.getClientId(), clientB.getClientSecret(), null, poolA)); + assertEquals("ResourceNotFoundException", failure.getErrorCode()); + + assertNotNull(service.issueClientCredentialsToken(clientB.getClientId(), clientB.getClientSecret(), null, poolB) + .get("access_token")); + assertNotNull(service.issueClientCredentialsToken(clientB.getClientId(), clientB.getClientSecret(), null, null) + .get("access_token")); + } + + /** The pool check precedes the secret check, so a wrong domain never reveals whether a secret is right. */ + @Test + void poolScopeIsCheckedBeforeTheClientSecret() { + String poolA = service.createUserPool(Map.of("PoolName", "pool-a"), "us-east-1").getId(); + String poolB = service.createUserPool(Map.of("PoolName", "pool-b"), "us-east-1").getId(); + UserPoolClient clientB = service.createUserPoolClient(poolB, "b", true, true, + List.of("client_credentials"), List.of("openid")); + + AwsException wrongPool = assertThrows(AwsException.class, () -> service.issueClientCredentialsToken( + clientB.getClientId(), "wrong-secret", null, poolA)); + assertEquals("ResourceNotFoundException", wrongPool.getErrorCode()); + + AwsException rightPool = assertThrows(AwsException.class, () -> service.issueClientCredentialsToken( + clientB.getClientId(), "wrong-secret", null, poolB)); + assertNotEquals("ResourceNotFoundException", rightPool.getErrorCode()); + } + + @Test + void endpointsUseTheCustomDomainWhenThePoolHasOne() { + String withDomain = createPoolWithCustomDomain("auth2.teos.localhost.floci.io").getId(); + String without = service.createUserPool(Map.of("PoolName", "without-domain"), "us-east-1").getId(); + service.createUserPoolDomain("prefix-only", without, null, null); + + assertEquals("https://auth2.teos.localhost.floci.io/oauth2/token", service.getTokenEndpoint(withDomain)); + assertEquals("https://auth2.teos.localhost.floci.io/oauth2/userInfo", service.getUserInfoEndpoint(withDomain)); + assertEquals("http://localhost:4566/cognito-idp/oauth2/token", service.getTokenEndpoint(without)); + assertEquals("http://localhost:4566/cognito-idp/oauth2/userInfo", service.getUserInfoEndpoint(without)); + } + @Test void deleteUserPoolDomainReleasesTheCertificate() { UserPool pool = createPoolWithCustomDomain("auth.example.com");