mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor) (#2086)
* feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor)
Adds a new services/mwaa package following the EKS lifecycle pattern
(Controller/Service/EnvironmentManager, one Docker container-set per
resource, readiness polling) and the Neptune/ElastiCache proxy pattern
(MwaaWebProxy/MwaaProxyManager: Floci owns the host-facing port, the
backing container stays internal-only).
Each environment is backed by two real containers — postgres:16-alpine
for the metadata DB and apache/airflow:<version>-python3.12 running
LocalExecutor — with AirflowVersion genuinely selecting the image tag
(validated against a configured allow-list), unlike EKS's cosmetic-only
version field. MwaaWebProxy fronts the real Airflow webserver and
intercepts POST /aws_mwaa/cli, bridging it to a docker-exec'd `airflow`
CLI call and returning the documented {stdout, stderr} shape.
DAGs and requirements.txt sync from S3 on a poller, reusing the existing
S3Service in-process rather than a new AWS-facing surface. The Airflow
container is pointed back at Floci via LaunchedContainerAwsEnv (the same
mechanism Lambda/ECS containers already use), so a DAG's own boto3 calls
resolve against Floci instead of real AWS.
StartupScriptS3Path is supported end-to-end: fetched from S3 at create
time, injected before the container starts (create -> inject -> start,
mirroring EksClusterManager's config-injection sequencing), sourced
before migrate/scheduler/webserver so exported vars propagate. The
airflow user gets a passwordless sudo grant (verified against the real
image — sudo ships but isn't passwordless by default, and AWS's own
startup-script examples assume sudo just works), and a fixed set of
Floci-critical env vars (Fernet key, DB DSN, executor, AWS-SDK-redirection
vars) are snapshotted before and restored after the script runs, mirroring
real MWAA's reserved-environment-variable protection.
Verified end-to-end against real Docker (not just the mock=true unit
suite): environment reaches AVAILABLE, proxy pass-through and the CLI
bridge both work with real output, a DAG uploaded to S3 syncs and parses,
a second environment on a different AirflowVersion pulls a genuinely
distinct image, and delete tears down both containers/volumes and the
proxy cleanly.
45 new tests (unit + RestAssured integration, all against mock=true in
the default suite so Docker is never required for `mvnw test`); full
suite otherwise unchanged.
* fix(mwaa): hard-fail startup-script injection failures, release proxy ports on delete
Two issues from review:
copyFileIntoContainer swallowed every failure identically, including the
one case where that's wrong: a configured StartupScriptS3Path that fails
to copy into the container. The entrypoint's "if [ -f /startup.sh ]"
guard would silently skip it and the environment would reach AVAILABLE
having never applied the requested setup, contradicting the documented
intent of gating environment creation on startup-script failure (matching
real MWAA). copyFileIntoContainer now reports success/failure; the
startup-script call site checks it and throws, while DAG sync and the
best-effort sudoers grant keep their existing soft-fail behavior.
deleteEnvironment allocated a proxy port via PortAllocator on create but
never released it on delete, unlike every other service that uses
PortAllocator (Lambda, MSK, EC2, ECR) — repeated create/delete cycles
would eventually exhaust the configured proxy port range even with zero
MWAA proxies actually running.
* fix(mwaa): roll back allocated proxy port and containers on create failure
If startEnvironment() succeeded (containers running) but PortAllocator.allocate
or MwaaProxyManager.startProxy failed afterward, createEnvironment's catch
block set CREATE_FAILED without releasing the reserved port or stopping the
containers that had already started — leaking both on every such failure.
Mirrors NeptuneService.createDbCluster/rollbackDbCluster's already-proven
shape for this exact class of problem (container + proxy + port, partial
failure must roll back everything): a provisioned flag set only after every
step succeeds, and a try/finally that runs rollbackFailedCreate whenever it
doesn't — stopping the proxy (a no-op if it never started), stopping any
containers that did start (MwaaEnvironmentManager.stopEnvironment already
null-checks each container id, so it's safe for partial startup too), and
always releasing the port.
* fix(mwaa): correct CreateEnvironment error shape, namespace container names, add docs
Two items from maintainer review:
- Duplicate CreateEnvironment threw ResourceAlreadyExistsException, a shape the
operation doesn't declare (verified against the real botocore mwaa/2020-07-01
model: CreateEnvironment's only errors are ServiceUnavailableException,
ValidationException, InternalServerException) — SDK clients couldn't map it.
Now throws ValidationException.
- dbContainerName/airflowContainerName built names via raw string concatenation
instead of routing through ContainerStorageHelper.dockerName like every other
Docker-backed service (EKS, RDS, ...), so MWAA alone didn't participate in the
FLOCI_DOCKER_RESOURCE_NAMESPACE convention that keeps multiple Floci instances
sharing one Docker daemon from colliding. Both static methods now take the
EmulatorConfig and route through the shared helper; volume names inherit the
fix automatically since they're built by extending the container name.
Also adds docs/services/mwaa.md (mkdocs nav updated) following eks.md's
structure — operations table, mock/real mode, the web/CLI proxy, startup-script
behavior (sudo grant, reserved-variable protection), config reference, ARN
format, CLI/SDK examples, and an honest "Not Implemented" section covering the
known gaps already discussed on the PR (PluginsS3Path, cross-account container
naming, restart restoration).
This commit is contained in:
1 parent
5f7d4d2dc8
commit
7e4e3e8c50
23 files changed
+3182
-1
No files matched your search
+297
@@ -0,0 +1,297 @@
|
||||
package io.github.hectorvent.floci.services.mwaa;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.services.mwaa.model.Environment;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import com.github.dockerjava.api.model.Mount;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class MwaaEnvironmentManagerTest {
|
||||
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private ContainerDetector containerDetector;
|
||||
private MwaaEnvironmentManager manager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
EmulatorConfig.DockerConfig dockerConfig = Mockito.mock(EmulatorConfig.DockerConfig.class);
|
||||
when(dockerConfig.imageRegistryBase()).thenReturn(Optional.empty());
|
||||
when(dockerConfig.logMaxSize()).thenReturn("10m");
|
||||
when(dockerConfig.logMaxFile()).thenReturn("3");
|
||||
|
||||
EmulatorConfig.MwaaServiceConfig mwaaConfig = Mockito.mock(EmulatorConfig.MwaaServiceConfig.class);
|
||||
when(mwaaConfig.dockerNetwork()).thenReturn(Optional.empty());
|
||||
when(mwaaConfig.defaultPostgresImage()).thenReturn("postgres:16-alpine");
|
||||
|
||||
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(servicesConfig.mwaa()).thenReturn(mwaaConfig);
|
||||
when(servicesConfig.dockerNetwork()).thenReturn(Optional.empty());
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
when(config.docker()).thenReturn(dockerConfig);
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
|
||||
DockerHostResolver dockerHostResolver = Mockito.mock(DockerHostResolver.class);
|
||||
EmbeddedDnsServer embeddedDnsServer = Mockito.mock(EmbeddedDnsServer.class);
|
||||
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
|
||||
ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer);
|
||||
|
||||
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
|
||||
containerDetector = Mockito.mock(ContainerDetector.class);
|
||||
|
||||
LaunchedContainerAwsEnv awsEnv = Mockito.mock(LaunchedContainerAwsEnv.class);
|
||||
when(awsEnv.sdkBaselineEnv(eq("us-east-1"), any())).thenReturn(List.of(
|
||||
"AWS_DEFAULT_REGION=us-east-1",
|
||||
"AWS_ACCESS_KEY_ID=test",
|
||||
"AWS_SECRET_ACCESS_KEY=test",
|
||||
"AWS_ENDPOINT_URL=http://localhost:4566"));
|
||||
|
||||
manager = new MwaaEnvironmentManager(containerBuilder, lifecycleManager, containerDetector, config, awsEnv);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private ContainerSpec startAirflowAndCaptureSpec(boolean runningInContainer) {
|
||||
return startAirflowAndCaptureSpec(runningInContainer, null);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private ContainerSpec startAirflowAndCaptureSpec(boolean runningInContainer, byte[] startupScriptContent) {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(runningInContainer);
|
||||
when(lifecycleManager.create(any())).thenReturn("airflow-container-id");
|
||||
ContainerInfo info = new ContainerInfo("airflow-container-id",
|
||||
Map.of(8080, new EndpointInfo("172.18.0.5", 8080)));
|
||||
when(lifecycleManager.startCreated(eq("airflow-container-id"), any())).thenReturn(info);
|
||||
|
||||
Environment environment = new Environment();
|
||||
environment.setName("my-env");
|
||||
|
||||
manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", startupScriptContent);
|
||||
|
||||
ArgumentCaptor<ContainerSpec> captor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
Mockito.verify(lifecycleManager).create(captor.capture());
|
||||
Mockito.verify(lifecycleManager).startCreated(eq("airflow-container-id"), any());
|
||||
|
||||
assertEquals("airflow-container-id", environment.getAirflowContainerId());
|
||||
assertEquals("172.18.0.5", environment.getAirflowInternalHost());
|
||||
assertEquals(8080, environment.getAirflowInternalPort());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void airflowImageTagSubstitutesTheRequestedVersion() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
assertEquals("apache/airflow:2.10.5-python3.12", spec.image());
|
||||
}
|
||||
|
||||
@Test
|
||||
void airflowEnvVarsWireTheResolvedPostgresDsn() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
|
||||
assertTrue(spec.env().contains("AIRFLOW__CORE__EXECUTOR=LocalExecutor"));
|
||||
assertTrue(spec.env().contains("AIRFLOW__CORE__LOAD_EXAMPLES=false"));
|
||||
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=")
|
||||
&& e.contains("172.18.0.9") && e.contains("db-secret-pw")));
|
||||
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("AIRFLOW__CORE__FERNET_KEY=")));
|
||||
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("AIRFLOW__WEBSERVER__SECRET_KEY=")));
|
||||
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("_AIRFLOW_WWW_USER_USERNAME=")));
|
||||
assertTrue(spec.env().stream().anyMatch(e -> e.startsWith("_AIRFLOW_WWW_USER_PASSWORD=")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void airflowContainerGetsPointedBackAtFlociForItsOwnAwsSdkCalls() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
|
||||
assertTrue(spec.env().contains("AWS_ENDPOINT_URL=http://localhost:4566"),
|
||||
"DAG code's own boto3 calls must target Floci, not real AWS");
|
||||
assertTrue(spec.env().contains("AWS_DEFAULT_REGION=us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void entrypointAndCmdOverrideTheStockImageDefaults() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
|
||||
assertEquals(List.of("sh", "-c"), spec.entrypoint());
|
||||
assertEquals(1, spec.cmd().size());
|
||||
String script = spec.cmd().get(0);
|
||||
assertTrue(script.contains("airflow db migrate"));
|
||||
assertTrue(script.contains("airflow users create"));
|
||||
assertTrue(script.contains("airflow scheduler &"));
|
||||
assertTrue(script.contains("exec airflow webserver"));
|
||||
// migrate/user-create must precede the background scheduler, not run inside its background chain.
|
||||
assertTrue(script.indexOf("airflow db migrate") < script.indexOf("airflow scheduler &"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bootstrapScriptSourcesAnOptionalStartupScriptBeforeMigrating() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
String script = spec.cmd().get(0);
|
||||
|
||||
assertTrue(script.contains("if [ -f /startup.sh ]; then . /startup.sh || exit 1; fi"));
|
||||
assertTrue(script.indexOf("/startup.sh") < script.indexOf("airflow db migrate"),
|
||||
"the startup script must run before migration, matching real MWAA's ordering");
|
||||
}
|
||||
|
||||
// Coverage for supplying startup-script bytes now lives in the ContainerFileInjection nested
|
||||
// class below, where the DockerClient is actually mocked — the copy must succeed for the
|
||||
// create -> inject -> start sequence to continue (see startupScriptInjectionFailurePreventsThe-
|
||||
// ContainerFromStarting for the failure path this class didn't previously test).
|
||||
|
||||
@Test
|
||||
void namedVolumesMountDagsAndLogs() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
|
||||
List<String> targets = spec.mounts().stream().map(Mount::getTarget).toList();
|
||||
assertTrue(targets.contains("/opt/airflow/dags"));
|
||||
assertTrue(targets.contains("/opt/airflow/logs"));
|
||||
assertTrue(spec.mounts().stream().map(Mount::getSource).anyMatch(s -> s.endsWith("-dags")));
|
||||
assertTrue(spec.mounts().stream().map(Mount::getSource).anyMatch(s -> s.endsWith("-logs")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nativeModeAllocatesADynamicHostPortForTheWebserver() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
|
||||
assertTrue(spec.exposedPorts().contains(8080));
|
||||
assertTrue(spec.portBindings().containsKey(8080));
|
||||
assertEquals(0, spec.portBindings().get(8080), "0 is the dynamic-allocation sentinel");
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerModePublishesNoHostPortForTheWebserver() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(true);
|
||||
|
||||
assertTrue(spec.exposedPorts().contains(8080));
|
||||
assertFalse(spec.portBindings().containsKey(8080));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerNamingMatchesThePlan() {
|
||||
assertEquals("floci-mwaa-my-env-db", MwaaEnvironmentManager.dbContainerName(null, "my-env"));
|
||||
assertEquals("floci-mwaa-my-env-airflow", MwaaEnvironmentManager.airflowContainerName(null, "my-env"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerNamingAppliesTheConfiguredResourceNamespace() {
|
||||
EmulatorConfig.DockerConfig dockerConfig = Mockito.mock(EmulatorConfig.DockerConfig.class);
|
||||
when(dockerConfig.resourceNamespace()).thenReturn(Optional.of("ns1"));
|
||||
EmulatorConfig namespacedConfig = Mockito.mock(EmulatorConfig.class);
|
||||
when(namespacedConfig.docker()).thenReturn(dockerConfig);
|
||||
|
||||
assertEquals("floci-ns1-mwaa-my-env-db",
|
||||
MwaaEnvironmentManager.dbContainerName(namespacedConfig, "my-env"));
|
||||
assertEquals("floci-ns1-mwaa-my-env-airflow",
|
||||
MwaaEnvironmentManager.airflowContainerName(namespacedConfig, "my-env"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void healthCheckRequiresBothMetadatabaseAndSchedulerHealthy() {
|
||||
String bothHealthy = "{\"metadatabase\":{\"status\":\"healthy\"},\"scheduler\":{\"status\":\"healthy\"}}";
|
||||
assertTrue(MwaaEnvironmentManager.healthySection(bothHealthy, "metadatabase"));
|
||||
assertTrue(MwaaEnvironmentManager.healthySection(bothHealthy, "scheduler"));
|
||||
|
||||
String schedulerUnhealthy = "{\"metadatabase\":{\"status\":\"healthy\"},\"scheduler\":{\"status\":\"unhealthy\"}}";
|
||||
assertTrue(MwaaEnvironmentManager.healthySection(schedulerUnhealthy, "metadatabase"));
|
||||
assertFalse(MwaaEnvironmentManager.healthySection(schedulerUnhealthy, "scheduler"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bootstrapScriptSnapshotsAndRestoresProtectedVarsAroundTheStartupScript() {
|
||||
String script = MwaaEnvironmentManager.airflowBootstrapScript();
|
||||
|
||||
int snapshotIdx = script.indexOf("_FLOCI_ORIG_AIRFLOW__CORE__FERNET_KEY=\"$AIRFLOW__CORE__FERNET_KEY\"");
|
||||
int startupIdx = script.indexOf("/startup.sh");
|
||||
int restoreIdx = script.indexOf("export AIRFLOW__CORE__FERNET_KEY=\"$_FLOCI_ORIG_AIRFLOW__CORE__FERNET_KEY\"");
|
||||
|
||||
assertTrue(snapshotIdx >= 0, "must snapshot the original value before the startup script can touch it");
|
||||
assertTrue(restoreIdx >= 0, "must re-export the snapshotted value after the startup script runs");
|
||||
assertTrue(snapshotIdx < startupIdx && startupIdx < restoreIdx,
|
||||
"ordering must be snapshot -> startup script -> restore, so an override can't survive");
|
||||
|
||||
// Spot-check a Floci-specific (non-AWS-reserved) var too, since a script accidentally
|
||||
// clobbering AWS_ENDPOINT_URL would break the AWS-SDK-redirection this environment depends on.
|
||||
assertTrue(script.contains("_FLOCI_ORIG_AWS_ENDPOINT_URL=\"$AWS_ENDPOINT_URL\""));
|
||||
assertTrue(script.contains("export AWS_ENDPOINT_URL=\"$_FLOCI_ORIG_AWS_ENDPOINT_URL\""));
|
||||
}
|
||||
|
||||
/** Sudoers-grant and startup-script injection, verified against a mocked DockerClient — mirrors
|
||||
* EksClusterManagerTest's InjectEcrRegistryMirror nested class for the same kind of assertion. */
|
||||
@Nested
|
||||
class ContainerFileInjection {
|
||||
|
||||
private DockerClient dockerClient;
|
||||
private CopyArchiveToContainerCmd copyCmd;
|
||||
|
||||
@BeforeEach
|
||||
void setUpDockerClient() {
|
||||
dockerClient = Mockito.mock(DockerClient.class);
|
||||
copyCmd = Mockito.mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sudoersGrantIsAlwaysInjectedEvenWithoutAStartupScript() {
|
||||
startAirflowAndCaptureSpec(false, null);
|
||||
|
||||
verify(copyCmd).withRemotePath("/etc/sudoers.d");
|
||||
verify(copyCmd, times(1)).exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupScriptIsInjectedInAdditionToTheSudoersGrantWhenProvided() {
|
||||
startAirflowAndCaptureSpec(false, "export FOO=bar\n".getBytes());
|
||||
|
||||
verify(copyCmd).withRemotePath("/etc/sudoers.d");
|
||||
verify(copyCmd).withRemotePath("/");
|
||||
verify(copyCmd, times(2)).exec();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupScriptInjectionFailurePreventsTheContainerFromStarting() {
|
||||
// Shared copyCmd mock, so this also makes the (best-effort) sudoers-grant copy fail —
|
||||
// that alone must not abort anything; only the configured-startup-script failure should.
|
||||
when(copyCmd.exec()).thenThrow(new RuntimeException("docker cp failed"));
|
||||
when(lifecycleManager.create(any())).thenReturn("airflow-container-id");
|
||||
|
||||
Environment environment = new Environment();
|
||||
environment.setName("my-env");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.startAirflowContainer(
|
||||
environment, "2.10.5", "172.18.0.9", "db-secret-pw", "export FOO=bar\n".getBytes()));
|
||||
|
||||
verify(lifecycleManager).removeIfExists("airflow-container-id");
|
||||
verify(lifecycleManager, never()).startCreated(anyString(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package io.github.hectorvent.floci.services.mwaa;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
/**
|
||||
* MWAA REST flow against {@code floci.services.mwaa.mock=true} (see test {@code application.yml}),
|
||||
* so no Docker daemon is touched. Mirrors {@code EksNodegroupIntegrationTest}'s style: real HTTP
|
||||
* calls via RestAssured, ordered because environment state carries across tests.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class MwaaIntegrationTest {
|
||||
|
||||
private static final String JSON = "application/json";
|
||||
private static final String ENV = "mwaa-it-env";
|
||||
|
||||
private static String createBody(String extraFields) {
|
||||
return "{\"ExecutionRoleArn\":\"arn:aws:iam::000000000000:role/mwaa-execution-role\","
|
||||
+ "\"SourceBucketArn\":\"arn:aws:s3:::mwaa-it-bucket\","
|
||||
+ "\"DagS3Path\":\"dags\","
|
||||
+ "\"NetworkConfiguration\":{\"SubnetIds\":[\"subnet-1\",\"subnet-2\"],\"SecurityGroupIds\":[\"sg-1\"]}"
|
||||
+ (extraFields != null ? "," + extraFields : "")
|
||||
+ "}";
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createEnvironment() {
|
||||
given().contentType(JSON)
|
||||
.body(createBody(null))
|
||||
.when().put("/environments/" + ENV)
|
||||
.then().statusCode(200)
|
||||
.body("Arn", containsString("environment/" + ENV))
|
||||
.body("Arn", containsString(":airflow:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getEnvironmentReturnsDefaultsAndAvailableStatus() {
|
||||
given().contentType(JSON)
|
||||
.when().get("/environments/" + ENV)
|
||||
.then().statusCode(200)
|
||||
.body("Environment.Name", equalTo(ENV))
|
||||
.body("Environment.Status", equalTo("AVAILABLE"))
|
||||
.body("Environment.AirflowVersion", equalTo("2.10.5"))
|
||||
.body("Environment.WebserverUrl", notNullValue())
|
||||
.body("Environment.NetworkConfiguration.SubnetIds", hasItem("subnet-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createEnvironmentDuplicateFails() {
|
||||
given().contentType(JSON)
|
||||
.body(createBody(null))
|
||||
.when().put("/environments/" + ENV)
|
||||
.then().statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void listEnvironmentsIncludesCreatedEnvironment() {
|
||||
given().contentType(JSON)
|
||||
.when().get("/environments")
|
||||
.then().statusCode(200)
|
||||
.body("Environments", hasItem(ENV));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void updateEnvironmentAppliesMetadataOnlyChange() {
|
||||
given().contentType(JSON)
|
||||
.body("{\"EnvironmentClass\":\"mw1.large\"}")
|
||||
.when().patch("/environments/" + ENV)
|
||||
.then().statusCode(200)
|
||||
.body("Arn", containsString("environment/" + ENV));
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().get("/environments/" + ENV)
|
||||
.then().statusCode(200)
|
||||
.body("Environment.EnvironmentClass", equalTo("mw1.large"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void updateEnvironmentRejectsAirflowVersionChange() {
|
||||
given().contentType(JSON)
|
||||
.body("{\"AirflowVersion\":\"2.9.3\"}")
|
||||
.when().patch("/environments/" + ENV)
|
||||
.then().statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void tagResourceUntagResourceAndListTagsForResourceRoundTrip() {
|
||||
String arn = given().contentType(JSON)
|
||||
.when().get("/environments/" + ENV)
|
||||
.then().statusCode(200)
|
||||
.extract().path("Environment.Arn");
|
||||
|
||||
given().contentType(JSON)
|
||||
.body("{\"Tags\":{\"team\":\"data\",\"env\":\"test\"}}")
|
||||
.when().post("/tags/" + arn)
|
||||
.then().statusCode(204);
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().get("/tags/" + arn)
|
||||
.then().statusCode(200)
|
||||
.body("Tags.team", equalTo("data"))
|
||||
.body("Tags.env", equalTo("test"));
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().delete("/tags/" + arn + "?tagKeys=env")
|
||||
.then().statusCode(204);
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().get("/tags/" + arn)
|
||||
.then().statusCode(200)
|
||||
.body("Tags.team", equalTo("data"))
|
||||
.body("Tags.env", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void createWebLoginTokenAndCliTokenReturnOpaqueTokens() {
|
||||
given().contentType(JSON)
|
||||
.when().post("/webtoken/" + ENV)
|
||||
.then().statusCode(200)
|
||||
.body("WebToken", notNullValue())
|
||||
.body("WebServerHostname", notNullValue());
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().post("/clitoken/" + ENV)
|
||||
.then().statusCode(200)
|
||||
.body("CliToken", notNullValue())
|
||||
.body("WebServerHostname", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void deleteEnvironment() {
|
||||
given().contentType(JSON)
|
||||
.when().delete("/environments/" + ENV)
|
||||
.then().statusCode(200);
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().get("/environments/" + ENV)
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void everySupportedAirflowVersionRoundTrips() {
|
||||
String[] versions = {"2.10.5", "2.9.3", "2.8.4"};
|
||||
for (String version : versions) {
|
||||
String name = "mwaa-it-v" + version.replace(".", "");
|
||||
given().contentType(JSON)
|
||||
.body(createBody("\"AirflowVersion\":\"" + version + "\""))
|
||||
.when().put("/environments/" + name)
|
||||
.then().statusCode(200);
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().get("/environments/" + name)
|
||||
.then().statusCode(200)
|
||||
.body("Environment.AirflowVersion", equalTo(version));
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().delete("/environments/" + name)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void unsupportedAirflowVersionIsRejected() {
|
||||
given().contentType(JSON)
|
||||
.body(createBody("\"AirflowVersion\":\"1.10.15\""))
|
||||
.when().put("/environments/mwaa-it-bad-version")
|
||||
.then().statusCode(400);
|
||||
|
||||
given().contentType(JSON)
|
||||
.when().get("/environments/mwaa-it-bad-version")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
package io.github.hectorvent.floci.services.mwaa;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.mwaa.model.CreateEnvironmentRequest;
|
||||
import io.github.hectorvent.floci.services.mwaa.model.Environment;
|
||||
import io.github.hectorvent.floci.services.mwaa.model.EnvironmentStatus;
|
||||
import io.github.hectorvent.floci.services.mwaa.model.NetworkConfiguration;
|
||||
import io.github.hectorvent.floci.services.mwaa.model.UpdateEnvironmentRequest;
|
||||
import io.github.hectorvent.floci.services.mwaa.proxy.MwaaProxyManager;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class MwaaServiceTest {
|
||||
|
||||
private MwaaService mwaaService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory storageFactory = new StorageFactory(null, null) {
|
||||
@Override
|
||||
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return new InMemoryStorage<>();
|
||||
}
|
||||
};
|
||||
|
||||
EmulatorConfig config = testConfig();
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
S3Service s3Service = Mockito.mock(S3Service.class);
|
||||
mwaaService = new MwaaService(storageFactory, config, regionResolver, null, null, null, s3Service);
|
||||
}
|
||||
|
||||
private EmulatorConfig testConfig() {
|
||||
EmulatorConfig.MwaaServiceConfig mwaaConfig = proxy(EmulatorConfig.MwaaServiceConfig.class,
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "enabled", "mock" -> true;
|
||||
case "supportedVersions" -> List.of("2.10.5", "2.9.3", "2.8.4");
|
||||
case "defaultVersion" -> "2.10.5";
|
||||
case "proxyBasePort" -> 8700;
|
||||
case "proxyMaxPort" -> 8799;
|
||||
case "dagSyncIntervalSeconds" -> 30;
|
||||
default -> defaultValue(method);
|
||||
});
|
||||
EmulatorConfig.ServicesConfig servicesConfig = proxy(EmulatorConfig.ServicesConfig.class,
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "mwaa" -> mwaaConfig;
|
||||
default -> defaultValue(method);
|
||||
});
|
||||
EmulatorConfig.TlsConfig tlsConfig = proxy(EmulatorConfig.TlsConfig.class,
|
||||
(proxy, method, args) -> defaultValue(method));
|
||||
return proxy(EmulatorConfig.class, (proxy, method, args) -> switch (method.getName()) {
|
||||
case "services" -> servicesConfig;
|
||||
case "tls" -> tlsConfig;
|
||||
case "defaultRegion" -> "us-east-1";
|
||||
case "defaultAccountId" -> "000000000000";
|
||||
case "hostname" -> Optional.empty();
|
||||
default -> defaultValue(method);
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> T proxy(Class<T> type, InvocationHandler handler) {
|
||||
return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, (proxy, method, args) -> {
|
||||
if (method.getDeclaringClass() == Object.class) {
|
||||
return switch (method.getName()) {
|
||||
case "toString" -> type.getSimpleName() + "TestProxy";
|
||||
case "hashCode" -> System.identityHashCode(proxy);
|
||||
case "equals" -> proxy == args[0];
|
||||
default -> method.invoke(this, args);
|
||||
};
|
||||
}
|
||||
return handler.invoke(proxy, method, args);
|
||||
});
|
||||
}
|
||||
|
||||
private Object defaultValue(Method method) {
|
||||
Class<?> returnType = method.getReturnType();
|
||||
if (returnType == boolean.class) {
|
||||
return false;
|
||||
}
|
||||
if (returnType == int.class) {
|
||||
return 0;
|
||||
}
|
||||
if (returnType == long.class) {
|
||||
return 0L;
|
||||
}
|
||||
if (returnType == Optional.class) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (returnType == String.class) {
|
||||
return "";
|
||||
}
|
||||
if (returnType == List.class) {
|
||||
return List.of();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private CreateEnvironmentRequest createRequest(String bucketArn, String dagPath) {
|
||||
CreateEnvironmentRequest request = new CreateEnvironmentRequest();
|
||||
request.setExecutionRoleArn("arn:aws:iam::000000000000:role/mwaa-execution-role");
|
||||
request.setSourceBucketArn(bucketArn);
|
||||
request.setDagS3Path(dagPath);
|
||||
NetworkConfiguration network = new NetworkConfiguration();
|
||||
network.setSubnetIds(List.of("subnet-1", "subnet-2"));
|
||||
network.setSecurityGroupIds(List.of("sg-1"));
|
||||
request.setNetworkConfiguration(network);
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEnvironment() {
|
||||
Environment environment = mwaaService.createEnvironment("test-env",
|
||||
createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
assertNotNull(environment);
|
||||
assertEquals("test-env", environment.getName());
|
||||
assertEquals(EnvironmentStatus.AVAILABLE, environment.getStatus());
|
||||
assertTrue(environment.getArn().contains("airflow"));
|
||||
assertTrue(environment.getArn().contains("environment/test-env"));
|
||||
assertEquals("2.10.5", environment.getAirflowVersion());
|
||||
assertNotNull(environment.getWebserverUrl());
|
||||
assertNotNull(environment.getCreatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEnvironmentDuplicateFails() {
|
||||
mwaaService.createEnvironment("dup-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> mwaaService.createEnvironment("dup-env", createRequest("arn:aws:s3:::my-bucket", "dags")));
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
// CreateEnvironment's botocore model declares no "already exists" shape.
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEnvironmentWithUnsupportedVersionFails() {
|
||||
CreateEnvironmentRequest request = createRequest("arn:aws:s3:::my-bucket", "dags");
|
||||
request.setAirflowVersion("1.10.15");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> mwaaService.createEnvironment("bad-version-env", request));
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEnvironmentWithSupportedVersionRoundTrips() {
|
||||
CreateEnvironmentRequest request = createRequest("arn:aws:s3:::my-bucket", "dags");
|
||||
request.setAirflowVersion("2.9.3");
|
||||
|
||||
Environment environment = mwaaService.createEnvironment("versioned-env", request);
|
||||
assertEquals("2.9.3", environment.getAirflowVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEnvironment() {
|
||||
mwaaService.createEnvironment("my-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
Environment described = mwaaService.getEnvironment("my-env");
|
||||
assertEquals("my-env", described.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getEnvironmentNotFound() {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> mwaaService.getEnvironment("nonexistent"));
|
||||
assertEquals(404, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listEnvironments() {
|
||||
mwaaService.createEnvironment("env-a", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
mwaaService.createEnvironment("env-b", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
List<String> names = mwaaService.listEnvironments();
|
||||
assertEquals(2, names.size());
|
||||
assertTrue(names.contains("env-a"));
|
||||
assertTrue(names.contains("env-b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteEnvironment() {
|
||||
mwaaService.createEnvironment("to-delete", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
Environment deleted = mwaaService.deleteEnvironment("to-delete");
|
||||
assertEquals(EnvironmentStatus.DELETING, deleted.getStatus());
|
||||
assertTrue(mwaaService.listEnvironments().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEnvironmentAppliesMetadataFields() {
|
||||
mwaaService.createEnvironment("update-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
|
||||
request.setEnvironmentClass("mw1.large");
|
||||
request.setDagS3Path("dags-v2");
|
||||
|
||||
Environment updated = mwaaService.updateEnvironment("update-env", request);
|
||||
assertNotNull(updated.getArn());
|
||||
|
||||
Environment described = mwaaService.getEnvironment("update-env");
|
||||
assertEquals("mw1.large", described.getEnvironmentClass());
|
||||
assertEquals("dags-v2", described.getDagS3Path());
|
||||
assertEquals("SUCCESS", described.getLastUpdate().getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEnvironmentRejectsAirflowVersionChange() {
|
||||
mwaaService.createEnvironment("no-version-change-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
|
||||
request.setAirflowVersion("2.9.3");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> mwaaService.updateEnvironment("no-version-change-env", request));
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEnvironmentRejectsAirflowConfigurationOptionsChange() {
|
||||
mwaaService.createEnvironment("no-config-change-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
|
||||
request.setAirflowConfigurationOptions(Map.of("core.parallelism", "10"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> mwaaService.updateEnvironment("no-config-change-env", request));
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEnvironmentRejectsStartupScriptS3PathChange() {
|
||||
CreateEnvironmentRequest createRequest = createRequest("arn:aws:s3:::my-bucket", "dags");
|
||||
createRequest.setStartupScriptS3Path("startup.sh");
|
||||
Environment environment = mwaaService.createEnvironment("no-startup-script-change-env", createRequest);
|
||||
assertEquals("startup.sh", environment.getStartupScriptS3Path());
|
||||
|
||||
UpdateEnvironmentRequest request = new UpdateEnvironmentRequest();
|
||||
request.setStartupScriptS3Path("startup-v2.sh");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> mwaaService.updateEnvironment("no-startup-script-change-env", request));
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void taggingOperations() {
|
||||
Environment environment = mwaaService.createEnvironment("tagged-env",
|
||||
createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
String arn = environment.getArn();
|
||||
|
||||
mwaaService.tagResource(null, arn, Map.of("env", "test", "team", "data"));
|
||||
Map<String, String> tags = mwaaService.listTags(null, arn);
|
||||
assertEquals("test", tags.get("env"));
|
||||
assertEquals("data", tags.get("team"));
|
||||
|
||||
mwaaService.untagResource(null, arn, List.of("env"));
|
||||
tags = mwaaService.listTags(null, arn);
|
||||
assertFalse(tags.containsKey("env"));
|
||||
assertEquals("data", tags.get("team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagHandlerServiceKeyIsAirflow() {
|
||||
assertEquals("airflow", mwaaService.serviceKey());
|
||||
assertEquals("Tags", mwaaService.tagsBodyKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWebLoginTokenReturnsTokenAndHostname() {
|
||||
mwaaService.createEnvironment("web-token-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
Map<String, Object> response = mwaaService.createWebLoginToken("web-token-env");
|
||||
assertNotNull(response.get("WebToken"));
|
||||
assertNotNull(response.get("WebServerHostname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createCliTokenIsValidatedByIsValidCliToken() {
|
||||
mwaaService.createEnvironment("cli-token-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
Map<String, Object> response = mwaaService.createCliToken("cli-token-env");
|
||||
String token = (String) response.get("CliToken");
|
||||
assertNotNull(token);
|
||||
assertTrue(mwaaService.isValidCliToken("cli-token-env", token));
|
||||
assertFalse(mwaaService.isValidCliToken("cli-token-env", "not-a-real-token"));
|
||||
assertFalse(mwaaService.isValidCliToken("other-env", token));
|
||||
}
|
||||
|
||||
/** Exercises the real (non-mock) create/delete path — the outer class's {@code mwaaService}
|
||||
* always runs with {@code mock=true}, which never touches {@code PortAllocator} at all. */
|
||||
@Nested
|
||||
class RealModeLifecycle {
|
||||
|
||||
private PortAllocator portAllocator;
|
||||
private MwaaEnvironmentManager environmentManager;
|
||||
private MwaaProxyManager proxyManager;
|
||||
private MwaaService realModeService;
|
||||
|
||||
@BeforeEach
|
||||
void setUpRealMode() {
|
||||
StorageFactory storageFactory = new StorageFactory(null, null) {
|
||||
@Override
|
||||
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return new InMemoryStorage<>();
|
||||
}
|
||||
};
|
||||
|
||||
EmulatorConfig.MwaaServiceConfig mwaaConfig = proxy(EmulatorConfig.MwaaServiceConfig.class,
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "enabled" -> true;
|
||||
case "mock" -> false;
|
||||
case "supportedVersions" -> List.of("2.10.5", "2.9.3", "2.8.4");
|
||||
case "defaultVersion" -> "2.10.5";
|
||||
case "proxyBasePort" -> 8700;
|
||||
case "proxyMaxPort" -> 8799;
|
||||
case "dagSyncIntervalSeconds" -> 30;
|
||||
default -> defaultValue(method);
|
||||
});
|
||||
EmulatorConfig.ServicesConfig servicesConfig = proxy(EmulatorConfig.ServicesConfig.class,
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "mwaa" -> mwaaConfig;
|
||||
default -> defaultValue(method);
|
||||
});
|
||||
EmulatorConfig.TlsConfig tlsConfig = proxy(EmulatorConfig.TlsConfig.class,
|
||||
(proxy, method, args) -> defaultValue(method));
|
||||
EmulatorConfig config = proxy(EmulatorConfig.class, (proxy, method, args) -> switch (method.getName()) {
|
||||
case "services" -> servicesConfig;
|
||||
case "tls" -> tlsConfig;
|
||||
case "defaultRegion" -> "us-east-1";
|
||||
case "defaultAccountId" -> "000000000000";
|
||||
case "hostname" -> Optional.empty();
|
||||
default -> defaultValue(method);
|
||||
});
|
||||
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
S3Service s3Service = Mockito.mock(S3Service.class);
|
||||
environmentManager = Mockito.mock(MwaaEnvironmentManager.class);
|
||||
proxyManager = Mockito.mock(MwaaProxyManager.class);
|
||||
portAllocator = Mockito.mock(PortAllocator.class);
|
||||
when(portAllocator.allocate(8700, 8799)).thenReturn(8701);
|
||||
|
||||
realModeService = new MwaaService(storageFactory, config, regionResolver,
|
||||
environmentManager, proxyManager, portAllocator, s3Service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnEnvironmentReleasesItsProxyPort() {
|
||||
Environment environment = realModeService.createEnvironment("real-env",
|
||||
createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
assertEquals(8701, environment.getProxyPort());
|
||||
|
||||
realModeService.deleteEnvironment("real-env");
|
||||
|
||||
verify(portAllocator).release(8701);
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyStartupFailureRollsBackTheAllocatedPortAndAnyStartedContainers() {
|
||||
// Containers start fine; only the proxy bind fails (e.g. the port got taken out from
|
||||
// under us between allocate() and bind()). The port must not leak, and whatever
|
||||
// startEnvironment() already started must get torn down, not orphaned.
|
||||
Mockito.doThrow(new RuntimeException("bind failed"))
|
||||
.when(proxyManager).startProxy(any(), anyInt(), any(), anyInt(), any(), any());
|
||||
|
||||
Environment environment = realModeService.createEnvironment("failed-proxy-env",
|
||||
createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
assertEquals(EnvironmentStatus.CREATE_FAILED, environment.getStatus());
|
||||
verify(portAllocator).release(8701);
|
||||
verify(environmentManager).stopEnvironment(environment);
|
||||
verify(proxyManager).stopProxy("failed-proxy-env");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.github.hectorvent.floci.services.mwaa.proxy;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Routing-decision tests for {@link MwaaWebProxy}: which requests get intercepted by the CLI
|
||||
* handler versus forwarded verbatim to the backend Airflow container, and bearer-token parsing.
|
||||
* No real sockets are used — {@code isCliRequest}/{@code extractBearerToken} are pure functions.
|
||||
*/
|
||||
class MwaaWebProxyTest {
|
||||
|
||||
@Test
|
||||
void interceptsOnlyPostToTheCliPath() {
|
||||
assertTrue(MwaaWebProxy.isCliRequest("POST", "/aws_mwaa/cli"));
|
||||
assertTrue(MwaaWebProxy.isCliRequest("post", "/aws_mwaa/cli"), "method match should be case-insensitive");
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardsEverythingElse() {
|
||||
assertFalse(MwaaWebProxy.isCliRequest("GET", "/aws_mwaa/cli"), "GET to the CLI path is not intercepted");
|
||||
assertFalse(MwaaWebProxy.isCliRequest("POST", "/"), "POST elsewhere is forwarded");
|
||||
assertFalse(MwaaWebProxy.isCliRequest("POST", "/api/v1/dags"), "Airflow REST API traffic is forwarded");
|
||||
assertFalse(MwaaWebProxy.isCliRequest("POST", "/aws_mwaa/cli/"), "trailing slash does not match");
|
||||
assertFalse(MwaaWebProxy.isCliRequest("PUT", "/aws_mwaa/cli"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractsBearerTokenCaseInsensitively() {
|
||||
assertEquals("abc123", MwaaWebProxy.extractBearerToken("Bearer abc123"));
|
||||
assertEquals("abc123", MwaaWebProxy.extractBearerToken("bearer abc123"));
|
||||
assertEquals("abc123", MwaaWebProxy.extractBearerToken("BEARER abc123".replace(" ", " ")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingOrMalformedAuthorizationHeaders() {
|
||||
assertNull(MwaaWebProxy.extractBearerToken(null));
|
||||
assertNull(MwaaWebProxy.extractBearerToken(""));
|
||||
assertNull(MwaaWebProxy.extractBearerToken("Basic dXNlcjpwYXNz"));
|
||||
assertNull(MwaaWebProxy.extractBearerToken("Bearer "));
|
||||
assertNull(MwaaWebProxy.extractBearerToken("Bearer"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user