fix(cognito): reject token validity outside AWS's limits (#5160)

* fix(cognito): reject token validity outside AWS's limits

CreateUserPoolClient and UpdateUserPoolClient accepted any positive token
validity, so a client with one-minute access and ID tokens, or a
20-minute refresh token, worked locally and failed on deploy. AWS allows
access and ID tokens between 5 minutes and 1 day and refresh tokens
between 60 minutes and 3,650 days, in each token's TokenValidityUnits
unit (hours for access and ID tokens, days for refresh tokens, by
default). A client outside them now fails with InvalidParameterException
"Invalid range for token validity.", the message AWS returns.

floci.services.cognito.enforce-token-validity-limits (env
FLOCI_SERVICES_COGNITO_ENFORCE_TOKEN_VALIDITY_LIMITS, default true) turns
the check off for tests that want tokens shorter than AWS allows.

* test(scheduler): start recurring test schedules in the future

Since #5610 a rate schedule's first occurrence is its creation time, so
a schedule is due the moment it exists. The application's own dispatcher
keeps ticking every 10 seconds during @QuarkusTest and sees every
schedule, so a tick that lands between CreateSchedule and the test's own
dispatcher fires the schedule once more than the test expects.

Four tests create an enabled rate(1 minute) schedule and count exact
deliveries: recurringScheduleStartsOneExecutionPerOccurrence,
stepFunctionsDeleteScheduleStopsFutureOccurrence,
rateScheduleDeliversEachOccurrenceWithItsScheduledTime and
executionIdsDifferBetweenOccurrences. They now create the schedule
through SchedulerTestHarness.createRecurringSchedule, which sets a
StartDate a day ahead, and tick past it on their scoped dispatcher. The
application's dispatcher skips a schedule before its StartDate, and the
test profile and its tick interval stay as they are.

* test(compat): poll OpenSearch domain readiness every 250 ms against Floci

OpenSearchTest waited for the domain to finish processing in its own loop
that slept 5 s between checks and swallowed InterruptedException. Floci
flips Processing to false on its own 3 s readiness poll, so the test
could sit up to 5 s past the moment the domain was ready.

The wait now goes through TestFixtures.await, polling every 250 ms
against Floci and keeping the 5 s cadence against real AWS, with the
same 3 minute timeout.

* fix(opensearch): run domain containers under an init process so a stop ends them at once

The OpenSearch image's entrypoint is a bash script that starts the server
as its child instead of exec'ing it. Running as PID 1, that script ignores
SIGTERM, so every DeleteDomain, and every shutdown for each domain, waited
out the whole 5 s stop timeout before Docker sent SIGKILL. The server
never saw the SIGTERM either way.

Domain containers now run under Docker's init process, which takes the
SIGTERM and ends the container at once. Stopping a ready 2.11.1 container
took 5.27 s (exit 137) without it and 0.26 s (exit 143) with it, and
DeleteDomain in the compatibility OpenSearchTest took 5.3 s.

The two startDomain tests' shared setup moves into one helper, which the
new init test uses too.

* fix(cognito): keep a RefreshTokenValidity of 0 at 30 days in any unit

AWS replaces a RefreshTokenValidity of 0 with "the default value of 30
days". Floci stored the bare number 30 in the client's refresh token
unit, so a client with RefreshToken=minutes issued 30-minute refresh
tokens. With the token validity limits, any later UpdateUserPoolClient
that left the validity alone re-checked that stored 30 minutes and
failed with "Invalid range for token validity.", for a client Floci had
accepted.

A 0 now becomes 30 days in the client's refresh token unit (2592000
seconds, 43200 minutes, 720 hours or 30 days), on create and on update,
and the limits check runs on that normalized value. Also imports UUID on
a test line that spelled it out in full.

* fix(cognito): reset the settings UpdateUserPoolClient omits to their defaults

