Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambda,iam): assume execution role for in-function SDK calls (#1909)
TiM573d4bdaffc9
diff --git a/docs/services/lambda.md b/docs/services/lambda.mdindex 98fe624c15..a804c8dda1 100644--- a/docs/services/lambda.md+++ b/docs/services/lambda.md@@ -81,7 +81,7 @@ aws lambda invoke --function-name my-function out.json## Hot-Reload via Bind Mount-For the tightest inner-loop development cycle, Floci supports a **bind-mount hot-reload** mode. Instead of packaging code into a ZIP and uploading it to S3, you point Floci directly at a directory on your host machine. The directory is bind-mounted into `/var/task` inside the container, so every invocation runs the files as they currently exist on disk — no upload, no redeploy.+For the tightest inner-loop development cycle, Floci supports a **bind-mount hot-reload** mode. Instead of packaging code into a ZIP and uploading it to S3, you point Floci directly at a directory on your host machine. The directory is bind-mounted into `/var/task` inside the container, so every invocation runs the files as they currently exist on disk, with no upload or redeploy.This is enabled by using the magic bucket name `hot-reload` when creating a function:@@ -101,7 +101,7 @@ The `S3Key` must be an **absolute path** reachable by the Docker daemon. When Fl1. `CreateFunction` with `S3Bucket=hot-reload` marks the function as a hot-reload function; `S3Key` is stored as the host-side path.2. On each invocation, Floci starts a **fresh ephemeral container** with the host path bind-mounted at `/var/task`.-3. The container executes the files as they exist at invocation time — editing a file and immediately invoking picks up the change without any API call.+3. The container executes the files as they exist at invocation time. Editing a file and immediately invoking picks up the change without any API call.4. After the invocation completes the container is stopped and removed, ensuring the next invocation always sees the current state of the directory.### Configuration@@ -115,7 +115,7 @@ FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=trueFLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS=/home/user/projects,/tmp```-**Docker Compose setup** — enable the feature and share the Docker socket:+**Docker Compose setup**: enable the feature and share the Docker socket:```yamlservices:@@ -129,9 +129,9 @@ services:### Limitations- The `S3Key` path is interpreted by the **Docker daemon**, not by Floci. When Floci itself runs inside Docker, the path must exist on the Docker host machine, not inside the Floci container.-- Hot-reload containers are always ephemeral — there is no warm-container reuse. Each invocation pays a cold-start penalty.+- Hot-reload containers are always ephemeral, so there is no warm-container reuse. Each invocation pays a cold-start penalty.- `UpdateFunctionCode` on a hot-reload function converts it back to a standard Zip function (the hot-reload bind-mount is removed).-- S3 reactive sync is skipped for hot-reload functions — edits are picked up directly from disk.+- S3 reactive sync is skipped for hot-reload functions because edits are picked up directly from disk.### Difference from Reactive S3 Sync@@ -146,7 +146,7 @@ services:!!! note "Concurrency enforcement"Reserved concurrency is enforced: invocations beyond the reserved valuereturn `TooManyRequestsException` (HTTP 429). Functions without a reserved- value share a **per-region** pool — AWS Lambda's "account-level" limit is+ value share a **per-region** pool. AWS Lambda's "account-level" limit isin fact a per-account-per-region quota, and Floci mirrors that bypartitioning counters on the ARN's region segment. The pool size (default1000) is configurable via `floci.services.lambda.region-concurrency-limit`@@ -157,7 +157,7 @@ services:and related provisioned-concurrency operations remain unimplemented.Reducing or clearing a function's reserved value does not kill- invocations that are already in flight — this matches AWS, which+ invocations that are already in flight. This matches AWS, whichapplies changes only to new invocations. As a consequence, during thedrain window `Σreserved-inflight + unreserved-inflight` can brieflyexceed `region-concurrency-limit`.@@ -206,7 +206,7 @@ for that callback (its own container IP on the shared network, or`host.docker.internal` when running on the host). In most setups this iscorrect and needs no configuration.-On unusual network topologies — for example rootless Podman — auto-detection+On unusual network topologies, for example rootless Podman, auto-detectioncan pick an address the Lambda container cannot reach, and invocations fail with`connect ECONNREFUSED <ip>:9200`. Set `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE`to the host or IP that containers can actually reach Floci on, and Floci uses it@@ -238,7 +238,7 @@ AWS SDKs use **virtual-hosted-style** S3 addressing by default, forming URLs likWhen Floci runs **inside Docker**, Lambda containers are on the same Dockernetwork. Docker's embedded DNS resolves the exact alias `localhost.floci.io`-correctly, but has no wildcard support — `my-bucket.localhost.floci.io`+correctly, but has no wildcard support. `my-bucket.localhost.floci.io`falls through to public DNS and resolves to the wrong IP, causing the Lambdainvocation to time out.@@ -251,7 +251,7 @@ use it as their DNS resolver. The embedded DNS server:falling back to public resolvers so **public hostnames** (e.g.`business-api.tiktok.com`) resolve from inside Lambda containers-No extra configuration or `cap_add` is needed — Docker containers have+No extra configuration or `cap_add` is needed because Docker containers have`CAP_NET_BIND_SERVICE` in their default capability set, so Floci (running as anon-root user) can bind UDP/53 without any changes to your Compose file.@@ -308,7 +308,7 @@ If your Lambda functions have `AWS_ENDPOINT_URL=http://localhost.localstack.clouhardcoded, add the LocalStack suffix to Floci's DNS resolver so it resolves toFloci's IP without any function-side changes:-Via environment variable — use a comma-separated list for multiple suffixes:+Via environment variable, use a comma-separated list for multiple suffixes:```bash# Single suffix@@ -320,9 +320,9 @@ FLOCI_DNS_EXTRA_SUFFIXES=localhost.localstack.cloud,localhost.example.internal### Real AWS Credentials-By default, Floci injects placeholder credentials (`test`/`test`/`test`) into Lambda containers. This is sufficient when all SDK calls target Floci's emulated services.+By default, a Lambda function whose execution role exists in Floci's IAM store receives temporary credentials for that role. SDK calls made by the function identify as `assumed-role/<role>/floci-session`, and IAM enforcement evaluates the role's policies. If the role is unknown to Floci, the container keeps the compatibility fallback described below.-For hybrid local/cloud testing — where some services are emulated and others hit real AWS — you can mount your host `~/.aws` directory into Lambda containers:+For hybrid local/cloud testing, where some services are emulated and others hit real AWS, you can mount your host `~/.aws` directory into Lambda containers:```yamlservices:@@ -340,7 +340,7 @@ When `aws-config-path` is set:- `AWS_SHARED_CREDENTIALS_FILE` and `AWS_CONFIG_FILE` env vars are set so the SDK discovers credentials regardless of the container's HOME directory- No `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN` env vars are injected-When unset (default), Floci reads credentials from its own environment and falls back to `test`/`test`/`test`.+When unset (default), Floci injects execution-role credentials for a known role. For an unknown role, Floci reads credentials from its own environment and falls back to `test`/`test`/`test`.!!! tip "Routing specific services to real AWS"To keep some services on Floci while others hit real AWS, clear the global endpoint and set service-specific overrides in your function's `--environment`:@@ -354,7 +354,7 @@ When unset (default), Floci reads credentials from its own environment and fallsThe AWS SDK supports `AWS_ENDPOINT_URL_<SERVICE>` natively. Services without an override will use real AWS endpoints.!!! note "Credential passthrough without mounting"- If you don't need the full `~/.aws` directory (e.g., you only have static credentials), you can pass them to Floci's environment directly. When `aws-config-path` is unset, Floci forwards its own `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` env vars into Lambda containers:+ For functions whose execution role is unknown to Floci, you can pass static credentials to Floci's environment directly. When `aws-config-path` is unset, Floci forwards its own `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` env vars into those Lambda containers:```yamlenvironment:@@ -363,6 +363,16 @@ When unset (default), Floci reads credentials from its own environment and fallsAWS_SESSION_TOKEN: ${AWS_SESSION_TOKEN}```+ A known execution role takes precedence over `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` values in the function environment. Use `aws-config-path` when the function must use mounted credentials instead of its emulated execution role.++ Passthrough is on whenever those three variables are set in Floci's own environment, so a+ Floci started from a shell that exports real AWS credentials (`aws-vault exec`, a sourced+ credentials file, a CI runner) hands them to any function whose role it does not know. An+ `AWS_PROFILE` or an `aws sso login` alone does not do this: those populate config and cache+ files, not the environment. Floci logs a `WARN` carrying the forwarded access-key prefix the+ first time it happens. Give the function a role Floci knows, or set `aws-config-path`, to keep+ host credentials out of the container.+### Private registry authenticationContainer image functions (`"PackageType": "Image"`) that pull from private registries need Docker credentials. See [Docker Configuration → Private Registry Authentication](../configuration/docker.md#private-registry-authentication) for the full guide.@@ -454,7 +464,7 @@ aws lambda create-event-source-mapping \Validation mirrors AWS: values outside 2–1000 are rejected with`InvalidParameterValueException`, and `ScalingConfig` on a non-SQS event-source (Kinesis / DynamoDB Streams) is also rejected — those services+source (Kinesis / DynamoDB Streams) is also rejected. Those servicesuse `ParallelizationFactor` instead, which is a separate field.!!! note "Enforcement status"diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 491f1f1686..6d45d36839 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -1507,8 +1507,9 @@ public interface EmulatorConfig {* When set, no AWS credential env vars are injected; instead* AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE are set to point at* the mounted files, ensuring SDK discovery works regardless of container HOME.- * When absent, Floci injects credentials from its own environment- * (AWS_ACCESS_KEY_ID, etc.) or falls back to test/test/test.+ * When absent, a function whose execution role exists in Floci receives temporary+ * credentials for that role. Functions with an unknown role retain the compatibility+ * fallback to Floci's own AWS credential environment or test/test/test.* Blank values are treated as absent.** Env var: FLOCI_SERVICES_LAMBDA_AWS_CONFIG_PATHdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex 0f655098a4..11b71099c6 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java@@ -33,6 +33,7 @@ import java.util.regex.Pattern;* <li>Access key is {@code "test"} (root/admin stand-in)</li>* <li>Access key is not found in the IAM store (backward-compatible with pre-existing credentials)</li>* <li>The action cannot be resolved (unknown mapping → permissive)</li>+ * <li>The action is {@code sts:GetCallerIdentity}, which AWS allows without permissions</li>* </ul>** <p>Evaluates the caller's identity policies, optional session policy, and optional@@ -115,6 +116,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {if (action == null) {return; // unknown action → ALLOW (permissive)}+ if ("sts:GetCallerIdentity".equals(action)) {+ return; // AWS returns caller identity even when an identity policy explicitly denies it+ }CallerContext caller = iamService.resolveCallerContext(akid);if (caller == null) {diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnv.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnv.javaindex 9d56bf8c5f..5d63cc4f67 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnv.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnv.java@@ -1,28 +1,35 @@package io.github.hectorvent.floci.core.common.docker;+import io.github.hectorvent.floci.services.iam.model.SessionCreds;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;+import org.jboss.logging.Logger;import java.net.URI;import java.util.ArrayList;import java.util.List;import java.util.Optional;+import java.util.concurrent.atomic.AtomicBoolean;/*** Builds the baseline AWS SDK environment for a container Floci launches, so the workload- * inside it can reach the emulator with working credentials — the same variables regardless of- * whether the container is a Lambda function or an ECS task.+ * inside it can reach the emulator with working credentials. It uses the same variables+ * regardless of whether the container is a Lambda function or an ECS task.** <p>Emulator-style, matching how a local AWS emulator satisfies the SDK credential-provider- * chain: the SDK is pointed at Floci via {@code AWS_ENDPOINT_URL} and given placeholder- * credentials (Floci does not verify request signatures). This mirrors how AWS itself supplies- * credentials to a launched workload — Lambda via its execution role, an ECS task via its task- * role — so that in either case the container starts with usable credentials rather than an+ * chain: the SDK is pointed at Floci via {@code AWS_ENDPOINT_URL} and given injected workload,+ * host, or placeholder credentials. This mirrors how AWS itself supplies credentials to a+ * launched workload, so the container starts with usable credentials rather than an* empty provider chain ({@code Could not load credentials from any providers}).*/@ApplicationScopedpublic class LaunchedContainerAwsEnv {+ private static final Logger LOG = Logger.getLogger(LaunchedContainerAwsEnv.class);++ /** Host-credential passthrough is a property of the process, so it is worth saying once. */+ private static final AtomicBoolean hostCredentialsWarned = new AtomicBoolean();+private final ContainerReachableEndpoint reachableEndpoint;@Inject@@ -37,23 +44,47 @@ public class LaunchedContainerAwsEnv {* @param region the AWS region the container should use* @param awsConfigMountDir in-container directory of a mounted AWS config/credentials* directory (as in {@code ~/.aws}); when present the SDK discovers- * credentials from there. Empty = inject placeholder credentials.+ * credentials from there. Empty = inject host or placeholder credentials.*/public List<String> sdkBaselineEnv(String region, Optional<String> awsConfigMountDir) {+ return sdkBaselineEnv(region, awsConfigMountDir, Optional.empty());+ }++ /**+ * Builds the baseline environment with optional workload-specific session credentials.+ * Mounted AWS configuration takes precedence over both injected and fallback credentials.+ */+ public List<String> sdkBaselineEnv(String region, Optional<String> awsConfigMountDir,+ Optional<SessionCreds> injectedCredentials) {List<String> env = new ArrayList<>();env.add("AWS_DEFAULT_REGION=" + region);env.add("AWS_REGION=" + region);if (awsConfigMountDir.isPresent() && !awsConfigMountDir.get().isBlank()) {- // ~/.aws is mounted — don't inject credentials, let the SDK discover them.+ // ~/.aws is mounted, so don't inject credentials. Let the SDK discover them.// Set explicit file paths so discovery works regardless of container HOME.String dir = awsConfigMountDir.get();env.add("AWS_SHARED_CREDENTIALS_FILE=" + dir + "/credentials");env.add("AWS_CONFIG_FILE=" + dir + "/config");+ } else if (injectedCredentials.isPresent()) {+ SessionCreds credentials = injectedCredentials.get();+ env.add("AWS_ACCESS_KEY_ID=" + credentials.accessKeyId());+ env.add("AWS_SECRET_ACCESS_KEY=" + credentials.secretAccessKey());+ env.add("AWS_SESSION_TOKEN=" + credentials.sessionToken());} else {// Use Floci's own env vars, falling back to placeholder credentials.String ak = System.getenv("AWS_ACCESS_KEY_ID");String sk = System.getenv("AWS_SECRET_ACCESS_KEY");String st = System.getenv("AWS_SESSION_TOKEN");+ if ((ak != null || sk != null || st != null) && hostCredentialsWarned.compareAndSet(false, true)) {+ // The container runs workload code, so surface that it is being handed the+ // credentials Floci itself was started with (an exported key pair, aws-vault, a+ // CI runner) rather than placeholders. Mount ~/.aws via aws-config-path, or give+ // the workload a role Floci knows, to keep host credentials out of it.+ // Once per process: ephemeral containers relaunch per invocation, and a warning+ // repeated on every launch is one people learn to scroll past.+ LOG.warnf("Forwarding Floci's own AWS credentials from the environment "+ + "(AWS_ACCESS_KEY_ID=%s...) into launched containers", abbreviate(ak));+ }env.add("AWS_ACCESS_KEY_ID=" + (ak != null ? ak : "test"));env.add("AWS_SECRET_ACCESS_KEY=" + (sk != null ? sk : "test"));env.add("AWS_SESSION_TOKEN=" + (st != null ? st : "test"));@@ -64,4 +95,12 @@ public class LaunchedContainerAwsEnv {env.add("AWS_ENDPOINT_URL=" + flociEndpoint);return env;}++ /** Enough of an access key to identify which credentials leaked, without logging the key. */+ private static String abbreviate(String accessKeyId) {+ if (accessKeyId == null || accessKeyId.isBlank()) {+ return "<unset>";+ }+ return accessKeyId.length() <= 4 ? accessKeyId : accessKeyId.substring(0, 4);+ }}diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.javaindex 0e3c1d6211..f5058b6290 100644--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;import io.github.hectorvent.floci.services.floci.ui.FlociUiManager;import io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager;import io.github.hectorvent.floci.services.kinesisanalytics.container.FlinkContainerManager;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;@@ -65,6 +66,7 @@ public class EmulatorLifecycle {private final StorageFactory storageFactory;private final ServiceRegistry serviceRegistry;private final EmulatorConfig config;+ private final IamService iamService;private final ElastiCacheContainerManager elastiCacheContainerManager;private final ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager;private final ElastiCacheProxyManager elastiCacheProxyManager;@@ -95,6 +97,7 @@ public class EmulatorLifecycle {@Injectpublic EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,EmulatorConfig config,+ IamService iamService,ElastiCacheContainerManager elastiCacheContainerManager,ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager,ElastiCacheProxyManager elastiCacheProxyManager,@@ -124,6 +127,7 @@ public class EmulatorLifecycle {this.storageFactory = storageFactory;this.serviceRegistry = serviceRegistry;this.config = config;+ this.iamService = iamService;this.elastiCacheContainerManager = elastiCacheContainerManager;this.elastiCacheMemcachedContainerManager = elastiCacheMemcachedContainerManager;this.elastiCacheProxyManager = elastiCacheProxyManager;@@ -174,6 +178,10 @@ public class EmulatorLifecycle {serviceRegistry.logEnabledServices();storageFactory.loadAll();+ int sweptSessions = iamService.sweepOrphanedLambdaExecutionRoleSessions();+ if (sweptSessions > 0) {+ LOG.infov("Removed {0} orphaned Lambda execution-role session(s)", sweptSessions);+ }schemaCreationWorker.recoverOrphans();schemaCreationWorker.rehydrateSchemas();diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex 3828d72818..68eabbcb22 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -1576,6 +1576,60 @@ public class IamService implements SessionAccountLookup {sessionPolicyDocument, originAccountId));}+ /**+ * Stores a non-expiring session for a Lambda execution role under the function's account.+ * Lambda launches can happen outside request scope, so the account namespace must be explicit.+ */+ public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId,+ String secretAccessKey, String roleArn) {+ if (accountId == null || accountId.isBlank()) {+ throw new IllegalArgumentException("Lambda function account ID must not be blank");+ }+ SessionCredential session = new SessionCredential(+ sessionAccessKeyId, secretAccessKey, roleArn, null, null, accountId);+ session.setLambdaExecutionRole(true);+ if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {+ aware.putForAccount(accountId, sessionAccessKeyId, session);+ } else {+ sessions.put(sessionAccessKeyId, session);+ }+ LOG.debugv("Registered Lambda execution-role session {0} under account {1} for {2}",+ sessionAccessKeyId, accountId, roleArn);+ }++ /** Removes a session from an explicit account namespace. */+ public void unregisterSession(String accountId, String sessionAccessKeyId) {+ if (sessionAccessKeyId == null || sessionAccessKeyId.isBlank()) {+ return;+ }+ if (accountId != null && !accountId.isBlank()+ && sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {+ aware.deleteForAccount(accountId, sessionAccessKeyId);+ } else {+ sessions.delete(sessionAccessKeyId);+ }+ LOG.debugv("Unregistered session {0} from account {1}", sessionAccessKeyId, accountId);+ }++ /**+ * Removes persisted Lambda-owned sessions left behind by a previous process. No Lambda+ * containers survive a Floci restart, so every marked session is orphaned at startup.+ */+ public int sweepOrphanedLambdaExecutionRoleSessions() {+ List<SessionCredential> storedSessions = sessions instanceof AccountAwareStorageBackend<SessionCredential> aware+ ? aware.scanAllAccounts()+ : sessions.scan(key -> true);+ int removed = 0;+ for (SessionCredential session : storedSessions) {+ if (!session.isLambdaExecutionRole()) {+ continue;+ }+ deleteSession(session.getAccessKeyId(), session);+ removed++;+ }+ return removed;+ }+/*** Resolves the account a temporary access key belongs to: the account encoded in the* session's role (or federated-user) ARN when present, otherwise the caller account captureddiff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.javaindex 5513f51457..887b60a61d 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java@@ -20,6 +20,8 @@ public class SessionCredential {* temporary credentials that carry no role ARN (e.g. GetSessionToken) back to the caller.*/private String originAccountId;+ /** True when this session belongs to a Floci-launched Lambda container. */+ private boolean lambdaExecutionRole;public SessionCredential() {}@@ -72,4 +74,7 @@ public class SessionCredential {public String getOriginAccountId() { return originAccountId; }public void setOriginAccountId(String originAccountId) { this.originAccountId = originAccountId; }++ public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }+ public void setLambdaExecutionRole(boolean lambdaExecutionRole) { this.lambdaExecutionRole = lambdaExecutionRole; }}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCreds.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCreds.javanew file mode 100644index 0000000000..93f756676e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCreds.java@@ -0,0 +1,5 @@+package io.github.hectorvent.floci.services.iam.model;++/** Temporary AWS credentials injected into an emulated workload. */+public record SessionCreds(String accessKeyId, String secretAccessKey, String sessionToken) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.javaindex 7e78bd1487..ac1f85a941 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerHandle.java@@ -15,6 +15,8 @@ public class ContainerHandle {private final RuntimeApiServer runtimeApiServer;private final long createdAt;private final boolean hotReload;+ private final String executionRoleAccessKeyId;+ private final String executionRoleSessionAccountId;private volatile ContainerState state;private volatile long lastUsedMs;private Closeable logStream;@@ -26,11 +28,19 @@ public class ContainerHandle {public ContainerHandle(String containerId, String functionName,RuntimeApiServer runtimeApiServer, ContainerState state, boolean hotReload) {+ this(containerId, functionName, runtimeApiServer, state, hotReload, null, null);+ }++ public ContainerHandle(String containerId, String functionName,+ RuntimeApiServer runtimeApiServer, ContainerState state, boolean hotReload,+ String executionRoleAccessKeyId, String executionRoleSessionAccountId) {this.containerId = containerId;this.functionName = functionName;this.runtimeApiServer = runtimeApiServer;this.state = state;this.hotReload = hotReload;+ this.executionRoleAccessKeyId = executionRoleAccessKeyId;+ this.executionRoleSessionAccountId = executionRoleSessionAccountId;this.createdAt = System.currentTimeMillis();this.lastUsedMs = this.createdAt;}@@ -38,6 +48,8 @@ public class ContainerHandle {public String getContainerId() { return containerId; }public String getFunctionName() { return functionName; }public boolean isHotReload() { return hotReload; }+ public String getExecutionRoleAccessKeyId() { return executionRoleAccessKeyId; }+ public String getExecutionRoleSessionAccountId() { return executionRoleSessionAccountId; }public RuntimeApiServer getRuntimeApiServer() { return runtimeApiServer; }public long getCreatedAt() { return createdAt; }public long getLastUsedMs() { return lastUsedMs; }diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.javaindex d7f66aa32b..eb7f393575 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;+import io.github.hectorvent.floci.services.iam.model.SessionCreds;import io.github.hectorvent.floci.services.lambda.LambdaLayerService;import io.github.hectorvent.floci.services.lambda.model.ContainerState;import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;@@ -90,6 +91,7 @@ public class ContainerLauncher {private final EcrRegistryManager ecrRegistryManager;private final LambdaLayerService layerService;private final LaunchedContainerAwsEnv awsEnv;+ private final LambdaExecutionRoleCredentials executionRoleCredentials;/** Matches an AWS-shaped ECR image URI: {@code <account>.dkr.ecr.<region>.amazonaws.com/<repo>[:tag]}. */private static final java.util.regex.Pattern AWS_ECR_URI =@@ -105,7 +107,8 @@ public class ContainerLauncher {EmulatorConfig config,EcrRegistryManager ecrRegistryManager,LambdaLayerService layerService,- LaunchedContainerAwsEnv awsEnv) {+ LaunchedContainerAwsEnv awsEnv,+ LambdaExecutionRoleCredentials executionRoleCredentials) {this.containerBuilder = containerBuilder;this.lifecycleManager = lifecycleManager;this.logStreamer = logStreamer;@@ -116,6 +119,7 @@ public class ContainerLauncher {this.ecrRegistryManager = ecrRegistryManager;this.layerService = layerService;this.awsEnv = awsEnv;+ this.executionRoleCredentials = executionRoleCredentials;}@PostConstruct@@ -193,6 +197,7 @@ public class ContainerLauncher {// must be visible in the catch block below to release its in-flight reference on any// failure path, not just the one where useCodeVolume's block itself throws.String reservedCodeVolume = null;+ Optional<SessionCreds> roleCredentials = Optional.empty();try {// Resolve image@@ -235,16 +240,25 @@ public class ContainerLauncher {if (fn.getHandler() != null && !fn.getHandler().isBlank()) {env.add("_HANDLER=" + fn.getHandler());}- // Region, credentials and the Floci endpoint the SDK should target — the same baseline- // Floci gives every launched container. When the host ~/.aws is mounted (awsConfigPath)- // the SDK discovers credentials from /opt/aws-config instead of the placeholders.+ // Region, credentials and the Floci endpoint the SDK should target: the same baseline+ // Floci gives every launched container. When the host ~/.aws is mounted (awsConfigPath),+ // the SDK discovers credentials from /opt/aws-config instead of injected credentials.Optional<String> awsConfigPath = config.services().lambda().awsConfigPath().filter(s -> !s.isBlank());+ if (awsConfigPath.isEmpty()) {+ roleCredentials = executionRoleCredentials.forFunction(fn);+ }env.addAll(awsEnv.sdkBaselineEnv(lambdaRegion,- awsConfigPath.isPresent() ? Optional.of("/opt/aws-config") : Optional.empty()));+ awsConfigPath.isPresent() ? Optional.of("/opt/aws-config") : Optional.empty(),+ roleCredentials));env.addAll(flociCaEnv(flociCaCert));if (fn.getEnvironment() != null) {- fn.getEnvironment().forEach((k, v) -> env.add(k + "=" + v));+ boolean hasExecutionRoleCredentials = roleCredentials.isPresent();+ fn.getEnvironment().forEach((k, v) -> {+ if (!hasExecutionRoleCredentials || !isAwsCredentialVariable(k)) {+ env.add(k + "=" + v);+ }+ });}ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)@@ -425,7 +439,10 @@ public class ContainerLauncher {// invocations without a slow extension is strictly better than failing the launch.awaitExtensionReadiness(runtimeApiServer, fn.getFunctionName());- ContainerHandle handle = new ContainerHandle(containerId, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM, fn.isHotReload());+ ContainerHandle handle = new ContainerHandle(+ containerId, fn.getFunctionName(), runtimeApiServer, ContainerState.WARM, fn.isHotReload(),+ roleCredentials.map(SessionCreds::accessKeyId).orElse(null),+ LambdaExecutionRoleCredentials.sessionAccountId(fn));// Attach log streamingCloseable logHandle = logStreamer.attach(@@ -443,13 +460,27 @@ public class ContainerLauncher {LOG.errorv("Container launch failed for function {0}; cleaning up: {1}",fn.getFunctionName(), e.getMessage());if (containerId != null) {- try { lifecycleManager.stopAndRemove(containerId, null); } catch (Exception ignore) { /* best effort */ }+ try {+ lifecycleManager.stopAndRemove(containerId, null);+ } catch (Exception cleanupError) {+ LOG.warnv(cleanupError, "Could not remove failed Lambda container {0}", containerId);+ }+ }+ if (roleCredentials.isPresent()) {+ executionRoleCredentials.unregister(+ LambdaExecutionRoleCredentials.sessionAccountId(fn),+ roleCredentials.get().accessKeyId());}// No-op if create() already succeeded and released this above (reservedCodeVolume is// null by then); otherwise the failure happened before Docker ever saw the volume, so// its in-flight reference must be released here or cleanup would wait on it forever.releaseCodeVolumeReference(reservedCodeVolume);- try { runtimeApiServerFactory.release(runtimeApiServer); } catch (Exception ignore) { /* best effort */ }+ try {+ runtimeApiServerFactory.release(runtimeApiServer);+ } catch (Exception cleanupError) {+ LOG.warnv(cleanupError, "Could not release Runtime API server for function {0}",+ fn.getFunctionName());+ }throw e;}}@@ -493,10 +524,25 @@ public class ContainerLauncher {LOG.warnv(e, "RuntimeApiServer did not close cleanly for container {0}",handle.getContainerId());} finally {- runtimeApiServerFactory.release(server);+ try {+ runtimeApiServerFactory.release(server);+ } finally {+ // The session is only reachable while the container is alive, so it is retired+ // here rather than on the launch path's failure branch alone. Runs even if the+ // release above throws, otherwise a failed release strands the registration and+ // its credentials stay authorizable for the rest of the process lifetime.+ executionRoleCredentials.unregister(+ handle.getExecutionRoleSessionAccountId(), handle.getExecutionRoleAccessKeyId());+ }}}+ private static boolean isAwsCredentialVariable(String name) {+ return "AWS_ACCESS_KEY_ID".equals(name)+ || "AWS_SECRET_ACCESS_KEY".equals(name)+ || "AWS_SESSION_TOKEN".equals(name);+ }+/*** Probes whether the handle's underlying container is still running.*diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.javanew file mode 100644index 0000000000..6fa803c45b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/LambdaExecutionRoleCredentials.java@@ -0,0 +1,101 @@+package io.github.hectorvent.floci.services.lambda.launcher;++import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.model.SessionCreds;+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.security.SecureRandom;+import java.util.Optional;++/** Mints and revokes the IAM sessions used by Lambda execution environments. */+@ApplicationScoped+public class LambdaExecutionRoleCredentials {++ private static final String UPPER_ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";+ private static final String SECRET_CHARACTERS =+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++ /**+ * These values are what {@code IamEnforcementFilter} authorizes a caller against, so they are+ * minted from a CSPRNG rather than a predictable generator.+ */+ private static final SecureRandom SECURE_RANDOM = new SecureRandom();++ private final IamService iamService;++ @Inject+ public LambdaExecutionRoleCredentials(IamService iamService) {+ this.iamService = iamService;+ }++ /**+ * Account that owns a function's execution-role session. Falls back to the function ARN because+ * a published version carries no {@code accountId}: {@code publishVersion} builds the snapshot+ * field by field and leaves it null, so keying off the field alone would hand every+ * version-qualified invoke the placeholder credentials and silently skip IAM enforcement while+ * {@code $LATEST} enforced it. Callers must resolve the account through here so the session is+ * unregistered under the account it was registered with.+ */+ public static String sessionAccountId(LambdaFunction function) {+ String accountId = function.getAccountId();+ if (accountId != null && !accountId.isBlank()) {+ return accountId;+ }+ return AwsArnUtils.accountOrDefault(function.getFunctionArn(), null);+ }++ /**+ * Mints a non-expiring session for a known execution role. Unknown or malformed roles retain+ * the existing container credential fallback rather than becoming an implicit deny-all caller.+ */+ public Optional<SessionCreds> forFunction(LambdaFunction function) {+ String roleArn = function.getRole();+ String functionAccountId = sessionAccountId(function);+ if (roleArn == null || roleArn.isBlank()+ || functionAccountId == null || functionAccountId.isBlank()) {+ return Optional.empty();+ }++ String roleName;+ try {+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(roleArn);+ if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {+ return Optional.empty();+ }+ roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);+ } catch (IllegalArgumentException e) {+ return Optional.empty();+ }+ if (roleName.isBlank()) {+ return Optional.empty();+ }++ String roleAccountId = AwsArnUtils.accountOrDefault(roleArn, functionAccountId);+ if (iamService.findRole(roleAccountId, roleName).isEmpty()) {+ return Optional.empty();+ }++ SessionCreds credentials = new SessionCreds(+ "ASIA" + random(UPPER_ALPHANUMERIC, 16),+ random(SECRET_CHARACTERS, 40),+ random(SECRET_CHARACTERS, 200));+ iamService.registerLambdaExecutionRoleSession(+ functionAccountId, credentials.accessKeyId(), credentials.secretAccessKey(), roleArn);+ return Optional.of(credentials);+ }++ public void unregister(String accountId, String accessKeyId) {+ iamService.unregisterSession(accountId, accessKeyId);+ }++ private static String random(String characters, int length) {+ StringBuilder value = new StringBuilder(length);+ for (int i = 0; i < length; i++) {+ value.append(characters.charAt(SECURE_RANDOM.nextInt(characters.length())));+ }+ return value.toString();+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 5cff8a47e7..95de580ceb 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -59,6 +59,7 @@ quarkus:- --initialize-at-run-time=io.github.hectorvent.floci.services.emr.EmrService- --initialize-at-run-time=io.github.hectorvent.floci.services.elasticbeanstalk.ElasticBeanstalkService- --initialize-at-run-time=graphql.util.IdGenerator+ - --initialize-at-run-time=io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentialsfloci:diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.javaindex bfb328b62b..cbabc48782 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java@@ -25,6 +25,7 @@ import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.ArgumentMatchers.isNull;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -118,6 +119,25 @@ class IamEnforcementFilterTest {verify(arnBuilder).build("lambda", containerRequest, "us-east-1", "222233334444");}+ @Test+ void getCallerIdentityBypassesPolicyEnforcement() {+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);+ String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260720/us-east-1/sts/aws4_request, "+ + "SignedHeaders=host, Signature=abc";++ when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");+ when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);+ when(actionRegistry.resolve("sts", containerRequest)).thenReturn("sts:GetCallerIdentity");++ IamEnforcementFilter filter = newFilter();++ filter.filter(containerRequest);++ verify(iamService, never()).resolveCallerContext(any());+ verify(evaluator, never()).evaluate(any(), any(), any(), any(), any());+ verify(containerRequest, never()).abortWith(any());+ }+@Testvoid filterPassesS3ListBucketConditionContext() {ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnvTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnvTest.javaindex 1e9edd5894..a79d11cc50 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnvTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/LaunchedContainerAwsEnvTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.core.common.docker;+import io.github.hectorvent.floci.services.iam.model.SessionCreds;import org.junit.jupiter.api.Test;import java.util.List;@@ -72,6 +73,36 @@ class LaunchedContainerAwsEnvTest {assertTrue(env.contains("AWS_ENDPOINT_URL=http://localhost:4566"));}+ @Test+ void injectsWorkloadSessionCredentialsInsteadOfFallbackCredentials() {+ LaunchedContainerAwsEnv awsEnv = awsEnvWithEndpoint("http://localhost:4566");+ SessionCreds credentials = new SessionCreds("ASIAEXECUTIONROLE", "role-secret", "role-token");++ List<String> env = awsEnv.sdkBaselineEnv(+ "us-east-1", Optional.empty(), Optional.of(credentials));++ assertTrue(env.contains("AWS_ACCESS_KEY_ID=ASIAEXECUTIONROLE"));+ assertTrue(env.contains("AWS_SECRET_ACCESS_KEY=role-secret"));+ assertTrue(env.contains("AWS_SESSION_TOKEN=role-token"));+ assertEquals(1, env.stream().filter(e -> e.startsWith("AWS_ACCESS_KEY_ID=")).count());+ assertEquals(1, env.stream().filter(e -> e.startsWith("AWS_SECRET_ACCESS_KEY=")).count());+ assertEquals(1, env.stream().filter(e -> e.startsWith("AWS_SESSION_TOKEN=")).count());+ }++ @Test+ void mountedConfigTakesPrecedenceOverWorkloadSessionCredentials() {+ LaunchedContainerAwsEnv awsEnv = awsEnvWithEndpoint("http://localhost:4566");+ SessionCreds credentials = new SessionCreds("ASIAEXECUTIONROLE", "role-secret", "role-token");++ List<String> env = awsEnv.sdkBaselineEnv(+ "us-east-1", Optional.of("/opt/aws-config"), Optional.of(credentials));++ assertTrue(env.contains("AWS_SHARED_CREDENTIALS_FILE=/opt/aws-config/credentials"));+ assertTrue(env.stream().noneMatch(e -> e.startsWith("AWS_ACCESS_KEY_ID=")));+ assertTrue(env.stream().noneMatch(e -> e.startsWith("AWS_SECRET_ACCESS_KEY=")));+ assertTrue(env.stream().noneMatch(e -> e.startsWith("AWS_SESSION_TOKEN=")));+ }+@Testvoid blankConfigDirFallsBackToPlaceholderCredentials() {LaunchedContainerAwsEnv awsEnv = awsEnvWithEndpoint("http://localhost:4566");diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.javaindex 55d28a9d51..d367787767 100644--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.lambda.KinesisEventSourcePoller;import io.github.hectorvent.floci.services.lambda.SqsEventSourcePoller;import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.pipes.PipesService;import io.github.hectorvent.floci.services.rds.RdsService;import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;@@ -58,6 +59,7 @@ class EmulatorLifecycleTest {@Mock private EmulatorConfig.ServicesConfig servicesConfig;@Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig;@Mock private EmulatorConfig.ElbV2ServiceConfig elbv2ServiceConfig;+ @Mock private IamService iamService;@Mock private ElastiCacheContainerManager elastiCacheContainerManager;@Mock private ElastiCacheMemcachedContainerManager elastiCacheMemcachedContainerManager;@Mock private ElastiCacheProxyManager elastiCacheProxyManager;@@ -100,6 +102,7 @@ class EmulatorLifecycleTest {emulatorLifecycle = new EmulatorLifecycle(storageFactory, serviceRegistry, config,+ iamService,elastiCacheContainerManager, elastiCacheMemcachedContainerManager,elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,memoryDbContainerManager, memoryDbProxyManager,@@ -127,10 +130,12 @@ class EmulatorLifecycleTest {emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));- var inOrder = Mockito.inOrder(initializationHooksRunner, storageFactory, initLifecycleState, rdsService);+ var inOrder = Mockito.inOrder(initializationHooksRunner, storageFactory, initLifecycleState,+ iamService, rdsService);inOrder.verify(initializationHooksRunner).run(InitializationHook.BOOT);inOrder.verify(initLifecycleState).markBootCompleted();inOrder.verify(storageFactory).loadAll();+ inOrder.verify(iamService).sweepOrphanedLambdaExecutionRoleSessions();inOrder.verify(rdsService).restorePersistedRuntime();}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.javaindex 58186f4597..e3a094c4eb 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java@@ -557,6 +557,46 @@ class IamServiceTest {assertTrue(sessions.getForAccount("111122223333", accessKeyId).isEmpty());}+ @Test+ void lambdaExecutionRoleSessionUsesExplicitAccountAndHasNoExpiration() {+ String accountId = "222233334444";+ String accessKeyId = "ASIALAMBDAEXPLICIT";+ AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), null, "000000000000");+ IamService service = iamService(false, new InMemoryStorage<>(), sessions);++ service.registerLambdaExecutionRoleSession(+ accountId, accessKeyId, "lambda-secret",+ "arn:aws:iam::222233334444:role/LambdaRole");++ SessionCredential stored = sessions.getForAccount(accountId, accessKeyId).orElseThrow();+ assertEquals(accountId, stored.getOriginAccountId());+ assertNull(stored.getExpiration());+ assertTrue(stored.isLambdaExecutionRole());+ assertTrue(sessions.getForAccount("000000000000", accessKeyId).isEmpty());++ service.unregisterSession(accountId, accessKeyId);+ assertTrue(sessions.getForAccount(accountId, accessKeyId).isEmpty());+ }++ @Test+ void lambdaExecutionRoleSessionSweepPreservesStsSessions() {+ AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), null, "000000000000");+ IamService service = iamService(false, new InMemoryStorage<>(), sessions);+ service.registerLambdaExecutionRoleSession(+ "222233334444", "ASIALAMBDAORPHAN", "lambda-secret",+ "arn:aws:iam::222233334444:role/LambdaRole");+ service.registerSession(+ "ASIASTSSESSION", "sts-secret", "arn:aws:iam::000000000000:role/StsRole",+ Instant.now().plusSeconds(3600), null, "000000000000");++ assertEquals(1, service.sweepOrphanedLambdaExecutionRoleSessions());++ assertTrue(sessions.getForAccount("222233334444", "ASIALAMBDAORPHAN").isEmpty());+ assertTrue(sessions.getForAccount("000000000000", "ASIASTSSESSION").isPresent());+ }+// =========================================================================// Instance Profiles// =========================================================================diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleCredentialsTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleCredentialsTest.javanew file mode 100644index 0000000000..d64c37b7e5--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleCredentialsTest.java@@ -0,0 +1,115 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.iam.model.CallerContext;+import io.github.hectorvent.floci.services.iam.model.SessionCreds;+import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.Optional;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++class LambdaExecutionRoleCredentialsTest {++ private static final String ACCOUNT_ID = "000000000000";+ private static final String ROLE_NAME = "LambdaExecutionRole";+ private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/" + ROLE_NAME;+ private static final String POLICY = """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Deny","Action":"s3:*","Resource":"*"}+ ]}+ """;++ private IamService iamService;+ private LambdaExecutionRoleCredentials credentials;++ @BeforeEach+ void setUp() {+ iamService = new IamService(+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new RegionResolver("us-east-1", ACCOUNT_ID));+ iamService.createRole(ROLE_NAME, "/", "{}", null, 0, null);+ iamService.putRolePolicy(ROLE_NAME, "DenyS3", POLICY);+ credentials = new LambdaExecutionRoleCredentials(iamService);+ }++ @Test+ void knownRoleMintsRegisteredNonExpiringSessionCredentials() {+ LambdaFunction function = function(ROLE_ARN);++ SessionCreds session = credentials.forFunction(function).orElseThrow();++ assertTrue(session.accessKeyId().startsWith("ASIA"));+ assertEquals(20, session.accessKeyId().length());+ assertEquals(40, session.secretAccessKey().length());+ assertEquals(200, session.sessionToken().length());+ CallerContext caller = iamService.resolveCallerContext(session.accessKeyId());+ assertNotNull(caller);+ assertEquals(java.util.List.of(POLICY), caller.identityPolicies());+ assertEquals(+ "arn:aws:sts::000000000000:assumed-role/LambdaExecutionRole/floci-session",+ iamService.resolveCallerArn(session.accessKeyId()).orElseThrow());+ }++ @Test+ void publishedVersionWithoutAccountIdResolvesAccountFromFunctionArn() {+ // publishVersion builds the snapshot field by field and never copies accountId, so a+ // version-qualified invoke must resolve the account from the function ARN. Keying off the+ // field alone drops to the placeholder credentials and skips IAM enforcement entirely,+ // while $LATEST still enforces.+ LambdaFunction version = function(ROLE_ARN);+ version.setAccountId(null);+ version.setVersion("1");+ version.setFunctionArn(+ "arn:aws:lambda:us-east-1:" + ACCOUNT_ID + ":function:function:1");++ assertEquals(ACCOUNT_ID, LambdaExecutionRoleCredentials.sessionAccountId(version));++ SessionCreds session = credentials.forFunction(version).orElseThrow();++ assertEquals(java.util.List.of(POLICY),+ iamService.resolveCallerContext(session.accessKeyId()).identityPolicies());+ }++ @Test+ void withoutAnAccountAnywhereKeepsCredentialFallback() {+ LambdaFunction function = function(ROLE_ARN);+ function.setAccountId(null);+ function.setFunctionArn(null);++ assertEquals(Optional.empty(), credentials.forFunction(function));+ }++ @Test+ void unknownRoleKeepsCredentialFallback() {+ assertTrue(credentials.forFunction(+ function("arn:aws:iam::000000000000:role/UnknownRole")).isEmpty());+ }++ @Test+ void missingOrMalformedRoleKeepsCredentialFallback() {+ for (String role : new String[]{null, "", " ", "not-an-arn", "arn:aws:s3:::bucket"}) {+ assertEquals(Optional.empty(), credentials.forFunction(function(role)), role);+ }+ }++ private static LambdaFunction function(String roleArn) {+ LambdaFunction function = new LambdaFunction();+ function.setFunctionName("function");+ function.setAccountId(ACCOUNT_ID);+ function.setRole(roleArn);+ return function;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleIamEnforcementIntegrationTest.javanew file mode 100644index 0000000000..44e05982e0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/LambdaExecutionRoleIamEnforcementIntegrationTest.java@@ -0,0 +1,150 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.services.iam.model.SessionCreds;+import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Test;++import java.util.Map;+import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;++@QuarkusTest+@TestProfile(LambdaExecutionRoleIamEnforcementIntegrationTest.IamEnforcementProfile.class)+class LambdaExecutionRoleIamEnforcementIntegrationTest {++ private static final String ACCOUNT_ID = "000000000000";+ private static final String REGION = "us-east-1";++ @Inject+ IamService iamService;++ @Inject+ LambdaExecutionRoleCredentials executionRoleCredentials;++ @Inject+ io.github.hectorvent.floci.services.lambda.LambdaService lambdaService;++ @Test+ void executionRoleDeniesS3ButCanGetCallerIdentity() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String roleName = "LambdaRuntimeRole" + suffix;+ String roleArn = "arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName;+ iamService.createRole(roleName, "/", "{}", null, 0, null);+ iamService.putRolePolicy(roleName, "RuntimePolicy", """+ {+ "Version": "2012-10-17",+ "Statement": [+ {"Effect": "Allow", "Action": "logs:*", "Resource": "*"},+ {"Effect": "Deny", "Action": "s3:*", "Resource": "*"}+ ]+ }+ """);++ LambdaFunction function = new LambdaFunction();+ function.setFunctionName("runtime-identity-" + suffix);+ function.setAccountId(ACCOUNT_ID);+ function.setRole(roleArn);+ SessionCreds credentials = executionRoleCredentials.forFunction(function).orElseThrow();++ try {+ given()+ .header("Authorization", auth(credentials.accessKeyId(), "s3"))+ .when()+ .get("/")+ .then()+ .statusCode(403)+ .body(containsString("<Code>AccessDenied</Code>"));++ given()+ .formParam("Action", "GetCallerIdentity")+ .header("Authorization", auth(credentials.accessKeyId(), "sts"))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Account", equalTo(ACCOUNT_ID))+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",+ equalTo("arn:aws:sts::" + ACCOUNT_ID+ + ":assumed-role/" + roleName + "/floci-session"));+ } finally {+ executionRoleCredentials.unregister(ACCOUNT_ID, credentials.accessKeyId());+ iamService.deleteRolePolicy(roleName, "RuntimePolicy");+ iamService.deleteRole(roleName);+ }+ }++ @Test+ void realPublishedVersionSnapshotStillResolvesItsSessionAccount() throws Exception {+ // Drives the real publishVersion rather than a hand-built snapshot, so a future regression+ // in the version ARN construction (dropping the account segment) fails here instead of+ // silently sending version-qualified invokes back to the placeholder credentials.+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String roleName = "LambdaVersionRole" + suffix;+ String functionName = "version-account-" + suffix;+ iamService.createRole(roleName, "/", "{}", null, 0, null);+ iamService.putRolePolicy(roleName, "RuntimePolicy",+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\","+ + "\"Action\":\"s3:*\",\"Resource\":\"*\"}]}");++ try {+ lambdaService.createFunction(REGION, Map.of(+ "FunctionName", functionName,+ "Role", "arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName,+ "Handler", "index.handler",+ "Runtime", "nodejs20.x",+ "Code", Map.of("ZipFile", handlerZipBase64())));++ LambdaFunction version = lambdaService.publishVersion(REGION, functionName, null);++ // The gap this guards: publishVersion builds the snapshot field by field and currently+ // leaves accountId null, so the account has to come off the ARN. Asserting the account+ // resolves (rather than that the field is null) keeps this passing either way.+ org.junit.jupiter.api.Assertions.assertEquals(+ ACCOUNT_ID, LambdaExecutionRoleCredentials.sessionAccountId(version));++ SessionCreds credentials = executionRoleCredentials.forFunction(version).orElseThrow();+ try {+ org.junit.jupiter.api.Assertions.assertEquals(+ "arn:aws:sts::" + ACCOUNT_ID + ":assumed-role/" + roleName + "/floci-session",+ iamService.resolveCallerArn(credentials.accessKeyId()).orElseThrow());+ } finally {+ executionRoleCredentials.unregister(+ LambdaExecutionRoleCredentials.sessionAccountId(version),+ credentials.accessKeyId());+ }+ } finally {+ iamService.deleteRolePolicy(roleName, "RuntimePolicy");+ iamService.deleteRole(roleName);+ }+ }++ private static String handlerZipBase64() throws Exception {+ java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();+ try (java.util.zip.ZipOutputStream zip = new java.util.zip.ZipOutputStream(bytes)) {+ zip.putNextEntry(new java.util.zip.ZipEntry("index.js"));+ zip.write("exports.handler = async () => ({});\n".getBytes());+ zip.closeEntry();+ }+ return java.util.Base64.getEncoder().encodeToString(bytes.toByteArray());+ }++ private static String auth(String accessKeyId, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260720/" + REGION + "/" + service+ + "/aws4_request, SignedHeaders=host, Signature=abc";+ }++ public static final class IamEnforcementProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.iam.enforcement-enabled", "true");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutionRoleDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutionRoleDockerIntegrationTest.javanew file mode 100644index 0000000000..20d7f3baca--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaExecutionRoleDockerIntegrationTest.java@@ -0,0 +1,176 @@+package io.github.hectorvent.floci.services.lambda;++import com.github.dockerjava.api.DockerClient;+import io.github.hectorvent.floci.services.iam.IamService;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import io.restassured.response.Response;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.io.ByteArrayOutputStream;+import java.nio.charset.StandardCharsets;+import java.util.Base64;+import java.util.Map;+import java.util.UUID;+import java.util.zip.ZipEntry;+import java.util.zip.ZipOutputStream;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.startsWith;+import static org.junit.jupiter.api.Assertions.assertNull;++@QuarkusTest+@TestProfile(LambdaExecutionRoleDockerIntegrationTest.IamEnforcementProfile.class)+class LambdaExecutionRoleDockerIntegrationTest {++ private static final String BASE_PATH = "/2015-03-31";+ private static final String ACCOUNT_ID = "000000000000";++ @Inject+ DockerClient dockerClient;++ @Inject+ IamService iamService;++ @BeforeEach+ void requireDocker() {+ Assumptions.assumeTrue(isDockerAvailable(),+ "Docker daemon must be available for Lambda execution-role integration tests");+ }++ @Test+ void runtimeUsesExecutionRoleCredentialsForSdkCalls() throws Exception {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String functionName = "execution-role-" + suffix;+ String roleName = "LambdaDockerRole" + suffix;+ String roleArn = "arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName;+ iamService.createRole(roleName, "/", "{}", null, 0, null);+ iamService.putRolePolicy(roleName, "RuntimePolicy", """+ {+ "Version": "2012-10-17",+ "Statement": [+ {"Effect": "Allow", "Action": "logs:*", "Resource": "*"},+ {"Effect": "Deny", "Action": "s3:*", "Resource": "*"}+ ]+ }+ """);++ try {+ given()+ .contentType("application/json")+ .body("""+ {+ "FunctionName": "%1$s",+ "Runtime": "nodejs20.x",+ "Role": "%2$s",+ "Handler": "index.handler",+ "Timeout": 60,+ "Code": {"ZipFile": "%3$s"},+ "Environment": {"Variables": {+ "AWS_ACCESS_KEY_ID": "test",+ "AWS_SECRET_ACCESS_KEY": "test",+ "AWS_SESSION_TOKEN": "test"+ }}+ }+ """.formatted(functionName, roleArn, handlerZipBase64()))+ .when()+ .post(BASE_PATH + "/functions")+ .then()+ .statusCode(201);++ Response response = given()+ .contentType("application/json")+ .body("{}")+ .when()+ .post(BASE_PATH + "/functions/" + functionName + "/invocations");++ response.then()+ .statusCode(200)+ .body("accessKeyId", startsWith("ASIA"))+ .body("signedAccessKeyId", startsWith("ASIA"))+ .body("account", equalTo(ACCOUNT_ID))+ .body("arn", startsWith(+ "arn:aws:sts::" + ACCOUNT_ID + ":assumed-role/" + roleName + "/"))+ .body("s3Denied", equalTo(true));++ String accessKeyId = response.jsonPath().getString("accessKeyId");+ assertNull(iamService.resolveCallerContext(accessKeyId),+ "ephemeral container stop should unregister its execution-role session");+ } finally {+ given().when().delete(BASE_PATH + "/functions/" + functionName);+ iamService.deleteRolePolicy(roleName, "RuntimePolicy");+ iamService.deleteRole(roleName);+ }+ }++ private static String handlerZipBase64() throws Exception {+ String handler = """+ const { STSClient, GetCallerIdentityCommand } = require('@aws-sdk/client-sts');+ const { S3Client, ListBucketsCommand } = require('@aws-sdk/client-s3');++ exports.handler = async () => {+ const options = {+ endpoint: process.env.AWS_ENDPOINT_URL,+ region: process.env.AWS_REGION+ };+ let signedAccessKeyId = null;+ const sts = new STSClient(options);+ sts.middlewareStack.add(+ (next) => async (args) => {+ const authorization = args.request.headers.authorization || '';+ signedAccessKeyId = authorization.match(/Credential=([^/]+)/)?.[1] || null;+ return next(args);+ },+ {step: 'finalizeRequest', name: 'captureCredential'}+ );+ const identity = await sts.send(new GetCallerIdentityCommand({}));+ let s3Denied = false;+ try {+ await new S3Client({...options, forcePathStyle: true}).send(new ListBucketsCommand({}));+ } catch (error) {+ s3Denied = error?.$metadata?.httpStatusCode === 403;+ }+ return {+ accessKeyId: process.env.AWS_ACCESS_KEY_ID,+ signedAccessKeyId,+ account: identity.Account,+ arn: identity.Arn,+ s3Denied+ };+ };+ """;+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();+ try (ZipOutputStream zip = new ZipOutputStream(bytes)) {+ zip.putNextEntry(new ZipEntry("index.js"));+ zip.write(handler.getBytes(StandardCharsets.UTF_8));+ zip.closeEntry();+ }+ return Base64.getEncoder().encodeToString(bytes.toByteArray());+ }++ private boolean isDockerAvailable() {+ try {+ dockerClient.pingCmd().exec();+ return true;+ } catch (Exception e) {+ return false;+ }+ }++ public static final class IamEnforcementProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.services.iam.enforcement-enabled", "true",+ "floci.services.lambda.ephemeral", "true",+ "quarkus.http.test-port", "4587",+ "floci.port", "4587",+ "floci.base-url", "http://localhost:4587");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.javaindex 67b0b3364b..51425743d5 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java@@ -252,7 +252,8 @@ class LambdaImageConfigTest {LaunchedContainerAwsEnv awsEnv = new LaunchedContainerAwsEnv(reachableEndpoint);launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,- mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv);+ mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv,+ mock(io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials.class));when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);when(runtimeApiServer.getPort()).thenReturn(9000);diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.javaindex 30b214ae1e..653ca8734a 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java@@ -58,7 +58,8 @@ class ContainerLauncherCodeVolumeReuseTest {super(mock(ContainerBuilder.class), lifecycleManager, mock(ContainerLogStreamer.class),mock(ImageResolver.class), mock(RuntimeApiServerFactory.class),mock(DockerHostResolver.class), config, mock(EcrRegistryManager.class),- mock(LambdaLayerService.class), mock(LaunchedContainerAwsEnv.class));+ mock(LambdaLayerService.class), mock(LaunchedContainerAwsEnv.class),+ mock(LambdaExecutionRoleCredentials.class));}@Overridediff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.javaindex 4d27c86f61..07b9e03e32 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;+import io.github.hectorvent.floci.services.iam.model.SessionCreds;import io.github.hectorvent.floci.services.lambda.model.LambdaFileSystemConfig;import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;@@ -47,6 +48,7 @@ import java.util.List;import java.util.Map;import java.util.Optional;import java.util.OptionalInt;+import java.util.concurrent.CompletableFuture;import java.util.concurrent.atomic.AtomicBoolean;import static org.junit.jupiter.api.Assertions.assertEquals;@@ -75,6 +77,7 @@ class ContainerLauncherTest {@Mock EmbeddedDnsServer embeddedDnsServer;@Mock RuntimeApiServer runtimeApiServer;@Mock DockerClient dockerClient;+ @Mock LambdaExecutionRoleCredentials executionRoleCredentials;@TempDirPath tempDir;@@ -124,11 +127,16 @@ class ContainerLauncherTest {LaunchedContainerAwsEnv awsEnv = new LaunchedContainerAwsEnv(reachableEndpoint);launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,- mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv);+ mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv,+ executionRoleCredentials);when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);when(runtimeApiServer.getPort()).thenReturn(9000);+ lenient().when(runtimeApiServer.stop()).thenReturn(CompletableFuture.completedFuture(null));+ // stop() quiesces then close()s; the unregister assertions below run past that call.+ lenient().when(runtimeApiServer.close()).thenReturn(CompletableFuture.completedFuture(null));when(dockerHostResolver.resolve()).thenReturn("127.0.0.1");+ lenient().when(executionRoleCredentials.forFunction(any())).thenReturn(Optional.empty());// lenient: the failure-path test (populate fails before any container is created) never// reaches these, but every success-path test does — they must not trip strict-stubs.@@ -377,47 +385,35 @@ class ContainerLauncherTest {}@Test- void launchFunction_userEnvironmentOverridesDefaultCredentials() throws Exception {+ void launchFunction_executionRoleCredentialsOverrideUserCredentialEnvironment() throws Exception {Path codePath = Files.createDirectory(tempDir.resolve("creds-override"));LambdaFunction fn = new LambdaFunction();fn.setFunctionName("override-fn");+ fn.setAccountId("000000000000");fn.setRuntime("nodejs20.x");fn.setHandler("index.handler");fn.setCodeLocalPath(codePath.toString());fn.setEnvironment(Map.of("AWS_ACCESS_KEY_ID", "user-key",- "AWS_SECRET_ACCESS_KEY", "user-secret"));+ "AWS_SECRET_ACCESS_KEY", "user-secret",+ "AWS_SESSION_TOKEN", "user-token"));+ when(executionRoleCredentials.forFunction(fn)).thenReturn(Optional.of(+ new SessionCreds("ASIAROLEKEY", "role-secret", "role-token")));launcher.launch(fn);List<String> env = captureRealContainerSpec().env();- // Docker honours the last occurrence of a duplicate Env entry, so user- // overrides must appear after the Floci defaults.- int defaultKeyIdx = -1;- int userKeyIdx = -1;- int defaultSecretIdx = -1;- int userSecretIdx = -1;- for (int i = 0; i < env.size(); i++) {- if (env.get(i).startsWith("AWS_ACCESS_KEY_ID=") && userKeyIdx < 0 && !env.get(i).equals("AWS_ACCESS_KEY_ID=user-key")) {- defaultKeyIdx = i;- }- if (env.get(i).equals("AWS_ACCESS_KEY_ID=user-key")) userKeyIdx = i;- if (env.get(i).startsWith("AWS_SECRET_ACCESS_KEY=") && userSecretIdx < 0 && !env.get(i).equals("AWS_SECRET_ACCESS_KEY=user-secret")) {- defaultSecretIdx = i;- }- if (env.get(i).equals("AWS_SECRET_ACCESS_KEY=user-secret")) userSecretIdx = i;- }- assertTrue(defaultKeyIdx >= 0, "default AWS_ACCESS_KEY_ID still present");- assertTrue(userKeyIdx > defaultKeyIdx,- "user AWS_ACCESS_KEY_ID must appear after the default");- assertTrue(defaultSecretIdx >= 0, "default AWS_SECRET_ACCESS_KEY still present");- assertTrue(userSecretIdx > defaultSecretIdx,- "user AWS_SECRET_ACCESS_KEY must appear after the default");-- // AWS_SESSION_TOKEN was not overridden so the default remains.+ assertTrue(env.contains("AWS_ACCESS_KEY_ID=ASIAROLEKEY"));+ assertTrue(env.contains("AWS_SECRET_ACCESS_KEY=role-secret"));+ assertTrue(env.contains("AWS_SESSION_TOKEN=role-token"));+ assertTrue(env.stream().noneMatch("AWS_ACCESS_KEY_ID=user-key"::equals));+ assertTrue(env.stream().noneMatch("AWS_SECRET_ACCESS_KEY=user-secret"::equals));+ assertTrue(env.stream().noneMatch("AWS_SESSION_TOKEN=user-token"::equals));+ assertEquals(1, env.stream().filter(e -> e.startsWith("AWS_ACCESS_KEY_ID=")).count());+ assertEquals(1, env.stream().filter(e -> e.startsWith("AWS_SECRET_ACCESS_KEY=")).count());assertEquals(1, env.stream().filter(e -> e.startsWith("AWS_SESSION_TOKEN=")).count(),- "AWS_SESSION_TOKEN should retain its default exactly once");+ "execution-role session token should appear exactly once");}@Test@@ -534,6 +530,91 @@ class ContainerLauncherTest {"AWS_SECRET_ACCESS_KEY should not be injected when awsConfigPath is set");assertTrue(env.stream().noneMatch(e -> e.startsWith("AWS_SESSION_TOKEN=")),"AWS_SESSION_TOKEN should not be injected when awsConfigPath is set");+ verify(executionRoleCredentials, never()).forFunction(any());+ }++ @Test+ void stopUnregistersExecutionRoleSession() throws Exception {+ Path codePath = Files.createDirectory(tempDir.resolve("role-session-stop"));+ LambdaFunction fn = new LambdaFunction();+ fn.setFunctionName("role-session-stop-fn");+ fn.setAccountId("222233334444");+ fn.setRuntime("nodejs20.x");+ fn.setHandler("index.handler");+ fn.setCodeLocalPath(codePath.toString());+ when(executionRoleCredentials.forFunction(fn)).thenReturn(Optional.of(+ new SessionCreds("ASIASTOPSESSION", "role-secret", "role-token")));++ ContainerHandle handle = launcher.launch(fn);+ launcher.stop(handle);++ verify(executionRoleCredentials).unregister("222233334444", "ASIASTOPSESSION");+ }++ @Test+ void launchFailureUnregistersExecutionRoleSession() throws Exception {+ Path codePath = Files.createDirectory(tempDir.resolve("role-session-failure"));+ LambdaFunction fn = new LambdaFunction();+ fn.setFunctionName("role-session-failure-fn");+ fn.setAccountId("222233334444");+ fn.setRuntime("nodejs20.x");+ fn.setHandler("index.handler");+ fn.setCodeLocalPath(codePath.toString());+ when(executionRoleCredentials.forFunction(fn)).thenReturn(Optional.of(+ new SessionCreds("ASIAFAILEDSESSION", "role-secret", "role-token")));+ doThrow(new RuntimeException("create failed")).when(lifecycleManager).create(any());++ assertThrows(RuntimeException.class, () -> launcher.launch(fn));++ verify(executionRoleCredentials).unregister("222233334444", "ASIAFAILEDSESSION");+ }++ @Test+ void publishedVersionUnregistersUnderTheAccountItRegisteredWith() throws Exception {+ // A published version has no accountId, so both the handle stamp and the revoke must take+ // the account from the function ARN. Reading the field directly revokes under null and+ // leaks a live, non-expiring session for the life of the process.+ Path codePath = Files.createDirectory(tempDir.resolve("role-session-version"));+ LambdaFunction fn = new LambdaFunction();+ fn.setFunctionName("role-session-version-fn");+ fn.setVersion("1");+ fn.setFunctionArn(+ "arn:aws:lambda:us-east-1:222233334444:function:role-session-version-fn:1");+ fn.setRuntime("nodejs20.x");+ fn.setHandler("index.handler");+ fn.setCodeLocalPath(codePath.toString());+ when(executionRoleCredentials.forFunction(fn)).thenReturn(Optional.of(+ new SessionCreds("ASIAVERSIONSESSION", "role-secret", "role-token")));++ ContainerHandle handle = launcher.launch(fn);+ assertEquals("222233334444", handle.getExecutionRoleSessionAccountId());++ launcher.stop(handle);++ verify(executionRoleCredentials).unregister("222233334444", "ASIAVERSIONSESSION");+ }++ @Test+ void publishedVersionLaunchFailureUnregistersUnderTheArnAccount() throws Exception {+ // The launch-failure path recomputes the account rather than reading it back off a handle+ // (there is no handle yet), so it needs the same ARN fallback. Reading the field here+ // revokes under null and leaks the session that forFunction just registered.+ Path codePath = Files.createDirectory(tempDir.resolve("role-session-version-failure"));+ LambdaFunction fn = new LambdaFunction();+ fn.setFunctionName("role-session-version-failure-fn");+ fn.setVersion("2");+ fn.setFunctionArn(+ "arn:aws:lambda:us-east-1:222233334444:function:role-session-version-failure-fn:2");+ fn.setRuntime("nodejs20.x");+ fn.setHandler("index.handler");+ fn.setCodeLocalPath(codePath.toString());+ when(executionRoleCredentials.forFunction(fn)).thenReturn(Optional.of(+ new SessionCreds("ASIAVERSIONFAILURE", "role-secret", "role-token")));+ doThrow(new RuntimeException("create failed")).when(lifecycleManager).create(any());++ assertThrows(RuntimeException.class, () -> launcher.launch(fn));++ verify(executionRoleCredentials).unregister("222233334444", "ASIAVERSIONFAILURE");}@Test@@ -1283,7 +1364,8 @@ class ContainerLauncherTest {imageResolver, runtimeApiServerFactory, dockerHostResolver, config,ecrRegistryManager,mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class),- new LaunchedContainerAwsEnv(reachableEndpoint));+ new LaunchedContainerAwsEnv(reachableEndpoint),+ executionRoleCredentials);stubExtensionDiscovery("otel-collector");// Feed a real stdout frame through whatever callback the launcher hands to execStartCmd.