Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/component_owners.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ components:
- toddbaert
tools/flagd-http-connector:
- liran2000
tools/flagd-testcontainer:
- joe-chambers
tools/tck:
- aepfli

Expand Down
1 change: 1 addition & 0 deletions .release-please-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
<module>providers/ofrep</module>
<module>providers/gcp</module>
<module>tools/flagd-http-connector</module>
<module>tools/flagd-testcontainer</module>
</modules>

<scm>
Expand Down
11 changes: 11 additions & 0 deletions release-please-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
14 changes: 14 additions & 0 deletions renovate.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 = \"(?<currentValue>[^\"]+)\"",
"ghcr\\.io\\/open-feature\\/flagd:(?<currentValue>v\\d[^\\s\"`;}]*)"
],
"depNameTemplate": "ghcr.io/open-feature/flagd",
"datasourceTemplate": "docker"
}
],
"ignoreDeps": [
Expand Down
6 changes: 6 additions & 0 deletions spotbugs-exclusions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@
<Bug pattern="SKIPPED_CLASS_TOO_BIG"/>
</Match>

<!-- Suppress: EQ_DOESNT_OVERRIDE_EQUALS in FlagdContainer; GenericContainer equality is by identity -->
<Match>
<Class name="dev.openfeature.contrib.tools.flagd.testcontainer.FlagdContainer"/>
<Bug pattern="EQ_DOESNT_OVERRIDE_EQUALS"/>
</Match>

<!-- All bugs in test classes, except for JUnit-specific bugs -->
<Match>
<Class name="~.*\.*Test" />
Expand Down
215 changes: 215 additions & 0 deletions tools/flagd-testcontainer/README.md
Original file line number Diff line number Diff line change
@@ -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
<dependency>
<groupId>dev.openfeature.contrib.tools</groupId>
<artifactId>flagd-testcontainer</artifactId>
<version>0.0.1</version> <!--x-release-please-version -->
<scope>test</scope>
</dependency>
```

## 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 \
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
-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
```
42 changes: 42 additions & 0 deletions tools/flagd-testcontainer/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>dev.openfeature.contrib</groupId>
<artifactId>parent</artifactId>
<version>[1.0,2.0)</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<groupId>dev.openfeature.contrib.tools</groupId>
<artifactId>flagd-testcontainer</artifactId>
<version>0.0.1</version> <!--x-release-please-version -->

<properties>
<module-name>${groupId}.flagdtestcontainer</module-name>
<testcontainers.version>2.0.5</testcontainers.version>
</properties>

<name>flagd-testcontainer</name>
<description>Testcontainers module for running flagd in integration tests</description>
<url>https://openfeature.dev</url>

<developers>
<developer>
<id>joe-chambers</id>
<name>Joe Chambers</name>
<organization>OpenFeature</organization>
<url>https://openfeature.dev/</url>
</developer>
</developers>

<dependencies>
<!-- compile scope: consumed as a test library alongside the adopter's own testcontainers setup -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontainers.version}</version>
</dependency>
</dependencies>

</project>
Loading
Loading