AWS: "If you don't provide a value for an attribute, Amazon Cognito sets
it to its default value." The developer guide adds that an update with
one parameter "sets all others to a default value". Floci kept the
stored value of every setting the request left out, so a client could
end up with a combination AWS never produces: an AccessTokenValidity of
60 kept from a minutes client, read in the hours of a units-only update,
was refused as out of range, where AWS resets the validity and accepts.

CreateUserPoolClient and UpdateUserPoolClient now build their settings
in one place, with a new client's default for each one the request
omits, and the update copies them onto the stored client. ClientName is
the exception: the API documents no default for it, so an update without
one keeps the name. The id, the secrets, the dates and the branding are
not settings and stay as they are. An explicitly empty list still clears
the setting.

The AuthSessionValidity tests and the boto3 compatibility test that
asserted the old keep-on-omit behaviour now expect the 3-minute default.

* test: share one self-signed and one user-cert TLS profile across the TLS integration tests

CustomDomainTlsIntegrationTest, TlsEnsureHostIntegrationTest, TlsHttp2HostRoutingIntegrationTest and EcrTlsDataPlaneDockerIntegrationTest each declared a self-signed TLS profile whose static block wrote its own CA-issued leaf before boot, and under @QuarkusTest that leaf is the one served. They now share SelfSignedTlsProfile, which writes one leaf for all four: the SANs TlsConfigSource uses by default, without 127.0.0.1, plus the API Gateway custom domain the HTTP/2 test routes to. The custom domain and ensure-host tests connect by IP and expect a name the leaf doesn't cover yet to be refused, and the JDK falls back to the peer address when the SNI name doesn't match, so a 127.0.0.1 SAN would let those handshakes through. The leaf and its metadata are written fresh every run, which also drops hostnames an earlier run learned at runtime, and the container CA bundle the ECR test relied on is written beside them.

TlsIntegrationTest and TlsUserCertIntegrationTest declared the same user-provided certificate setup apart from paths. They share UserCertTlsProfile, which keeps the certificate file carrying its private key, since TlsUserCertIntegrationTest checks /_floci/ca.pem never echoes it.

Both profiles live in the config test package, beside every class that uses them and the package-private default SAN list, and expose their paths as compile-time constants, so a test can read them without initializing the profile class and rerunning its static block under the running application.

Sharing an application also means no class may leave anything behind for the next. TlsHttp2HostRoutingIntegrationTest now removes the bucket, CloudFront public key, key group and distribution, and the REST API, domain name and base path mapping it creates. EcrTlsDataPlaneDockerIntegrationTest deletes the manifest it pushes, TlsIntegrationTest its queue and TlsUserCertIntegrationTest its parameter. CustomDomainTlsIntegrationTest and TlsEnsureHostIntegrationTest already end with a state reset, which keeps the configured names from the profile's metadata, so neither changes the leaf a later class is served.

The ECR test's registry container also outlived every run: keep-running-on-shutdown defaults to true and the test config never overrides it, and the next application to start adopted the container by name, a developer's own Floci registry included. SelfSignedTlsProfile now names it in the run's sidecar namespace, which SidecarContainersProfile exposes for this, and stops it at shutdown. The test checks for Docker through SidecarContainersProfile.requireDockerAndImage, so a registry a killed run left behind is removed like any other abandoned sidecar.

Part of #4542.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
jwoa95andPriamo authored and GitHub committed 2026-10-14 17:40:23 -04:00
1 parent 91c67c69df
commit 17c40cecbd
27 files changed
+837 -613

No files matched your search

