mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
22 files changed
+975
-68
No files matched your search
@@ -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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterPassesS3ListBucketConditionContext() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
|
||||
+31
@@ -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=")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankConfigDirFallsBackToPlaceholderCredentials() {
|
||||
LaunchedContainerAwsEnv awsEnv = awsEnvWithEndpoint("http://localhost:4566");
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
// =========================================================================
|
||||
|
||||
+115
@@ -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;
|
||||
}
|
||||
}
|
||||
+150
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+176
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+2
-1
@@ -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));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+111
-29
@@ -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;
|
||||
|
||||
@TempDir
|
||||
Path 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.
|
||||
|
||||
Reference in new issue
Block a user