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

@@ -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) {
}
}