@@ -1920,6 +1920,18 @@ public interface EmulatorConfig {
interface CognitoServiceConfig {
@WithDefault("true")
boolean enabled();
/**
* Rejects an app client whose token validity is outside AWS's limits: access and ID tokens
* between 5 minutes and 1 day, refresh tokens between 60 minutes and 3,650 days. Env:
* {@code FLOCI_SERVICES_COGNITO_ENFORCE_TOKEN_VALIDITY_LIMITS}
*
* <p>On by default, because a client that Floci accepts and AWS refuses only fails when it is
* deployed. Turn it off to keep tokens shorter than AWS allows, such as a one-minute access
* token for a test of what happens when it expires.
*/
@WithDefault("true")
boolean enforceTokenValidityLimits();
}
interface StepFunctionsServiceConfig {
@@ -98,6 +98,10 @@ import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownR
@ApplicationScoped
public class CognitoService implements ResourceProvider {
private static final int DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS = 30;
private static final Duration MIN_ACCESS_AND_ID_TOKEN_VALIDITY = Duration.ofMinutes(5);
private static final Duration MAX_ACCESS_AND_ID_TOKEN_VALIDITY = Duration.ofDays(1);
private static final Duration MIN_REFRESH_TOKEN_VALIDITY = Duration.ofMinutes(60);
private static final Duration MAX_REFRESH_TOKEN_VALIDITY = Duration.ofDays(3650);
static final List<String> DEFAULT_EXPLICIT_AUTH_FLOWS =
List.of("ALLOW_REFRESH_TOKEN_AUTH", "ALLOW_USER_SRP_AUTH", "ALLOW_CUSTOM_AUTH");
private static final String COGNITO_PASSWORD_SYMBOLS =
@@ -168,6 +172,7 @@ public class CognitoService implements ResourceProvider {
private final VerificationCodeService verificationCodeService;
private final CognitoMessageDispatcher messageDispatcher;
private final TlsCertificateManager certificateManager;
private final boolean enforceTokenValidityLimits;
private final Object[] userLocks = newUserLockStripes();
// The userKey of each username an AdminCreateUser is creating, from before its existence check
// until it stores the user or fails, so an overlapping request for the same username is refused
@@ -221,7 +226,8 @@ public class CognitoService implements ResourceProvider {
new VerificationCodeService(storageFactory, clock),
new CognitoMessageDispatcher(sesService, snsService, regionResolver.getDefaultRegion()),
certificateManager,
clock
clock,
emulatorConfig.services().cognito().enforceTokenValidityLimits()
);
}
@@ -293,10 +299,10 @@ public class CognitoService implements ResourceProvider {
}
/**
* Full constructor accepting the {@link Clock} used to time-bound Cognito auth challenge
* sessions (see {@link CognitoAuthFlowHandler}). Production code reaches this through the
* {@code @Inject} constructor above with the CDI-managed clock; every other constructor here
* defaults to {@link Clock#systemUTC()} so existing call sites are unaffected.
* Accepts the {@link Clock} used to time-bound Cognito auth challenge sessions (see
* {@link CognitoAuthFlowHandler}); every constructor above defaults to {@link Clock#systemUTC()}
* so existing call sites are unaffected. Enforces AWS's token validity limits, as Floci does by
* default.
*/
CognitoService(StorageBackend<String, UserPool> poolStore,
StorageBackend<String, UserPoolClient> clientStore,
@@ -313,6 +319,34 @@ public class CognitoService implements ResourceProvider {
CognitoMessageDispatcher messageDispatcher,
TlsCertificateManager certificateManager,
Clock clock) {
this(poolStore, clientStore, resourceServerStore, domainStore, identityProviderStore, userStore,
groupStore, revokedTokenStore, baseUrl, cloudFrontDomainSuffix, regionResolver, lambdaService,
acmService, verificationCodeService, messageDispatcher, certificateManager, clock, true);
}
/**
* Full constructor. Production code reaches this through the {@code @Inject} constructor above,
* with the CDI-managed clock and {@code floci.services.cognito.enforce-token-validity-limits}.
*
* @param enforceTokenValidityLimits whether an app client's token validity must be within AWS's
* limits; see {@link #validateTokenValidityLimits}
*/
CognitoService(StorageBackend<String, UserPool> poolStore,
StorageBackend<String, UserPoolClient> clientStore,
StorageBackend<String, ResourceServer> resourceServerStore,
StorageBackend<String, UserPoolDomain> domainStore,
StorageBackend<String, IdentityProvider> identityProviderStore,
StorageBackend<String, CognitoUser> userStore,
StorageBackend<String, CognitoGroup> groupStore,
StorageBackend<String, RevokedTokenInfo> revokedTokenStore,
String baseUrl,
String cloudFrontDomainSuffix,
RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService,
VerificationCodeService verificationCodeService,
CognitoMessageDispatcher messageDispatcher,
TlsCertificateManager certificateManager,
Clock clock,
boolean enforceTokenValidityLimits) {
this.poolStore = poolStore;
this.clientStore = clientStore;
this.resourceServerStore = resourceServerStore;
@@ -329,6 +363,7 @@ public class CognitoService implements ResourceProvider {
this.verificationCodeService = verificationCodeService;
this.messageDispatcher = messageDispatcher;
this.certificateManager = certificateManager;
this.enforceTokenValidityLimits = enforceTokenValidityLimits;
this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver, clock);
this.webAuthn = new CognitoWebAuthn(clock);
}
@@ -1055,59 +1090,17 @@ public class CognitoService implements ResourceProvider {
validateAuthSessionValidity(authSessionValidity);
UserPool userPool = describeUserPool(userPoolId);
String clientId = clientIdFor(userPool, clientName);
List<String> normalizedAllowedOAuthFlows = normalizeStringList(allowedOAuthFlows);
List<String> normalizedAllowedOAuthScopes = normalizeStringList(allowedOAuthScopes);
List<String> normalizedCallbackUrls = normalizeStringList(callbackURLs);
String normalizedDefaultRedirectUri = normalizeOptionalString(defaultRedirectURI);
List<String> normalizedExplicitAuthFlows = normalizeStringList(explicitAuthFlows);
List<String> normalizedLogoutUrls = normalizeStringList(logoutURLs);
List<String> normalizedReadAttributes = normalizeStringList(readAttributes);
List<String> normalizedSupportedIdentityProviders = normalizeStringList(supportedIdentityProviders);
Map<String, String> copiedTokenValidityUnits = copyStringMap(tokenValidityUnits);
List<String> normalizedWriteAttributes = normalizeStringList(writeAttributes);
Integer normalizedRefreshTokenValidity = normalizeRefreshTokenValidity(refreshTokenValidity);
validateUserPoolClientConfiguration(
allowedOAuthFlowsUserPoolClient,
normalizedAllowedOAuthFlows,
normalizedAllowedOAuthScopes,
normalizedCallbackUrls,
normalizedDefaultRedirectUri,
accessTokenValidity,
idTokenValidity,
normalizedRefreshTokenValidity,
normalizedLogoutUrls,
copiedTokenValidityUnits
);
UserPoolClient client = new UserPoolClient();
UserPoolClient client = requestedClientSettings(clientName, allowedOAuthFlowsUserPoolClient,
allowedOAuthFlows, allowedOAuthScopes, analyticsConfiguration, callbackURLs, defaultRedirectURI,
explicitAuthFlows, accessTokenValidity, idTokenValidity, logoutURLs, preventUserExistenceErrors,
readAttributes, refreshTokenValidity, supportedIdentityProviders, tokenValidityUnits,
writeAttributes, refreshTokenRotation, enableTokenRevocation, authSessionValidity);
if (client.getSupportedIdentityProviders().isEmpty()) {
client.setSupportedIdentityProviders(List.of("COGNITO"));
}
client.setClientId(clientId);
client.setUserPoolId(userPoolId);
client.setClientName(clientName);
client.setGenerateSecret(generateSecret);
client.setAllowedOAuthFlowsUserPoolClient(allowedOAuthFlowsUserPoolClient);
client.setAllowedOAuthFlows(normalizedAllowedOAuthFlows);
client.setAllowedOAuthScopes(normalizedAllowedOAuthScopes);
client.setAnalyticsConfiguration(copyObjectMap(analyticsConfiguration));
client.setCallbackURLs(normalizedCallbackUrls);
client.setDefaultRedirectURI(normalizedDefaultRedirectUri);
client.setExplicitAuthFlows(normalizedExplicitAuthFlows);
client.setAccessTokenValidity(accessTokenValidity);
client.setIdTokenValidity(idTokenValidity);
if (authSessionValidity != null) {
client.setAuthSessionValidity(authSessionValidity);
}
client.setLogoutURLs(normalizedLogoutUrls);
client.setPreventUserExistenceErrors(preventUserExistenceErrors);
client.setReadAttributes(normalizedReadAttributes);
client.setRefreshTokenValidity(normalizedRefreshTokenValidity);
client.setSupportedIdentityProviders(normalizedSupportedIdentityProviders.isEmpty()
? List.of("COGNITO")
: normalizedSupportedIdentityProviders);
client.setTokenValidityUnits(copiedTokenValidityUnits);
client.setWriteAttributes(normalizedWriteAttributes);
client.setRefreshTokenRotation(copyObjectMap(refreshTokenRotation));
client.setEnableTokenRevocation(enableTokenRevocation != null ? enableTokenRevocation : Boolean.TRUE);
if (generateSecret) {
String clientSecret = generateSecretValue();
if (userPool.getClientSecretOverride() != null) {
@@ -1241,6 +1234,12 @@ public class CognitoService implements ResourceProvider {
enableTokenRevocation, null);
}
/**
* AWS: "If you don't provide a value for an attribute, Amazon Cognito sets it to its default value."
* So a setting the request leaves out, null here, takes the default a new client gets rather than
* keeping its stored value. The name is the exception: the API documents no default for it, so an
* update without one keeps the client's.
*/
public UserPoolClient updateUserPoolClient(String userPoolId, String clientId, String clientName,
Boolean allowedOAuthFlowsUserPoolClient,
List<String> allowedOAuthFlows, List<String> allowedOAuthScopes,
@@ -1254,108 +1253,13 @@ public class CognitoService implements ResourceProvider {
Boolean enableTokenRevocation, Integer authSessionValidity) {
validateAuthSessionValidity(authSessionValidity);
UserPoolClient client = describeUserPoolClient(userPoolId, clientId);
boolean effectiveAllowedOAuthFlowsUserPoolClient = allowedOAuthFlowsUserPoolClient != null
? allowedOAuthFlowsUserPoolClient
: client.isAllowedOAuthFlowsUserPoolClient();
List<String> effectiveAllowedOAuthFlows = allowedOAuthFlows != null
? normalizeStringList(allowedOAuthFlows)
: client.getAllowedOAuthFlows();
List<String> effectiveAllowedOAuthScopes = allowedOAuthScopes != null
? normalizeStringList(allowedOAuthScopes)
: client.getAllowedOAuthScopes();
List<String> effectiveCallbackUrls = callbackURLs != null
? normalizeStringList(callbackURLs)
: client.getCallbackURLs();
String effectiveDefaultRedirectUri = defaultRedirectURI != null
? normalizeOptionalString(defaultRedirectURI)
: client.getDefaultRedirectURI();
Integer effectiveAccessTokenValidity = accessTokenValidity != null
? accessTokenValidity
: client.getAccessTokenValidity();
Integer effectiveIdTokenValidity = idTokenValidity != null
? idTokenValidity
: client.getIdTokenValidity();
Integer effectiveRefreshTokenValidity = refreshTokenValidity != null
? normalizeRefreshTokenValidity(refreshTokenValidity)
: client.getRefreshTokenValidity();
Map<String, String> effectiveTokenValidityUnits = tokenValidityUnits != null
? copyStringMap(tokenValidityUnits)
: client.getTokenValidityUnits();
List<String> effectiveLogoutUrls = logoutURLs != null
? normalizeStringList(logoutURLs)
: client.getLogoutURLs();
validateUserPoolClientConfiguration(
effectiveAllowedOAuthFlowsUserPoolClient,
effectiveAllowedOAuthFlows,
effectiveAllowedOAuthScopes,
effectiveCallbackUrls,
effectiveDefaultRedirectUri,
effectiveAccessTokenValidity,
effectiveIdTokenValidity,
effectiveRefreshTokenValidity,
effectiveLogoutUrls,
effectiveTokenValidityUnits
);
if (clientName != null) client.setClientName(clientName);
if (allowedOAuthFlowsUserPoolClient != null) {
client.setAllowedOAuthFlowsUserPoolClient(allowedOAuthFlowsUserPoolClient);
}
if (allowedOAuthFlows != null) {
client.setAllowedOAuthFlows(effectiveAllowedOAuthFlows);
}
if (allowedOAuthScopes != null) {
client.setAllowedOAuthScopes(effectiveAllowedOAuthScopes);
}
if (analyticsConfiguration != null) {
client.setAnalyticsConfiguration(copyObjectMap(analyticsConfiguration));
}
if (callbackURLs != null) {
client.setCallbackURLs(effectiveCallbackUrls);
}
if (defaultRedirectURI != null) {
client.setDefaultRedirectURI(effectiveDefaultRedirectUri);
}
if (explicitAuthFlows != null) {
client.setExplicitAuthFlows(normalizeStringList(explicitAuthFlows));
}
if (accessTokenValidity != null) {
client.setAccessTokenValidity(accessTokenValidity);
}
if (idTokenValidity != null) {
client.setIdTokenValidity(idTokenValidity);
}
if (logoutURLs != null) {
client.setLogoutURLs(effectiveLogoutUrls);
}
if (preventUserExistenceErrors != null) {
client.setPreventUserExistenceErrors(preventUserExistenceErrors);
}
if (readAttributes != null) {
client.setReadAttributes(normalizeStringList(readAttributes));
}
if (refreshTokenValidity != null) {
client.setRefreshTokenValidity(effectiveRefreshTokenValidity);
}
if (supportedIdentityProviders != null) {
client.setSupportedIdentityProviders(normalizeStringList(supportedIdentityProviders));
}
if (tokenValidityUnits != null) {
client.setTokenValidityUnits(effectiveTokenValidityUnits);
}
if (writeAttributes != null) {
client.setWriteAttributes(normalizeStringList(writeAttributes));
}
if (refreshTokenRotation != null) {
client.setRefreshTokenRotation(copyObjectMap(refreshTokenRotation));
}
if (enableTokenRevocation != null) {
client.setEnableTokenRevocation(enableTokenRevocation);
}
if (authSessionValidity != null) {
client.setAuthSessionValidity(authSessionValidity);
}
UserPoolClient settings = requestedClientSettings(clientName != null ? clientName : client.getClientName(),
Boolean.TRUE.equals(allowedOAuthFlowsUserPoolClient), allowedOAuthFlows, allowedOAuthScopes,
analyticsConfiguration, callbackURLs, defaultRedirectURI, explicitAuthFlows, accessTokenValidity,
idTokenValidity, logoutURLs, preventUserExistenceErrors, readAttributes, refreshTokenValidity,
supportedIdentityProviders, tokenValidityUnits, writeAttributes, refreshTokenRotation,
enableTokenRevocation, authSessionValidity);
copyUserPoolClientSettings(settings, client);
client.setLastModifiedDate(System.currentTimeMillis() / 1000L);
clientStore.put(clientId, client);
@@ -1377,9 +1281,9 @@ public class CognitoService implements ResourceProvider {
}
/**
* Puts back the settings {@link #userPoolClientSettings} copied, including clearing one the
* update added, which {@link #updateUserPoolClient} cannot do since a null there keeps the
* current value. The client's id, secrets and branding stay as they are now.
* Puts back the settings {@link #userPoolClientSettings} copied, exactly as they were, which
* {@link #updateUserPoolClient} cannot do since it applies a create's defaults and normalization.
* The client's id, secrets and branding stay as they are now.
*/
public UserPoolClient restoreUserPoolClientSettings(UserPoolClient settings) {
UserPoolClient client = describeUserPoolClient(settings.getUserPoolId(), settings.getClientId());
@@ -1392,6 +1296,75 @@ public class CognitoService implements ResourceProvider {
return restored;
}
/**
* The settings a create or an update sets, from the request: normalized, checked, and with the
* default a new client gets for each one the request omits. The client's id, pool, secret and dates
* are the caller's.
*/
private UserPoolClient requestedClientSettings(String clientName, boolean allowedOAuthFlowsUserPoolClient,
List<String> allowedOAuthFlows, List<String> allowedOAuthScopes,
Map<String, Object> analyticsConfiguration,
List<String> callbackURLs,
String defaultRedirectURI, List<String> explicitAuthFlows,
Integer accessTokenValidity, Integer idTokenValidity,
List<String> logoutURLs, String preventUserExistenceErrors,
List<String> readAttributes, Integer refreshTokenValidity,
List<String> supportedIdentityProviders,
Map<String, String> tokenValidityUnits, List<String> writeAttributes,
Map<String, Object> refreshTokenRotation,
Boolean enableTokenRevocation, Integer authSessionValidity) {
List<String> normalizedAllowedOAuthFlows = normalizeStringList(allowedOAuthFlows);
List<String> normalizedAllowedOAuthScopes = normalizeStringList(allowedOAuthScopes);
List<String> normalizedCallbackUrls = normalizeStringList(callbackURLs);
String normalizedDefaultRedirectUri = normalizeOptionalString(defaultRedirectURI);
List<String> normalizedLogoutUrls = normalizeStringList(logoutURLs);
Map<String, String> copiedTokenValidityUnits = copyStringMap(tokenValidityUnits);
Integer normalizedRefreshTokenValidity = normalizeRefreshTokenValidity(refreshTokenValidity,
copiedTokenValidityUnits);
validateUserPoolClientConfiguration(
allowedOAuthFlowsUserPoolClient,
normalizedAllowedOAuthFlows,
normalizedAllowedOAuthScopes,
normalizedCallbackUrls,
normalizedDefaultRedirectUri,
accessTokenValidity,
idTokenValidity,
normalizedRefreshTokenValidity,
normalizedLogoutUrls,
copiedTokenValidityUnits
);
validateTokenValidityLimits(accessTokenValidity, idTokenValidity, normalizedRefreshTokenValidity,
copiedTokenValidityUnits);
UserPoolClient settings = new UserPoolClient();
settings.setClientName(clientName);
settings.setAllowedOAuthFlowsUserPoolClient(allowedOAuthFlowsUserPoolClient);
settings.setAllowedOAuthFlows(normalizedAllowedOAuthFlows);
settings.setAllowedOAuthScopes(normalizedAllowedOAuthScopes);
settings.setAnalyticsConfiguration(copyObjectMap(analyticsConfiguration));
settings.setCallbackURLs(normalizedCallbackUrls);
settings.setDefaultRedirectURI(normalizedDefaultRedirectUri);
settings.setExplicitAuthFlows(normalizeStringList(explicitAuthFlows));
settings.setAccessTokenValidity(accessTokenValidity);
settings.setIdTokenValidity(idTokenValidity);
if (authSessionValidity != null) {
settings.setAuthSessionValidity(authSessionValidity);
}
settings.setLogoutURLs(normalizedLogoutUrls);
settings.setPreventUserExistenceErrors(preventUserExistenceErrors);
settings.setReadAttributes(normalizeStringList(readAttributes));
settings.setRefreshTokenValidity(normalizedRefreshTokenValidity);
settings.setSupportedIdentityProviders(supportedIdentityProviders == null
? List.of("COGNITO")
: normalizeStringList(supportedIdentityProviders));
settings.setTokenValidityUnits(copiedTokenValidityUnits);
settings.setWriteAttributes(normalizeStringList(writeAttributes));
settings.setRefreshTokenRotation(copyObjectMap(refreshTokenRotation));
settings.setEnableTokenRevocation(enableTokenRevocation != null ? enableTokenRevocation : Boolean.TRUE);
return settings;
}
/** The name and every field {@link #updateUserPoolClient} sets. */
private static void copyUserPoolClientSettings(UserPoolClient from, UserPoolClient to) {
to.setClientName(from.getClientName());
@@ -4876,11 +4849,66 @@ public class CognitoService implements ResourceProvider {
}
}
private Integer normalizeRefreshTokenValidity(Integer value) {
if (value != null && value == 0) {
return DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS;
/**
* AWS: access and ID tokens "Must be set to a value between 5 minutes and 1 day", refresh tokens
* "between 60 minutes and 3,650 days", each in its TokenValidityUnits unit: hours for access and ID
* tokens and days for refresh tokens when the client names none. Runs after
* {@link #validateTokenValidityUnits}, so every unit is a known one, and after
* {@link #normalizeRefreshTokenValidity}, so a refresh token validity of 0 is already AWS's 30-day
* default. {@code floci.services.cognito.enforce-token-validity-limits=false} turns it off.
*/
private void validateTokenValidityLimits(Integer accessTokenValidity, Integer idTokenValidity,
Integer refreshTokenValidity, Map<String, String> tokenValidityUnits) {
if (!enforceTokenValidityLimits) {
return;
}
return value;
boolean outOfRange = outsideLimits(accessTokenValidity,
tokenValidityUnit(tokenValidityUnits, "AccessToken", "hours"),
MIN_ACCESS_AND_ID_TOKEN_VALIDITY, MAX_ACCESS_AND_ID_TOKEN_VALIDITY)
|| outsideLimits(idTokenValidity, tokenValidityUnit(tokenValidityUnits, "IdToken", "hours"),
MIN_ACCESS_AND_ID_TOKEN_VALIDITY, MAX_ACCESS_AND_ID_TOKEN_VALIDITY)
|| outsideLimits(refreshTokenValidity, tokenValidityUnit(tokenValidityUnits, "RefreshToken", "days"),
MIN_REFRESH_TOKEN_VALIDITY, MAX_REFRESH_TOKEN_VALIDITY);
if (outOfRange) {
// AWS's message names neither the token nor the limit.
throw new AwsException("InvalidParameterException", "Invalid range for token validity.", 400);
}
}
private static String tokenValidityUnit(Map<String, String> tokenValidityUnits, String token, String defaultUnit) {
String unit = tokenValidityUnits == null ? null : tokenValidityUnits.get(token);
return unit == null || unit.isBlank() ? defaultUnit : unit.trim().toLowerCase(Locale.ROOT);
}
private static boolean outsideLimits(Integer value, String unit, Duration min, Duration max) {
if (value == null) {
return false;
}
Duration validity = switch (unit) {
case "seconds" -> Duration.ofSeconds(value);
case "minutes" -> Duration.ofMinutes(value);
case "hours" -> Duration.ofHours(value);
default -> Duration.ofDays(value);
};
return validity.compareTo(min) < 0 || validity.compareTo(max) > 0;
}
/**
* AWS: "You can't set RefreshTokenValidity to 0. If you do, Amazon Cognito overrides the value with the
* default value of 30 days." The 30 days are kept in the client's refresh token unit, so a client in
* minutes stores 43200 rather than 30 minutes.
*/
private Integer normalizeRefreshTokenValidity(Integer value, Map<String, String> tokenValidityUnits) {
if (value == null || value != 0) {
return value;
}
Duration defaultValidity = Duration.ofDays(DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS);
return switch (tokenValidityUnit(tokenValidityUnits, "RefreshToken", "days")) {
case "seconds" -> (int) defaultValidity.toSeconds();
case "minutes" -> (int) defaultValidity.toMinutes();
case "hours" -> (int) defaultValidity.toHours();
default -> DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS;
};
}
private List<ResourceServerScope> normalizeScopes(List<ResourceServerScope> scopes) {
@@ -117,6 +117,10 @@ public class OpenSearchDomainManager {
.withEnv("discovery.type", "single-node")
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation()
// The OpenSearch image's entrypoint is a bash script that runs the server as its
// child rather than exec'ing it. As PID 1 that script ignores SIGTERM, so every
// DeleteDomain, and every shutdown for each domain, waited out the whole stop timeout.
.withInit()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"opensearch", domain.getDomainName(), regionResolver.getAccountId(),
regionResolver.getDefaultRegion()));