Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): reject token validity outside AWS's limits (#5160)
jwoa9517c40cecbdfd
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OpenSearchTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OpenSearchTest.javaindex 4ce3328284..2f5f0f8fc3 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OpenSearchTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OpenSearchTest.java@@ -143,27 +143,16 @@ class OpenSearchTest {@Test@Order(7)- void domainEndpointReachable() {+ void domainEndpointReachable() throws InterruptedException {if (domainEndpoint == null || domainEndpoint.isBlank()) {// Mock mode: endpoint is empty — skip HTTP probereturn;}- // Wait for domain to be ready (processing = false)- long start = System.currentTimeMillis();- boolean ready = false;- while (System.currentTimeMillis() - start < 180000) { // 3 minutes timeout- DescribeDomainResponse response = opensearch.describeDomain(DescribeDomainRequest.builder()- .domainName(DOMAIN_NAME)- .build());- if (!response.domainStatus().processing()) {- ready = true;- break;- }- try { Thread.sleep(5000); } catch (InterruptedException e) {}- }-- assertThat(ready).as("Domain did not become ready in time").isTrue();+ TestFixtures.await(() -> !opensearch.describeDomain(DescribeDomainRequest.builder()+ .domainName(DOMAIN_NAME)+ .build()).domainStatus().processing(),+ DOMAIN_NAME, "processing to finish", 180_000_000_000L, TestFixtures.isRealAws() ? 5_000 : 250);try {HttpURLConnection conn = (HttpURLConnection)diff --git a/compatibility-tests/sdk-test-python/tests/test_cognito.py b/compatibility-tests/sdk-test-python/tests/test_cognito.pyindex 93c5ce3db2..14ea3e437d 100644--- a/compatibility-tests/sdk-test-python/tests/test_cognito.py+++ b/compatibility-tests/sdk-test-python/tests/test_cognito.py@@ -61,7 +61,8 @@ class TestCognitoUserPoolClient:omitted = cognito_client.update_user_pool_client(UserPoolId=pool_id, ClientId=client_id, ClientName="renamed")["UserPoolClient"]- assert omitted["AuthSessionValidity"] == updated_minutes+ # As on AWS, an update that omits a setting resets it to its default.+ assert omitted["AuthSessionValidity"] == 3finally:cognito_client.delete_user_pool(UserPoolId=pool_id)diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.mdindex 3d29354f04..f698b73343 100644--- a/docs/configuration/advanced/application-yml.md+++ b/docs/configuration/advanced/application-yml.md@@ -247,6 +247,7 @@ floci:cognito:enabled: true+ enforce-token-validity-limits: true # Reject app clients whose token validity is outside AWS's limits; false allows shorter tokensstepfunctions:enabled: truediff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.mdindex f5f6cae2ba..261156a121 100644--- a/docs/configuration/environment-variables.md+++ b/docs/configuration/environment-variables.md@@ -343,6 +343,7 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s| Variable | Default | Description ||---|---|---|| `FLOCI_SERVICES_COGNITO_ENABLED` | `true` | Enable the Cognito User Pools service |+| `FLOCI_SERVICES_COGNITO_ENFORCE_TOKEN_VALIDITY_LIMITS` | `true` | Reject app clients whose token validity is outside AWS's limits (access and ID tokens 5 minutes to 1 day, refresh tokens 60 minutes to 3,650 days). Set to `false` to allow shorter tokens, for example in expiry tests |### Step Functionsdiff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex 32a84773f8..a772d6ff95 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -30,7 +30,7 @@ An action given a user pool ID that does not resolve returns `ResourceNotFoundEx`CreateUserPoolClient` and `UpdateUserPoolClient` store `AuthSessionValidity` in minutes,and `DescribeUserPoolClient` returns it. Values must be integers from 3 through 15.-New clients default to 3 minutes; an update that omits the field retains its stored value.+New clients default to 3 minutes, and an update that omits the field resets it to 3.An explicit JSON `null` behaves as an omitted field. Wrong JSON types or numbersoutside the 32-bit integer range return `SerializationException`. Integer durationsoutside 3 through 15 return `InvalidParameterException` with Cognito's constraint-error@@ -92,7 +92,7 @@ pool's Region rather than the `SourceArn` Region, and does not apply `ReplyToEma| CreateUserPoolClient | Creates an app client for a user pool, including optional generated secret handling. || DescribeUserPoolClient | Returns the stored app client configuration. || ListUserPoolClients | Lists app clients for a user pool. |-| UpdateUserPoolClient | Updates an app client's settings. A field the request omits keeps its stored value, where AWS resets it to its default. |+| UpdateUserPoolClient | Updates an app client's settings. As on AWS, a setting the request omits is reset to its default, the one a new client gets. An omitted `ClientName` keeps the client's name, since the API documents no default for it. || DeleteUserPoolClient | Deletes an app client from a user pool. || AddUserPoolClientSecret | Adds a client secret to an app client, up to 2. A supplied `ClientSecret` must be 24 to 64 word characters; without one Floci generates the secret and returns its value. || ListUserPoolClientSecrets | Lists an app client's client secrets, without their values. |@@ -789,9 +789,21 @@ Cognito JSON protocol.## Configuration-| Variable | Default | Description |-|----------------------------------|---------|-------------------------------|-| `FLOCI_SERVICES_COGNITO_ENABLED` | `true` | Enable or disable the service |+| Variable | Default | Description |+|--------------------------------------------------------|---------|-------------------------------|+| `FLOCI_SERVICES_COGNITO_ENABLED` | `true` | Enable or disable the service |+| `FLOCI_SERVICES_COGNITO_ENFORCE_TOKEN_VALIDITY_LIMITS` | `true` | Reject app clients whose token validity is outside AWS's limits |++`CreateUserPoolClient` and `UpdateUserPoolClient` enforce AWS's token validity limits: access and+ID tokens 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, days for refresh tokens, by default).+A client outside them fails with `InvalidParameterException` (`Invalid range for token validity.`),+as on AWS. A `RefreshTokenValidity` of `0` is accepted and becomes AWS's 30-day default, stored in+the client's refresh token unit (`43200` for `minutes`). An update is checked as it is sent, since a+token validity or unit the request omits is reset to its default rather than kept. To keep tokens+shorter than AWS allows, for example a one-minute access token to test what happens+when it expires, set `FLOCI_SERVICES_COGNITO_ENFORCE_TOKEN_VALIDITY_LIMITS=false`+(`floci.services.cognito.enforce-token-validity-limits`).## Examplesdiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex f6351b4b12..fd4a8eec52 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -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 {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.javaindex d1c7e13556..c338a01cef 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@@ -98,6 +98,10 @@ import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownR@ApplicationScopedpublic 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) {diff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.javaindex c20d68582a..869f2339a1 100644--- a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.java@@ -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()));diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 45283ea2ad..7c652b975a 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -545,6 +545,7 @@ floci:enabled: truecognito:enabled: true+ enforce-token-validity-limits: truestepfunctions:enabled: trueallow-plaintext-http: falsediff --git a/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.javaindex ebbad5f0bf..edfd13210d 100644--- a/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java@@ -1,12 +1,8 @@package io.github.hectorvent.floci.config;import com.fasterxml.jackson.databind.JsonNode;-import com.fasterxml.jackson.databind.ObjectMapper;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import io.restassured.http.ContentType;import org.eclipse.microprofile.config.inject.ConfigProperty;@@ -20,17 +16,13 @@ import javax.net.ssl.SSLParameters;import javax.net.ssl.SSLSocket;import javax.net.ssl.TrustManagerFactory;import java.io.ByteArrayInputStream;-import java.io.IOException;import java.net.InetAddress;import java.net.InetSocketAddress;import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;import java.security.KeyStore;import java.security.cert.CertificateFactory;import java.security.cert.X509Certificate;import java.util.List;-import java.util.Map;import java.util.Set;import java.util.TreeSet;@@ -51,11 +43,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* by IP, so the SNI name is the only one the identity check can match.*/@QuarkusTest-@TestProfile(CustomDomainTlsIntegrationTest.Profile.class)+@TestProfile(SelfSignedTlsProfile.class)class CustomDomainTlsIntegrationTest {- static final Path DATA_DIR = Path.of("target", "floci-custom-domain-tls-test").toAbsolutePath();- static final Path TLS_DIR = DATA_DIR.resolve("tls");static final String API_DOMAIN = "api.custom-domain-it.localhost.floci.io";static final String IOT_DOMAIN = "iot.custom-domain-it.localhost.floci.io";static final String AUTH_DOMAIN = "auth.custom-domain-it.localhost.floci.io";@@ -152,42 +142,4 @@ class CustomDomainTlsIntegrationTest {}return sans;}-- /**- * Boots with TLS on and a CA-issued leaf like the one TlsConfigSource writes, in a directory- * of its own. The wildcard covers one label only, so the three-label names are uncovered- * until the operations add them.- */- public static final class Profile implements QuarkusTestProfile {-- static {- try {- Files.createDirectories(TLS_DIR);- for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {- Files.deleteIfExists(TLS_DIR.resolve(name));- }- FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);- List<String> sans = List.of("localhost", "*.localhost.floci.io");- CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);- Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());- Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());- Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),- new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));- } catch (IOException e) {- throw new IllegalStateException("could not prepare the TLS fixtures", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.of(- "floci.tls.enabled", "true",- "floci.tls.self-signed", "true",- "floci.tls.aws-https-port", "0",- "floci.storage.persistent-path", DATA_DIR.toString(),- "quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),- "quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),- "quarkus.http.insecure-requests", "enabled");- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.javaindex d8c16e866b..86bc1bfc3e 100644--- a/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/EcrTlsDataPlaneDockerIntegrationTest.java@@ -1,10 +1,8 @@package io.github.hectorvent.floci.config;import io.github.hectorvent.floci.core.common.Digests;-import io.github.hectorvent.floci.services.acm.CertificateGenerator.GeneratedCertificate;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.SidecarContainersProfile;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import io.vertx.core.MultiMap;import io.vertx.core.Vertx;@@ -17,18 +15,12 @@ import io.vertx.core.net.PemTrustOptions;import io.vertx.core.net.SocketAddress;import jakarta.inject.Inject;import org.eclipse.microprofile.config.inject.ConfigProperty;-import org.junit.jupiter.api.Assumptions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;-import java.io.IOException;import java.nio.charset.StandardCharsets;-import java.nio.file.Files;import java.nio.file.Path;-import java.security.GeneralSecurityException;-import java.util.ArrayList;import java.util.List;-import java.util.Map;import java.util.concurrent.TimeUnit;import static org.junit.jupiter.api.Assertions.assertArrayEquals;@@ -42,7 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* of the regional wildcard SANs and regression coverage for plain HTTP.*/@QuarkusTest-@TestProfile(EcrTlsDataPlaneDockerIntegrationTest.Profile.class)+@TestProfile(SelfSignedTlsProfile.class)class EcrTlsDataPlaneDockerIntegrationTest {@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")@@ -56,19 +48,7 @@ class EcrTlsDataPlaneDockerIntegrationTest {@BeforeAllstatic void requireDocker() {- Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for ECR data plane tests");- }-- private static boolean isDockerAvailable() {- try {- Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")- .redirectErrorStream(true)- .start();- int exit = process.waitFor();- return exit == 0;- } catch (Exception e) {- return false;- }+ SidecarContainersProfile.requireDockerAndImage("floci.services.ecr.registry-image");}@Test@@ -78,7 +58,8 @@ class EcrTlsDataPlaneDockerIntegrationTest {.setSsl(true).setForceSni(true).setTrustOptions(new PemTrustOptions().addCertPath(- FlociCertificateAuthority.loadOrCreate(Profile.TLS_DIR).certificatePath().toString()))+ FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR))+ .certificatePath().toString())).setVerifyHost(true));try {@@ -183,6 +164,11 @@ class EcrTlsDataPlaneDockerIntegrationTest {} finally {httpClient.close();}++ // 9. Delete the manifest over TLS, since every class on this profile shares one application+ SimpleResponse deleteManifest = execute(tlsClient, HttpMethod.DELETE, sslPort, tlsHost,+ "/v2/tls-repo/manifests/" + manifestDigest, null, null, null);+ assertEquals(202, deleteManifest.statusCode());} finally {tlsClient.close();}@@ -223,39 +209,4 @@ class EcrTlsDataPlaneDockerIntegrationTest {return headers.get(name);}}-- public static final class Profile implements QuarkusTestProfile {-- static final Path DATA_DIR = Path.of("target", "floci-ecr-tls-dataplane-test").toAbsolutePath();- static final Path TLS_DIR = DATA_DIR.resolve("tls");- static final Path CERT_FILE = TLS_DIR.resolve("floci-server.crt");- static final Path KEY_FILE = TLS_DIR.resolve("floci-server.key");-- static {- try {- Files.createDirectories(TLS_DIR);- FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);- List<String> sans = new ArrayList<>(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);- GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);- Files.writeString(CERT_FILE, leaf.certificatePem());- Files.writeString(KEY_FILE, leaf.privateKeyPem());- ContainerCaBundle.write(TLS_DIR, ca.certificatePath());- } catch (IOException | GeneralSecurityException e) {- throw new IllegalStateException("Failed to prepare TLS test files", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.of(- "floci.tls.enabled", "true",- "floci.tls.self-signed", "true",- "floci.tls.aws-https-port", "0",- "floci.storage.persistent-path", DATA_DIR.toString(),- "quarkus.tls.key-store.pem.0.cert", CERT_FILE.toString(),- "quarkus.tls.key-store.pem.0.key", KEY_FILE.toString(),- "quarkus.http.insecure-requests", "enabled"- );- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/config/SelfSignedTlsProfile.java b/src/test/java/io/github/hectorvent/floci/config/SelfSignedTlsProfile.javanew file mode 100644index 0000000000..6da6331a0d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/SelfSignedTlsProfile.java@@ -0,0 +1,85 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.SidecarContainersProfile;+import io.quarkus.test.junit.QuarkusTestProfile;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.GeneralSecurityException;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;++/**+ * TLS on in Floci's self-signed mode, for the classes that test what it serves. Quarkus builds the+ * application once per distinct profile class, so they share one rather than each declaring their+ * own.+ *+ * <p>Under {@code @QuarkusTest} the server serves the leaf this class writes before boot, issued by+ * the local CA in {@link #TLS_DIR}. It carries the SANs {@link TlsConfigSource} uses by default,+ * which cover the CloudFront and ECR hosts, except {@code 127.0.0.1}, plus the API Gateway custom+ * domain {@link TlsHttp2HostRoutingIntegrationTest} routes to. The default wildcards cover one label only,+ * so a name two labels below {@code localhost.floci.io} stays uncovered until a test adds it. Each+ * run writes a fresh leaf and metadata, which also drops hostnames an earlier run learned at+ * runtime, so a name a test expects to be absent at boot really is. The CA is kept.+ *+ * <p>{@link EcrTlsDataPlaneDockerIntegrationTest} pushes through the ECR registry container, which+ * by default outlives the application and is adopted by name on the next start. This profile names+ * it in this run's {@link SidecarContainersProfile#namespace() sidecar namespace} and stops it at+ * shutdown, so the test never pushes into a registry a developer's Floci or another run owns and+ * leaves none behind. The other classes start no containers, so both overrides are inert for them.+ *+ * <p>The paths are compile-time constants so a test can use them without initializing this class,+ * which would write a new leaf under the running application.+ */+public class SelfSignedTlsProfile implements QuarkusTestProfile {++ public static final String DATA_DIR = "target/floci-self-signed-tls-test";++ public static final String TLS_DIR = DATA_DIR + "/tls";++ static {+ Path tlsDir = Path.of(TLS_DIR);+ try {+ Files.createDirectories(tlsDir);+ for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {+ Files.deleteIfExists(tlsDir.resolve(name));+ }+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);+ List<String> sans = new ArrayList<>(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);+ // CustomDomainTlsIntegrationTest and TlsEnsureHostIntegrationTest connect by IP and send+ // a name the leaf must not cover yet as SNI. The JDK falls back to the peer address when+ // the SNI name does not match, so a 127.0.0.1 SAN would let those handshakes through.+ sans.remove("127.0.0.1");+ sans.add(TlsHttp2HostRoutingIntegrationTest.API_DOMAIN);+ CertificateGenerator.GeneratedCertificate leaf =+ ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);+ Files.writeString(tlsDir.resolve("floci-server.crt"), leaf.certificatePem());+ Files.writeString(tlsDir.resolve("floci-server.key"), leaf.privateKeyPem());+ Files.writeString(tlsDir.resolve("floci-server.metadata.json"),+ new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));+ ContainerCaBundle.write(tlsDir, ca.certificatePath());+ } catch (IOException | GeneralSecurityException e) {+ throw new IllegalStateException("Could not prepare the TLS fixtures in " + tlsDir, e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ Path tlsDir = Path.of(TLS_DIR).toAbsolutePath();+ return Map.of(+ "floci.tls.enabled", "true",+ "floci.tls.self-signed", "true",+ "floci.tls.aws-https-port", "0",+ "floci.storage.persistent-path", Path.of(DATA_DIR).toAbsolutePath().toString(),+ "quarkus.tls.key-store.pem.0.cert", tlsDir.resolve("floci-server.crt").toString(),+ "quarkus.tls.key-store.pem.0.key", tlsDir.resolve("floci-server.key").toString(),+ "quarkus.http.insecure-requests", "enabled",+ "floci.docker.resource-namespace", SidecarContainersProfile.namespace(),+ "floci.services.ecr.keep-running-on-shutdown", "false");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.javaindex 4d2b303455..6565ea4014 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java@@ -1,10 +1,6 @@package io.github.hectorvent.floci.config;-import com.fasterxml.jackson.databind.ObjectMapper;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import jakarta.inject.Inject;import org.eclipse.microprofile.config.inject.ConfigProperty;@@ -17,16 +13,13 @@ import javax.net.ssl.SSLHandshakeException;import javax.net.ssl.SSLParameters;import javax.net.ssl.SSLSocket;import javax.net.ssl.TrustManagerFactory;-import java.io.IOException;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.URI;-import java.nio.file.Files;import java.nio.file.Path;import java.security.KeyStore;import java.security.cert.X509Certificate;import java.util.List;-import java.util.Map;import java.util.Set;import java.util.TreeSet;@@ -44,11 +37,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* handshake can.*/@QuarkusTest-@TestProfile(TlsEnsureHostIntegrationTest.Profile.class)+@TestProfile(SelfSignedTlsProfile.class)class TlsEnsureHostIntegrationTest {- static final Path DATA_DIR = Path.of("target", "floci-tls-ensure-host-test").toAbsolutePath();- static final Path TLS_DIR = DATA_DIR.resolve("tls");static final String NEW_HOST = "api.example.localhost.floci.io";@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")@@ -127,7 +118,8 @@ class TlsEnsureHostIntegrationTest {private static SSLContext trustOnlyTheCa() throws Exception {KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());trust.load(null, null);- trust.setCertificateEntry("floci", FlociCertificateAuthority.loadOrCreate(TLS_DIR).certificate());+ trust.setCertificateEntry("floci",+ FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate());TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(trust);SSLContext ctx = SSLContext.getInstance("TLS");@@ -142,43 +134,4 @@ class TlsEnsureHostIntegrationTest {}return sans;}-- /**- * Boots with TLS on and a CA-issued leaf like the one TlsConfigSource writes. TlsConfigSource- * itself reads system properties, not profile overrides, so the profile lays the files down- * and points the TLS registry's default entry at them. The wildcard covers one label only- * (RFC 6125), so the three-label name is genuinely uncovered before ensureHost.- */- public static final class Profile implements QuarkusTestProfile {-- static {- try {- Files.createDirectories(TLS_DIR);- for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {- Files.deleteIfExists(TLS_DIR.resolve(name));- }- FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);- List<String> sans = List.of("localhost", "*.localhost.floci.io");- CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);- Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());- Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());- Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),- new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));- } catch (IOException e) {- throw new IllegalStateException("could not prepare the TLS fixtures", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.of(- "floci.tls.enabled", "true",- "floci.tls.self-signed", "true",- "floci.tls.aws-https-port", "0",- "floci.storage.persistent-path", DATA_DIR.toString(),- "quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),- "quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),- "quarkus.http.insecure-requests", "enabled");- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.javaindex 53522cdc26..79eb6ec504 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java@@ -1,7 +1,5 @@package io.github.hectorvent.floci.config;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;import io.github.hectorvent.floci.services.cloudfront.model.Distribution;@@ -11,7 +9,6 @@ import io.github.hectorvent.floci.services.cloudfront.model.Origin;import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;import io.github.hectorvent.floci.services.s3.S3Service;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import io.restassured.http.ContentType;import io.vertx.core.Vertx;@@ -24,11 +21,10 @@ import io.vertx.core.net.PemTrustOptions;import io.vertx.core.net.SocketAddress;import jakarta.inject.Inject;import org.eclipse.microprofile.config.inject.ConfigProperty;+import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Test;-import java.io.IOException;import java.nio.charset.StandardCharsets;-import java.nio.file.Files;import java.nio.file.Path;import java.security.KeyPair;import java.security.KeyPairGenerator;@@ -53,11 +49,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* certificate, so no DNS lookup is needed.*/@QuarkusTest-@TestProfile(TlsHttp2HostRoutingIntegrationTest.Profile.class)+@TestProfile(SelfSignedTlsProfile.class)class TlsHttp2HostRoutingIntegrationTest {- static final Path DATA_DIR = Path.of("target", "floci-tls-http2-host-routing-test").toAbsolutePath();- static final Path TLS_DIR = DATA_DIR.resolve("tls");static final String API_DOMAIN = "api.h2-routing.example.test";private static final String REGION = "us-east-1";@@ -73,13 +67,25 @@ class TlsHttp2HostRoutingIntegrationTest {@InjectCloudFrontService cloudFrontService;+ /** What the test created, removed newest first: every class on this profile shares one application. */+ private final List<Runnable> cleanup = new ArrayList<>();++ @AfterEach+ void removeWhatTheTestCreated() {+ for (int i = cleanup.size() - 1; i >= 0; i--) {+ cleanup.get(i).run();+ }+ }+@Testvoid cloudFrontServesACannedSignedUrlOnEachLocalDeliveryHost() throws Exception {String suffix = Long.toString(System.nanoTime(), 36);String bucket = "cf-h2-" + suffix;s3Service.createBucket(bucket, REGION);+ cleanup.add(() -> s3Service.deleteBucket(bucket));s3Service.putObject(bucket, "private/report.txt", ("H2-" + suffix).getBytes(StandardCharsets.UTF_8),"text/plain", Map.of());+ cleanup.add(() -> s3Service.deleteObject(bucket, "private/report.txt"));KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");generator.initialize(2048);@@ -91,10 +97,16 @@ class TlsHttp2HostRoutingIntegrationTest {+ Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded())+ "\n-----END PUBLIC KEY-----");publicKey = cloudFrontService.createPublicKey(publicKey);+ String publicKeyId = publicKey.getId();+ cleanup.add(() -> cloudFrontService.deletePublicKey(publicKeyId,+ cloudFrontService.getPublicKey(publicKeyId).getEtag()));KeyGroup keyGroup = new KeyGroup();keyGroup.setName("kg-" + suffix);keyGroup.setItems(List.of(publicKey.getId()));keyGroup = cloudFrontService.createKeyGroup(keyGroup);+ String keyGroupId = keyGroup.getId();+ cleanup.add(() -> cloudFrontService.deleteKeyGroup(keyGroupId,+ cloudFrontService.getKeyGroup(keyGroupId).getEtag()));Origin origin = new Origin();origin.setId("o");@@ -111,6 +123,9 @@ class TlsHttp2HostRoutingIntegrationTest {Distribution distribution = new Distribution();distribution.setConfig(config);distribution = cloudFrontService.createDistribution(distribution, Map.of());+ String distributionId = distribution.getId();+ // The test owns the distribution, so it skips the disable-then-delete round trip.+ cleanup.add(() -> cloudFrontService.removeDistribution(distributionId));// A browser sends the host in lower case, and a canned policy signs the port too.String id = distribution.getId().toLowerCase(Locale.ROOT);@@ -136,6 +151,7 @@ class TlsHttp2HostRoutingIntegrationTest {.body("{\"name\":\"h2-host-routing\"}").when().post("/restapis").then().statusCode(201).extract().path("id");+ cleanup.add(() -> given().when().delete("/restapis/" + apiId).then().statusCode(202));String rootId = given().when().get("/restapis/" + apiId + "/resources").then().statusCode(200).extract().path("item[0].id");String resourceId = given().contentType(ContentType.JSON)@@ -163,9 +179,12 @@ class TlsHttp2HostRoutingIntegrationTest {given().contentType(ContentType.JSON).body("{\"domainName\":\"" + API_DOMAIN + "\"}").when().post("/domainnames").then().statusCode(201);+ cleanup.add(() -> given().when().delete("/domainnames/" + API_DOMAIN).then().statusCode(202));given().contentType(ContentType.JSON).body("{\"basePath\":\"v1\",\"restApiId\":\"" + apiId + "\",\"stage\":\"dev\"}").when().post("/domainnames/" + API_DOMAIN + "/basepathmappings").then().statusCode(201);+ cleanup.add(() -> given().when().delete("/domainnames/" + API_DOMAIN + "/basepathmappings/v1")+ .then().statusCode(202));Http2Response response = getOverHttp2(API_DOMAIN, "/v1/ping");assertEquals(HttpVersion.HTTP_2, response.version());@@ -181,7 +200,8 @@ class TlsHttp2HostRoutingIntegrationTest {.setUseAlpn(true).setForceSni(true).setTrustOptions(new PemTrustOptions().addCertPath(- FlociCertificateAuthority.loadOrCreate(TLS_DIR).certificatePath().toString()))+ FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR))+ .certificatePath().toString())).setVerifyHost(true).setProtocolVersion(HttpVersion.HTTP_2));try {@@ -204,37 +224,4 @@ class TlsHttp2HostRoutingIntegrationTest {private static String cloudFrontBase64(byte[] bytes) {return Base64.getEncoder().encodeToString(bytes).replace('+', '-').replace('=', '_').replace('/', '~');}-- /**- * Boots with TLS on and a CA-issued leaf carrying the SANs TlsConfigSource writes, plus the API- * Gateway custom domain.- */- public static final class Profile implements QuarkusTestProfile {-- static {- try {- Files.createDirectories(TLS_DIR);- FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);- List<String> sans = new ArrayList<>(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);- sans.add(API_DOMAIN);- CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);- Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());- Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());- } catch (IOException e) {- throw new IllegalStateException("could not prepare the TLS fixtures", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.of(- "floci.tls.enabled", "true",- "floci.tls.self-signed", "true",- "floci.tls.aws-https-port", "0",- "floci.storage.persistent-path", DATA_DIR.toString(),- "quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),- "quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),- "quarkus.http.insecure-requests", "enabled");- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.javaindex 4217697d1a..a02115faab 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java@@ -1,7 +1,5 @@package io.github.hectorvent.floci.config;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.QuarkusTestProfile;@@ -9,23 +7,14 @@ import io.quarkus.test.junit.TestProfile;import io.restassured.RestAssured;import io.restassured.config.RestAssuredConfig;import io.restassured.config.SSLConfig;-import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.eclipse.microprofile.config.inject.ConfigProperty;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;-import java.io.IOException;-import java.nio.file.Files;-import java.nio.file.Path;-import java.security.Security;-import java.util.List;-import java.util.Map;-import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;import static org.hamcrest.Matchers.is;-import static org.hamcrest.Matchers.notNullValue;import static org.hamcrest.Matchers.startsWith;/**@@ -35,7 +24,7 @@ import static org.hamcrest.Matchers.startsWith;* HTTP server serves HTTPS alongside HTTP (dual-mode, LocalStack parity).*/@QuarkusTest-@TestProfile(TlsIntegrationTest.TlsEnabledProfile.class)+@TestProfile(UserCertTlsProfile.class)@TestInstance(TestInstance.Lifecycle.PER_CLASS)class TlsIntegrationTest {@@ -81,7 +70,7 @@ class TlsIntegrationTest {@Testvoid sqsCreateQueueOverHttps() {- given()+ String queueUrl = given().baseUri("https://localhost:" + testSslPort).header("X-Amz-Target", "AmazonSQS.CreateQueue").contentType("application/x-amz-json-1.0")@@ -90,7 +79,18 @@ class TlsIntegrationTest {.post("/").then().statusCode(200)- .body("QueueUrl", startsWith("https://"));+ .body("QueueUrl", startsWith("https://"))+ .extract().path("QueueUrl");++ given()+ .baseUri("https://localhost:" + testSslPort)+ .header("X-Amz-Target", "AmazonSQS.DeleteQueue")+ .contentType("application/x-amz-json-1.0")+ .body("{\"QueueUrl\": \"" + queueUrl + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);}// ==================== STS via HTTPS ====================@@ -108,50 +108,4 @@ class TlsIntegrationTest {.statusCode(200).body(containsString("GetCallerIdentityResult"));}-- // ==================== Test Profile ====================-- public static final class TlsEnabledProfile implements QuarkusTestProfile {-- private static final Path CERT_DIR = Path.of("/tmp/floci-tls-integration-test");- private static final Path CERT_FILE = CERT_DIR.resolve("test.crt");- private static final Path KEY_FILE = CERT_DIR.resolve("test.key");-- static {- generateCertIfNeeded();- }-- private static void generateCertIfNeeded() {- if (Files.exists(CERT_FILE) && Files.exists(KEY_FILE)) {- return;- }- try {- Files.createDirectories(CERT_DIR);- if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {- Security.addProvider(new BouncyCastleProvider());- }- CertificateGenerator gen = new CertificateGenerator();- CertificateGenerator.GeneratedCertificate cert = gen.generateSelfSignedCertificate(- "localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);- Files.writeString(CERT_FILE, cert.certificatePem());- Files.writeString(KEY_FILE, cert.privateKeyPem());- } catch (IOException e) {- throw new RuntimeException("Failed to generate test cert", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.of(- "floci.tls.enabled", "true",- "floci.tls.self-signed", "false",- "floci.tls.cert-path", CERT_FILE.toAbsolutePath().toString(),- "floci.tls.key-path", KEY_FILE.toAbsolutePath().toString(),- "floci.storage.persistent-path", "/tmp/floci-tls-integration-test-data",- "quarkus.http.ssl.certificate.files", CERT_FILE.toAbsolutePath().toString(),- "quarkus.http.ssl.certificate.key-files", KEY_FILE.toAbsolutePath().toString(),- "quarkus.http.insecure-requests", "enabled"- );- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.javaindex 508755e892..157090bce9 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java@@ -1,31 +1,24 @@package io.github.hectorvent.floci.config;import io.github.hectorvent.floci.core.common.Pem;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import io.restassured.RestAssured;import io.restassured.config.RestAssuredConfig;import io.restassured.config.SSLConfig;-import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.eclipse.microprofile.config.inject.ConfigProperty;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;import java.io.ByteArrayInputStream;-import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;-import java.security.Security;import java.security.cert.CertificateFactory;import java.security.cert.X509Certificate;import java.util.List;-import java.util.Map;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.is;@@ -43,7 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* form OpenSSL tooling produces, so the tests prove that key never leaves the host.*/@QuarkusTest-@TestProfile(TlsUserCertIntegrationTest.UserCertProfile.class)+@TestProfile(UserCertTlsProfile.class)@TestInstance(TestInstance.Lifecycle.PER_CLASS)class TlsUserCertIntegrationTest {@@ -85,13 +78,13 @@ class TlsUserCertIntegrationTest {.stream().map(X509Certificate.class::cast).toList();assertEquals(2, bundle.size(), "user certificate plus the local CA");assertEquals(- Pem.parseCertificate(Files.readString(UserCertProfile.CERT_FILE)), bundle.get(0),+ Pem.parseCertificate(Files.readString(Path.of(UserCertTlsProfile.CERT_FILE))), bundle.get(0),"the user certificate, which signs the HTTPS endpoint, comes first");X509Certificate localCa = bundle.get(1);assertTrue(localCa.getBasicConstraints() >= 0, "the local CA is a CA");assertEquals("CN=Floci Local CA", localCa.getSubjectX500Principal().getName());assertTrue(pem.endsWith(Files.readString(- Path.of("/tmp/floci-tls-usercert-test-data/tls/floci-root-ca.crt"))),+ Path.of(UserCertTlsProfile.DATA_DIR, "tls", "floci-root-ca.crt"))),"the local CA served is the one on disk");}@@ -106,46 +99,15 @@ class TlsUserCertIntegrationTest {.post("/").then().statusCode(200);- }-- public static final class UserCertProfile implements QuarkusTestProfile {-- private static final Path CERT_DIR = Path.of("/tmp/floci-tls-usercert-test");- static final Path CERT_FILE = CERT_DIR.resolve("user-test.crt");- private static final Path KEY_FILE = CERT_DIR.resolve("user-test.key");- static {- generateCertIfNeeded();- }-- private static void generateCertIfNeeded() {- try {- Files.createDirectories(CERT_DIR);- if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {- Security.addProvider(new BouncyCastleProvider());- }- CertificateGenerator gen = new CertificateGenerator();- CertificateGenerator.GeneratedCertificate cert = gen.generateSelfSignedCertificate(- "localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);- Files.writeString(CERT_FILE, cert.certificatePem() + cert.privateKeyPem());- Files.writeString(KEY_FILE, cert.privateKeyPem());- } catch (IOException e) {- throw new RuntimeException("Failed to generate test cert", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.of(- "floci.tls.enabled", "true",- "floci.tls.self-signed", "false",- "floci.tls.cert-path", CERT_FILE.toAbsolutePath().toString(),- "floci.tls.key-path", KEY_FILE.toAbsolutePath().toString(),- "floci.storage.persistent-path", "/tmp/floci-tls-usercert-test-data",- "quarkus.http.ssl.certificate.files", CERT_FILE.toAbsolutePath().toString(),- "quarkus.http.ssl.certificate.key-files", KEY_FILE.toAbsolutePath().toString(),- "quarkus.http.insecure-requests", "enabled"- );- }+ given()+ .baseUri("https://localhost:" + testSslPort)+ .header("X-Amz-Target", "AmazonSSM.DeleteParameter")+ .contentType("application/x-amz-json-1.1")+ .body("{\"Name\": \"/tls-user-cert-test\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);}}diff --git a/src/test/java/io/github/hectorvent/floci/config/UserCertTlsProfile.java b/src/test/java/io/github/hectorvent/floci/config/UserCertTlsProfile.javanew file mode 100644index 0000000000..b94cd28ebd--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/UserCertTlsProfile.java@@ -0,0 +1,65 @@+package io.github.hectorvent.floci.config;++import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.quarkus.test.junit.QuarkusTestProfile;+import org.bouncycastle.jce.provider.BouncyCastleProvider;++import java.io.IOException;+import java.io.UncheckedIOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.Security;+import java.util.List;+import java.util.Map;++/**+ * TLS on with a user-provided certificate rather than Floci's self-signed one: a self-signed+ * {@code localhost} certificate generated once per run, with plain HTTP still enabled beside+ * HTTPS. The certificate file carries the private key after the certificate, as some users'+ * combined PEMs do, so a test can check the key is never served back.+ *+ * <p>The paths are compile-time constants so a test can use them without initializing this class,+ * which would generate a new certificate under the running application.+ */+public class UserCertTlsProfile implements QuarkusTestProfile {++ private static final String DIR = "target/floci-user-cert-tls-test";++ /** The certificate, followed by its private key. */+ public static final String CERT_FILE = DIR + "/user-test.crt";++ public static final String DATA_DIR = DIR + "/data";++ private static final String KEY_FILE = DIR + "/user-test.key";++ static {+ try {+ Files.createDirectories(Path.of(DIR));+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ CertificateGenerator.GeneratedCertificate cert = new CertificateGenerator().generateSelfSignedCertificate(+ "localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);+ Files.writeString(Path.of(CERT_FILE), cert.certificatePem() + cert.privateKeyPem());+ Files.writeString(Path.of(KEY_FILE), cert.privateKeyPem());+ } catch (IOException e) {+ throw new UncheckedIOException("Could not generate the user certificate in " + DIR, e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ String certFile = Path.of(CERT_FILE).toAbsolutePath().toString();+ String keyFile = Path.of(KEY_FILE).toAbsolutePath().toString();+ return Map.of(+ "floci.tls.enabled", "true",+ "floci.tls.self-signed", "false",+ "floci.tls.cert-path", certFile,+ "floci.tls.key-path", keyFile,+ "floci.storage.persistent-path", Path.of(DATA_DIR).toAbsolutePath().toString(),+ "quarkus.http.ssl.certificate.files", certFile,+ "quarkus.http.ssl.certificate.key-files", keyFile,+ "quarkus.http.insecure-requests", "enabled");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthSessionValidityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthSessionValidityIntegrationTest.javaindex 515adfd1e3..ced8c7a038 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthSessionValidityIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAuthSessionValidityIntegrationTest.java@@ -62,8 +62,12 @@ class CognitoAuthSessionValidityIntegrationTest {assertEquals(minutes, describeClient(clientId).path("AuthSessionValidity").asInt());}+ /**+ * AWS on UpdateUserPoolClient: "If you don't provide a value for an attribute, Amazon Cognito sets it+ * to its default value."+ */@Test- void omittedCreateUsesDefaultAndOmittedUpdatePreservesConfiguredValue() throws Exception {+ void omittedCreateAndOmittedUpdateBothUseTheDefault() throws Exception {JsonNode defaultClient = cognitoJson("CreateUserPoolClient", """{"UserPoolId":"%s","ClientName":"default-client"}""".formatted(poolId)).path("UserPoolClient");@@ -75,8 +79,8 @@ class CognitoAuthSessionValidityIntegrationTest {JsonNode updated = cognitoJson("UpdateUserPoolClient", """{"UserPoolId":"%s","ClientId":"%s","ClientName":"renamed"}""".formatted(poolId, clientId)).path("UserPoolClient");- assertEquals(10, updated.path("AuthSessionValidity").asInt());- assertEquals(10, describeClient(clientId).path("AuthSessionValidity").asInt());+ assertEquals(3, updated.path("AuthSessionValidity").asInt());+ assertEquals(3, describeClient(clientId).path("AuthSessionValidity").asInt());}@Test@@ -90,9 +94,9 @@ class CognitoAuthSessionValidityIntegrationTest {JsonNode updated = cognitoJson("UpdateUserPoolClient", """{"UserPoolId":"%s","ClientId":"%s","ClientName":"renamed","AuthSessionValidity":null}""".formatted(poolId, clientId)).path("UserPoolClient");- assertEquals(10, updated.path("AuthSessionValidity").asInt());+ assertEquals(3, updated.path("AuthSessionValidity").asInt());JsonNode stored = describeClient(clientId);- assertEquals(10, stored.path("AuthSessionValidity").asInt());+ assertEquals(3, stored.path("AuthSessionValidity").asInt());assertEquals("renamed", stored.path("ClientName").asText());}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.javaindex e9d2401e1a..d10ec9b9ea 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java@@ -2797,6 +2797,49 @@ class CognitoIntegrationTest {.statusCode(400);}+ /**+ * 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". The first two requests are the reproduction in #5147.+ */+ @Test+ @Order(96)+ void createAndUpdateUserPoolClientRejectTokenValidityOutsideAwsLimits() throws Exception {+ String limitsPoolId = cognitoJson("CreateUserPool", """+ {"PoolName": "TokenValidityLimitsPool"}+ """).path("UserPool").path("Id").asText();++ for (String validity : List.of(+ """+ "AccessTokenValidity": 1, "IdTokenValidity": 1,+ "TokenValidityUnits": {"AccessToken": "minutes", "IdToken": "minutes"}""",+ """+ "RefreshTokenValidity": 20, "TokenValidityUnits": {"RefreshToken": "minutes"}""",+ """+ "AccessTokenValidity": 25""")) {+ cognitoAction("CreateUserPoolClient", """+ {"UserPoolId": "%s", "ClientName": "short-tokens", %s}+ """.formatted(limitsPoolId, validity))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo("Invalid range for token validity."));+ }++ String limitsClientId = cognitoJson("CreateUserPoolClient", """+ {"UserPoolId": "%s", "ClientName": "limit-tokens",+ "AccessTokenValidity": 5, "IdTokenValidity": 1440, "RefreshTokenValidity": 60,+ "TokenValidityUnits": {"AccessToken": "minutes", "IdToken": "minutes", "RefreshToken": "minutes"}}+ """.formatted(limitsPoolId)).path("UserPoolClient").path("ClientId").asText();+ cognitoAction("UpdateUserPoolClient", """+ {"UserPoolId": "%s", "ClientId": "%s", "AccessTokenValidity": 4,+ "TokenValidityUnits": {"AccessToken": "minutes"}}+ """.formatted(limitsPoolId, limitsClientId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo("Invalid range for token validity."));+ }+@Test@Order(97)void createUserPoolClientRejectsInconsistentOAuthFlowConfiguration() throws Exception {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.javaindex d7a7cd702d..3f9fe5766e 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@@ -1193,6 +1193,151 @@ class CognitoServiceTest {assertEquals(30, client.getRefreshTokenValidity());}+ // =========================================================================+ // Issue #5147: token validity within AWS's limits+ // =========================================================================++ /**+ * 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", in hours for access and ID tokens and days for refresh tokens+ * when TokenValidityUnits names no unit.+ */+ @ParameterizedTest+ @CsvSource({+ "AccessToken, 1, minutes",+ "AccessToken, 299, seconds",+ "AccessToken, 25, ",+ "IdToken, 4, minutes",+ "IdToken, 1441, minutes",+ "IdToken, 2, days",+ "RefreshToken, 20, minutes",+ "RefreshToken, 3599, seconds",+ "RefreshToken, 3651, ",+ "RefreshToken, 87601, hours",+ })+ void createUserPoolClientRejectsTokenValidityOutsideAwsLimits(String token, int validity, String unit) {+ UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1");++ AwsException exception = assertThrows(AwsException.class,+ () -> clientWithTokenValidity(pool, token, validity, unit));++ assertEquals("InvalidParameterException", exception.getErrorCode());+ assertEquals("Invalid range for token validity.", exception.getMessage());+ }++ /** The limits are inclusive, and a refresh token validity of 0 is AWS's 30-day default in any unit. */+ @ParameterizedTest+ @CsvSource({+ "AccessToken, 5, minutes",+ "AccessToken, 300, seconds",+ "AccessToken, 24, ",+ "IdToken, 1440, minutes",+ "IdToken, 1, days",+ "RefreshToken, 60, minutes",+ "RefreshToken, 1, hours",+ "RefreshToken, 3650, ",+ "RefreshToken, 0, minutes",+ })+ void createUserPoolClientAcceptsTokenValidityAtAwsLimits(String token, int validity, String unit) {+ UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1");++ assertNotNull(clientWithTokenValidity(pool, token, validity, unit).getClientId());+ }++ /**+ * An update is checked as it is sent: a token validity or unit it omits is reset to its default rather+ * than kept, so a units-only change no longer stretches the stored validity.+ */+ @Test+ void updateUserPoolClientChecksTokenValidityAsSent() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1");+ UserPoolClient client = clientWithTokenValidity(pool, "AccessToken", 60, "minutes");++ AwsException shorter = assertThrows(AwsException.class, () -> service.updateUserPoolClient(+ pool.getId(), client.getClientId(), null, null, null, null, null, null, null, null,+ 4, null, null, null, null, null, null, Map.of("AccessToken", "minutes"), null, null, null));+ assertEquals("Invalid range for token validity.", shorter.getMessage());+ assertEquals(60, service.describeUserPoolClient(pool.getId(), client.getClientId()).getAccessTokenValidity());++ UserPoolClient unitsOnly = service.updateUserPoolClient(+ pool.getId(), client.getClientId(), null, null, null, null, null, null, null, null,+ null, null, null, null, null, null, null, Map.of("AccessToken", "hours"), null, null, null);+ assertNull(unitsOnly.getAccessTokenValidity());+ assertEquals(Map.of("AccessToken", "hours"), unitsOnly.getTokenValidityUnits());+ }++ /**+ * AWS: "If you don't provide a value for an attribute, Amazon Cognito sets it to its default value."+ * The API documents no default name, so the name stays; the id and the secret are not settings.+ */+ @Test+ void updateUserPoolClientResetsEveryOmittedSettingToItsDefault() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1");+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "configured", true, true,+ List.of("code"), List.of("openid"), Map.of("ApplicationId", "app"), List.of("https://example.com"),+ "https://example.com", List.of("ALLOW_USER_AUTH"), 15, 20, List.of("https://example.com/logout"),+ "ENABLED", List.of("email"), 7, List.of("COGNITO", "Google"),+ Map.of("AccessToken", "minutes", "IdToken", "minutes", "RefreshToken", "days"),+ List.of("family_name"), Map.of("Feature", "ENABLED"), false, 10);+ String secret = client.getClientSecret();++ UserPoolClient updated = service.updateUserPoolClient(pool.getId(), client.getClientId(), null, null,+ null, null, null, null, null, null, 2, null, null, null, null, null, null, null, null, null, null);++ assertEquals("configured", updated.getClientName());+ assertEquals(client.getClientId(), updated.getClientId());+ assertEquals(secret, updated.getClientSecret());+ assertEquals(2, updated.getAccessTokenValidity());+ assertFalse(updated.isAllowedOAuthFlowsUserPoolClient());+ assertEquals(List.of(), updated.getAllowedOAuthFlows());+ assertEquals(List.of(), updated.getAllowedOAuthScopes());+ assertNull(updated.getAnalyticsConfiguration());+ assertEquals(List.of(), updated.getCallbackURLs());+ assertNull(updated.getDefaultRedirectURI());+ assertEquals(List.of(), updated.getExplicitAuthFlows());+ assertNull(updated.getIdTokenValidity());+ assertEquals(3, updated.getAuthSessionValidity());+ assertEquals(List.of(), updated.getLogoutURLs());+ assertNull(updated.getPreventUserExistenceErrors());+ assertEquals(List.of(), updated.getReadAttributes());+ assertNull(updated.getRefreshTokenValidity());+ assertEquals(List.of("COGNITO"), updated.getSupportedIdentityProviders());+ assertNull(updated.getTokenValidityUnits());+ assertEquals(List.of(), updated.getWriteAttributes());+ assertNull(updated.getRefreshTokenRotation());+ assertTrue(updated.getEnableTokenRevocation());+ }++ /**+ * AWS replaces a RefreshTokenValidity of 0 with "the default value of 30 days" whatever the refresh token+ * unit, so the client issues 30-day refresh tokens, whether the 0 came on create or on update.+ */+ @ParameterizedTest+ @CsvSource({"seconds, 2592000", "minutes, 43200", "hours, 720", "days, 30"})+ void refreshTokenValidityZeroBecomesThirtyDaysInTheRefreshTokenUnit(String unit, int expected) {+ UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1");+ UserPoolClient client = clientWithTokenValidity(pool, "RefreshToken", 0, unit);+ assertEquals(expected, client.getRefreshTokenValidity());+ String issuedTwentyNineDaysAgo = String.valueOf(System.currentTimeMillis() - Duration.ofDays(29).toMillis());++ assertFalse(service.isRefreshTokenExpired(client,+ new String[] {pool.getId(), "alice", client.getClientId(), issuedTwentyNineDaysAgo, "token"}));+ assertEquals(expected, service.updateUserPoolClient(pool.getId(), client.getClientId(), null, null, null,+ null, null, null, null, null, null, null, null, null, null, 0, null, Map.of("RefreshToken", unit),+ null, null, null).getRefreshTokenValidity());+ }++ /** A client whose {@code token} validity is {@code validity}, in {@code unit} or its default unit when null. */+ private UserPoolClient clientWithTokenValidity(UserPool pool, String token, int validity, String unit) {+ return service.createUserPoolClient(pool.getId(), "validity-client", false, false, List.of(), List.of(),+ null, List.of(), null, List.of(),+ "AccessToken".equals(token) ? validity : null,+ "IdToken".equals(token) ? validity : null,+ List.of(), null, List.of(),+ "RefreshToken".equals(token) ? validity : null,+ List.of(), unit == null ? null : Map.of(token, unit), List.of(), null, null);+ }+@Testvoid createUserPoolClientRejectsLogoutUrlsWhenOAuthFlowsUserPoolClientIsFalse() {UserPool pool = service.createUserPool(Map.of("PoolName", "ClientPool"), "us-east-1");@@ -4540,16 +4685,16 @@ class CognitoServiceTest {List.of(),null,List.of(),- 1,+ 60,List.of(),- Map.of("RefreshToken", "seconds"),+ Map.of("RefreshToken", "minutes"),List.of(),null,null);- long issuedAt = (System.currentTimeMillis() / 1000L) - 5;- String raw = pool.getId() + "|alice|" + client.getClientId() + "|" + issuedAt + "|" + java.util.UUID.randomUUID();+ long issuedAtMillis = System.currentTimeMillis() - Duration.ofMinutes(61).toMillis();+ String raw = pool.getId() + "|alice|" + client.getClientId() + "|" + issuedAtMillis + "|" + UUID.randomUUID();String expiredRefreshToken = signRawRefreshToken(pool, raw);AwsException exception = assertThrows(AwsException.class, () ->@@ -4596,19 +4741,19 @@ class CognitoServiceTest {List.of(),null,List.of(),- 1,+ 60,List.of(),- Map.of("RefreshToken", "seconds"),+ Map.of("RefreshToken", "minutes"),List.of(),null,null);// issued-at is epoch MILLISECONDS, exactly as buildRefreshToken writes it. A token- // issued 10s ago against a 1s refresh lifetime is expired only if isRefreshTokenExpired+ // issued 61 minutes ago against a 60-minute refresh lifetime is expired only if isRefreshTokenExpired// converts millis to seconds before comparing — before the fix the InitiateAuth// REFRESH_TOKEN_AUTH path never called the check at all, so this minted fresh tokens.- long issuedAtMillis = System.currentTimeMillis() - 10_000L;+ long issuedAtMillis = System.currentTimeMillis() - Duration.ofMinutes(61).toMillis();String raw = pool.getId() + "|alice|" + client.getClientId() + "|" + issuedAtMillis + "|"+ java.util.UUID.randomUUID();String expiredRefreshToken = signRawRefreshToken(pool, raw);diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTokenValidityLimitsOffIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTokenValidityLimitsOffIntegrationTest.javanew file mode 100644index 0000000000..b25bbdafc6--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTokenValidityLimitsOffIntegrationTest.java@@ -0,0 +1,69 @@+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.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.jwtPayload;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;+import static org.junit.jupiter.api.Assertions.assertEquals;++/**+ * With {@code floci.services.cognito.enforce-token-validity-limits=false}, an app client keeps tokens+ * shorter than AWS allows, as tests of what happens when a token expires want.+ */+@QuarkusTest+@TestProfile(CognitoTokenValidityLimitsOffIntegrationTest.TokenValidityLimitsOffProfile.class)+class CognitoTokenValidityLimitsOffIntegrationTest {++ private static final String PASSWORD = "Perm1234!";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void oneMinuteTokensAreAcceptedAndIssued() throws Exception {+ String poolId = cognitoJson("CreateUserPool", """+ {"PoolName": "ShortTokensPool"}+ """).path("UserPool").path("Id").asText();+ JsonNode client = cognitoJson("CreateUserPoolClient", """+ {"UserPoolId": "%s", "ClientName": "short-tokens",+ "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],+ "AccessTokenValidity": 1, "IdTokenValidity": 1, "RefreshTokenValidity": 20,+ "TokenValidityUnits": {"AccessToken": "minutes", "IdToken": "minutes", "RefreshToken": "minutes"}}+ """.formatted(poolId)).path("UserPoolClient");+ assertEquals(1, client.path("AccessTokenValidity").asInt());+ assertEquals(20, client.path("RefreshTokenValidity").asInt());+ cognitoAction("AdminCreateUser", """+ {"UserPoolId": "%s", "Username": "carol", "MessageAction": "SUPPRESS"}+ """.formatted(poolId)).then().statusCode(200);+ cognitoAction("AdminSetUserPassword", """+ {"UserPoolId": "%s", "Username": "carol", "Password": "%s", "Permanent": true}+ """.formatted(poolId, PASSWORD)).then().statusCode(200);++ JsonNode result = cognitoJson("InitiateAuth", """+ {"ClientId": "%s", "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "carol", "PASSWORD": "%s"}}+ """.formatted(client.path("ClientId").asText(), PASSWORD)).path("AuthenticationResult");++ assertEquals(60, result.path("ExpiresIn").asInt());+ JsonNode idToken = jwtPayload(result.path("IdToken").asText());+ assertEquals(60, idToken.path("exp").asLong() - idToken.path("iat").asLong());+ }++ public static final class TokenValidityLimitsOffProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.cognito.enforce-token-validity-limits", "false");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.javaindex b306e4e8a1..f3471ee46b 100644--- a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java@@ -29,51 +29,9 @@ class OpenSearchDomainManagerTest {@Testvoid startDomainLabelsContainerWithResourceIdentity() {- EmulatorConfig config = mock(EmulatorConfig.class);- EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);- EmulatorConfig.OpenSearchServiceConfig opensearch = mock(EmulatorConfig.OpenSearchServiceConfig.class);- when(config.services()).thenReturn(services);- when(services.opensearch()).thenReturn(opensearch);- when(services.dockerNetwork()).thenReturn(Optional.empty());- when(opensearch.proxyBasePort()).thenReturn(9400);- when(opensearch.proxyMaxPort()).thenReturn(9499);- when(opensearch.defaultImage()).thenReturn(Optional.of("opensearchproject/opensearch:2.11.0"));- EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);- when(config.docker()).thenReturn(docker);- lenient().when(docker.logMaxSize()).thenReturn("10m");- lenient().when(docker.logMaxFile()).thenReturn("3");- EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);- when(config.storage()).thenReturn(storage);- when(storage.hostPersistentPath()).thenReturn("floci-data");- when(storage.persistentPath()).thenReturn("/data");-- PortAllocator portAllocator = mock(PortAllocator.class);- when(portAllocator.allocate(9400, 9499)).thenReturn(9400);-- ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);- when(lifecycleManager.createAndStart(any())).thenReturn(- new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(- 9200, new ContainerLifecycleManager.EndpointInfo("172.17.0.5", 9200))));-- ContainerBuilder containerBuilder = mock(ContainerBuilder.class);- ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);- when(containerBuilder.newContainer(anyString())).thenReturn(builder);- when(builder.build()).thenReturn(new ContainerSpec("test-image"));-- RegionResolver regionResolver = mock(RegionResolver.class);- when(regionResolver.getAccountId()).thenReturn("000000000000");- when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");+ Started started = startDomain("my-domain", 9400, false);- OpenSearchDomainManager manager = new OpenSearchDomainManager(containerBuilder, lifecycleManager,- mock(ContainerDetector.class), portAllocator, config, regionResolver);-- Domain domain = new Domain();- domain.setDomainName("my-domain");- domain.setEngineVersion("OpenSearch_2.11");-- manager.startDomain(domain);-- verify(builder).withLabels(Map.of(+ verify(started.builder()).withLabels(Map.of("io.floci", "aws","io.floci.service", "opensearch","io.floci.resource-id", "my-domain",@@ -90,57 +48,23 @@ class OpenSearchDomainManagerTest {*/@Testvoid startDomainPublishesAHostPortEvenWhenFlociRunsInAContainer() {- EmulatorConfig config = mock(EmulatorConfig.class);- EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);- EmulatorConfig.OpenSearchServiceConfig opensearch = mock(EmulatorConfig.OpenSearchServiceConfig.class);- when(config.services()).thenReturn(services);- when(services.opensearch()).thenReturn(opensearch);- when(services.dockerNetwork()).thenReturn(Optional.empty());- when(opensearch.proxyBasePort()).thenReturn(9400);- when(opensearch.proxyMaxPort()).thenReturn(9499);- when(opensearch.defaultImage()).thenReturn(Optional.of("opensearchproject/opensearch:2.11.0"));- EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);- when(config.docker()).thenReturn(docker);- lenient().when(docker.logMaxSize()).thenReturn("10m");- lenient().when(docker.logMaxFile()).thenReturn("3");- EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);- when(config.storage()).thenReturn(storage);- when(storage.hostPersistentPath()).thenReturn("floci-data");- when(storage.persistentPath()).thenReturn("/data");-- PortAllocator portAllocator = mock(PortAllocator.class);- when(portAllocator.allocate(9400, 9499)).thenReturn(9401);-- ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);- when(lifecycleManager.createAndStart(any())).thenReturn(- new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(- 9200, new ContainerLifecycleManager.EndpointInfo("172.17.0.5", 9200))));-- ContainerBuilder containerBuilder = mock(ContainerBuilder.class);- ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);- when(containerBuilder.newContainer(anyString())).thenReturn(builder);- when(builder.build()).thenReturn(new ContainerSpec("test-image"));-- RegionResolver regionResolver = mock(RegionResolver.class);- when(regionResolver.getAccountId()).thenReturn("000000000000");- when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");-- ContainerDetector containerDetector = mock(ContainerDetector.class);- lenient().when(containerDetector.isRunningInContainer()).thenReturn(true);+ Started started = startDomain("host-reach", 9401, true);- OpenSearchDomainManager manager = new OpenSearchDomainManager(containerBuilder, lifecycleManager,- containerDetector, portAllocator, config, regionResolver);-- Domain domain = new Domain();- domain.setDomainName("host-reach");- domain.setEngineVersion("OpenSearch_2.11");+ verify(started.portAllocator()).allocate(9400, 9499);+ verify(started.builder()).withPortBinding(9200, 9401);+ assertEquals("http://172.17.0.5:9200", started.domain().getEndpoint());+ assertEquals(Integer.valueOf(9401), started.domain().getHostPort());+ }- manager.startDomain(domain);+ /**+ * The image's entrypoint keeps the server as a child of a bash PID 1, which ignores SIGTERM.+ * Without an init process each DeleteDomain waits out the whole stop timeout.+ */+ @Test+ void startDomainRunsTheContainerUnderAnInitProcess() {+ Started started = startDomain("init", 9400, false);- verify(portAllocator).allocate(9400, 9499);- verify(builder).withPortBinding(9200, 9401);- assertEquals("http://172.17.0.5:9200", domain.getEndpoint());- assertEquals(Integer.valueOf(9401), domain.getHostPort());+ verify(started.builder()).withInit();}/**@@ -207,4 +131,58 @@ class OpenSearchDomainManagerTest {verify(lifecycleManager).stopAndRemove("container-id", null);verify(portAllocator).release(9401);}++ private record Started(ContainerBuilder.Builder builder, PortAllocator portAllocator, Domain domain) {+ }++ /** Starts an OpenSearch 2.11 domain against a mocked builder and lifecycle, with no Docker. */+ private static Started startDomain(String domainName, int hostPort, boolean flociInContainer) {+ EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.OpenSearchServiceConfig opensearch = mock(EmulatorConfig.OpenSearchServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.opensearch()).thenReturn(opensearch);+ when(services.dockerNetwork()).thenReturn(Optional.empty());+ when(opensearch.proxyBasePort()).thenReturn(9400);+ when(opensearch.proxyMaxPort()).thenReturn(9499);+ when(opensearch.defaultImage()).thenReturn(Optional.of("opensearchproject/opensearch:2.11.0"));+ EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);+ when(config.docker()).thenReturn(docker);+ lenient().when(docker.logMaxSize()).thenReturn("10m");+ lenient().when(docker.logMaxFile()).thenReturn("3");+ EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);+ when(config.storage()).thenReturn(storage);+ when(storage.hostPersistentPath()).thenReturn("floci-data");+ when(storage.persistentPath()).thenReturn("/data");++ PortAllocator portAllocator = mock(PortAllocator.class);+ when(portAllocator.allocate(9400, 9499)).thenReturn(hostPort);++ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);+ when(lifecycleManager.createAndStart(any())).thenReturn(+ new ContainerLifecycleManager.ContainerInfo("container-id", Map.of(+ 9200, new ContainerLifecycleManager.EndpointInfo("172.17.0.5", 9200))));++ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);+ ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);+ when(builder.build()).thenReturn(new ContainerSpec("test-image"));++ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");++ ContainerDetector containerDetector = mock(ContainerDetector.class);+ lenient().when(containerDetector.isRunningInContainer()).thenReturn(flociInContainer);++ OpenSearchDomainManager manager = new OpenSearchDomainManager(containerBuilder, lifecycleManager,+ containerDetector, portAllocator, config, regionResolver);++ Domain domain = new Domain();+ domain.setDomainName(domainName);+ domain.setEngineVersion("OpenSearch_2.11");++ manager.startDomain(domain);+ return new Started(builder, portAllocator, domain);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.javaindex 68376af8df..3dee41f1fc 100644--- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerContextAttributesIntegrationTest.java@@ -97,16 +97,16 @@ class SchedulerContextAttributesIntegrationTest {String queueName = uniqueName("ctx-rate-q");String queueUrl = createQueue(queueName);String scheduleName = uniqueName("ctx-rate");- harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED", queueArn(queueName), CONTEXT_INPUT);+ Instant firstFire = harness.createRecurringSchedule(scheduleName, "rate(1 minute)", queueArn(queueName),+ CONTEXT_INPUT);Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);- Instant firstFire = schedule.getCreationDate();ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName);dispatcher.tick(firstFire.plusSeconds(1));JsonNode body = singleBody(queueUrl);assertEquals(schedule.getArn(), body.path("arn").asText());- assertEquals(firstFire.truncatedTo(ChronoUnit.SECONDS).toString(), body.path("time").asText());+ assertEquals(firstFire.toString(), body.path("time").asText());assertTrue(body.path("executionId").asText().matches("[0-9a-f]{16}"), body.toString());assertEquals(1, body.path("attempt").asInt());}@@ -188,9 +188,8 @@ class SchedulerContextAttributesIntegrationTest {String queueName = uniqueName("ctx-ids-q");String queueUrl = createQueue(queueName);String scheduleName = uniqueName("ctx-ids");- harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED", queueArn(queueName), CONTEXT_INPUT);- Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);- Instant firstFire = schedule.getCreationDate();+ Instant firstFire = harness.createRecurringSchedule(scheduleName, "rate(1 minute)", queueArn(queueName),+ CONTEXT_INPUT);ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName);dispatcher.tick(firstFire.plusSeconds(1));diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.javaindex f45b3d3393..8ffb897e2a 100644--- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerStepFunctionsIntegrationTest.java@@ -77,9 +77,8 @@ class SchedulerStepFunctionsIntegrationTest {void recurringScheduleStartsOneExecutionPerOccurrence() {String stateMachineArn = createPassStateMachine();String scheduleName = uniqueName("sfn-rate");- harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED", stateMachineArn, "{\"kind\":\"recurring\"}");- Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);- Instant firstFire = schedule.getCreationDate().plus(61, ChronoUnit.SECONDS);+ Instant firstFire = harness.createRecurringSchedule(scheduleName, "rate(1 minute)", stateMachineArn,+ "{\"kind\":\"recurring\"}");ScheduleDispatcher dispatcher = harness.dispatcherFor(scheduleName);dispatcher.tick(firstFire);@@ -104,10 +103,8 @@ class SchedulerStepFunctionsIntegrationTest {void stepFunctionsDeleteScheduleStopsFutureOccurrence() {String targetStateMachineArn = createPassStateMachine();String scheduleName = uniqueName("sfn-delete");- harness.createSchedule(scheduleName, "rate(1 minute)", "ENABLED",+ Instant fireAt = harness.createRecurringSchedule(scheduleName, "rate(1 minute)",targetStateMachineArn, "{\"deleted\":false}");- Schedule schedule = schedulerService.getSchedule(scheduleName, null, REGION);- Instant fireAt = schedule.getCreationDate().plus(61, ChronoUnit.SECONDS);String deleterStateMachineArn = harness.createStateMachine(uniqueName("schedule-deleter"), """{"QueryLanguage": "JSONata",diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.javaindex 2ea86d419c..60ddaa3815 100644--- a/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java+++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/SchedulerTestHarness.java@@ -12,6 +12,7 @@ import java.time.Duration;import java.time.Instant;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;+import java.time.temporal.ChronoUnit;import java.util.ArrayList;import java.util.List;import java.util.Map;@@ -63,6 +64,23 @@ final class SchedulerTestHarness {}void createSchedule(String name, String expression, String state, String targetArn, String input) {+ postSchedule(name, scheduleRequest(expression, state, targetArn, input));+ }++ /**+ * Creates an enabled recurring schedule that starts a day from now, and returns that start, its+ * first occurrence. The application's own dispatcher keeps ticking while a test runs, so a+ * schedule that is already due could fire there as well as on the test's dispatcher.+ */+ Instant createRecurringSchedule(String name, String expression, String targetArn, String input) {+ Instant startDate = Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.SECONDS);+ ObjectNode request = scheduleRequest(expression, "ENABLED", targetArn, input);+ request.put("StartDate", startDate.getEpochSecond());+ postSchedule(name, request);+ return startDate;+ }++ private static ObjectNode scheduleRequest(String expression, String state, String targetArn, String input) {ObjectNode request = MAPPER.createObjectNode();request.put("ScheduleExpression", expression);request.putObject("FlexibleTimeWindow").put("Mode", "OFF");@@ -71,7 +89,10 @@ final class SchedulerTestHarness {target.put("Arn", targetArn);target.put("RoleArn", ROLE_ARN);target.put("Input", input);+ return request;+ }+ private void postSchedule(String name, ObjectNode request) {given().contentType("application/json").body(request.toString())diff --git a/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.java b/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.javaindex 9c154afe18..964e8f34ce 100644--- a/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.java+++ b/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.java@@ -69,6 +69,15 @@ public class SidecarContainersProfile implements QuarkusTestProfile {"floci.services.bcm-data-exports.emit-mode", "off");}+ /**+ * This run's namespace, for a profile of another kind whose classes start containers that need+ * the same isolation. Its containers are then removed by {@link #requireDockerAndImage} too when+ * a killed run leaves them behind.+ */+ public static String namespace() {+ return NAMESPACE;+ }+/*** Identifies this machine and process id namespace, the scope a process id is valid in. On* Linux the namespace is {@code /proc/self/ns/pid}; elsewhere the host name has to do alone.diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 48cb95f540..1a60b2f551 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -262,6 +262,7 @@ floci:enabled: truecognito:enabled: true+ enforce-token-validity-limits: truestepfunctions:enabled: trueallow-plaintext-http: true