mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cognito): route custom domains by Host (#3095)
* feat(cognito): route /oauth2 requests on a custom domain by Host CognitoCustomDomainFilter (PreMatching, priority 12) resolves the request Host against the domain store and rewrites /oauth2/token and /oauth2/userInfo onto the /cognito-idp/oauth2 handlers. The pool the domain belongs to travels in a request property, so the controllers pin exactly the pool the filter matched and a caller cannot supply it. The token endpoint refuses a client of another pool with invalid_client and userInfo refuses a token of another pool with invalid_token, as AWS does. The lookups scan every account because an OAuth call carries no SigV4 account. The discovery document advertises https://<domain>/oauth2/... for a pool with a custom domain. S3VirtualHostFilter skips a request the Cognito filter routed, the way it already skips CloudFront ones, since a custom domain under a Floci suffix looks like a bucket host. * docs(cognito): custom domain routing * fix(cognito): run custom domain requests in the domain's account and keep domain names unique A request on a custom domain carries no AWS credential, so AccountContextFilter put it in the default account and the client, pool and user lookups missed a domain created under another account. The Cognito filter now pins the domain's account in a request property that AccountContextFilter honours before header resolution. Domain creation checks the name across every account, as AWS's single domain namespace does, and a name two accounts already hold from older data is not routed. Also adds the OAuth contract tests for the routed endpoints (client_secret_post, error codes, token claims, userInfo refusals, unserved paths, prefix domains, interleaved requests on several threads) in a second integration class. * fix(cognito): make the domain uniqueness check and write one step Two accounts creating the same custom domain at once both passed the cross-account scan and wrote under their own account-prefixed keys, leaving a name that routing then refused as ambiguous. The check and the write now run under one lock, the way identity-provider mutations already do. A 16-thread unit race and a two-account integration race pin exactly one owner.
This commit is contained in:
1 parent
8686651de1
commit
b4d80a5596
14 files changed
+1212
-19
No files matched your search
@@ -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);
|
||||
|
||||
+85
@@ -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://<domain>/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<UserPoolDomain> 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;
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -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<String, String> formParams) {
|
||||
return issueToken(authorization, formParams);
|
||||
String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY);
|
||||
return issueToken(authorization, formParams, domainPoolId);
|
||||
}
|
||||
|
||||
private Response issueToken(String authorization, MultivaluedMap<String, String> formParams) {
|
||||
private Response issueToken(String authorization, MultivaluedMap<String, String> 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<String, Object> result = cognitoService.issueClientCredentialsToken(clientId, clientSecret, scope);
|
||||
Map<String, Object> result = cognitoService.issueClientCredentialsToken(
|
||||
clientId, clientSecret, scope, domainPoolId);
|
||||
return Response.ok(objectMapper.valueToTree(result))
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.header("Cache-Control", "no-store")
|
||||
|
||||
@@ -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<UserPoolDomain> findCustomDomain(String hostname) {
|
||||
List<UserPoolDomain> 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<UserPoolDomain> findDomains(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
return allDomains().stream()
|
||||
.filter(d -> name.equalsIgnoreCase(d.getDomain()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Optional<UserPoolDomain> findCustomDomainForPool(String poolId) {
|
||||
return allDomains().stream()
|
||||
.filter(d -> d.isCustomDomain() && poolId.equals(d.getUserPoolId()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private List<UserPoolDomain> allDomains() {
|
||||
return domainStore instanceof AccountAwareStorageBackend<UserPoolDomain> 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<String, Object> 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<String, Object> 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 ────────────────────────────
|
||||
|
||||
+8
-1
@@ -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 {
|
||||
|
||||
+2
-2
@@ -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"]}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user