diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 2d20b2b5ea..b87481b6db 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -46,6 +46,8 @@ components: - toddbaert tools/flagd-http-connector: - liran2000 + tools/flagd-testcontainer: + - joe-chambers tools/tck: - aepfli diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c09544dc05..697d54ab5c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -15,6 +15,7 @@ "providers/gcp": "0.0.2", "tools/junit-openfeature": "0.2.2", "tools/flagd-http-connector": "0.0.5", + "tools/flagd-testcontainer": "0.0.1", "tools/flagd-api": "1.0.0", "tools/flagd-api-testkit": "0.3.0", "tools/flagd-core": "3.0.0", diff --git a/pom.xml b/pom.xml index 6d03c2f353..b0bb087ad7 100644 --- a/pom.xml +++ b/pom.xml @@ -49,6 +49,7 @@ providers/ofrep providers/gcp tools/flagd-http-connector + tools/flagd-testcontainer diff --git a/release-please-config.json b/release-please-config.json index 54129737e7..e11dc29123 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -238,6 +238,17 @@ "README.md" ] }, + "tools/flagd-testcontainer": { + "package-name": "dev.openfeature.contrib.tools.flagdtestcontainer", + "release-type": "simple", + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": true, + "versioning": "default", + "extra-files": [ + "pom.xml", + "README.md" + ] + }, ".": { "package-name": "dev.openfeature.contrib.parent", "release-type": "simple", diff --git a/renovate.json b/renovate.json index 7f6720d613..3f7d8faa2c 100644 --- a/renovate.json +++ b/renovate.json @@ -15,6 +15,20 @@ ], "depNameTemplate": "open-feature/test-harness", "datasourceTemplate": "github-releases" + }, + { + "customType": "regex", + "description": "flagd image used by the flagd-testcontainer module", + "managerFilePatterns": [ + "/^tools/flagd-testcontainer/README\\.md$/", + "/^tools/flagd-testcontainer/src/main/java/.+/FlagdContainer\\.java$/" + ], + "matchStrings": [ + "DEFAULT_TAG = \"(?[^\"]+)\"", + "ghcr\\.io\\/open-feature\\/flagd:(?v\\d[^\\s\"`;}]*)" + ], + "depNameTemplate": "ghcr.io/open-feature/flagd", + "datasourceTemplate": "docker" } ], "ignoreDeps": [ diff --git a/spotbugs-exclusions.xml b/spotbugs-exclusions.xml index 7f1d7ae129..c05e176f80 100644 --- a/spotbugs-exclusions.xml +++ b/spotbugs-exclusions.xml @@ -29,6 +29,12 @@ + + + + + + diff --git a/tools/flagd-testcontainer/README.md b/tools/flagd-testcontainer/README.md new file mode 100644 index 0000000000..eecab61dae --- /dev/null +++ b/tools/flagd-testcontainer/README.md @@ -0,0 +1,215 @@ +# flagd Testcontainer + +A [Testcontainers](https://java.testcontainers.org/) module that runs [flagd](https://flagd.dev) in Docker for integration tests. + +## Installation + +```xml + + dev.openfeature.contrib.tools + flagd-testcontainer + 0.0.1 + test + +``` + +## Usage + +Give the container at least one flag source, start it, and point your provider at the mapped ports. + +```java +try (FlagdContainer flagd = new FlagdContainer().withFlagsFromClasspath("flags.json")) { + flagd.start(); + + FlagdProvider provider = new FlagdProvider(FlagdOptions.builder() + .host(flagd.getHost()) + .port(flagd.getEvaluationPort()) + .build()); +} +``` + +With JUnit 5 and `org.testcontainers:testcontainers-junit-jupiter`: + +```java +@Testcontainers +class MyTest { + @Container + static FlagdContainer flagd = new FlagdContainer().withFlagsFromClasspath("flags.json"); +} +``` + +### Flag sources + +| Method | Source | +| --- | --- | +| `withFlagsFromClasspath(String)` | a classpath resource | +| `withFlagsFromFile(Path)` | a file on the host | +| `withFlags(String)` | a flag definition JSON string | +| `withFlagSource(String)` | any flagd `--uri`, e.g. `https://...` or `grpc://...` | + +Sources can be combined. File-based sources are copied into the container, not bind-mounted. + +### Changing flags at runtime + +With exactly one file-based source, `updateFlags(String)` replaces the flag definition in the running container. +flagd picks the change up through its file watcher, so wait for it (for example with Awaitility) rather than asserting immediately. + +```java +flagd.updateFlags(newFlagsJson); +``` + +### Ports + +| Service | Container port | Accessor | +| --- | --- | --- | +| Evaluation (gRPC / Connect), for RPC providers | 8013 | `getEvaluationPort()` | +| Management (health, metrics) | 8014 | `getManagementPort()` | +| Sync, for in-process providers | 8015 | `getSyncPort()` | +| OFREP | 8016 | `getOfrepPort()`, `getOfrepEndpoint()` | + +The container is ready once flagd's `/readyz` endpoint answers on the management port. + +### Connecting an application + +`FlagdConnection` describes where flagd is reachable from, and how, so an application can be configured from it rather than from hard-coded ports. + +| Accessor | Vantage point | Host and ports | +| --- | --- | --- | +| `getConnection()` | the test host (the test JVM, a process it launches) | `getHost()` and mapped ports | +| `getNetworkConnection()` | another container on the same Docker network | the last network alias and container ports | + +`toEnv(FlagdResolver)` returns the environment variables the flagd provider reads: + +- `FLAGD_RESOLVER`, `FLAGD_HOST` and `FLAGD_PORT`: the evaluation port for `RPC`, the sync port for `IN_PROCESS` +- `FLAGD_SYNC_PORT` for `IN_PROCESS`, which the provider prefers over `FLAGD_PORT` +- `FLAGD_TLS`, set to `true` or `false` so that it overrides any value already in the application's environment +- `FLAGD_SERVER_CERT_PATH` when TLS is enabled and the path is known +- `FLAGD_SOURCE_SELECTOR` when a selector is set + +```java +Network network = Network.newNetwork(); +FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withNetwork(network) + .withNetworkAliases("flagd"); + +GenericContainer app = new GenericContainer<>("my-app:latest") + .withNetwork(network) + .withEnv(flagd.getNetworkConnection().toEnv(FlagdResolver.IN_PROCESS)) + .dependsOn(flagd); +``` + +`getEvaluationEndpoint()` and `getOfrepEndpoint()` return base URLs with the right scheme, and `getFlagSources()`, `isTlsEnabled()`, `getContextValues()` and `getContextFromHeaders()` report how the container was configured. + +### Selecting a flag source + +With several sources, an in-process provider can sync just one of them. +`getSourceSelectors()` returns the selector of each source, in the order they were added. flagd names a file source by its path without `file:`, so these differ from `getFlagSources()`. + +```java +String selector = flagd.getSourceSelectors().get(1); +flagd.getConnection().withSourceSelector(selector).toEnv(FlagdResolver.IN_PROCESS); // adds FLAGD_SOURCE_SELECTOR +``` + +### TLS + +```java +new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withTls(Paths.get("server-cert.pem"), Paths.get("server-key.pem")); +``` + +flagd serves the evaluation and sync services over TLS; the management and OFREP services stay on plain HTTP. +The certificate must be valid for the name clients use: `getHost()` from the test host, the network alias from other containers. +`getHost()` is usually `localhost`, but with a remote Docker host, as in some CI environments, it is that host's name or IP address. + +From the test host, `getConnection()` sets `FLAGD_SERVER_CERT_PATH` to the certificate you passed in. +From another container, only you know where that container has the certificate, so add it: + +```java +flagd.getNetworkConnection().withServerCertPath("/certs/ca.pem").toEnv(FlagdResolver.RPC); +``` + +#### Creating a test certificate and key + +A self-signed certificate is enough for tests. The client trusts the certificate itself, so no separate CA is needed. +List every name clients connect with as a subject alternative name. Hostname verification checks these, not the common name. + +```bash +mkdir -p src/test/resources/tls +openssl req -x509 -newkey rsa:2048 -nodes -days 36500 \ + -keyout src/test/resources/tls/server-key.pem \ + -out src/test/resources/tls/server-cert.pem \ + -subj "/CN=flagd-test" \ + -addext "subjectAltName=DNS:localhost,DNS:flagd,IP:127.0.0.1" +``` + +- `-nodes` leaves the key unencrypted, which flagd requires. +- `DNS:flagd` must match the alias given to `withNetworkAliases`; add one entry per alias. +- If `getHost()` is not `localhost` in your environment, add its value too, as `DNS:` for a name or `IP:` for an address. +- Requires OpenSSL 1.1.1 or later for `-addext`. Run `openssl x509 -in src/test/resources/tls/server-cert.pem -noout -ext subjectAltName` to check the names. +- The long validity keeps committed test fixtures from expiring. Use this key for tests only. + +Then point flagd and the provider at the files: + +```java +Path cert = Paths.get("src/test/resources/tls/server-cert.pem"); +Path key = Paths.get("src/test/resources/tls/server-key.pem"); + +FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withTls(cert, key); +flagd.start(); + +FlagdProvider provider = new FlagdProvider(FlagdOptions.builder() + .host(flagd.getHost()) + .port(flagd.getEvaluationPort()) + .tls(true) + .certPath(cert.toAbsolutePath().toString()) + .build()); +``` + +### Evaluation context + +```java +new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withContextValue("env", "test") // --context-value, added to every evaluation + .withContextFromHeader("X-Tier", "tier"); // --context-from-header, request header to context key +``` + +Values are encoded so that flagd receives them unchanged, including commas, quotes and line breaks. +flagd cannot take some entries, so these are rejected with an `IllegalArgumentException`: + +- a key or header that contains `=` or starts with `[` +- a value that ends with whitespace or `]` +- a value with no `=` in it whose key starts with `"`, or which itself ends with `"` +- an entry containing a CRLF line break + +### Other flagd options + +`withFlagdArgs(String...)` appends raw arguments to `flagd start`, for options without a dedicated method: + +```java +new FlagdContainer().withFlagsFromClasspath("flags.json").withFlagdArgs("--stream-deadline", "30s"); +``` + +Don't use it to change the service ports, because the accessors assume flagd's defaults. + +### Image + +The default image is `ghcr.io/open-feature/flagd` at the tag in `FlagdContainer.DEFAULT_TAG`. +Pass another tag, or a compatible image, to the constructor: + +```java +new FlagdContainer("ghcr.io/open-feature/flagd:v0.18.1"); +new FlagdContainer(DockerImageName.parse("my-registry/flagd:dev").asCompatibleSubstituteFor("ghcr.io/open-feature/flagd")); +``` + +## Development + +Tests start real containers, so a running Docker daemon is required. + +```bash +mvn --projects tools/flagd-testcontainer clean verify +``` diff --git a/tools/flagd-testcontainer/pom.xml b/tools/flagd-testcontainer/pom.xml new file mode 100644 index 0000000000..dc0fa9be19 --- /dev/null +++ b/tools/flagd-testcontainer/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + dev.openfeature.contrib + parent + [1.0,2.0) + ../../pom.xml + + dev.openfeature.contrib.tools + flagd-testcontainer + 0.0.1 + + + ${groupId}.flagdtestcontainer + 2.0.5 + + + flagd-testcontainer + Testcontainers module for running flagd in integration tests + https://openfeature.dev + + + + joe-chambers + Joe Chambers + OpenFeature + https://openfeature.dev/ + + + + + + + org.testcontainers + testcontainers + ${testcontainers.version} + + + + diff --git a/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdConnection.java b/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdConnection.java new file mode 100644 index 0000000000..5faf1bdeca --- /dev/null +++ b/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdConnection.java @@ -0,0 +1,232 @@ +package dev.openfeature.contrib.tools.flagd.testcontainer; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Where a flagd container can be reached from a particular vantage point: either the test host + * ({@link FlagdContainer#getConnection()}) or another container on the same Docker network + * ({@link FlagdContainer#getNetworkConnection()}). + */ +public final class FlagdConnection { + + /** Environment variable the flagd provider reads its resolver from. */ + public static final String RESOLVER_ENV_VAR = "FLAGD_RESOLVER"; + + /** Environment variable the flagd provider reads its host from. */ + public static final String HOST_ENV_VAR = "FLAGD_HOST"; + + /** Environment variable the flagd provider reads its port from. */ + public static final String PORT_ENV_VAR = "FLAGD_PORT"; + + /** Environment variable an in-process flagd provider prefers over {@code FLAGD_PORT}. */ + public static final String SYNC_PORT_ENV_VAR = "FLAGD_SYNC_PORT"; + + /** Environment variable the flagd provider reads whether to use TLS from. */ + public static final String TLS_ENV_VAR = "FLAGD_TLS"; + + /** Environment variable the flagd provider reads the trusted certificate path from. */ + public static final String SERVER_CERT_PATH_ENV_VAR = "FLAGD_SERVER_CERT_PATH"; + + /** Environment variable the flagd provider reads the flag source selector from. */ + public static final String SOURCE_SELECTOR_ENV_VAR = "FLAGD_SOURCE_SELECTOR"; + + private final String host; + private final int evaluationPort; + private final int managementPort; + private final int syncPort; + private final int ofrepPort; + private final boolean tls; + private final String serverCertPath; + private final String sourceSelector; + + FlagdConnection( + String host, + int evaluationPort, + int managementPort, + int syncPort, + int ofrepPort, + boolean tls, + String serverCertPath, + String sourceSelector) { + this.host = host; + this.evaluationPort = evaluationPort; + this.managementPort = managementPort; + this.syncPort = syncPort; + this.ofrepPort = ofrepPort; + this.tls = tls; + this.serverCertPath = serverCertPath; + this.sourceSelector = sourceSelector; + } + + /** + * Returns the host flagd is reachable on. + * + * @return the host name or network alias + */ + public String getHost() { + return host; + } + + /** + * Returns the port of the flag evaluation service, for RPC providers. + * + * @return the evaluation port + */ + public int getEvaluationPort() { + return evaluationPort; + } + + /** + * Returns the port of the management service (health, readiness and metrics). + * + * @return the management port + */ + public int getManagementPort() { + return managementPort; + } + + /** + * Returns the port of the flag sync service, for in-process providers. + * + * @return the sync port + */ + public int getSyncPort() { + return syncPort; + } + + /** + * Returns the port of the OFREP service. + * + * @return the OFREP port + */ + public int getOfrepPort() { + return ofrepPort; + } + + /** + * Returns whether the evaluation and sync services are served over TLS. The management and OFREP + * services are always plain HTTP. + * + * @return true if TLS is enabled + */ + public boolean isTls() { + return tls; + } + + /** + * Returns the path of the certificate a client should trust, as seen from this connection's + * vantage point. + * + * @return the certificate path, or null if TLS is disabled or the path is unknown + */ + public String getServerCertPath() { + return serverCertPath; + } + + /** + * Returns a copy of this connection with the given trusted certificate path, e.g. where an + * application container has the certificate mounted. + * + * @param path the certificate path + * @return a new connection + */ + public FlagdConnection withServerCertPath(String path) { + return new FlagdConnection( + host, evaluationPort, managementPort, syncPort, ofrepPort, tls, path, sourceSelector); + } + + /** + * Returns the selector that restricts which flag source a provider receives. + * + * @return the selector, or null to receive every source + */ + public String getSourceSelector() { + return sourceSelector; + } + + /** + * Returns a copy of this connection that selects the given flag source, typically one of {@link + * FlagdContainer#getSourceSelectors()}. + * + * @param selector the source selector + * @return a new connection + */ + public FlagdConnection withSourceSelector(String selector) { + return new FlagdConnection( + host, evaluationPort, managementPort, syncPort, ofrepPort, tls, serverCertPath, selector); + } + + /** + * Returns the port a provider using the given resolver connects to. + * + * @param resolver the provider's resolver + * @return the evaluation port for {@link FlagdResolver#RPC}, the sync port for {@link + * FlagdResolver#IN_PROCESS} + */ + public int getPort(FlagdResolver resolver) { + return resolver == FlagdResolver.IN_PROCESS ? syncPort : evaluationPort; + } + + /** + * Returns the base URL of the flag evaluation service, which also accepts Connect requests over + * HTTP, e.g. {@code https://localhost:32768}. + * + * @return the evaluation base URL + */ + public String getEvaluationEndpoint() { + return (tls ? "https://" : "http://") + authority(evaluationPort); + } + + /** + * Returns the base URL of the OFREP service, e.g. {@code http://localhost:32768}. + * + * @return the OFREP base URL + */ + public String getOfrepEndpoint() { + return "http://" + authority(ofrepPort); + } + + /** + * Returns the environment variables that point a flagd provider at this connection, for + * example to pass to an application container with {@code withEnv(...)}. + * + * @param resolver the resolver the provider should use + * @return {@code FLAGD_RESOLVER}, {@code FLAGD_HOST}, {@code FLAGD_PORT} and {@code FLAGD_TLS}; + * {@code FLAGD_SYNC_PORT} for {@link FlagdResolver#IN_PROCESS}; {@code + * FLAGD_SERVER_CERT_PATH} when TLS is enabled and the path is known; {@code + * FLAGD_SOURCE_SELECTOR} when a selector is set. {@code FLAGD_TLS} is set even when false, + * so it overrides a value already in the application's environment. + */ + public Map toEnv(FlagdResolver resolver) { + Map env = new LinkedHashMap<>(); + env.put(RESOLVER_ENV_VAR, resolver.getValue()); + env.put(HOST_ENV_VAR, host); + env.put(PORT_ENV_VAR, String.valueOf(getPort(resolver))); + if (resolver == FlagdResolver.IN_PROCESS) { + env.put(SYNC_PORT_ENV_VAR, String.valueOf(syncPort)); + } + env.put(TLS_ENV_VAR, String.valueOf(tls)); + if (tls && serverCertPath != null) { + env.put(SERVER_CERT_PATH_ENV_VAR, serverCertPath); + } + if (sourceSelector != null) { + env.put(SOURCE_SELECTOR_ENV_VAR, sourceSelector); + } + return Collections.unmodifiableMap(env); + } + + // an IPv6 literal must be bracketed to be a valid URL authority + private String authority(int port) { + boolean ipv6 = host.indexOf(':') >= 0 && !host.startsWith("["); + return (ipv6 ? "[" + host + "]" : host) + ":" + port; + } + + @Override + public String toString() { + return "FlagdConnection{host=" + host + ", evaluationPort=" + evaluationPort + ", managementPort=" + + managementPort + ", syncPort=" + syncPort + ", ofrepPort=" + ofrepPort + ", tls=" + tls + + ", serverCertPath=" + serverCertPath + ", sourceSelector=" + sourceSelector + "}"; + } +} diff --git a/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainer.java b/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainer.java new file mode 100644 index 0000000000..9462832266 --- /dev/null +++ b/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainer.java @@ -0,0 +1,441 @@ +package dev.openfeature.contrib.tools.flagd.testcontainer; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.images.builder.Transferable; +import org.testcontainers.utility.DockerImageName; +import org.testcontainers.utility.MountableFile; + +/** + * Testcontainers implementation for flagd. + * + *

Flag definitions are copied into the container and served by flagd's file sync, so they can + * be replaced at runtime with {@link #updateFlags(String)}. Remote sources (http, grpc, etc.) can + * be added with {@link #withFlagSource(String)}. + * + *

{@code
+ * try (FlagdContainer flagd = new FlagdContainer().withFlagsFromClasspath("flags.json")) {
+ *     flagd.start();
+ *     FlagdProvider provider = new FlagdProvider(FlagdOptions.builder()
+ *             .host(flagd.getHost())
+ *             .port(flagd.getEvaluationPort())
+ *             .build());
+ * }
+ * }
+ */ +public class FlagdContainer extends GenericContainer { + + /** The flagd image this module is tested against. */ + public static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("ghcr.io/open-feature/flagd"); + + /** The flagd image tag this module is tested against. */ + public static final String DEFAULT_TAG = "v0.18.1"; + + /** Port of the flag evaluation service (gRPC and Connect/HTTP). */ + public static final int EVALUATION_PORT = 8013; + + /** Port of the management service (health, readiness and metrics). */ + public static final int MANAGEMENT_PORT = 8014; + + /** Port of the flag sync service used by in-process providers. */ + public static final int SYNC_PORT = 8015; + + /** Port of the OFREP service. */ + public static final int OFREP_PORT = 8016; + + private static final String FLAGS_DIR = "/etc/flagd/"; + private static final String TLS_CERT_PATH = FLAGS_DIR + "tls/server-cert.pem"; + private static final String TLS_KEY_PATH = FLAGS_DIR + "tls/server-key.pem"; + // rw-r--r--: flagd runs as a non-root user and must be able to read every file copied in, + // whatever the host file's own mode + private static final int READABLE_FILE_MODE = 0b110_100_100; + + private final List sources = new ArrayList<>(); + private final Map contextValues = new LinkedHashMap<>(); + private final Map contextFromHeaders = new LinkedHashMap<>(); + private final List extraArgs = new ArrayList<>(); + private int flagFileCount = 0; + private Path tlsCertPath; + + /** Creates a container from the default flagd image. */ + public FlagdContainer() { + this(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG)); + } + + /** + * Creates a container from the given flagd image. + * + * @param dockerImageName the full image name, e.g. {@code ghcr.io/open-feature/flagd:v0.18.1} + */ + public FlagdContainer(String dockerImageName) { + this(DockerImageName.parse(dockerImageName)); + } + + /** + * Creates a container from the given flagd image. + * + * @param dockerImageName the image; must be compatible with {@code ghcr.io/open-feature/flagd} + */ + public FlagdContainer(DockerImageName dockerImageName) { + super(dockerImageName); + dockerImageName.assertCompatibleWith(DEFAULT_IMAGE_NAME); + withExposedPorts(EVALUATION_PORT, MANAGEMENT_PORT, SYNC_PORT, OFREP_PORT); + waitingFor(Wait.forHttp("/readyz").forPort(MANAGEMENT_PORT).forStatusCode(200)); + } + + /** + * Serves the given flag definition JSON. + * + * @param flagsJson a flagd flag definition document + * @return this container + */ + public FlagdContainer withFlags(String flagsJson) { + return withFlagFile(Transferable.of(flagsJson.getBytes(StandardCharsets.UTF_8))); + } + + /** + * Serves the flag definition from the given classpath resource. + * + * @param resourcePath the classpath resource path + * @return this container + */ + public FlagdContainer withFlagsFromClasspath(String resourcePath) { + return withFlagFile(MountableFile.forClasspathResource(resourcePath, READABLE_FILE_MODE)); + } + + /** + * Serves the flag definition from the given host file. + * + * @param path the host file path + * @return this container + */ + public FlagdContainer withFlagsFromFile(Path path) { + return withFlagFile(MountableFile.forHostPath(path, READABLE_FILE_MODE)); + } + + /** + * Adds a flag source URI, passed to flagd as {@code --uri}. Use this for sources that are not + * files in the container, such as {@code https://...} or {@code grpc://...}. + * + * @param uri the flag source URI + * @return this container + */ + public FlagdContainer withFlagSource(String uri) { + sources.add(uri); + return this; + } + + /** + * Serves the evaluation and sync services over TLS. The management and OFREP services stay on + * plain HTTP; this is flagd's behaviour, not this module's. + * + *

The certificate must be valid for the host clients connect to, typically {@code localhost} + * from the test host and the network alias from other containers. For a self-signed + * certificate, clients trust the certificate itself. + * + * @param certPath the host path of the PEM server certificate + * @param keyPath the host path of the PEM private key + * @return this container + */ + public FlagdContainer withTls(Path certPath, Path keyPath) { + this.tlsCertPath = certPath.toAbsolutePath(); + withCopyFileToContainer(MountableFile.forHostPath(certPath, READABLE_FILE_MODE), TLS_CERT_PATH); + return withCopyFileToContainer(MountableFile.forHostPath(keyPath, READABLE_FILE_MODE), TLS_KEY_PATH); + } + + /** + * Adds a static value to the evaluation context of every evaluation, passed to flagd as {@code + * --context-value}. + * + * @param key the context key + * @param value the context value + * @return this container + * @throws IllegalArgumentException if flagd cannot receive the pair intact, see {@link + * #withContextFromHeader(String, String)} + */ + public FlagdContainer withContextValue(String key, String value) { + checkMapEntry(key, value); + contextValues.put(key, value); + return this; + } + + /** + * Maps a request header into the evaluation context, passed to flagd as {@code + * --context-from-header}. + * + * @param header the request header name + * @param contextKey the context key its value is stored under + * @return this container + * @throws IllegalArgumentException if flagd cannot receive the pair intact: the first argument + * contains {@code =} or starts with {@code [}, the second ends with whitespace or {@code ]}, + * either contains a CRLF, or the second contains no {@code =} and the first starts or the + * second ends with {@code "} + */ + public FlagdContainer withContextFromHeader(String header, String contextKey) { + checkMapEntry(header, contextKey); + contextFromHeaders.put(header, contextKey); + return this; + } + + /** + * Appends raw arguments to the {@code flagd start} command, for options without a dedicated + * method, e.g. {@code withFlagdArgs("--stream-deadline", "30s")}. Do not use it to change the + * service ports; the accessors assume flagd's defaults. + * + * @param args the arguments + * @return this container + */ + public FlagdContainer withFlagdArgs(String... args) { + Collections.addAll(extraArgs, args); + return this; + } + + /** + * Returns whether the evaluation and sync services are served over TLS. + * + * @return true if {@link #withTls(Path, Path)} was used + */ + public boolean isTlsEnabled() { + return tlsCertPath != null; + } + + /** + * Returns the static evaluation context values flagd is started with. + * + * @return the {@code --context-value} entries + */ + public Map getContextValues() { + return Collections.unmodifiableMap(contextValues); + } + + /** + * Returns the header-to-context mappings flagd is started with. + * + * @return the {@code --context-from-header} entries, keyed by header name + */ + public Map getContextFromHeaders() { + return Collections.unmodifiableMap(contextFromHeaders); + } + + /** + * Replaces the flags of a running container. flagd picks the change up through its file watcher, + * so the new definition is served shortly after this returns, not immediately. + * + *

Only applies to containers configured with exactly one file source. + * + * @param flagsJson a flagd flag definition document + */ + public void updateFlags(String flagsJson) { + if (flagFileCount != 1) { + throw new IllegalStateException( + "updateFlags requires exactly one file flag source, found " + flagFileCount); + } + copyFileToContainer(Transferable.of(flagsJson.getBytes(StandardCharsets.UTF_8)), flagFilePath(0)); + } + + /** + * Returns the mapped host port of the flag evaluation service, for RPC providers. + * + * @return the mapped evaluation port + */ + public int getEvaluationPort() { + return getMappedPort(EVALUATION_PORT); + } + + /** + * Returns the mapped host port of the management service. + * + * @return the mapped management port + */ + public int getManagementPort() { + return getMappedPort(MANAGEMENT_PORT); + } + + /** + * Returns the mapped host port of the flag sync service, for in-process providers. + * + * @return the mapped sync port + */ + public int getSyncPort() { + return getMappedPort(SYNC_PORT); + } + + /** + * Returns the mapped host port of the OFREP service. + * + * @return the mapped OFREP port + */ + public int getOfrepPort() { + return getMappedPort(OFREP_PORT); + } + + /** + * Returns the base URL of the OFREP service, e.g. {@code http://localhost:32768}. + * + * @return the OFREP base URL + */ + public String getOfrepEndpoint() { + return getConnection().getOfrepEndpoint(); + } + + /** + * Returns where flagd is reachable from the test host, using the mapped ports. Use this to + * configure a provider running in the test JVM. + * + * @return the host-side connection + */ + public FlagdConnection getConnection() { + return new FlagdConnection( + getHost(), + getMappedPort(EVALUATION_PORT), + getMappedPort(MANAGEMENT_PORT), + getMappedPort(SYNC_PORT), + getMappedPort(OFREP_PORT), + isTlsEnabled(), + isTlsEnabled() ? tlsCertPath.toString() : null, + null); + } + + /** + * Returns where flagd is reachable from another container on the same Docker network, using the + * most recently added network alias and the container-internal ports. Use this to configure an + * application container, e.g. {@code app.withEnv(flagd.getNetworkConnection().toEnv(...))}. + * + *

Does not require the container to be started. With TLS, the certificate path is not set, + * since only the caller knows where the application container has the certificate; add it with + * {@link FlagdConnection#withServerCertPath(String)}. + * + * @return the in-network connection + * @throws IllegalStateException if the container has no network + */ + public FlagdConnection getNetworkConnection() { + List aliases = getNetworkAliases(); + if (getNetwork() == null || aliases.isEmpty()) { + throw new IllegalStateException("flagd has no network; use withNetwork and withNetworkAliases"); + } + return new FlagdConnection( + aliases.get(aliases.size() - 1), + EVALUATION_PORT, + MANAGEMENT_PORT, + SYNC_PORT, + OFREP_PORT, + isTlsEnabled(), + null, + null); + } + + /** + * Returns the flag source URIs flagd is started with, in the order they were added. + * + * @return the {@code --uri} values + */ + public List getFlagSources() { + return Collections.unmodifiableList(sources); + } + + /** + * Returns the selector that picks each flag source, in the order they were added, for + * in-process providers ({@code FLAGD_SOURCE_SELECTOR}) or the {@code Flagd-Selector} header. + * flagd names a file source by its path without the {@code file:} prefix and any other source + * by its URI. + * + * @return the selector of each source + */ + public List getSourceSelectors() { + List selectors = new ArrayList<>(sources.size()); + for (String source : sources) { + selectors.add(source.startsWith("file:") ? source.substring("file:".length()) : source); + } + return Collections.unmodifiableList(selectors); + } + + @Override + protected void configure() { + if (sources.isEmpty()) { + throw new IllegalStateException("flagd needs at least one flag source; use withFlags* or withFlagSource"); + } + List command = new ArrayList<>(); + command.add("start"); + for (String source : sources) { + command.add("--uri"); + command.add(csvField(source)); + } + if (isTlsEnabled()) { + Collections.addAll(command, "--server-cert-path", TLS_CERT_PATH, "--server-key-path", TLS_KEY_PATH); + } + contextValues.forEach((key, value) -> Collections.addAll(command, "--context-value", mapEntry(key, value))); + contextFromHeaders.forEach( + (header, key) -> Collections.addAll(command, "--context-from-header", mapEntry(header, key))); + command.addAll(extraArgs); + setCommand(command.toArray(new String[0])); + } + + private FlagdContainer withFlagFile(Transferable file) { + String path = flagFilePath(flagFileCount++); + withCopyToContainer(file, path); + return withFlagSource("file:" + path); + } + + private FlagdContainer withFlagFile(MountableFile file) { + String path = flagFilePath(flagFileCount++); + withCopyFileToContainer(file, path); + return withFlagSource("file:" + path); + } + + private static String flagFilePath(int index) { + return FLAGS_DIR + "flags-" + index + ".json"; + } + + // flagd parses --uri as CSV, so a value containing a comma, quote or line break is quoted to stay + // a single entry; other values are passed through unchanged + private static String csvField(String value) { + if (value.chars().noneMatch(c -> c == ',' || c == '"' || c == '\n' || c == '\r')) { + return value; + } + return '"' + value.replace("\"", "\"\"") + '"'; + } + + // flagd's map flags take an entry with exactly one '=' as is, apart from trimming quotes at either + // end, and parse an entry with more than one '=' as CSV + private static String mapEntry(String key, String value) { + String entry = key + "=" + value; + return value.indexOf('=') < 0 ? entry : csvField(entry); + } + + // flagd re-reads its map flags from their serialized form, [k1=v1,k2=v2], which drops whitespace + // and brackets at either end, and Go's CSV reader turns CRLF into LF; entries are serialized in + // random order, so any key may come first and any value last + private static void checkMapEntry(String key, String value) { + if (key.indexOf('=') >= 0) { + throw new IllegalArgumentException("flagd splits a context entry at its first '=': " + key); + } + if (value.indexOf('=') < 0 && (key.startsWith("\"") || value.endsWith("\""))) { + throw new IllegalArgumentException( + "flagd trims a leading or trailing '\"' from a context entry: " + key + "=" + value); + } + if (key.startsWith("[") || value.endsWith("]") || endsWithWhitespace(value)) { + throw new IllegalArgumentException( + "flagd trims a leading '[' or a trailing ']' or whitespace from a context entry: " + key + "=" + + value); + } + if (key.contains("\r\n") || value.contains("\r\n")) { + throw new IllegalArgumentException("flagd turns CRLF into LF in a context entry: " + key + "=" + value); + } + } + + // matches Go's unicode.IsSpace, which flagd trims with + private static boolean endsWithWhitespace(String value) { + if (value.isEmpty()) { + return false; + } + char last = value.charAt(value.length() - 1); + return Character.isWhitespace(last) || Character.isSpaceChar(last) || last == '\u0085'; + } +} diff --git a/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdResolver.java b/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdResolver.java new file mode 100644 index 0000000000..902f2e8e53 --- /dev/null +++ b/tools/flagd-testcontainer/src/main/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdResolver.java @@ -0,0 +1,24 @@ +package dev.openfeature.contrib.tools.flagd.testcontainer; + +/** How a flagd provider connects to flagd; mirrors the provider's {@code FLAGD_RESOLVER} values. */ +public enum FlagdResolver { + /** Evaluate each flag remotely against the evaluation service. */ + RPC("rpc"), + /** Stream flag definitions from the sync service and evaluate them locally. */ + IN_PROCESS("in-process"); + + private final String value; + + FlagdResolver(String value) { + this.value = value; + } + + /** + * Returns the value the flagd provider expects in {@code FLAGD_RESOLVER}. + * + * @return the resolver name + */ + public String getValue() { + return value; + } +} diff --git a/tools/flagd-testcontainer/src/test/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainerConnectivityTest.java b/tools/flagd-testcontainer/src/test/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainerConnectivityTest.java new file mode 100644 index 0000000000..90d3195bba --- /dev/null +++ b/tools/flagd-testcontainer/src/test/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainerConnectivityTest.java @@ -0,0 +1,359 @@ +package dev.openfeature.contrib.tools.flagd.testcontainer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.InputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; +import org.testcontainers.utility.MountableFile; + +class FlagdContainerConnectivityTest { + + private static final String RESOLVE_BOOLEAN = "/flagd.evaluation.v1.Service/ResolveBoolean"; + + @Test + void servesEvaluationAndSyncOverTls() throws Exception { + try (FlagdContainer flagd = + new FlagdContainer().withFlagsFromClasspath("flags.json").withTls(cert(), key())) { + flagd.start(); + FlagdConnection connection = flagd.getConnection(); + HttpClient https = + HttpClient.newBuilder().sslContext(trusting(cert())).build(); + + assertThat(connection.isTls()).isTrue(); + assertThat(connection.getEvaluationEndpoint()).startsWith("https://"); + assertThat(connection.toEnv(FlagdResolver.RPC)) + .containsEntry("FLAGD_TLS", "true") + .containsEntry( + "FLAGD_SERVER_CERT_PATH", cert().toAbsolutePath().toString()); + + HttpResponse evaluation = https.send( + post(connection.getEvaluationEndpoint() + RESOLVE_BOOLEAN, "{\"flagKey\":\"boolean-flag\"}"), + HttpResponse.BodyHandlers.ofString()); + assertThat(evaluation.body().replace(" ", "")).contains("\"value\":true"); + + String syncUrl = "https://" + connection.getHost() + ":" + connection.getSyncPort() + "/v1/flags"; + HttpResponse sync = https.send( + HttpRequest.newBuilder(URI.create(syncUrl)).build(), HttpResponse.BodyHandlers.ofString()); + assertThat(sync.statusCode()).isEqualTo(200); + + // OFREP stays plain HTTP even with TLS enabled + HttpResponse ofrep = HttpClient.newHttpClient() + .send( + post(connection.getOfrepEndpoint() + "/ofrep/v1/evaluate/flags/boolean-flag", "{}"), + HttpResponse.BodyHandlers.ofString()); + assertThat(ofrep.statusCode()).isEqualTo(200); + } + } + + @Test + void isReachableOverTlsFromContainerOnSameNetwork() throws Exception { + try (Network network = Network.newNetwork(); + FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withTls(cert(), key()) + .withNetwork(network) + .withNetworkAliases("flagd")) { + flagd.start(); + FlagdConnection connection = flagd.getNetworkConnection().withServerCertPath("/certs/ca.pem"); + assertThat(connection.toEnv(FlagdResolver.RPC)) + .containsEntry("FLAGD_TLS", "true") + .containsEntry("FLAGD_SERVER_CERT_PATH", "/certs/ca.pem"); + + try (GenericContainer app = new GenericContainer<>("curlimages/curl:8.11.1") + .withNetwork(network) + .withCopyFileToContainer(MountableFile.forHostPath(cert(), 0644), "/certs/ca.pem") + .withCommand( + "-s", + "--cacert", + connection.getServerCertPath(), + "-X", + "POST", + "-H", + "Content-Type: application/json", + "-d", + "{\"flagKey\":\"boolean-flag\"}", + connection.getEvaluationEndpoint() + RESOLVE_BOOLEAN) + .withStartupCheckStrategy(new OneShotStartupCheckStrategy().withTimeout(Duration.ofSeconds(30)))) { + app.start(); + + assertThat(app.getLogs().replace(" ", "")).contains("\"value\":true"); + } + } + } + + @Test + void appliesContextValuesAndHeaders() throws Exception { + try (FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("targeted-flags.json") + .withContextValue("env", "test") + .withContextValue("list", "a,b") + .withContextFromHeader("X-Tier", "tier")) { + flagd.start(); + HttpClient http = HttpClient.newHttpClient(); + String base = flagd.getConnection().getEvaluationEndpoint() + RESOLVE_BOOLEAN; + + HttpResponse env = + http.send(post(base, "{\"flagKey\":\"env-flag\"}"), HttpResponse.BodyHandlers.ofString()); + assertThat(env.body().replace(" ", "")).contains("\"value\":true"); + + HttpResponse list = + http.send(post(base, "{\"flagKey\":\"list-flag\"}"), HttpResponse.BodyHandlers.ofString()); + assertThat(list.body().replace(" ", "")).contains("\"value\":true"); + + HttpResponse tier = http.send( + HttpRequest.newBuilder(URI.create(base)) + .header("Content-Type", "application/json") + .header("X-Tier", "gold") + .POST(HttpRequest.BodyPublishers.ofString("{\"flagKey\":\"tier-flag\"}")) + .build(), + HttpResponse.BodyHandlers.ofString()); + assertThat(tier.body().replace(" ", "")).contains("\"value\":true"); + } + } + + @Test + void buildsCommandFromConfiguration() throws Exception { + FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withTls(cert(), key()) + .withContextValue("env", "test") + .withContextFromHeader("X-Tier", "tier") + .withFlagdArgs("--stream-deadline", "30s"); + + flagd.configure(); + + assertThat(flagd.isTlsEnabled()).isTrue(); + assertThat(flagd.getContextValues()).containsEntry("env", "test"); + assertThat(flagd.getContextFromHeaders()).containsEntry("X-Tier", "tier"); + assertThat(flagd.getCommandParts()) + .containsExactly( + "start", + "--uri", + "file:/etc/flagd/flags-0.json", + "--server-cert-path", + "/etc/flagd/tls/server-cert.pem", + "--server-key-path", + "/etc/flagd/tls/server-key.pem", + "--context-value", + "env=test", + "--context-from-header", + "X-Tier=tier", + "--stream-deadline", + "30s"); + } + + @Test + void selectsSingleSourceBySelector() throws Exception { + try (FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withFlagsFromClasspath("targeted-flags.json") + .withFlagSource("https://example.com/flags.json")) { + assertThat(flagd.getSourceSelectors()) + .containsExactly( + "/etc/flagd/flags-0.json", "/etc/flagd/flags-1.json", "https://example.com/flags.json"); + } + + try (FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withFlagsFromClasspath("targeted-flags.json")) { + flagd.start(); + String selector = flagd.getSourceSelectors().get(1); + FlagdConnection connection = flagd.getConnection().withSourceSelector(selector); + + assertThat(connection.toEnv(FlagdResolver.IN_PROCESS)).containsEntry("FLAGD_SOURCE_SELECTOR", selector); + + String syncUrl = "http://" + connection.getHost() + ":" + connection.getSyncPort() + "/v1/flags"; + HttpResponse sync = HttpClient.newHttpClient() + .send( + HttpRequest.newBuilder(URI.create(syncUrl)) + .header("Flagd-Selector", connection.getSourceSelector()) + .build(), + HttpResponse.BodyHandlers.ofString()); + assertThat(sync.body()).contains("env-flag").doesNotContain("boolean-flag"); + } + } + + @Test + void encodesArgumentsTheWayFlagdParsesThem() { + FlagdContainer flagd = new FlagdContainer() + .withFlagSource("https://example.com/flags.json?groups=a,b") + .withContextValue("say", "a\"b") + .withContextValue("list", "a,b") + .withContextValue("expr", "x=\"1\"") + .withContextValue("lines", "a=b\nc"); + + flagd.configure(); + + assertThat(flagd.getCommandParts()) + .containsExactly( + "start", + "--uri", + "\"https://example.com/flags.json?groups=a,b\"", + "--context-value", + "say=a\"b", + "--context-value", + "list=a,b", + "--context-value", + "\"expr=x=\"\"1\"\"\"", + "--context-value", + "\"lines=a=b\nc\""); + assertThat(flagd.getFlagSources()).containsExactly("https://example.com/flags.json?groups=a,b"); + } + + @Test + void passesContextValuesToFlagdIntact() throws Exception { + Map values = new LinkedHashMap<>(); + values.put("quote", "a\"b"); + values.put("comma", "a,b"); + values.put("leading", "\"a"); + values.put("equals", "x=\"1\""); + values.put("quoteEquals", "x=1\""); + values.put("lines", "a=b\nc"); + values.put("commaEquals", "a=b,c=d"); + values.put("leadingSpace", " a"); + values.put("innerBrackets", "[a]b"); + values.put("carriageReturn", "a\rb"); + + StringBuilder flags = new StringBuilder("{\"flags\":{"); + values.forEach((key, value) -> flags.append(String.format( + "\"%s\":{\"state\":\"ENABLED\",\"variants\":{\"on\":true,\"off\":false}," + + "\"defaultVariant\":\"off\",\"targeting\":{\"if\":[{\"==\":[{\"var\":\"%s\"},%s]},\"on\",\"off\"]}},", + key, key, jsonString(value)))); + flags.setLength(flags.length() - 1); + flags.append("}}"); + + FlagdContainer flagd = new FlagdContainer().withFlags(flags.toString()); + values.forEach(flagd::withContextValue); + try (flagd) { + flagd.start(); + + for (String key : values.keySet()) { + HttpResponse response = HttpClient.newHttpClient() + .send( + post( + flagd.getConnection().getEvaluationEndpoint() + RESOLVE_BOOLEAN, + "{\"flagKey\":\"" + key + "\"}"), + HttpResponse.BodyHandlers.ofString()); + assertThat(response.body().replace(" ", "")) + .as("context value %s", key) + .contains("\"value\":true"); + } + } + } + + @Test + void rejectsContextEntriesFlagdCannotReceive() { + FlagdContainer flagd = new FlagdContainer(); + + assertThatThrownBy(() -> flagd.withContextValue("a=b", "c")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextValue("say", "\"hi\"")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextValue("\"say", "hi")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextFromHeader("X-Tier", "tier\"")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextValue("say", "hi ")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextValue("say", "a=b\u00a0")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextValue("say", "hi]")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextValue("[say", "hi")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextValue("say", "a=b\r\nc")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> flagd.withContextFromHeader("X-Tier", "tier ")) + .isInstanceOf(IllegalArgumentException.class); + assertThat(flagd.getContextValues()).isEmpty(); + assertThat(flagd.getContextFromHeaders()).isEmpty(); + } + + @Test + void bracketsIpv6HostsInEndpoints() { + FlagdConnection ipv6 = new FlagdConnection("::1", 1, 2, 3, 4, true, null, null); + FlagdConnection bracketed = new FlagdConnection("[::1]", 1, 2, 3, 4, false, null, null); + + assertThat(ipv6.getEvaluationEndpoint()).isEqualTo("https://[::1]:1"); + assertThat(ipv6.getOfrepEndpoint()).isEqualTo("http://[::1]:4"); + assertThat(bracketed.getOfrepEndpoint()).isEqualTo("http://[::1]:4"); + assertThat(ipv6.getHost()).isEqualTo("::1"); + } + + @Test + void setsSyncPortOnlyForInProcess() { + FlagdConnection connection = new FlagdConnection("localhost", 1, 2, 3, 4, false, null, null); + + assertThat(connection.toEnv(FlagdResolver.IN_PROCESS)) + .containsEntry("FLAGD_PORT", "3") + .containsEntry("FLAGD_SYNC_PORT", "3"); + assertThat(connection.toEnv(FlagdResolver.RPC)).doesNotContainKey("FLAGD_SYNC_PORT"); + } + + @Test + void exportsDisabledTlsExplicitly() { + FlagdConnection connection = new FlagdConnection("localhost", 1, 2, 3, 4, false, null, null); + + assertThat(connection.toEnv(FlagdResolver.RPC)) + .containsEntry("FLAGD_TLS", "false") + .doesNotContainKeys("FLAGD_SERVER_CERT_PATH", "FLAGD_SOURCE_SELECTOR"); + assertThat(connection.getEvaluationEndpoint()).isEqualTo("http://localhost:1"); + } + + private static String jsonString(String value) { + return '"' + + value.replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + + '"'; + } + + private static HttpRequest post(String url, String body) { + return HttpRequest.newBuilder(URI.create(url)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(); + } + + private static Path cert() throws Exception { + return resource("tls/server-cert.pem"); + } + + private static Path key() throws Exception { + return resource("tls/server-key.pem"); + } + + private static Path resource(String name) throws Exception { + return Paths.get(FlagdContainerConnectivityTest.class + .getClassLoader() + .getResource(name) + .toURI()); + } + + private static SSLContext trusting(Path certPath) throws Exception { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + try (InputStream in = Files.newInputStream(certPath)) { + trustStore.setCertificateEntry( + "flagd", CertificateFactory.getInstance("X.509").generateCertificate(in)); + } + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(trustStore); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, tmf.getTrustManagers(), null); + return context; + } +} diff --git a/tools/flagd-testcontainer/src/test/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainerTest.java b/tools/flagd-testcontainer/src/test/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainerTest.java new file mode 100644 index 0000000000..6b9c9ad801 --- /dev/null +++ b/tools/flagd-testcontainer/src/test/java/dev/openfeature/contrib/tools/flagd/testcontainer/FlagdContainerTest.java @@ -0,0 +1,231 @@ +package dev.openfeature.contrib.tools.flagd.testcontainer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFilePermissions; +import java.time.Duration; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; +import org.testcontainers.images.builder.Transferable; + +class FlagdContainerTest { + + private static final String STRING_FLAG = "{\"flags\":{\"string-flag\":{\"state\":\"ENABLED\"," + + "\"variants\":{\"greeting\":\"hi\",\"parting\":\"bye\"},\"defaultVariant\":\"%s\"}}}"; + + private final HttpClient http = HttpClient.newHttpClient(); + + @Test + void servesFlagsFromClasspath() throws Exception { + try (FlagdContainer flagd = new FlagdContainer().withFlagsFromClasspath("flags.json")) { + flagd.start(); + + assertThat(evaluate(flagd, "boolean-flag")).contains("\"value\":true"); + } + } + + @Test + void servesFlagsFromString() throws Exception { + try (FlagdContainer flagd = new FlagdContainer().withFlags(String.format(STRING_FLAG, "greeting"))) { + flagd.start(); + + assertThat(evaluate(flagd, "string-flag")).contains("\"value\":\"hi\""); + } + } + + @Test + void servesFlagsFromHostFile(@TempDir Path dir) throws Exception { + Path file = Files.writeString(dir.resolve("flags.json"), String.format(STRING_FLAG, "parting")); + try (FlagdContainer flagd = new FlagdContainer().withFlagsFromFile(file)) { + flagd.start(); + + assertThat(evaluate(flagd, "string-flag")).contains("\"value\":\"bye\""); + } + } + + @Test + void servesFlagsFromOwnerOnlyHostFile(@TempDir Path dir) throws Exception { + Path file = Files.writeString(dir.resolve("flags.json"), String.format(STRING_FLAG, "parting")); + assumeTrue(Files.getFileAttributeView(file, PosixFileAttributeView.class) != null); + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-------")); + try (FlagdContainer flagd = new FlagdContainer().withFlagsFromFile(file)) { + flagd.start(); + + assertThat(evaluate(flagd, "string-flag")).contains("\"value\":\"bye\""); + } + assertThat(Files.getPosixFilePermissions(file)).isEqualTo(PosixFilePermissions.fromString("rw-------")); + } + + @Test + void servesFlagSourceWithCommaInUri() throws Exception { + try (FlagdContainer flagd = new FlagdContainer() + .withCopyToContainer(Transferable.of(String.format(STRING_FLAG, "greeting")), "/etc/flagd/a,b.json") + .withFlagSource("file:/etc/flagd/a,b.json")) { + flagd.start(); + + assertThat(evaluate(flagd, "string-flag")).contains("\"value\":\"hi\""); + } + } + + @Test + void servesFlagsFromMultipleSources() throws Exception { + try (FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withFlags(String.format(STRING_FLAG, "greeting"))) { + flagd.start(); + + assertThat(evaluate(flagd, "boolean-flag")).contains("\"value\":true"); + assertThat(evaluate(flagd, "string-flag")).contains("\"value\":\"hi\""); + } + } + + @Test + void updatesFlagsAtRuntime() throws Exception { + try (FlagdContainer flagd = new FlagdContainer().withFlags(String.format(STRING_FLAG, "greeting"))) { + flagd.start(); + assertThat(evaluate(flagd, "string-flag")).contains("\"value\":\"hi\""); + + flagd.updateFlags(String.format(STRING_FLAG, "parting")); + + await().atMost(Duration.ofSeconds(10)) + .untilAsserted( + () -> assertThat(evaluate(flagd, "string-flag")).contains("\"value\":\"bye\"")); + } + } + + @Test + void exposesAllServicePorts() { + try (FlagdContainer flagd = new FlagdContainer().withFlagsFromClasspath("flags.json")) { + flagd.start(); + + assertThat(flagd.getEvaluationPort()).isPositive(); + assertThat(flagd.getManagementPort()).isPositive(); + assertThat(flagd.getSyncPort()).isPositive(); + assertThat(flagd.getOfrepPort()).isPositive(); + assertThat(flagd.getOfrepEndpoint()).isEqualTo("http://" + flagd.getHost() + ":" + flagd.getOfrepPort()); + } + } + + @Test + void exposesHostConnection() { + try (FlagdContainer flagd = new FlagdContainer().withFlagsFromClasspath("flags.json")) { + flagd.start(); + + FlagdConnection connection = flagd.getConnection(); + assertThat(connection.getHost()).isEqualTo(flagd.getHost()); + assertThat(connection.getEvaluationPort()).isEqualTo(flagd.getEvaluationPort()); + assertThat(connection.getManagementPort()).isEqualTo(flagd.getManagementPort()); + assertThat(connection.getSyncPort()).isEqualTo(flagd.getSyncPort()); + assertThat(connection.getOfrepPort()).isEqualTo(flagd.getOfrepPort()); + assertThat(connection.toEnv(FlagdResolver.RPC)) + .isEqualTo(Map.of( + "FLAGD_RESOLVER", + "rpc", + "FLAGD_HOST", + flagd.getHost(), + "FLAGD_PORT", + String.valueOf(flagd.getEvaluationPort()), + "FLAGD_TLS", + "false")); + assertThat(connection.toEnv(FlagdResolver.IN_PROCESS)) + .containsEntry("FLAGD_RESOLVER", "in-process") + .containsEntry("FLAGD_PORT", String.valueOf(flagd.getSyncPort())) + .containsEntry("FLAGD_SYNC_PORT", String.valueOf(flagd.getSyncPort())); + } + } + + @Test + void isReachableFromContainerOnSameNetwork() { + try (Network network = Network.newNetwork(); + FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withNetwork(network) + .withNetworkAliases("flagd")) { + flagd.start(); + FlagdConnection connection = flagd.getNetworkConnection(); + assertThat(connection.toEnv(FlagdResolver.IN_PROCESS)) + .containsEntry("FLAGD_HOST", "flagd") + .containsEntry("FLAGD_PORT", "8015"); + + try (GenericContainer app = new GenericContainer<>("curlimages/curl:8.11.1") + .withNetwork(network) + .withEnv(connection.toEnv(FlagdResolver.RPC)) + .withCommand( + "-s", + "-X", + "POST", + "-H", + "Content-Type: application/json", + "-d", + "{\"context\":{}}", + connection.getOfrepEndpoint() + "/ofrep/v1/evaluate/flags/boolean-flag") + .withStartupCheckStrategy(new OneShotStartupCheckStrategy().withTimeout(Duration.ofSeconds(30)))) { + app.start(); + + assertThat(app.getLogs().replace(" ", "")).contains("\"value\":true"); + } + } + } + + @Test + void rejectsNetworkConnectionWithoutNetwork() { + FlagdContainer flagd = new FlagdContainer().withFlagsFromClasspath("flags.json"); + + assertThatThrownBy(flagd::getNetworkConnection).isInstanceOf(IllegalStateException.class); + } + + @Test + void listsFlagSources() { + FlagdContainer flagd = new FlagdContainer() + .withFlagsFromClasspath("flags.json") + .withFlagSource("https://example.com/flags.json"); + + assertThat(flagd.getFlagSources()) + .containsExactly("file:/etc/flagd/flags-0.json", "https://example.com/flags.json"); + } + + @Test + void failsToStartWithoutFlagSource() { + try (FlagdContainer flagd = new FlagdContainer()) { + assertThatThrownBy(flagd::start).hasStackTraceContaining("at least one flag source"); + } + } + + @Test + void rejectsUpdateWithoutSingleFileSource() { + FlagdContainer flagd = new FlagdContainer().withFlagSource("https://example.com/flags.json"); + + assertThatThrownBy(() -> flagd.updateFlags("{}")).isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsIncompatibleImage() { + assertThatThrownBy(() -> new FlagdContainer("nginx:latest")).isInstanceOf(IllegalStateException.class); + } + + private String evaluate(FlagdContainer flagd, String flagKey) throws IOException, InterruptedException { + HttpRequest request = HttpRequest.newBuilder( + URI.create(flagd.getOfrepEndpoint() + "/ofrep/v1/evaluate/flags/" + flagKey)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString("{\"context\":{}}")) + .build(); + HttpResponse response = http.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).isEqualTo(200); + return response.body().replace(" ", ""); + } +} diff --git a/tools/flagd-testcontainer/src/test/resources/flags.json b/tools/flagd-testcontainer/src/test/resources/flags.json new file mode 100644 index 0000000000..3ec360052e --- /dev/null +++ b/tools/flagd-testcontainer/src/test/resources/flags.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://flagd.dev/schema/v0/flags.json", + "flags": { + "boolean-flag": { + "state": "ENABLED", + "variants": { + "on": true, + "off": false + }, + "defaultVariant": "on" + } + } +} diff --git a/tools/flagd-testcontainer/src/test/resources/targeted-flags.json b/tools/flagd-testcontainer/src/test/resources/targeted-flags.json new file mode 100644 index 0000000000..31171144d4 --- /dev/null +++ b/tools/flagd-testcontainer/src/test/resources/targeted-flags.json @@ -0,0 +1,71 @@ +{ + "$schema": "https://flagd.dev/schema/v0/flags.json", + "flags": { + "env-flag": { + "state": "ENABLED", + "variants": { + "on": true, + "off": false + }, + "defaultVariant": "off", + "targeting": { + "if": [ + { + "==": [ + { + "var": "env" + }, + "test" + ] + }, + "on", + "off" + ] + } + }, + "tier-flag": { + "state": "ENABLED", + "variants": { + "on": true, + "off": false + }, + "defaultVariant": "off", + "targeting": { + "if": [ + { + "==": [ + { + "var": "tier" + }, + "gold" + ] + }, + "on", + "off" + ] + } + }, + "list-flag": { + "state": "ENABLED", + "variants": { + "on": true, + "off": false + }, + "defaultVariant": "off", + "targeting": { + "if": [ + { + "==": [ + { + "var": "list" + }, + "a,b" + ] + }, + "on", + "off" + ] + } + } + } +} diff --git a/tools/flagd-testcontainer/src/test/resources/tls/README.md b/tools/flagd-testcontainer/src/test/resources/tls/README.md new file mode 100644 index 0000000000..a6ac243ea5 --- /dev/null +++ b/tools/flagd-testcontainer/src/test/resources/tls/README.md @@ -0,0 +1,8 @@ +Self-signed certificate and key for tests only; never use outside this module's tests. + +Regenerate with: + +```bash +openssl req -x509 -newkey rsa:2048 -nodes -keyout server-key.pem -out server-cert.pem -days 36500 \ + -subj "/CN=flagd-testcontainer" -addext "subjectAltName=DNS:localhost,DNS:flagd,IP:127.0.0.1" +``` diff --git a/tools/flagd-testcontainer/src/test/resources/tls/server-cert.pem b/tools/flagd-testcontainer/src/test/resources/tls/server-cert.pem new file mode 100644 index 0000000000..fa25d679e9 --- /dev/null +++ b/tools/flagd-testcontainer/src/test/resources/tls/server-cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgIUICX/jpcoG0S7eP3fGsFT4P1yuGUwDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTZmxhZ2QtdGVzdGNvbnRhaW5lcjAgFw0yNjExMjYyMzMx +NDhaGA8yMTI2MTEwMjIzMzE0OFowHjEcMBoGA1UEAwwTZmxhZ2QtdGVzdGNvbnRh +aW5lcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMuEEkWBGWJrmtSo +NppWoD++EqFwj+rtknAG4iTPJm01ktr1OCbA/lRV2MTC3mE6qio2UKT9EUEfBjrr +qTmyqhpX+CjJnQJQmIbMsHbTM4SEnYU5TsIf+I1kq7Uh6eK5WGMF2d9bOmVFG8R5 +0FdGAImsmacH0FD+EFtJjPGb+Xa+DAqDjiHRKb86ilUuEQKwuVY1iOpQ4qiS7f57 +311rO6Bd85beTlCFCieMPnw0ljCt4M0duDbAWrAbQPuE7zVat8lwo/IK6xNWjCIy +GPYppVjB6twv2JEoBeN2UMkRBeVgNp4J8fYxpQaZ03IYrjsk2tA6Eyk0IYTZbaEr +jKyDR0sCAwEAAaN2MHQwHQYDVR0OBBYEFAwdWW5Kxx5zh0JCbgX7T6t1ElHKMB8G +A1UdIwQYMBaAFAwdWW5Kxx5zh0JCbgX7T6t1ElHKMA8GA1UdEwEB/wQFMAMBAf8w +IQYDVR0RBBowGIIJbG9jYWxob3N0ggVmbGFnZIcEfwAAATANBgkqhkiG9w0BAQsF +AAOCAQEAEwx0m/YoWNQJsWgEGOleqUbkR/TeGZe5CyzApShGriMo4FHsFuA6ccaT +9IxIX/ggJzH62ADCspj7B+rXko5Z1o8/Zp8/0KfM+NEdXY2WSHTUTVhP49KsdHhG +oj0Kt9uTb0yhPIS+ukQoIkW9NTdWONS7Z3Nsvv8SM3XL3WjcqYdBhEozmtrHlpuK +gftjDQjrT1yrLLM3+IGknCyF5b7JqdDaoirqPrke/MwDY+hCyWaXKeFQdPsbiPzs +Xu5edAXz4m72b6EEmn1ozu6RbU6jj+vf3xhZObg3XuJfPI7EFofmNu5FbOUa64lG ++xunnLaKT+lK4tTFvjAibz5XT+lQmg== +-----END CERTIFICATE----- diff --git a/tools/flagd-testcontainer/src/test/resources/tls/server-key.pem b/tools/flagd-testcontainer/src/test/resources/tls/server-key.pem new file mode 100644 index 0000000000..e5916c8eed --- /dev/null +++ b/tools/flagd-testcontainer/src/test/resources/tls/server-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDLhBJFgRlia5rU +qDaaVqA/vhKhcI/q7ZJwBuIkzyZtNZLa9TgmwP5UVdjEwt5hOqoqNlCk/RFBHwY6 +66k5sqoaV/goyZ0CUJiGzLB20zOEhJ2FOU7CH/iNZKu1IeniuVhjBdnfWzplRRvE +edBXRgCJrJmnB9BQ/hBbSYzxm/l2vgwKg44h0Sm/OopVLhECsLlWNYjqUOKoku3+ +e99dazugXfOW3k5QhQonjD58NJYwreDNHbg2wFqwG0D7hO81WrfJcKPyCusTVowi +Mhj2KaVYwercL9iRKAXjdlDJEQXlYDaeCfH2MaUGmdNyGK47JNrQOhMpNCGE2W2h +K4ysg0dLAgMBAAECggEAF4PKv1XRArU02O4YDlyEpuN7BZpFlrsdLhfYLgadWwWo +p+dTi0QbXs/jJwDubu+Mqn9HcXjSyI0hdtIJ5eJwkxtST2wphGie5wcO5fvgj6bp +sx38V/kXtUafgbifFz+b0yfhlP7Wes2xt/xB3Vj3m5tiJDwxOVp8YKqD6tq/HUAC +y/y2i6lZ+PS6E4YqwCwI1LVnFPoz0VRwMiKsifC5rnODFN5MpIRYKDVreAnj+o5a +NQ47wTwn+bXY/vlSntSqYnZOr7je3lk0VYnYl10+QzfmT/NOBSG5s9RPKN6JOssc +Q8/H/0+8X2MRftEPyO3crHPSqPpKgkyPrQE/lKUMMQKBgQDq52aF3w+GD4TvyKvT +T1nW9pfoaDoaHxtX2g5d7OwjaP8kUEuwoy6LZWVnTy0Q3ZITgnfZCCk+noePf5lI +p8gbZdV2SI0wYLk0acla2azxHEvJ6vqYYT3JWyZf4tS2VtAE2q4BzvnGnL+f+mOk +A2nV56i8m/rAqi01VDUOBN7j0wKBgQDdywoazuzEb2sI91qktg0d3ymnDc4MW+Li +YX/XFhkfQOXAFVYg8hoxqLtPewK4NkhHG6QTPZqNBfbnscaoF3llB+5lRihkGT1i +wvCNqIijrXN/DjR/J8aqYEi3yBQZa5hUJdOwoE1qKyuF1llHI4Ozi9cRQ8YaAgtp +KrUXd6X7qQKBgQDOSIdv6ILpZ5eGOuMpnfV3IPYl0eG0Lr0EWSlksjpsnjfw29Kc +O7EUGOcD4jPhK7KsD1bP8KrHos/I5HTnqO/Bn5vlU7EpWsdJj9yTO7Tzx7WGjCOk +zUBFIxZ//eJufa4PlTpZvDj8gYqGIox968F1Zwp3F0MNDmTFAD3XIc/aoQKBgHMI +pwIGhujPPP2WhW3eemke4NSjJVZlpgRyO0MMVBVQrJj2uAg4aXuOHzB3BY8ToGM5 +I91S20D/cfLz0qxGGJFdDrl6LOLV8G+z2d4vJkd2Y+vnKzU0JSci7zRa0onos0YZ +pHT8f4psP5OX/BAYjGtoQTDULQA6RT7Thr9YMD+ZAoGBAMOFcp/M2PXxBWHdXCfU +9eZEjYu1Tafg1a/Jy+8oW7IwBrgktBkou1eBBrnBZyIQpyebP/4W3vru5EPO78+U +rPBVnG8BSdulZXfwaLV30RpMqt2f4LfX+DvNabtZfRv+z5m1rWw113w8mRhffRPL +Axjh7Chgk8whAOtPGc4tZU7n +-----END PRIVATE KEY----- diff --git a/tools/flagd-testcontainer/version.txt b/tools/flagd-testcontainer/version.txt new file mode 100644 index 0000000000..8acdd82b76 --- /dev/null +++ b/tools/flagd-testcontainer/version.txt @@ -0,0 +1 @@ +0.0.1