fix(lambda,iam): assume execution role for in-function SDK calls (#1909)

* fix(lambda,iam): assume execution role for in-function SDK calls

- Run Lambda SDK calls as known execution roles so IAM policies and caller identity match AWS behavior.
- Preserve unknown-role and mounted-credential fallbacks while leaving ECS behavior unchanged.
- Revoke container-bound sessions on cleanup and sweep orphaned sessions after restart.
- Resolve the session account from the function ARN when the model carries no account, so a
  published version enforces its execution role instead of dropping to the placeholder
  credentials, and revokes under the account it registered with. PublishVersion builds its
  snapshot field by field and leaves accountId unset (#2040), so the account has to come off
  the version ARN; routing every read through one helper keeps register and revoke in step.
- Add unit, enforcement, lifecycle, and real Docker coverage, plus updated documentation.

* fix(lambda): mint execution-role sessions from a CSPRNG and flag credential passthrough

The session key and secret are what IamEnforcementFilter authorizes a caller
against, so mint them from SecureRandom rather than ThreadLocalRandom, matching
how CertificateGenerator already sources security-relevant values. Register the
class for native-image run-time initialization so the static instance is not
captured, frozen-seed, into the image heap.

Credential passthrough (Floci's own AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/
AWS_SESSION_TOKEN forwarded into a launched container) applies whenever those
variables are set, so a Floci started from a shell that exports real credentials
hands them to every workload whose role it cannot resolve. Log a WARN carrying
the access-key prefix the first time the fallback forwards host credentials, and
say so in the docs, so the accidental case is visible instead of looking
identical to the deliberate one.
This commit is contained in:
TiM authored and GitHub committed 2026-08-15 20:59:05 -05:00
1 parent 4c510e576c
commit 573d4bdaff
22 files changed
+975 -68

No files matched your search

@@ -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_PATH
@@ -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) {
@@ -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}).
*/
@ApplicationScoped
public 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);
}
}
@@ -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 {
@Inject
public 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();
@@ -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 captured
@@ -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; }
}
@@ -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) {
}
@@ -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; }
@@ -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 streaming
Closeable 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.
*
@@ -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();
}
}