feat(lambdaweb): serve the Lambda metadata endpoint (#6391)

* feat(lambdaweb): serve the Lambda metadata endpoint

AWS gives each environment AWS_LAMBDA_METADATA_API, AWS_LAMBDA_METADATA_TOKEN
and AWS_LAMBDA_RUNTIME_API, all at one server. It answers the zone id to a
Bearer token with any method, "Client.Unauthorized" with 401 to anything
else, Go's 404 to another path before the token, and a 307 to the clean
path.

* fix(lambdaweb): take the metadata port outside the Runtime API range

The width of that range is the Lambda concurrency, and its ports are only
reached over the Docker network, as any other port is. A listen that fails
now closes its server.

* fix(lambdaweb): start the metadata server before a start mints a session

A metadata server that could not start left the role session and the token
of an environment that never ran.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-23 23:05:55 -04:00
1 parent b9c67b75f7
commit 54b3db771a
6 files changed
+447 -19

No files matched your search

+3 -1
View File
@@ -68,7 +68,7 @@ The `Host` must match the domain exactly, as on AWS: another case or another por
A CloudFront distribution of this Floci can use the endpoint as a custom origin, named by its `domainName` without the port as on AWS. Under an `always-amz-auth` origin access control, CloudFront signs the requests to an `IamAuth` endpoint, and the function's resource policy has to allow `cloudfront.amazonaws.com` when IAM enforcement is on. See [CloudFront](cloudfront.md).
An execution environment is a `public.ecr.aws/lambda/nodejs:24` container that a request starts when every environment of the endpoint is full. The code is the revision's S3 object unpacked into `/var/task`. Node starts `/var/runtime/index.js` with the flags AWS uses, as on AWS, and that runtime imports `index.js` or the file `AWS_LAMBDA_NODEJS_ENTRYPOINT` names. So `require.main` is not the app's module, as on AWS. A `--max-old-space-size` or `--max-semi-space-size` in `NODE_OPTIONS` takes the place of both default heap flags, as on AWS. Other flags there do not replace a default flag, so `--max-http-header-size` in `NODE_OPTIONS` has no effect, and a flag Node does not allow in `NODE_OPTIONS` fails the start with `502 Runtime.ExitError`, as on AWS. The app sees `AWS_LAMBDA_HTTP_ENDPOINT=0.0.0.0:3000`, `AWS_LAMBDA_INITIALIZATION_TYPE=native-http`, `AWS_EXECUTION_ENV`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE=2048`, `AWS_LAMBDA_LOG_LEVEL`, `AWS_ACCOUNT_ID`, `AWS_REGION`, credentials and `AWS_ENDPOINT_URL` for Floci, `NODE_PATH`, and its own variables. The server has 9 seconds to listen. An environment that sees no request for `floci.services.lambda.container-idle-timeout-seconds` is stopped with `SIGTERM` and one second, as on scale to zero. Node runs under Docker's init, so a server without a `SIGTERM` handler stops at once, as on AWS. A process that exits between requests is replaced by a fresh environment on the next request.
An execution environment is a `public.ecr.aws/lambda/nodejs:24` container that a request starts when every environment of the endpoint is full. The code is the revision's S3 object unpacked into `/var/task`. Node starts `/var/runtime/index.js` with the flags AWS uses, as on AWS, and that runtime imports `index.js` or the file `AWS_LAMBDA_NODEJS_ENTRYPOINT` names. So `require.main` is not the app's module, as on AWS. A `--max-old-space-size` or `--max-semi-space-size` in `NODE_OPTIONS` takes the place of both default heap flags, as on AWS. Other flags there do not replace a default flag, so `--max-http-header-size` in `NODE_OPTIONS` has no effect, and a flag Node does not allow in `NODE_OPTIONS` fails the start with `502 Runtime.ExitError`, as on AWS. The app sees `AWS_LAMBDA_HTTP_ENDPOINT=0.0.0.0:3000`, `AWS_LAMBDA_INITIALIZATION_TYPE=native-http`, `AWS_EXECUTION_ENV`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE=2048`, `AWS_LAMBDA_LOG_LEVEL`, `AWS_LAMBDA_METADATA_API`, `AWS_LAMBDA_METADATA_TOKEN`, `AWS_LAMBDA_RUNTIME_API`, `AWS_ACCOUNT_ID`, `AWS_REGION`, credentials and `AWS_ENDPOINT_URL` for Floci, `NODE_PATH`, and its own variables. The server has 9 seconds to listen. An environment that sees no request for `floci.services.lambda.container-idle-timeout-seconds` is stopped with `SIGTERM` and one second, as on scale to zero. Node runs under Docker's init, so a server without a `SIGTERM` handler stops at once, as on AWS. A process that exits between requests is replaced by a fresh environment on the next request.
Each endpoint scales on its own, as on AWS. An environment takes up to the revision's `maxConcurrencyPerEnvironment` requests at once, the least busy one first, so requests rotate over the environments. A request that finds every environment full starts another one, or waits for one that is starting and has room. When the endpoint already runs `maxEnvironments`, an idle environment of another revision makes room, and without one the request is refused with `429` and `Platform.EndpointMaxEnvThrottle`. A `rateLimit` admits a burst of up to `rateLimit` requests that refills at `rateLimit` per second, and refuses the rest with `429` and `Platform.EndpointRequestThrottle`. AWS adjusts the concurrency of each environment under `maxConcurrencyPerEnvironment` from the measured load, so a burst there can spread over more environments than in Floci, and the account quotas are not applied.
@@ -80,6 +80,8 @@ The revision's `timeoutSeconds` bounds the whole exchange, as on AWS: a response
The container gets the execution role's session credentials, so SDK calls from the app land in the function's account. An environment assumes the role with the function ARN as `aws:SourceArn` and its account as `aws:SourceAccount`. When the role was deleted or no longer trusts Lambda, the request gets `502 Platform.CannotAssumeRole` and the revision stays `Active`, as on AWS.
The [metadata endpoint](https://docs.aws.amazon.com/lambda/latest/dg/configuration-metadata-endpoint.html) answers `GET http://${AWS_LAMBDA_METADATA_API}/2026-01-15/metadata/execution-environment` with `{"AvailabilityZoneID":"<id>"}` when the request carries `Authorization: Bearer ${AWS_LAMBDA_METADATA_TOKEN}`, and with `401` and `"Client.Unauthorized"` otherwise. As on AWS, it takes any method, has no `Cache-Control`, answers another path with `404` before it looks at the token, and redirects a path with `//`, `.` or `..` segments with `307`. `AWS_LAMBDA_RUNTIME_API` names the same server, as on AWS. The server listens on a port the system picks, outside the Lambda Runtime API range, at the host the container reaches Floci at, where AWS uses `169.254.100.1:9001`, and the zone is always the region's first zone id, such as `use1-az1`.
The platform answers these cases itself, with the AWS HTML pages and `lambda-web-error-type`:
| Status | Error type | When |
@@ -133,6 +133,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
/** Requests sent to the environment and not reported yet. Guarded by the environment. */
private int openExchanges;
private volatile SessionCreds roleCredentials;
private volatile String metadataToken;
private final AtomicInteger inFlight = new AtomicInteger();
private final AtomicLong lastUsed = new AtomicLong(System.nanoTime());
private final AtomicBoolean alive = new AtomicBoolean(true);
@@ -267,6 +268,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
private final LaunchedContainerAwsEnv awsEnv;
private final LambdaExecutionRoleCredentials executionRoleCredentials;
private final LambdaWebExecutionRole executionRole;
private final LambdaWebMetadataServer metadata;
private final LambdaWebLogs logs;
private final LambdaWebMetrics metrics;
private final byte[] runtime;
@@ -285,8 +287,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
EcrRegistryManager ecrRegistryManager, LambdaWebCode code,
ZipExtractor zipExtractor, LaunchedContainerAwsEnv awsEnv,
LambdaExecutionRoleCredentials executionRoleCredentials,
LambdaWebExecutionRole executionRole, LambdaWebLogs logs,
LambdaWebMetrics metrics) {
LambdaWebExecutionRole executionRole, LambdaWebMetadataServer metadata,
LambdaWebLogs logs, LambdaWebMetrics metrics) {
this.config = config;
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
@@ -298,6 +300,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
this.awsEnv = awsEnv;
this.executionRoleCredentials = executionRoleCredentials;
this.executionRole = executionRole;
this.metadata = metadata;
this.logs = logs;
this.metrics = metrics;
this.runtime = runtimeScript();
@@ -547,6 +550,8 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
if (!executionRole.assumableFor(region, fn.functionArn, revision.serviceConfig.executionRoleArn)) {
throw new StartFailure(LambdaWebErrorPages.CANNOT_ASSUME_ROLE);
}
// Before the session and the token, which a failed start must not leave behind.
String metadataApi = metadata.address();
String accountId = environment.accountId;
String image = ecrRegistryManager.rewriteImageUri(imageResolver.resolve(revision.buildConfig.runtime));
String shortId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
@@ -562,9 +567,11 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
if (roleCredentials.isEmpty()) {
throw new StartFailure(LambdaWebErrorPages.CANNOT_ASSUME_ROLE);
}
String metadataToken = metadata.register(region);
ContainerSpec spec = containerBuilder.newContainer(image)
.withName(name)
.withEnv(environment(accountId, region, revision, userEnv, roleCredentials))
.withEnv(environment(accountId, region, revision, userEnv, roleCredentials, metadataApi,
metadataToken))
.withEntrypoint(List.of("/var/lang/bin/node"))
.withCmd(cmd)
.withWorkingDir(TASK_DIR)
@@ -582,6 +589,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
containerId = lifecycleManager.create(spec);
} catch (RuntimeException e) {
roleCredentials.ifPresent(creds -> executionRoleCredentials.unregister(accountId, creds.accessKeyId()));
metadata.forget(metadataToken);
throw e;
}
LambdaWebPlatformLog platform = null;
@@ -607,6 +615,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
environment.host = endpoint.host();
environment.port = endpoint.port();
environment.roleCredentials = roleCredentials.orElse(null);
environment.metadataToken = metadataToken;
platform.invokeStart(environment.inFlight.get());
environment.summaries = reaper.scheduleAtFixedRate(() -> summarize(environment),
SUMMARY_PERIOD.toMillis(), SUMMARY_PERIOD.toMillis(), TimeUnit.MILLISECONDS);
@@ -631,6 +640,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
platform.spinDownReport(null, System.nanoTime() - stopping);
}
roleCredentials.ifPresent(creds -> executionRoleCredentials.unregister(accountId, creds.accessKeyId()));
metadata.forget(metadataToken);
throw e;
}
}
@@ -685,13 +695,18 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
}
private List<String> environment(String accountId, String region, WebFunctionRevision revision,
Map<String, String> userEnv, Optional<SessionCreds> roleCredentials) {
Map<String, String> userEnv, Optional<SessionCreds> roleCredentials,
String metadataApi, String metadataToken) {
List<String> env = new ArrayList<>();
env.add("AWS_LAMBDA_HTTP_ENDPOINT=0.0.0.0:" + APP_PORT);
env.add("AWS_LAMBDA_INITIALIZATION_TYPE=native-http");
env.add("AWS_EXECUTION_ENV=AWS_Lambda_" + revision.buildConfig.runtime + "-lite");
env.add("AWS_LAMBDA_FUNCTION_MEMORY_SIZE=" + MEMORY_MB);
env.add("AWS_LAMBDA_LOG_LEVEL=" + revision.serviceConfig.applicationLogLevel);
// AWS names the metadata server as the runtime API too, and it answers the runtime paths with 404.
env.add("AWS_LAMBDA_METADATA_API=" + metadataApi);
env.add("AWS_LAMBDA_METADATA_TOKEN=" + metadataToken);
env.add("AWS_LAMBDA_RUNTIME_API=" + metadataApi);
env.add("AWS_ACCOUNT_ID=" + accountId);
env.add("NODE_PATH=" + TASK_DIR);
env.addAll(awsEnv.sdkBaselineEnv(region, Optional.empty(), roleCredentials, accountId));
@@ -704,6 +719,7 @@ public class LambdaWebEnvironmentManager implements ContainerTeardown {
if (credentials != null) {
executionRoleCredentials.unregister(environment.accountId, credentials.accessKeyId());
}
metadata.forget(environment.metadataToken);
}
/** The code goes in by {@code docker cp}, so it works when Floci itself runs in a container. */
@@ -0,0 +1,202 @@
package io.github.hectorvent.floci.services.lambdaweb;
import io.github.hectorvent.floci.core.common.AvailabilityZoneIds;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
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.HttpVersion;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* The Lambda metadata endpoint that {@code AWS_LAMBDA_METADATA_API} names, which answers the zone
* id to a request with the environment's {@code AWS_LAMBDA_METADATA_TOKEN}. One server serves every
* environment, and the token tells them apart. Its port is one the system picks, so it takes none
* of the Runtime API range, whose width is the Lambda concurrency. AWS serves it with Go's
* {@code ServeMux}, so paths, redirects and the 404 follow that.
*/
@ApplicationScoped
public class LambdaWebMetadataServer {
private static final List<String> SEGMENTS = List.of("/2026-01-15/metadata/execution-environment".split("/", -1));
private static final String BEARER = "Bearer ";
private static final String JSON = "application/json";
private static final String TEXT = "text/plain; charset=utf-8";
private static final String HTML = "text/html; charset=utf-8";
private static final String UNAUTHORIZED = "\"Client.Unauthorized\"\n";
private static final String NOT_FOUND = "404 page not found\n";
private static final String NO_HOST = "Bad Request: missing required Host header";
private static final DateTimeFormatter HTTP_DATE =
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.ROOT).withZone(ZoneOffset.UTC);
private static final Logger LOG = Logger.getLogger(LambdaWebMetadataServer.class);
private final Vertx vertx;
private final ContainerReachableEndpoint reachableEndpoint;
private final Map<String, String> zones = new ConcurrentHashMap<>();
/** Guarded by this. */
private HttpServer server;
private int port;
@Inject
public LambdaWebMetadataServer(Vertx vertx, ContainerReachableEndpoint reachableEndpoint) {
this.vertx = vertx;
this.reachableEndpoint = reachableEndpoint;
}
/** A token for a new environment in {@code region}. Floci answers the region's first zone. */
String register(String region) {
String token = UUID.randomUUID().toString();
zones.put(token, AvailabilityZoneIds.forIndex(region, 1));
return token;
}
void forget(String token) {
if (token != null) {
zones.remove(token);
}
}
/** The host and port an environment reaches the server at, the host being the one it reaches Floci at. */
synchronized String address() {
if (server == null) {
start();
}
return URI.create(reachableEndpoint.baseUrl()).getHost() + ":" + port;
}
private void start() {
HttpServer created = vertx.createHttpServer(new HttpServerOptions().setHttp2ClearTextEnabled(false))
.requestHandler(this::handle);
try {
created.listen(0, "0.0.0.0").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
} catch (Exception e) {
created.close();
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new IllegalStateException("Could not start the Lambda Web metadata server", e);
}
server = created;
port = created.actualPort();
LOG.infov("Lambda Web metadata server started on port {0}", String.valueOf(port));
}
@PreDestroy
synchronized void stop() {
if (server != null) {
server.close();
server = null;
}
}
private void handle(HttpServerRequest request) {
HttpServerResponse response = request.response();
if (request.version() == HttpVersion.HTTP_1_1 && request.headers().get("Host") == null) {
response.setStatusCode(400).setStatusMessage(NO_HOST).putHeader("Content-Type", TEXT)
.putHeader("Connection", "close");
end(response, "400 " + NO_HOST).onComplete(ignored -> request.connection().close());
return;
}
String path = request.path();
String clean = LambdaWebIamAuth.signedPath(path);
if (!clean.equals(path)) {
redirect(request, clean + (request.query() == null ? "" : "?" + request.query()));
return;
}
if (!isMetadataPath(path)) {
response.putHeader("Content-Type", TEXT).putHeader("X-Content-Type-Options", "nosniff");
answer(request, 404, NOT_FOUND);
return;
}
response.putHeader("Content-Type", JSON);
String zone = zoneOf(request.headers().get("Authorization"));
if (zone == null) {
answer(request, 401, UNAUTHORIZED);
return;
}
answer(request, 200, "{\"AvailabilityZoneID\":\"" + zone + "\"}\n");
}
private String zoneOf(String authorization) {
if (authorization == null || !authorization.startsWith(BEARER)) {
return null;
}
return zones.get(authorization.substring(BEARER.length()));
}
/** Go matches each segment unescaped, so an escaped slash stays inside its segment. */
private static boolean isMetadataPath(String path) {
String[] segments = path.split("/", -1);
if (segments.length != SEGMENTS.size()) {
return false;
}
try {
for (int i = 0; i < segments.length; i++) {
if (!URLDecoder.decode(segments[i].replace("+", "%2B"), StandardCharsets.UTF_8).equals(SEGMENTS.get(i))) {
return false;
}
}
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/** Go's {@code http.Redirect}: a body for GET only, and a content type for GET and HEAD. */
private static void redirect(HttpServerRequest request, String location) {
HttpServerResponse response = request.response().setStatusCode(307);
HttpMethod method = request.method();
if (method == HttpMethod.GET || method == HttpMethod.HEAD) {
response.putHeader("Content-Type", HTML);
}
response.putHeader("Location", location).putHeader("Date", HTTP_DATE.format(Instant.now()));
if (method == HttpMethod.GET) {
end(response, "<a href=\"" + htmlEscape(location) + "\">Temporary Redirect</a>.\n\n");
} else if (method == HttpMethod.HEAD) {
response.end();
} else {
end(response, "");
}
}
private static void answer(HttpServerRequest request, int status, String body) {
HttpServerResponse response = request.response().setStatusCode(status)
.putHeader("Date", HTTP_DATE.format(Instant.now()));
if (request.method() == HttpMethod.HEAD) {
response.putHeader("Content-Length", String.valueOf(body.getBytes(StandardCharsets.UTF_8).length)).end();
} else {
end(response, body);
}
}
private static Future<Void> end(HttpServerResponse response, String body) {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
return response.putHeader("Content-Length", String.valueOf(bytes.length)).end(Buffer.buffer(bytes));
}
private static String htmlEscape(String value) {
return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&#34;").replace("'", "&#39;");
}
}
@@ -105,6 +105,16 @@ class LambdaWebDataPlaneDockerIntegrationTest {
if (req.url.startsWith('/status/')) {
res.writeHead(Number(req.url.split('/')[2]), {'x-app': 'yes'}); res.end('status body'); return;
}
if (req.url.startsWith('/metadata')) {
const url = 'http://' + process.env.AWS_LAMBDA_METADATA_API + '/2026-01-15/metadata/execution-environment';
const auth = {headers: {authorization: 'Bearer ' + process.env.AWS_LAMBDA_METADATA_TOKEN}};
Promise.all([fetch(url, auth), fetch(url)]).then(async ([ok, refused]) => {
res.end(JSON.stringify({status: ok.status, body: await ok.text(), refused: refused.status,
api: process.env.AWS_LAMBDA_METADATA_API, runtimeApi: process.env.AWS_LAMBDA_RUNTIME_API,
token: process.env.AWS_LAMBDA_METADATA_TOKEN}));
}, (e) => { res.statusCode = 500; res.end(String(e)); });
return;
}
if (req.url.startsWith('/crash')) { setTimeout(() => process.exit(1), 50); return; }
if (req.url.startsWith('/exit')) { res.end('bye', () => process.exit(0)); return; }
let body = '';
@@ -409,6 +419,20 @@ class LambdaWebDataPlaneDockerIntegrationTest {
.then().statusCode(200).header("lambda-web-logstream", not(equalTo(logStream)));
}
@Test
@Timeout(180)
void theMetadataEndpointAnswersTheZoneToTheEnvironmentToken() throws Exception {
String domain = createFunction(30);
JsonPath answer = given().header("Host", domain).when().get("/metadata").then().statusCode(200)
.extract().jsonPath();
assertEquals(200, answer.getInt("status"));
assertEquals("{\"AvailabilityZoneID\":\"use1-az1\"}\n", answer.getString("body"));
assertEquals(401, answer.getInt("refused"));
assertEquals(answer.getString("api"), answer.getString("runtimeApi"));
assertTrue(answer.getString("token").matches("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"));
}
@Test
@Timeout(180)
void anEnvironmentRunsTheCodeTheRevisionWasCreatedFrom() throws Exception {
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManager
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManager.StartFailure;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionRevision;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
@@ -29,6 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -38,6 +41,16 @@ class LambdaWebEnvironmentManagerTest {
"--no-experimental-require-module");
private static final List<String> DEFAULT_HEAP = List.of("--max-semi-space-size=102", "--max-old-space-size=1024");
private final LambdaWebExecutionRole executionRole = mock(LambdaWebExecutionRole.class);
private final LambdaExecutionRoleCredentials credentials = mock(LambdaExecutionRoleCredentials.class);
private final LambdaWebMetadataServer metadata = mock(LambdaWebMetadataServer.class);
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
@BeforeEach
void trustTheRole() {
when(executionRole.assumableFor(any(), any(), any())).thenReturn(true);
}
@Test
void heapFlagsInNodeOptionsReplaceBothDefaultHeapFlags() {
assertEquals(flags(DEFAULT_HEAP), LambdaWebEnvironmentManager.nodeFlags(null));
@@ -74,17 +87,23 @@ class LambdaWebEnvironmentManagerTest {
@Test
void aRoleDeletedAfterTheTrustCheckStartsNoContainer() {
LambdaWebExecutionRole executionRole = mock(LambdaWebExecutionRole.class);
when(executionRole.assumableFor(any(), any(), any())).thenReturn(true);
LambdaExecutionRoleCredentials credentials = mock(LambdaExecutionRoleCredentials.class);
when(credentials.forRole(any(), any(), any())).thenReturn(Optional.empty());
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
LambdaWebEnvironmentManager manager = new LambdaWebEnvironmentManager(
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), containerBuilder,
mock(ContainerLifecycleManager.class), mock(DockerClient.class), mock(ImageResolver.class),
mock(EcrRegistryManager.class), mock(LambdaWebCode.class), mock(ZipExtractor.class),
mock(LaunchedContainerAwsEnv.class), credentials, executionRole, mock(LambdaWebLogs.class),
mock(LambdaWebMetrics.class));
StartFailure failure = assertThrows(StartFailure.class, this::acquire);
assertEquals(LambdaWebErrorPages.CANNOT_ASSUME_ROLE, failure.page());
verifyNoInteractions(containerBuilder);
}
@Test
void aMetadataServerThatCannotStartLeavesNoSessionOrToken() {
when(metadata.address()).thenThrow(new IllegalStateException("no port"));
assertThrows(IllegalStateException.class, this::acquire);
verifyNoInteractions(credentials, containerBuilder);
verify(metadata, never()).register(any());
}
private void acquire() {
WebFunction fn = new WebFunction();
fn.functionName = "fn";
fn.functionArn = "arn:aws:lambda:us-east-1:000000000000:web-function/fn";
@@ -92,11 +111,14 @@ class LambdaWebEnvironmentManagerTest {
revision.revisionId = "1";
revision.buildConfig.runtime = "nodejs24.x";
revision.serviceConfig.executionRoleArn = "arn:aws:iam::000000000000:role/web";
LambdaWebEnvironmentManager manager = new LambdaWebEnvironmentManager(
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), containerBuilder,
mock(ContainerLifecycleManager.class), mock(DockerClient.class), mock(ImageResolver.class),
mock(EcrRegistryManager.class), mock(LambdaWebCode.class), mock(ZipExtractor.class),
mock(LaunchedContainerAwsEnv.class), credentials, executionRole, metadata,
mock(LambdaWebLogs.class), mock(LambdaWebMetrics.class));
try {
StartFailure failure = assertThrows(StartFailure.class,
() -> manager.acquire("000000000000", "us-east-1", fn, "endpoint", null, revision));
assertEquals(LambdaWebErrorPages.CANNOT_ASSUME_ROLE, failure.page());
verifyNoInteractions(containerBuilder);
manager.acquire("000000000000", "us-east-1", fn, "endpoint", null, revision);
} finally {
manager.shutdown();
}
@@ -0,0 +1,162 @@
package io.github.hectorvent.floci.services.lambdaweb;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.vertx.core.Vertx;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class LambdaWebMetadataServerTest {
private static final String PATH = "/2026-01-15/metadata/execution-environment";
private static final String ZONE = "{\"AvailabilityZoneID\":\"use1-az1\"}\n";
private static final String UNAUTHORIZED = "\"Client.Unauthorized\"\n";
private static final String NOT_FOUND = "404 page not found\n";
private static final String HTTP_DATE = "[A-Z][a-z]{2}, \\d{2} [A-Z][a-z]{2} \\d{4} \\d{2}:\\d{2}:\\d{2} GMT";
private final Vertx vertx = Vertx.vertx();
private LambdaWebMetadataServer server;
private int port;
private String token;
@BeforeEach
void start() {
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
when(endpoint.baseUrl()).thenReturn("http://floci.test:4566");
server = new LambdaWebMetadataServer(vertx, endpoint);
token = server.register("us-east-1");
String address = server.address();
assertTrue(address.matches("floci\\.test:\\d+"), address);
port = Integer.parseInt(address.substring(address.indexOf(':') + 1));
}
@AfterEach
void stop() {
server.stop();
vertx.close();
}
@Test
void theEnvironmentTokenGetsTheZoneWithAnyMethod() throws IOException {
Answer ok = send(request("GET", PATH, "Bearer " + token));
assertEquals("HTTP/1.1 200 OK", ok.status);
assertEquals("application/json", ok.headers.get("Content-Type"));
assertEquals("34", ok.headers.get("Content-Length"));
assertTrue(ok.headers.get("Date").matches(HTTP_DATE), ok.headers.get("Date"));
assertFalse(ok.headers.containsKey("Cache-Control"));
assertEquals(ZONE, ok.body);
for (String method : new String[] {"POST", "PUT", "DELETE", "PATCH", "OPTIONS", "FOO"}) {
assertEquals(ZONE, send(request(method, PATH, "Bearer " + token)).body, method);
}
assertEquals(ZONE, send(request("GET", PATH + "?a=1", "Bearer " + token + " ")).body);
assertEquals(ZONE, send(request("GET", "/2026-01-15/metadata/execution%2Denvironment", "Bearer " + token)).body);
assertEquals(ZONE, send(request("GET", "http://example.com" + PATH, "Bearer " + token)).body);
assertEquals(ZONE, send("GET " + PATH + " HTTP/1.0\r\nAuthorization: Bearer " + token + "\r\n\r\n").body);
Answer head = send(request("HEAD", PATH, "Bearer " + token));
assertEquals("HTTP/1.1 200 OK", head.status);
assertEquals("34", head.headers.get("Content-Length"));
assertEquals("", head.body);
}
@Test
void anyOtherAuthorizationIsUnauthorized() throws IOException {
for (String authorization : new String[] {null, "Bearer x" + token.substring(1), "bearer " + token,
"Bearer " + token, "Bearer\t" + token, token, "Bearer ", "Bearer " + token.toUpperCase()}) {
Answer refused = send(request("GET", PATH, authorization));
assertEquals("HTTP/1.1 401 Unauthorized", refused.status, authorization);
assertEquals("application/json", refused.headers.get("Content-Type"));
assertEquals("22", refused.headers.get("Content-Length"));
assertEquals(UNAUTHORIZED, refused.body);
}
server.forget(token);
assertEquals(UNAUTHORIZED, send(request("GET", PATH, "Bearer " + token)).body);
}
@Test
void anotherPathIsNotFoundBeforeTheTokenIsChecked() throws IOException {
for (String path : new String[] {"/", PATH + "/", PATH.replace("metadata", "Metadata"),
"/2026-01-15/metadata%2Fexecution-environment", PATH + "#x", "/2018-06-01/runtime/invocation/next"}) {
Answer missing = send(request("GET", path, null));
assertEquals("HTTP/1.1 404 Not Found", missing.status, path);
assertEquals("text/plain; charset=utf-8", missing.headers.get("Content-Type"));
assertEquals("nosniff", missing.headers.get("X-Content-Type-Options"));
assertEquals(NOT_FOUND, missing.body);
}
Answer head = send(request("HEAD", "/", null));
assertEquals("19", head.headers.get("Content-Length"));
assertEquals("", head.body);
}
@Test
void anUncleanPathIsRedirectedToItsCleanForm() throws IOException {
Answer get = send(request("GET", "/2026-01-15//metadata/execution-environment?a=1&b=%20", null));
assertEquals("HTTP/1.1 307 Temporary Redirect", get.status);
assertEquals("text/html; charset=utf-8", get.headers.get("Content-Type"));
assertEquals(PATH + "?a=1&b=%20", get.headers.get("Location"));
assertEquals("<a href=\"" + PATH + "?a=1&amp;b=%20\">Temporary Redirect</a>.\n\n", get.body);
assertEquals("92", get.headers.get("Content-Length"));
assertEquals(PATH, send(request("GET", "/2026-01-15/metadata/./execution-environment", null))
.headers.get("Location"));
assertEquals(PATH, send(request("GET", PATH + "/.", null)).headers.get("Location"));
assertEquals("/x", send(request("GET", "//x", null)).headers.get("Location"));
Answer post = send(request("POST", "//x", null));
assertEquals("HTTP/1.1 307 Temporary Redirect", post.status);
assertFalse(post.headers.containsKey("Content-Type"));
assertEquals("0", post.headers.get("Content-Length"));
Answer head = send(request("HEAD", "//x", null));
assertEquals("text/html; charset=utf-8", head.headers.get("Content-Type"));
assertFalse(head.headers.containsKey("Content-Length"));
}
@Test
void anHttp11RequestWithoutHostIsBadRequest() throws IOException {
Answer refused = send("GET " + PATH + " HTTP/1.1\r\nAuthorization: Bearer " + token + "\r\n\r\n");
assertEquals("HTTP/1.1 400 Bad Request: missing required Host header", refused.status);
assertEquals("text/plain; charset=utf-8", refused.headers.get("Content-Type"));
assertFalse(refused.headers.containsKey("Date"));
assertEquals("400 Bad Request: missing required Host header", refused.body);
}
private static String request(String method, String target, String authorization) {
return method + " " + target + " HTTP/1.1\r\nHost: 169.254.100.1:9001\r\n"
+ (authorization == null ? "" : "Authorization: " + authorization + "\r\n")
+ "Connection: close\r\n\r\n";
}
private Answer send(String request) throws IOException {
try (Socket socket = new Socket("127.0.0.1", port)) {
socket.setSoTimeout(5000);
socket.getOutputStream().write(request.getBytes(StandardCharsets.ISO_8859_1));
InputStream in = socket.getInputStream();
String raw = new String(in.readAllBytes(), StandardCharsets.ISO_8859_1);
int end = raw.indexOf("\r\n\r\n");
String[] lines = raw.substring(0, end).split("\r\n");
Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (int i = 1; i < lines.length; i++) {
String[] header = lines[i].split(": ", 2);
headers.put(header[0], header[1]);
}
return new Answer(lines[0], headers, raw.substring(end + 4));
}
}
private record Answer(String status, Map<String, String> headers, String body) {
}
}