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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Part of #4542.

---------

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

No files matched your search

@@ -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");
}
}
}
@@ -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 {
@BeforeAll
static 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"
);
}
}
}
@@ -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");
}
}
@@ -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");
}
}
}
@@ -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 {
@Inject
CloudFrontService 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();
}
}
@Test
void 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");
}
}
}
@@ -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 {
@Test
void 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"
);
}
}
}
@@ -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);
}
}
@@ -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");
}
}
@@ -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());
}
@@ -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 {
@@ -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);
}
@Test
void 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);
@@ -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");
}
}
}
@@ -29,51 +29,9 @@ class OpenSearchDomainManagerTest {
@Test
void 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");
Started started = startDomain("my-domain", 9400, false);
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");
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 {
*/
@Test
void 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");
Started started = startDomain("host-reach", 9401, true);
PortAllocator portAllocator = mock(PortAllocator.class);
when(portAllocator.allocate(9400, 9499)).thenReturn(9401);
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());
}
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))));
/**
* 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);
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);
OpenSearchDomainManager manager = new OpenSearchDomainManager(containerBuilder, lifecycleManager,
containerDetector, portAllocator, config, regionResolver);
Domain domain = new Domain();
domain.setDomainName("host-reach");
domain.setEngineVersion("OpenSearch_2.11");
manager.startDomain(domain);
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);
}
}
@@ -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));
@@ -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",
@@ -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())
@@ -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.