mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(mwaa): sign in through /aws_mwaa/login with a web login token (#8419)
CreateWebLoginToken returned a token nothing accepted: the proxy had no /aws_mwaa/login, so a client following Amazon MWAA's REST API guide got a 404, and with Airflow's session-only API auth every /api/v1 call then answered 403. Web login tokens are now kept per environment for the 60 seconds AWS documents. The proxy intercepts POST /aws_mwaa/login: a valid token in the `token` form field signs in through Airflow's own login form (CSRF token and anonymous session from GET /login/, then the admin credentials Floci generated) and answers 302 to /home with Airflow's session cookie, which the UI and /api/v1 accept. An unknown or expired token gets 401. With floci.tls.enabled, WebserverUrl already named an https endpoint while the proxy only spoke HTTP; the proxies now serve TLS with Floci's server certificate and follow its reissues, so a client that builds https://{WebServerHostname} reaches them.
This commit is contained in:
1 parent
9bee320d83
commit
0baf1a1b79
11 files changed
+771
-25
No files matched your search
@@ -44,6 +44,12 @@ Once Airflow's unauthenticated `/health` endpoint reports `metadatabase`, `sched
|
||||
|
||||
Floci runs its own HTTP proxy per environment (published on a host port from the configured range) that fronts the real Airflow webserver: every request is forwarded through to Airflow as-is, **except** `POST /aws_mwaa/cli`, which the proxy intercepts itself. It validates the `Authorization: Bearer <CliToken>` from `CreateCliToken`, then runs supported Amazon MWAA Airflow CLI commands inside the container via `docker exec` and returns the AWS-documented `{stdout, stderr}` (base64) shape. Unsupported commands return an error in `stderr` without reaching the container. The supported commands match the [Amazon MWAA Airflow v2 CLI list](https://docs.aws.amazon.com/mwaa/latest/userguide/airflow-cli-command-reference.html); as in that list, `providers notifications` needs Airflow 2.8 or later, so a 2.7.2 environment refuses it. `Environment.WebserverUrl` and the URL returned by `CreateWebLoginToken` both point at this proxy, so Airflow-UI browsing and the CLI-token flow go through the same place.
|
||||
|
||||
### Web login (`CreateWebLoginToken`)
|
||||
|
||||
The token from `CreateWebLoginToken` works the way Amazon MWAA's [Apache Airflow REST API guide](https://docs.aws.amazon.com/mwaa/latest/userguide/access-mwaa-apache-airflow-rest-api.html) describes. POST it as the `token` form field to `/aws_mwaa/login` on the `WebServerHostname`. The proxy signs in to Airflow's own login form as the `admin` user Floci created for the environment, and answers `302` to `/home` with Airflow's `session` cookie. That cookie opens the Airflow UI and the REST API, for example `GET /api/v1/dags` or `POST /api/v1/dags/{dag_id}/dagRuns`. A token is valid for 60 seconds, as on AWS. An unknown or expired token gets `401`.
|
||||
|
||||
With `floci.tls.enabled`, `WebserverUrl` and `WebServerHostname` name an `https` endpoint, and the proxy serves TLS with Floci's own server certificate, so a client that builds `https://{WebServerHostname}` (as AWS's sample code does) reaches it.
|
||||
|
||||
### Startup scripts (`StartupScriptS3Path`)
|
||||
|
||||
If configured, the script is fetched from S3 at environment-creation time and injected into the Airflow container before it starts. It runs first, then `requirements.txt` is installed, then `airflow db migrate` and the triggerer, scheduler and webserver start, matching real MWAA's ordering. Variables the script exports (a private index URL for `pip`, for example) are still set when `requirements.txt` installs, at creation and on every later reinstall. Two behaviors worth knowing about since they're not obvious from the API surface:
|
||||
@@ -185,7 +191,6 @@ The following are current, known gaps:
|
||||
|
||||
- `PluginsS3Path` is accepted and stored on the environment but not fetched or applied — real MWAA's `plugins.zip` mechanism for shipping custom binaries has no equivalent here yet.
|
||||
- `UpdateEnvironment` supports metadata-only fields (tags, description, logging-config toggles). Changing `AirflowVersion`, `AirflowConfigurationOptions`, or `RequirementsS3Path` requires deleting and recreating the environment — these would require recreating the running container, which is out of scope for an in-place update today.
|
||||
- `CreateWebLoginToken` returns a stubbed token rather than performing a real Airflow FAB/JWT SSO handshake.
|
||||
- No per-component `MWAA_AIRFLOW_COMPONENT` environment variable. Real MWAA runs the startup script separately on webserver, scheduler, and worker; Floci runs the webserver, scheduler and triggerer together in one container, so there's no per-component distinction to expose.
|
||||
- Docker container and volume names are namespace-aware (via `FLOCI_DOCKER_RESOURCE_NAMESPACE`, same as every other Docker-backed service) but not scoped by AWS account id — two accounts creating an identically-named environment can collide. This is a pre-existing characteristic shared by every Docker-backed Floci service (EKS, RDS, ...), not unique to MWAA.
|
||||
- Environments loaded from persistent storage on Floci restart are not automatically reconnected to their Docker containers — again, a gap shared by every Docker-backed service today, not specific to MWAA.
|
||||
@@ -70,6 +70,8 @@ public class MwaaEnvironmentManager {
|
||||
private static final String STARTUP_ENV_PATH = REQUIREMENTS_DIR + "/mwaa-startup.env";
|
||||
/** A first {@code pip install} of a real requirements file can take minutes. */
|
||||
private static final int REQUIREMENTS_INSTALL_TIMEOUT_SECONDS = 900;
|
||||
/** The Airflow web UI admin Floci creates, and the identity a web login token signs in as. */
|
||||
static final String AIRFLOW_ADMIN_USER = "admin";
|
||||
private static final Set<String> MWAA_CLI_COMMANDS = Set.of("cheat-sheet", "version");
|
||||
private static final Map<String, Set<String>> MWAA_CLI_SUBCOMMANDS = Map.of(
|
||||
"connections", Set.of("add", "delete"),
|
||||
@@ -168,8 +170,8 @@ public class MwaaEnvironmentManager {
|
||||
lifecycleManager.ensureVolume(logsVolume);
|
||||
|
||||
String image = "apache/airflow:%s-%s".formatted(airflowVersion, pythonTagFor(airflowVersion));
|
||||
String adminUser = "admin";
|
||||
String adminPassword = generateSecret(24);
|
||||
environment.setAirflowAdminPassword(adminPassword);
|
||||
String sqlAlchemyConn = "postgresql+psycopg2://airflow:" + dbPassword + "@" + dbIp + ":" + POSTGRES_PORT + "/airflow";
|
||||
|
||||
// Points DAG code's own AWS SDK calls (boto3, botocore) at Floci itself, the same way
|
||||
@@ -183,9 +185,10 @@ public class MwaaEnvironmentManager {
|
||||
"AIRFLOW__CORE__FERNET_KEY=" + generateFernetKey(),
|
||||
"AIRFLOW__WEBSERVER__SECRET_KEY=" + generateSecret(32),
|
||||
"AIRFLOW__CORE__LOAD_EXAMPLES=false",
|
||||
"_AIRFLOW_WWW_USER_USERNAME=" + adminUser,
|
||||
"_AIRFLOW_WWW_USER_USERNAME=" + AIRFLOW_ADMIN_USER,
|
||||
"_AIRFLOW_WWW_USER_PASSWORD=" + adminPassword));
|
||||
env.addAll(airflowConfigurationOptionsEnv(environment.getAirflowConfigurationOptions()));
|
||||
env.addAll(signInRateLimitEnv(airflowVersion, environment.getAirflowConfigurationOptions()));
|
||||
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
|
||||
.withName(airflowContainerName)
|
||||
@@ -566,6 +569,22 @@ public class MwaaEnvironmentManager {
|
||||
return isAtLeast(airflowVersion, 2, 11) ? "python3.12" : "python3.11";
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns off Airflow's sign-in rate limit, which counts sign-ins by client address (5 per 40 seconds by default):
|
||||
* every sign-in reaches Airflow from the web proxy's one address, each {@code /aws_mwaa/login} and each UI login
|
||||
* it forwards, so the limit would count every client of the environment together. The option moved from
|
||||
* {@code webserver} to {@code fab} in Airflow 2.9. An {@code AirflowConfigurationOptions} entry setting it in
|
||||
* either section is kept.
|
||||
*/
|
||||
static List<String> signInRateLimitEnv(String airflowVersion, Map<String, String> options) {
|
||||
if (options != null && (options.containsKey("webserver.auth_rate_limited")
|
||||
|| options.containsKey("fab.auth_rate_limited"))) {
|
||||
return List.of();
|
||||
}
|
||||
return List.of((isAtLeast(airflowVersion, 2, 9) ? "AIRFLOW__FAB__" : "AIRFLOW__WEBSERVER__")
|
||||
+ "AUTH_RATE_LIMITED=False");
|
||||
}
|
||||
|
||||
static boolean isAtLeast(String airflowVersion, int major, int minor) {
|
||||
String[] parts = airflowVersion.split("\\.", 3);
|
||||
int actualMajor = Integer.parseInt(parts[0]);
|
||||
|
||||
@@ -16,6 +16,7 @@ import io.floci.aws.services.mwaa.model.Environment;
|
||||
import io.floci.aws.services.mwaa.model.EnvironmentStatus;
|
||||
import io.floci.aws.services.mwaa.model.UpdateEnvironmentRequest;
|
||||
import io.floci.aws.services.mwaa.proxy.MwaaProxyManager;
|
||||
import io.floci.aws.services.mwaa.proxy.MwaaWebProxy;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
@@ -25,6 +26,8 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -60,6 +63,9 @@ public class MwaaService implements TagHandler {
|
||||
private static final Set<String> MISSING_OBJECT_ERRORS = Set.of("NoSuchKey", "NoSuchBucket");
|
||||
private static final int REQUIREMENTS_INSTALL_THREADS = 2;
|
||||
|
||||
/** Amazon MWAA's web login token "expires after 60 seconds" (Apache Airflow REST API guide). */
|
||||
static final Duration WEB_LOGIN_TOKEN_LIFETIME = Duration.ofSeconds(60);
|
||||
|
||||
private final StorageBackend<String, Environment> storage;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -69,6 +75,7 @@ public class MwaaService implements TagHandler {
|
||||
private final S3Service s3Service;
|
||||
/** Runs DAG-sync reinstalls, which can take minutes, off the poller that syncs every environment. */
|
||||
private final Executor requirementsInstaller;
|
||||
private final Clock clock;
|
||||
|
||||
private final ScheduledExecutorService readinessPoller = Executors.newSingleThreadScheduledExecutor();
|
||||
private final ScheduledExecutorService dagSyncPoller = Executors.newSingleThreadScheduledExecutor();
|
||||
@@ -76,6 +83,9 @@ public class MwaaService implements TagHandler {
|
||||
/** Opaque CLI tokens minted by CreateCliToken, per environment. In-memory only — not persisted. */
|
||||
private final Map<String, Set<String>> cliTokensByEnvironment = new ConcurrentHashMap<>();
|
||||
|
||||
/** CreateWebLoginToken tokens and the instant each one expires, per environment. In-memory only. */
|
||||
private final Map<String, Map<String, Instant>> webTokensByEnvironment = new ConcurrentHashMap<>();
|
||||
|
||||
/** Last-synced DAG file state (S3 key relative to DagS3Path -> ETag), per environment. */
|
||||
private final Map<String, Map<String, String>> dagSyncState = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -97,12 +107,14 @@ public class MwaaService implements TagHandler {
|
||||
Thread thread = new Thread(runnable, "mwaa-requirements-install");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}));
|
||||
}),
|
||||
Clock.systemUTC());
|
||||
}
|
||||
|
||||
MwaaService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
MwaaEnvironmentManager environmentManager, MwaaProxyManager proxyManager,
|
||||
PortAllocator portAllocator, S3Service s3Service, Executor requirementsInstaller) {
|
||||
PortAllocator portAllocator, S3Service s3Service, Executor requirementsInstaller,
|
||||
Clock clock) {
|
||||
this.storage = storageFactory.create("mwaa", "mwaa-environments.json",
|
||||
new TypeReference<Map<String, Environment>>() {
|
||||
});
|
||||
@@ -113,6 +125,7 @@ public class MwaaService implements TagHandler {
|
||||
this.portAllocator = portAllocator;
|
||||
this.s3Service = s3Service;
|
||||
this.requirementsInstaller = requirementsInstaller;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -209,10 +222,18 @@ public class MwaaService implements TagHandler {
|
||||
environment.setProxyPort(proxyPort);
|
||||
environment.setWebserverUrl(buildWebserverUrl(proxyPort));
|
||||
String airflowContainerId = environment.getAirflowContainerId();
|
||||
// The proxy reads this environment's own token map, not whatever the name maps to later: a token
|
||||
// issued while an earlier environment of this name was being deleted lands in that one's map, not
|
||||
// in this.
|
||||
Map<String, Instant> webTokens = new ConcurrentHashMap<>();
|
||||
webTokensByEnvironment.put(environmentIdentity(environment), webTokens);
|
||||
proxyManager.startProxy(environmentIdentity(environment), proxyPort,
|
||||
environment.getAirflowInternalHost(), environment.getAirflowInternalPort(),
|
||||
this::isValidCliToken,
|
||||
cliCommand -> environmentManager.runAirflowCli(airflowContainerId, version, cliCommand));
|
||||
cliCommand -> environmentManager.runAirflowCli(airflowContainerId, version, cliCommand),
|
||||
(proxyIdentity, token) -> isUnexpired(webTokens, token),
|
||||
new MwaaWebProxy.AirflowAccount(MwaaEnvironmentManager.AIRFLOW_ADMIN_USER,
|
||||
environment.getAirflowAdminPassword()));
|
||||
provisioned = true;
|
||||
} catch (Exception e) {
|
||||
LOG.errorv(e, "Failed to start MWAA environment {0}", name);
|
||||
@@ -356,6 +377,7 @@ public class MwaaService implements TagHandler {
|
||||
}
|
||||
String environmentIdentity = environmentIdentity(environment);
|
||||
cliTokensByEnvironment.remove(environmentIdentity);
|
||||
webTokensByEnvironment.remove(environmentIdentity);
|
||||
dagSyncState.remove(environmentIdentity);
|
||||
requirementsEtagByEnvironment.remove(environmentIdentity);
|
||||
bootstrapInstallsToCheck.remove(environmentIdentity);
|
||||
@@ -366,11 +388,26 @@ public class MwaaService implements TagHandler {
|
||||
public Map<String, Object> createWebLoginToken(String name) {
|
||||
Environment environment = getEnvironment(name);
|
||||
String token = generateToken();
|
||||
Map<String, Instant> tokens = webTokensByEnvironment.computeIfAbsent(environmentIdentity(environment),
|
||||
k -> new ConcurrentHashMap<>());
|
||||
Instant now = clock.instant();
|
||||
tokens.values().removeIf(expiresAt -> !now.isBefore(expiresAt));
|
||||
tokens.put(token, now.plus(WEB_LOGIN_TOKEN_LIFETIME));
|
||||
return Map.of(
|
||||
"WebToken", token,
|
||||
"WebServerHostname", hostnameFromUrl(environment.getWebserverUrl()),
|
||||
"IamIdentity", "assumed-role/floci-local/user",
|
||||
"AirflowIdentity", "admin");
|
||||
"AirflowIdentity", MwaaEnvironmentManager.AIRFLOW_ADMIN_USER);
|
||||
}
|
||||
|
||||
boolean isValidWebToken(String environmentIdentity, String token) {
|
||||
Map<String, Instant> tokens = webTokensByEnvironment.get(environmentIdentity);
|
||||
return tokens != null && isUnexpired(tokens, token);
|
||||
}
|
||||
|
||||
private boolean isUnexpired(Map<String, Instant> tokens, String token) {
|
||||
Instant expiresAt = tokens.get(token);
|
||||
return expiresAt != null && clock.instant().isBefore(expiresAt);
|
||||
}
|
||||
|
||||
public Map<String, Object> createCliToken(String name) {
|
||||
|
||||
@@ -103,6 +103,9 @@ public class Environment {
|
||||
@JsonIgnore
|
||||
private String dbPassword;
|
||||
|
||||
@JsonIgnore
|
||||
private String airflowAdminPassword;
|
||||
|
||||
public Environment() {}
|
||||
|
||||
public String getName() { return name; }
|
||||
@@ -192,6 +195,9 @@ public class Environment {
|
||||
public String getDbPassword() { return dbPassword; }
|
||||
public void setDbPassword(String dbPassword) { this.dbPassword = dbPassword; }
|
||||
|
||||
public String getAirflowAdminPassword() { return airflowAdminPassword; }
|
||||
public void setAirflowAdminPassword(String airflowAdminPassword) { this.airflowAdminPassword = airflowAdminPassword; }
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class LastUpdate {
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
package io.floci.aws.services.mwaa.proxy;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.tls.ReloadingKeyManager;
|
||||
import io.quarkus.tls.CertificateUpdatedEvent;
|
||||
import io.quarkus.tls.TlsConfiguration;
|
||||
import io.quarkus.tls.TlsConfigurationRegistry;
|
||||
import io.quarkus.tls.runtime.config.TlsConfig;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.net.KeyCertOptions;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -10,6 +18,10 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
/**
|
||||
* Registry of all active {@link MwaaWebProxy} instances. One proxy per MWAA environment,
|
||||
* started/stopped alongside the environment's containers. Mirrors {@code NeptuneProxyManager}.
|
||||
*
|
||||
* <p>With {@code floci.tls.enabled}, {@code WebserverUrl} and {@code WebServerHostname} name an
|
||||
* {@code https} endpoint, so every proxy serves TLS with Floci's own server certificate, the way
|
||||
* the IoT MQTT TLS listener does, and follows that certificate when it is reissued.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class MwaaProxyManager {
|
||||
@@ -17,19 +29,25 @@ public class MwaaProxyManager {
|
||||
private static final Logger LOG = Logger.getLogger(MwaaProxyManager.class);
|
||||
|
||||
private final Vertx vertx;
|
||||
private final EmulatorConfig config;
|
||||
private final TlsConfigurationRegistry tlsRegistry;
|
||||
private final ConcurrentHashMap<String, MwaaWebProxy> proxies = new ConcurrentHashMap<>();
|
||||
private ReloadingKeyManager keyManager;
|
||||
|
||||
@Inject
|
||||
public MwaaProxyManager(Vertx vertx) {
|
||||
public MwaaProxyManager(Vertx vertx, EmulatorConfig config, TlsConfigurationRegistry tlsRegistry) {
|
||||
this.vertx = vertx;
|
||||
this.config = config;
|
||||
this.tlsRegistry = tlsRegistry;
|
||||
}
|
||||
|
||||
public void startProxy(String environmentName, int proxyPort, String backendHost, int backendPort,
|
||||
MwaaWebProxy.CliTokenValidator tokenValidator, MwaaWebProxy.CliExecutor cliExecutor) {
|
||||
MwaaWebProxy.TokenValidator cliTokenValidator, MwaaWebProxy.CliExecutor cliExecutor,
|
||||
MwaaWebProxy.TokenValidator webTokenValidator, MwaaWebProxy.AirflowAccount airflowAccount) {
|
||||
MwaaWebProxy proxy = new MwaaWebProxy(environmentName, vertx, backendHost, backendPort,
|
||||
tokenValidator, cliExecutor);
|
||||
cliTokenValidator, cliExecutor, webTokenValidator, airflowAccount);
|
||||
try {
|
||||
proxy.start(proxyPort);
|
||||
proxy.start(proxyPort, serverKeyCertOptions());
|
||||
proxies.put(environmentName, proxy);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to start MWAA web proxy for environment " + environmentName
|
||||
@@ -37,6 +55,36 @@ public class MwaaProxyManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Floci's server certificate when TLS is on, {@code null} for a plain HTTP proxy. */
|
||||
synchronized KeyCertOptions serverKeyCertOptions() {
|
||||
if (!config.tls().enabled()) {
|
||||
return null;
|
||||
}
|
||||
if (keyManager == null) {
|
||||
TlsConfiguration tls = tlsRegistry.getDefault().orElseThrow(() -> new IllegalStateException(
|
||||
"floci.tls.enabled is true but no default TLS configuration is registered"));
|
||||
keyManager = new ReloadingKeyManager(ReloadingKeyManager.keyManagerOf(vertx, tls.getKeyStoreOptions()));
|
||||
}
|
||||
return KeyCertOptions.wrap(keyManager);
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows a reissued server certificate (a hostname learned by {@code TlsCertificateManager.ensureHost},
|
||||
* or a reload): the next handshake on every proxy presents it. A key store that cannot be loaded, which
|
||||
* {@link ReloadingKeyManager#keyManagerOf} reports as an {@link IllegalStateException}, keeps the previous
|
||||
* one; any other failure propagates.
|
||||
*/
|
||||
synchronized void onCertificateUpdated(@Observes CertificateUpdatedEvent event) {
|
||||
if (keyManager == null || !TlsConfig.DEFAULT_NAME.equalsIgnoreCase(event.name())) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
keyManager.reload(ReloadingKeyManager.keyManagerOf(vertx, event.tlsConfiguration().getKeyStoreOptions()));
|
||||
} catch (IllegalStateException e) {
|
||||
LOG.warnv(e, "MWAA web proxies keep their previous server certificate: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void stopProxy(String environmentName) {
|
||||
MwaaWebProxy proxy = proxies.remove(environmentName);
|
||||
if (proxy != null) {
|
||||
|
||||
@@ -1,23 +1,33 @@
|
||||
package io.floci.aws.services.mwaa.proxy;
|
||||
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.WorkerExecutor;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpClientOptions;
|
||||
import io.vertx.core.http.HttpClientRequest;
|
||||
import io.vertx.core.http.HttpClientResponse;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerOptions;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.HttpServerResponse;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.core.net.KeyCertOptions;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* HTTP relay for a single MWAA environment's webserver traffic.
|
||||
@@ -30,11 +40,20 @@ import java.util.concurrent.TimeoutException;
|
||||
* {@code CreateCliToken} for this environment, then runs the request body (the raw Airflow CLI
|
||||
* command, e.g. {@code "dags list"}) inside the Airflow container and returns the
|
||||
* AWS-documented {@code {"stdout": "<base64>", "stderr": "<base64>"}} shape.
|
||||
*
|
||||
* <p>{@code POST /aws_mwaa/login} is intercepted too. A valid {@code CreateWebLoginToken} token in
|
||||
* its {@code token} form field signs in to Airflow's own login form as the environment's admin, and
|
||||
* the response hands back Airflow's {@code session} cookie with a redirect to {@code /home}, the
|
||||
* cookie Amazon MWAA's REST API guide has clients send to {@code /api/v1}.
|
||||
*/
|
||||
public class MwaaWebProxy {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(MwaaWebProxy.class);
|
||||
private static final String CLI_PATH = "/aws_mwaa/cli";
|
||||
private static final String LOGIN_PATH = "/aws_mwaa/login";
|
||||
private static final String AIRFLOW_LOGIN_PATH = "/login/";
|
||||
private static final Pattern CSRF_TOKEN_INPUT = Pattern.compile("<input[^>]*name=\"csrf_token\"[^>]*>");
|
||||
private static final Pattern VALUE_ATTRIBUTE = Pattern.compile("value=\"([^\"]*)\"");
|
||||
// CLI execs get their own small pool, shared by name across environments, so a burst of
|
||||
// slow Docker execs cannot occupy the Vert.x worker pool the rest of the emulator uses.
|
||||
private static final String CLI_WORKER_POOL_NAME = "mwaa-cli";
|
||||
@@ -48,32 +67,49 @@ public class MwaaWebProxy {
|
||||
private final Vertx vertx;
|
||||
private final String backendHost;
|
||||
private final int backendPort;
|
||||
private final CliTokenValidator tokenValidator;
|
||||
private final TokenValidator cliTokenValidator;
|
||||
private final CliExecutor cliExecutor;
|
||||
private final TokenValidator webTokenValidator;
|
||||
private final AirflowAccount airflowAccount;
|
||||
private final WorkerExecutor cliWorkers;
|
||||
|
||||
private HttpServer server;
|
||||
private HttpClient client;
|
||||
|
||||
public MwaaWebProxy(String environmentName, Vertx vertx, String backendHost, int backendPort,
|
||||
CliTokenValidator tokenValidator, CliExecutor cliExecutor) {
|
||||
TokenValidator cliTokenValidator, CliExecutor cliExecutor,
|
||||
TokenValidator webTokenValidator, AirflowAccount airflowAccount) {
|
||||
this.environmentName = environmentName;
|
||||
this.vertx = vertx;
|
||||
this.backendHost = backendHost;
|
||||
this.backendPort = backendPort;
|
||||
this.tokenValidator = tokenValidator;
|
||||
this.cliTokenValidator = cliTokenValidator;
|
||||
this.cliExecutor = cliExecutor;
|
||||
this.webTokenValidator = webTokenValidator;
|
||||
this.airflowAccount = airflowAccount;
|
||||
this.cliWorkers = vertx.createSharedWorkerExecutor(CLI_WORKER_POOL_NAME, CLI_WORKER_POOL_SIZE);
|
||||
}
|
||||
|
||||
/** Starts listening on {@code proxyPort}, blocking until bound (or throwing on failure). */
|
||||
/** Starts listening on {@code proxyPort} over plain HTTP, blocking until bound (or throwing on failure). */
|
||||
public void start(int proxyPort) throws Exception {
|
||||
start(proxyPort, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts listening on {@code proxyPort}, blocking until bound (or throwing on failure). With
|
||||
* {@code serverKeyCertOptions} the proxy serves HTTPS with that key and certificate.
|
||||
*/
|
||||
public void start(int proxyPort, KeyCertOptions serverKeyCertOptions) throws Exception {
|
||||
client = vertx.createHttpClient(new HttpClientOptions()
|
||||
.setConnectTimeout(5000)
|
||||
.setKeepAlive(true));
|
||||
server = vertx.createHttpServer(new HttpServerOptions()
|
||||
HttpServerOptions serverOptions = new HttpServerOptions()
|
||||
.setHost("0.0.0.0")
|
||||
.setPort(proxyPort));
|
||||
.setPort(proxyPort);
|
||||
if (serverKeyCertOptions != null) {
|
||||
serverOptions.setSsl(true).setKeyCertOptions(serverKeyCertOptions);
|
||||
}
|
||||
server = vertx.createHttpServer(serverOptions);
|
||||
server.requestHandler(this::handleRequest);
|
||||
try {
|
||||
server.listen().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
@@ -104,6 +140,8 @@ public class MwaaWebProxy {
|
||||
private void handleRequest(HttpServerRequest req) {
|
||||
if (req.method() == HttpMethod.POST && CLI_PATH.equals(req.path())) {
|
||||
handleCli(req);
|
||||
} else if (req.method() == HttpMethod.POST && LOGIN_PATH.equals(req.path())) {
|
||||
handleLogin(req);
|
||||
} else {
|
||||
forward(req);
|
||||
}
|
||||
@@ -111,7 +149,7 @@ public class MwaaWebProxy {
|
||||
|
||||
private void handleCli(HttpServerRequest req) {
|
||||
String token = extractBearerToken(req.getHeader("Authorization"));
|
||||
if (token == null || !tokenValidator.isValid(environmentName, token)) {
|
||||
if (token == null || !cliTokenValidator.isValid(environmentName, token)) {
|
||||
req.response().setStatusCode(401)
|
||||
.putHeader("Content-Type", "application/json")
|
||||
.end("{\"message\":\"Missing or invalid CLI token\"}");
|
||||
@@ -138,6 +176,115 @@ public class MwaaWebProxy {
|
||||
});
|
||||
}
|
||||
|
||||
private void handleLogin(HttpServerRequest req) {
|
||||
req.setExpectMultipart(true);
|
||||
req.endHandler(ignored -> {
|
||||
String token = req.getFormAttribute("token");
|
||||
if (token == null || !webTokenValidator.isValid(environmentName, token)) {
|
||||
req.response().setStatusCode(401)
|
||||
.putHeader("Content-Type", "application/json")
|
||||
.end("{\"message\":\"Missing, invalid or expired web login token\"}");
|
||||
return;
|
||||
}
|
||||
signInToAirflow()
|
||||
.onSuccess(cookies -> {
|
||||
HttpServerResponse response = req.response().setStatusCode(302).putHeader("Location", "/home");
|
||||
cookies.forEach(cookie -> response.headers().add("Set-Cookie", cookie));
|
||||
response.end();
|
||||
})
|
||||
.onFailure(e -> {
|
||||
LOG.warnv("MWAA web login failed for environment {0}: {1}", environmentName, e.getMessage());
|
||||
req.response().setStatusCode(502)
|
||||
.putHeader("Content-Type", "application/json")
|
||||
.end("{\"message\":\"" + escapeJson(e.getMessage()) + "\"}");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in through Airflow's login form the way a browser does: GET it for the CSRF token and
|
||||
* the anonymous session cookie, POST the admin credentials back with both, and return the
|
||||
* {@code Set-Cookie} headers of the redirect Airflow answers a successful sign-in with.
|
||||
*/
|
||||
private Future<List<String>> signInToAirflow() {
|
||||
return client.request(backendRequest(HttpMethod.GET, AIRFLOW_LOGIN_PATH))
|
||||
.compose(HttpClientRequest::send)
|
||||
.compose(loginPage -> loginPage.body().compose(body -> client.request(backendRequest(HttpMethod.POST,
|
||||
AIRFLOW_LOGIN_PATH))
|
||||
.compose(post -> {
|
||||
String cookie = sessionCookie(loginPage.cookies());
|
||||
if (cookie != null) {
|
||||
post.putHeader("Cookie", cookie);
|
||||
}
|
||||
post.putHeader("Content-Type", "application/x-www-form-urlencoded");
|
||||
return post.send(loginForm(csrfToken(body.toString(StandardCharsets.UTF_8)), airflowAccount));
|
||||
})))
|
||||
.compose(response -> response.body().compose(ignored -> signedInCookies(response)));
|
||||
}
|
||||
|
||||
private RequestOptions backendRequest(HttpMethod method, String uri) {
|
||||
return new RequestOptions()
|
||||
.setHost(backendHost)
|
||||
.setPort(backendPort)
|
||||
.setURI(uri)
|
||||
.setMethod(method);
|
||||
}
|
||||
|
||||
private static Future<List<String>> signedInCookies(HttpClientResponse response) {
|
||||
String location = response.getHeader("Location");
|
||||
if (response.statusCode() != 302 || sessionCookie(response.cookies()) == null
|
||||
|| !leavesTheLoginForm(location)) {
|
||||
return Future.failedFuture("Airflow did not accept the environment's admin sign-in (HTTP "
|
||||
+ response.statusCode() + (location != null ? ", redirected to " + location : "") + ")");
|
||||
}
|
||||
return Future.succeededFuture(response.cookies());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a sign-in's redirect leads away from the login form. Flask-AppBuilder answers refused
|
||||
* credentials with a redirect back to it, carrying a session cookie that only holds the flashed
|
||||
* message.
|
||||
*/
|
||||
static boolean leavesTheLoginForm(String location) {
|
||||
if (location == null || location.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
String path = URI.create(location).getPath();
|
||||
return path != null && !path.startsWith("/login");
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static String csrfToken(String loginPage) {
|
||||
Matcher input = CSRF_TOKEN_INPUT.matcher(loginPage);
|
||||
if (!input.find()) {
|
||||
return null;
|
||||
}
|
||||
Matcher value = VALUE_ATTRIBUTE.matcher(input.group());
|
||||
return value.find() ? value.group(1) : null;
|
||||
}
|
||||
|
||||
static String sessionCookie(List<String> setCookieHeaders) {
|
||||
for (String header : setCookieHeaders) {
|
||||
if (header.startsWith("session=")) {
|
||||
int end = header.indexOf(';');
|
||||
return end >= 0 ? header.substring(0, end) : header;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Buffer loginForm(String csrfToken, AirflowAccount account) {
|
||||
String form = "username=" + URLEncoder.encode(account.username(), StandardCharsets.UTF_8)
|
||||
+ "&password=" + URLEncoder.encode(account.password(), StandardCharsets.UTF_8);
|
||||
if (csrfToken != null) {
|
||||
form += "&csrf_token=" + URLEncoder.encode(csrfToken, StandardCharsets.UTF_8);
|
||||
}
|
||||
return Buffer.buffer(form);
|
||||
}
|
||||
|
||||
private void forward(HttpServerRequest req) {
|
||||
req.bodyHandler(body -> {
|
||||
RequestOptions opts = new RequestOptions()
|
||||
@@ -193,10 +340,14 @@ public class MwaaWebProxy {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface CliTokenValidator {
|
||||
public interface TokenValidator {
|
||||
boolean isValid(String environmentName, String token);
|
||||
}
|
||||
|
||||
/** The Airflow web UI account a valid web login token signs in as. */
|
||||
public record AirflowAccount(String username, String password) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface CliExecutor {
|
||||
ContainerExec.Result execute(String cliCommand) throws Exception;
|
||||
|
||||
@@ -31,6 +31,7 @@ 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.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -216,6 +217,37 @@ class MwaaEnvironmentManagerTest {
|
||||
assertFalse(captor.getValue().env().contains("AIRFLOW__CORE__EXECUTOR=CeleryExecutor"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theGeneratedAdminPasswordIsKeptOnTheEnvironmentForWebLogins() {
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
when(lifecycleManager.create(any())).thenReturn("airflow-container-id");
|
||||
when(lifecycleManager.startCreated(eq("airflow-container-id"), any())).thenReturn(new ContainerInfo(
|
||||
"airflow-container-id", Map.of(8080, new EndpointInfo("172.18.0.5", 8080))));
|
||||
Environment environment = new Environment();
|
||||
environment.setName("my-env");
|
||||
|
||||
manager.startAirflowContainer(environment, "2.10.5", "172.18.0.9", "db-secret-pw", null, null);
|
||||
|
||||
ArgumentCaptor<ContainerSpec> captor = ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).create(captor.capture());
|
||||
assertNotNull(environment.getAirflowAdminPassword());
|
||||
assertTrue(captor.getValue().env().contains("_AIRFLOW_WWW_USER_PASSWORD=" + environment.getAirflowAdminPassword()));
|
||||
assertTrue(captor.getValue().env().contains("_AIRFLOW_WWW_USER_USERNAME=admin"));
|
||||
assertTrue(captor.getValue().env().contains("AIRFLOW__FAB__AUTH_RATE_LIMITED=False"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSignInRateLimitIsOffInTheSectionEachVersionReadsUnlessAnOptionSetsIt() {
|
||||
assertEquals(List.of("AIRFLOW__WEBSERVER__AUTH_RATE_LIMITED=False"),
|
||||
MwaaEnvironmentManager.signInRateLimitEnv("2.8.4", null));
|
||||
assertEquals(List.of("AIRFLOW__FAB__AUTH_RATE_LIMITED=False"),
|
||||
MwaaEnvironmentManager.signInRateLimitEnv("2.9.2", Map.of()));
|
||||
assertEquals(List.of(), MwaaEnvironmentManager.signInRateLimitEnv("2.10.5",
|
||||
Map.of("fab.auth_rate_limited", "True")));
|
||||
assertEquals(List.of(), MwaaEnvironmentManager.signInRateLimitEnv("2.10.5",
|
||||
Map.of("webserver.auth_rate_limited", "True")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void airflowEnvVarsWireTheResolvedPostgresDsn() {
|
||||
ContainerSpec spec = startAirflowAndCaptureSpec(false);
|
||||
|
||||
@@ -15,17 +15,22 @@ import io.floci.aws.services.mwaa.model.EnvironmentStatus;
|
||||
import io.floci.aws.services.mwaa.model.NetworkConfiguration;
|
||||
import io.floci.aws.services.mwaa.model.UpdateEnvironmentRequest;
|
||||
import io.floci.aws.services.mwaa.proxy.MwaaProxyManager;
|
||||
import io.floci.aws.services.mwaa.proxy.MwaaWebProxy;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
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.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -45,6 +50,7 @@ import static org.mockito.Mockito.when;
|
||||
class MwaaServiceTest {
|
||||
|
||||
private MwaaService mwaaService;
|
||||
private MutableClock clock;
|
||||
private AccountAwareStorageBackend<Environment> environmentStorage;
|
||||
private String currentAccount;
|
||||
private String currentRegion;
|
||||
@@ -67,7 +73,9 @@ class MwaaServiceTest {
|
||||
when(regionResolver.getAccountId()).thenAnswer(invocation -> currentAccount);
|
||||
when(regionResolver.getRegion()).thenAnswer(invocation -> currentRegion);
|
||||
S3Service s3Service = Mockito.mock(S3Service.class);
|
||||
mwaaService = new MwaaService(storageFactory, config, regionResolver, null, null, null, s3Service);
|
||||
clock = new MutableClock();
|
||||
mwaaService = new MwaaService(storageFactory, config, regionResolver, null, null, null, s3Service,
|
||||
Runnable::run, clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -529,6 +537,44 @@ class MwaaServiceTest {
|
||||
Map<String, Object> response = mwaaService.createWebLoginToken("web-token-env");
|
||||
assertNotNull(response.get("WebToken"));
|
||||
assertNotNull(response.get("WebServerHostname"));
|
||||
assertEquals("admin", response.get("AirflowIdentity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void webLoginTokenIsValidForSixtySecondsAndOnlyForItsEnvironment() {
|
||||
mwaaService.createEnvironment("web-login-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
String identity = mwaaService.environmentIdentity(mwaaService.getEnvironment("web-login-env"));
|
||||
String token = (String) mwaaService.createWebLoginToken("web-login-env").get("WebToken");
|
||||
|
||||
assertTrue(mwaaService.isValidWebToken(identity, token));
|
||||
assertFalse(mwaaService.isValidWebToken("other-env", token));
|
||||
assertFalse(mwaaService.isValidWebToken(identity, "not-a-real-token"));
|
||||
|
||||
clock.advance(Duration.ofSeconds(60));
|
||||
|
||||
assertFalse(mwaaService.isValidWebToken(identity, token));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cliTokensAndWebLoginTokensAreNotInterchangeable() {
|
||||
mwaaService.createEnvironment("two-tokens-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
String identity = mwaaService.environmentIdentity(mwaaService.getEnvironment("two-tokens-env"));
|
||||
String cliToken = (String) mwaaService.createCliToken("two-tokens-env").get("CliToken");
|
||||
String webToken = (String) mwaaService.createWebLoginToken("two-tokens-env").get("WebToken");
|
||||
|
||||
assertFalse(mwaaService.isValidWebToken(identity, cliToken));
|
||||
assertFalse(mwaaService.isValidCliToken(identity, webToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnEnvironmentDropsItsWebLoginTokens() {
|
||||
mwaaService.createEnvironment("deleted-web-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
String identity = mwaaService.environmentIdentity(mwaaService.getEnvironment("deleted-web-env"));
|
||||
String token = (String) mwaaService.createWebLoginToken("deleted-web-env").get("WebToken");
|
||||
|
||||
mwaaService.deleteEnvironment("deleted-web-env");
|
||||
|
||||
assertFalse(mwaaService.isValidWebToken(identity, token));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -605,7 +651,50 @@ class MwaaServiceTest {
|
||||
when(portAllocator.allocate(8700, 8799)).thenReturn(8701);
|
||||
|
||||
realModeService = new MwaaService(storageFactory, config, regionResolver,
|
||||
environmentManager, proxyManager, portAllocator, s3Service, queuedInstalls::add);
|
||||
environmentManager, proxyManager, portAllocator, s3Service, queuedInstalls::add, Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theProxySignsWebLoginsInAsTheEnvironmentsAdminAfterCheckingTheToken() {
|
||||
Mockito.doAnswer(invocation -> {
|
||||
invocation.getArgument(0, Environment.class).setAirflowAdminPassword("generated-pw");
|
||||
return null;
|
||||
}).when(environmentManager).startEnvironment(any(), any(), any(), any());
|
||||
|
||||
Environment environment = realModeService.createEnvironment("login-env",
|
||||
createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
String token = (String) realModeService.createWebLoginToken("login-env").get("WebToken");
|
||||
|
||||
ArgumentCaptor<MwaaWebProxy.TokenValidator> webTokenValidator =
|
||||
ArgumentCaptor.forClass(MwaaWebProxy.TokenValidator.class);
|
||||
ArgumentCaptor<MwaaWebProxy.AirflowAccount> account = ArgumentCaptor.forClass(MwaaWebProxy.AirflowAccount.class);
|
||||
verify(proxyManager).startProxy(any(), anyInt(), any(), anyInt(), any(), any(), webTokenValidator.capture(),
|
||||
account.capture());
|
||||
assertEquals(new MwaaWebProxy.AirflowAccount("admin", "generated-pw"), account.getValue());
|
||||
String identity = realModeService.environmentIdentity(environment);
|
||||
assertTrue(webTokenValidator.getValue().isValid(identity, token));
|
||||
assertFalse(webTokenValidator.getValue().isValid(identity, "not-a-real-token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachProxyAcceptsOnlyTheTokensOfItsOwnEnvironmentNotOfALaterOneOfTheSameName() {
|
||||
ArgumentCaptor<MwaaWebProxy.TokenValidator> validators =
|
||||
ArgumentCaptor.forClass(MwaaWebProxy.TokenValidator.class);
|
||||
Environment first = realModeService.createEnvironment("reused-env",
|
||||
createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
String identity = realModeService.environmentIdentity(first);
|
||||
String firstToken = (String) realModeService.createWebLoginToken("reused-env").get("WebToken");
|
||||
realModeService.deleteEnvironment("reused-env");
|
||||
realModeService.createEnvironment("reused-env", createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
String secondToken = (String) realModeService.createWebLoginToken("reused-env").get("WebToken");
|
||||
|
||||
verify(proxyManager, Mockito.times(2)).startProxy(any(), anyInt(), any(), anyInt(), any(), any(),
|
||||
validators.capture(), any());
|
||||
MwaaWebProxy.TokenValidator firstProxy = validators.getAllValues().get(0);
|
||||
MwaaWebProxy.TokenValidator secondProxy = validators.getAllValues().get(1);
|
||||
assertTrue(secondProxy.isValid(identity, secondToken));
|
||||
assertFalse(secondProxy.isValid(identity, firstToken));
|
||||
assertFalse(firstProxy.isValid(identity, secondToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -635,7 +724,7 @@ class MwaaServiceTest {
|
||||
// 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());
|
||||
.when(proxyManager).startProxy(any(), anyInt(), any(), anyInt(), any(), any(), any(), any());
|
||||
|
||||
Environment environment = realModeService.createEnvironment("failed-proxy-env",
|
||||
createRequest("arn:aws:s3:::my-bucket", "dags"));
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package io.floci.aws.services.mwaa.proxy;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.testutil.FreePorts;
|
||||
import io.quarkus.tls.CertificateUpdatedEvent;
|
||||
import io.quarkus.tls.TlsConfiguration;
|
||||
import io.quarkus.tls.TlsConfigurationRegistry;
|
||||
import io.quarkus.tls.runtime.config.TlsConfig;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpClientOptions;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.core.net.PemKeyCertOptions;
|
||||
import io.vertx.core.net.SelfSignedCertificate;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@code WebserverUrl} says {@code https} when {@code floci.tls.enabled} is on, so the proxy has to
|
||||
* serve TLS then, and stay plain HTTP otherwise.
|
||||
*/
|
||||
class MwaaProxyManagerTlsTest {
|
||||
|
||||
private Vertx vertx;
|
||||
private HttpServer backend;
|
||||
private MwaaProxyManager manager;
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
private final EmulatorConfig.TlsConfig tlsConfig = mock(EmulatorConfig.TlsConfig.class);
|
||||
private final TlsConfigurationRegistry registry = mock(TlsConfigurationRegistry.class);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
backend = vertx.createHttpServer()
|
||||
.requestHandler(req -> req.response().end("airflow"))
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
when(config.tls()).thenReturn(tlsConfig);
|
||||
manager = new MwaaProxyManager(vertx, config, registry);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
manager.stopAll();
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private int startProxy() throws Exception {
|
||||
int port = FreePorts.anyInterfacePort();
|
||||
manager.startProxy("env1", port, "127.0.0.1", backend.actualPort(),
|
||||
(environmentName, token) -> false, command -> new ContainerExec.Result(0, "", "", false),
|
||||
(environmentName, token) -> false, new MwaaWebProxy.AirflowAccount("admin", "pw"));
|
||||
return port;
|
||||
}
|
||||
|
||||
private String get(int port, boolean ssl) throws Exception {
|
||||
HttpClient client = vertx.createHttpClient(new HttpClientOptions().setSsl(ssl).setTrustAll(true)
|
||||
.setVerifyHost(false));
|
||||
return client.request(new RequestOptions().setHost("127.0.0.1").setPort(port)
|
||||
.setMethod(HttpMethod.GET).setURI("/home"))
|
||||
.compose(request -> request.send())
|
||||
.compose(response -> response.body())
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS).toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theProxyServesHttpsWithFlocisCertificateWhenTlsIsEnabled() throws Exception {
|
||||
when(tlsConfig.enabled()).thenReturn(true);
|
||||
TlsConfiguration tls = mock(TlsConfiguration.class);
|
||||
when(registry.getDefault()).thenReturn(Optional.of(tls));
|
||||
when(tls.getKeyStoreOptions()).thenReturn(SelfSignedCertificate.create("localhost").keyCertOptions());
|
||||
|
||||
int port = startProxy();
|
||||
|
||||
assertEquals("airflow", get(port, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyStoreThatCannotBeLoadedKeepsThePreviousCertificateAndOtherFailuresPropagate() throws Exception {
|
||||
when(tlsConfig.enabled()).thenReturn(true);
|
||||
TlsConfiguration tls = mock(TlsConfiguration.class);
|
||||
when(registry.getDefault()).thenReturn(Optional.of(tls));
|
||||
when(tls.getKeyStoreOptions()).thenReturn(SelfSignedCertificate.create("localhost").keyCertOptions());
|
||||
int port = startProxy();
|
||||
TlsConfiguration unloadable = mock(TlsConfiguration.class);
|
||||
when(unloadable.getKeyStoreOptions()).thenReturn(new PemKeyCertOptions()
|
||||
.addCertValue(Buffer.buffer("not a certificate"))
|
||||
.addKeyValue(Buffer.buffer("not a key")));
|
||||
TlsConfiguration broken = mock(TlsConfiguration.class);
|
||||
when(broken.getKeyStoreOptions()).thenThrow(new UnsupportedOperationException("broken registry"));
|
||||
|
||||
manager.onCertificateUpdated(new CertificateUpdatedEvent(TlsConfig.DEFAULT_NAME, unloadable));
|
||||
|
||||
assertEquals("airflow", get(port, true));
|
||||
assertThrows(UnsupportedOperationException.class,
|
||||
() -> manager.onCertificateUpdated(new CertificateUpdatedEvent(TlsConfig.DEFAULT_NAME, broken)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theProxyStaysPlainHttpWhenTlsIsDisabled() throws Exception {
|
||||
when(tlsConfig.enabled()).thenReturn(false);
|
||||
|
||||
int port = startProxy();
|
||||
|
||||
assertNull(manager.serverKeyCertOptions());
|
||||
assertEquals("airflow", get(port, false));
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
*/
|
||||
class MwaaWebProxyCliOffloadTest {
|
||||
|
||||
private static final MwaaWebProxy.AirflowAccount NO_ACCOUNT = new MwaaWebProxy.AirflowAccount("admin", "unused");
|
||||
|
||||
private Vertx vertx;
|
||||
|
||||
@AfterEach
|
||||
@@ -66,7 +68,7 @@ class MwaaWebProxyCliOffloadTest {
|
||||
};
|
||||
|
||||
MwaaWebProxy proxy = new MwaaWebProxy("env1", vertx, "127.0.0.1", backend.actualPort(),
|
||||
(environmentName, token) -> true, slowExecutor);
|
||||
(environmentName, token) -> true, slowExecutor, (environmentName, token) -> false, NO_ACCOUNT);
|
||||
int proxyPort = FreePorts.anyInterfacePort();
|
||||
proxy.start(proxyPort);
|
||||
|
||||
@@ -138,7 +140,7 @@ class MwaaWebProxyCliOffloadTest {
|
||||
return new ContainerExec.Result(0, "", "", false);
|
||||
};
|
||||
MwaaWebProxy proxy = new MwaaWebProxy("env1", vertx, "127.0.0.1", 1,
|
||||
(environmentName, token) -> true, slowExecutor);
|
||||
(environmentName, token) -> true, slowExecutor, (environmentName, token) -> false, NO_ACCOUNT);
|
||||
int proxyPort = FreePorts.anyInterfacePort();
|
||||
proxy.start(proxyPort);
|
||||
|
||||
@@ -185,7 +187,7 @@ class MwaaWebProxyCliOffloadTest {
|
||||
throw new IllegalStateException("exec timed out in container abc123");
|
||||
};
|
||||
MwaaWebProxy proxy = new MwaaWebProxy("env1", vertx, "127.0.0.1", 1,
|
||||
(environmentName, token) -> true, failingExecutor);
|
||||
(environmentName, token) -> true, failingExecutor, (environmentName, token) -> false, NO_ACCOUNT);
|
||||
int proxyPort = FreePorts.anyInterfacePort();
|
||||
proxy.start(proxyPort);
|
||||
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package io.floci.aws.services.mwaa.proxy;
|
||||
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.testutil.FreePorts;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpClientOptions;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.core.net.SelfSignedCertificate;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* {@code POST /aws_mwaa/login} against a fake Airflow that serves the same login form shape as
|
||||
* Airflow 2.x's Flask-AppBuilder: a GET that sets an anonymous {@code session} cookie and renders a
|
||||
* {@code csrf_token} hidden input, and a POST that only signs in when the cookie, the CSRF token
|
||||
* and the credentials all match, answering a {@code 302} to {@code /home} with a new cookie. Wrong
|
||||
* credentials get what Flask-AppBuilder answers them with, a {@code 302} back to the login form with
|
||||
* a session cookie holding the flashed message, and a form that fails validation gets the form again.
|
||||
*/
|
||||
class MwaaWebProxyLoginTest {
|
||||
|
||||
private static final String CSRF = "IjJiOWM0MDA2YWFmMzJhMTBhMzlkNGM2NDkzZDFiM2QzYjVlYTQ1NDYi.avj96w.5B4Sc88q";
|
||||
private static final String SIGNED_IN_COOKIE = "session=signed-in.abc; Expires=Tue, 15 Dec 2026 00:33:56 GMT; "
|
||||
+ "HttpOnly; Path=/; SameSite=Lax";
|
||||
|
||||
private Vertx vertx;
|
||||
private HttpServer backend;
|
||||
private MwaaWebProxy proxy;
|
||||
private int proxyPort;
|
||||
private final List<String> backendRequests = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
backend = vertx.createHttpServer()
|
||||
.requestHandler(this::fakeAirflow)
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
if (proxy != null) {
|
||||
proxy.stop();
|
||||
}
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private void fakeAirflow(HttpServerRequest req) {
|
||||
backendRequests.add(req.method() + " " + req.uri());
|
||||
if (req.method() == HttpMethod.GET && "/login/".equals(req.path())) {
|
||||
req.response()
|
||||
.putHeader("Set-Cookie", "session=anonymous.xyz; HttpOnly; Path=/; SameSite=Lax")
|
||||
.putHeader("Content-Type", "text/html; charset=utf-8")
|
||||
.end("<form method=\"post\"><input id=\"csrf_token\" name=\"csrf_token\" type=\"hidden\" value=\""
|
||||
+ CSRF + "\"><input name=\"username\"><input name=\"password\"></form>");
|
||||
return;
|
||||
}
|
||||
if (req.method() == HttpMethod.POST && "/login/".equals(req.path())) {
|
||||
req.body().onSuccess(body -> {
|
||||
Map<String, String> form = parseForm(body.toString(StandardCharsets.UTF_8));
|
||||
boolean validForm = "session=anonymous.xyz".equals(req.getHeader("Cookie"))
|
||||
&& CSRF.equals(form.get("csrf_token"));
|
||||
boolean signedIn = "admin".equals(form.get("username")) && "s3cret&=".equals(form.get("password"));
|
||||
if (!validForm) {
|
||||
req.response().setStatusCode(200).end("<form>The CSRF token is missing.</form>");
|
||||
} else if (signedIn) {
|
||||
req.response().setStatusCode(302).putHeader("Location", "/home")
|
||||
.putHeader("Set-Cookie", SIGNED_IN_COOKIE).end();
|
||||
} else {
|
||||
req.response().setStatusCode(302).putHeader("Location", "/login/?next=")
|
||||
.putHeader("Set-Cookie", "session=flashed-invalid-login.xyz; HttpOnly; Path=/").end();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
req.response().setStatusCode(200).end("forwarded " + req.path());
|
||||
}
|
||||
|
||||
private static Map<String, String> parseForm(String body) {
|
||||
Map<String, String> form = new HashMap<>();
|
||||
for (String pair : body.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
form.put(URLDecoder.decode(pair.substring(0, eq), StandardCharsets.UTF_8),
|
||||
URLDecoder.decode(pair.substring(eq + 1), StandardCharsets.UTF_8));
|
||||
}
|
||||
return form;
|
||||
}
|
||||
|
||||
private void startProxy(String password) throws Exception {
|
||||
proxy = new MwaaWebProxy("env1", vertx, "127.0.0.1", backend.actualPort(),
|
||||
(environmentName, token) -> false,
|
||||
command -> new ContainerExec.Result(0, "", "", false),
|
||||
(environmentName, token) -> "env1".equals(environmentName) && "good-token".equals(token),
|
||||
new MwaaWebProxy.AirflowAccount("admin", password));
|
||||
proxyPort = FreePorts.anyInterfacePort();
|
||||
proxy.start(proxyPort);
|
||||
}
|
||||
|
||||
private LoginResponse postLogin(String contentType, String body) throws Exception {
|
||||
HttpClient client = vertx.createHttpClient();
|
||||
return client.request(new RequestOptions()
|
||||
.setHost("127.0.0.1")
|
||||
.setPort(proxyPort)
|
||||
.setMethod(HttpMethod.POST)
|
||||
.setURI("/aws_mwaa/login"))
|
||||
.compose(request -> {
|
||||
request.putHeader("Content-Type", contentType);
|
||||
return request.send(Buffer.buffer(body));
|
||||
})
|
||||
.compose(response -> response.body().map(responseBody -> new LoginResponse(response.statusCode(),
|
||||
response.getHeader("Location"), response.cookies(), responseBody.toString())))
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValidWebTokenSignsInAndReturnsAirflowsSessionCookie() throws Exception {
|
||||
startProxy("s3cret&=");
|
||||
|
||||
LoginResponse response = postLogin("application/x-www-form-urlencoded", "token=good-token");
|
||||
|
||||
assertEquals(302, response.statusCode());
|
||||
assertEquals("/home", response.location());
|
||||
assertEquals(List.of(SIGNED_IN_COOKIE), response.cookies());
|
||||
assertEquals(List.of("GET /login/", "POST /login/"), backendRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownOrExpiredWebTokenIsRefusedWithoutReachingAirflow() throws Exception {
|
||||
startProxy("s3cret&=");
|
||||
|
||||
LoginResponse wrongToken = postLogin("application/x-www-form-urlencoded", "token=other-token");
|
||||
LoginResponse noToken = postLogin("application/x-www-form-urlencoded", "something=else");
|
||||
|
||||
assertEquals(401, wrongToken.statusCode());
|
||||
assertEquals(401, noToken.statusCode());
|
||||
assertTrue(wrongToken.cookies().isEmpty());
|
||||
assertEquals(List.of(), backendRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAirflowThatRefusesTheSignInAnswersBadGateway() throws Exception {
|
||||
startProxy("wrong-password");
|
||||
|
||||
LoginResponse response = postLogin("application/x-www-form-urlencoded", "token=good-token");
|
||||
|
||||
assertEquals(502, response.statusCode());
|
||||
assertTrue(response.cookies().isEmpty());
|
||||
assertTrue(response.body().contains("HTTP 302") && response.body().contains("/login/"), response.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignInWhoseRedirectLeadsBackToTheLoginFormIsRefused() {
|
||||
assertTrue(MwaaWebProxy.leavesTheLoginForm("/home"));
|
||||
assertTrue(MwaaWebProxy.leavesTheLoginForm("http://airflow:8080/"));
|
||||
assertFalse(MwaaWebProxy.leavesTheLoginForm("/login/?next="));
|
||||
assertFalse(MwaaWebProxy.leavesTheLoginForm("http://airflow:8080/login/"));
|
||||
assertFalse(MwaaWebProxy.leavesTheLoginForm(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherRequestsAreStillForwarded() throws Exception {
|
||||
startProxy("s3cret&=");
|
||||
HttpClient client = vertx.createHttpClient();
|
||||
|
||||
String body = client.request(new RequestOptions().setHost("127.0.0.1").setPort(proxyPort)
|
||||
.setMethod(HttpMethod.GET).setURI("/aws_mwaa/login"))
|
||||
.compose(request -> request.send())
|
||||
.compose(response -> response.body())
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS).toString();
|
||||
|
||||
assertEquals("forwarded /aws_mwaa/login", body);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLoginWorksOverHttpsToo() throws Exception {
|
||||
proxy = new MwaaWebProxy("env1", vertx, "127.0.0.1", backend.actualPort(),
|
||||
(environmentName, token) -> false,
|
||||
command -> new ContainerExec.Result(0, "", "", false),
|
||||
(environmentName, token) -> "good-token".equals(token),
|
||||
new MwaaWebProxy.AirflowAccount("admin", "s3cret&="));
|
||||
proxyPort = FreePorts.anyInterfacePort();
|
||||
proxy.start(proxyPort, SelfSignedCertificate.create("localhost").keyCertOptions());
|
||||
HttpClient client = vertx.createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)
|
||||
.setVerifyHost(false));
|
||||
|
||||
int status = client.request(new RequestOptions().setHost("127.0.0.1").setPort(proxyPort)
|
||||
.setMethod(HttpMethod.POST).setURI("/aws_mwaa/login"))
|
||||
.compose(request -> {
|
||||
request.putHeader("Content-Type", "application/x-www-form-urlencoded");
|
||||
return request.send(Buffer.buffer("token=good-token"));
|
||||
})
|
||||
.map(response -> response.statusCode())
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(302, status);
|
||||
}
|
||||
|
||||
@Test
|
||||
void csrfTokenIsReadFromTheHiddenInputWhateverItsAttributeOrder() {
|
||||
assertEquals("abc", MwaaWebProxy.csrfToken("<input id=\"csrf_token\" name=\"csrf_token\" type=\"hidden\" "
|
||||
+ "value=\"abc\">"));
|
||||
assertEquals("abc", MwaaWebProxy.csrfToken("<input value=\"abc\" type=\"hidden\" name=\"csrf_token\">"));
|
||||
assertNull(MwaaWebProxy.csrfToken("<input name=\"username\" value=\"abc\">"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionCookieIsTheNameValuePairOfTheSessionSetCookie() {
|
||||
assertEquals("session=abc", MwaaWebProxy.sessionCookie(List.of("other=1; Path=/", "session=abc; HttpOnly")));
|
||||
assertNull(MwaaWebProxy.sessionCookie(List.of("other=1; Path=/")));
|
||||
}
|
||||
|
||||
private record LoginResponse(int statusCode, String location, List<String> cookies, String body) {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user