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:
Priamo Germosen authored and GitHub committed 2026-11-15 00:19:35 -04:00
1 parent 9bee320d83
commit 0baf1a1b79
11 files changed
+771 -25

No files matched your search

@@ -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;