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.java index 0e4fa60c71..be979b23c1 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 @@ -10,6 +10,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.UnaryOperator; +import java.util.regex.Pattern; /** * Builds the baseline AWS SDK environment for a container Floci launches, so the workload @@ -30,11 +32,21 @@ public class LaunchedContainerAwsEnv { /** Host-credential passthrough is a property of the process, so it is worth saying once. */ private static final AtomicBoolean hostCredentialsWarned = new AtomicBoolean(); + /** AccountResolver reads a 12-digit access-key ID as the caller's account directly. */ + private static final Pattern ACCOUNT_ID_PATTERN = Pattern.compile("\\d{12}"); + private final ContainerReachableEndpoint reachableEndpoint; + private final UnaryOperator hostEnv; @Inject public LaunchedContainerAwsEnv(ContainerReachableEndpoint reachableEndpoint) { + this(reachableEndpoint, System::getenv); + } + + /** Lets tests supply a host environment; Java cannot mutate its own process env. */ + LaunchedContainerAwsEnv(ContainerReachableEndpoint reachableEndpoint, UnaryOperator hostEnv) { this.reachableEndpoint = reachableEndpoint; + this.hostEnv = hostEnv; } /** @@ -67,12 +79,37 @@ public class LaunchedContainerAwsEnv { return sdkBaselineEnv(region, awsConfigMountDir, reachableEndpoint.baseUrl(), injectedCredentials); } + /** + * Variant for a workload whose owning AWS account is known. When it falls through to + * placeholder credentials — no mounted config, no session credentials, which is every + * Lambda that never assumes an execution role — a 12-digit {@code ownerAccountId} is + * injected as {@code AWS_ACCESS_KEY_ID}, and it wins over Floci's own ambient + * {@code AWS_ACCESS_KEY_ID}. The server process's credentials describe the server, not the + * container it launches, so they must never override a known owning account: AccountResolver + * reads a 12-digit access-key ID as the caller's account directly, and the literal + * {@code "test"} it would otherwise see resolves every such container to the emulator's + * default (management) account. Account-partitioned reads and writes — EC2 security groups, + * IAM service-linked roles — then collide or miss whenever the real resource lives elsewhere. + */ + public List sdkBaselineEnv(String region, Optional awsConfigMountDir, + Optional injectedCredentials, String ownerAccountId) { + return sdkBaselineEnv(region, awsConfigMountDir, reachableEndpoint.baseUrl(), + injectedCredentials, ownerAccountId); + } + /** * Full variant taking both the Floci endpoint the workload should target and optional * workload-specific session credentials. */ public List sdkBaselineEnv(String region, Optional awsConfigMountDir, String flociEndpoint, Optional injectedCredentials) { + return sdkBaselineEnv(region, awsConfigMountDir, flociEndpoint, injectedCredentials, null); + } + + /** Full variant, additionally taking the workload's owning account. */ + public List sdkBaselineEnv(String region, Optional awsConfigMountDir, + String flociEndpoint, Optional injectedCredentials, + String ownerAccountId) { var env = new ArrayList(); env.add("AWS_DEFAULT_REGION=" + region); env.add("AWS_REGION=" + region); @@ -88,23 +125,33 @@ public class LaunchedContainerAwsEnv { 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. - var ak = System.getenv("AWS_ACCESS_KEY_ID"); - var sk = System.getenv("AWS_SECRET_ACCESS_KEY"); - var st = System.getenv("AWS_SESSION_TOKEN"); - if ((ak != null || sk != null || st != null) && hostCredentialsWarned.compareAndSet(false, true)) { + // The launched container is a distinct principal from the Floci server process, so + // its identity comes from the workload's owning account when we know it; Floci's own + // env vars are the fallback for launch paths that don't (ownerAccountId == null). + var ak = hostEnv.apply("AWS_ACCESS_KEY_ID"); + var sk = hostEnv.apply("AWS_SECRET_ACCESS_KEY"); + var st = hostEnv.apply("AWS_SESSION_TOKEN"); + boolean hasOwnerAccountId = ownerAccountId != null && ACCOUNT_ID_PATTERN.matcher(ownerAccountId).matches(); + if (!hasOwnerAccountId && (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. + // repeated on every launch is one people learn to scroll past. Only fires when + // Floci's own ambient credentials are actually forwarded — the owner-account + // branch below never forwards them, so the warning would otherwise be false. 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")); + // The numeric owner-account access key is only ever validated (by the S3, RDS and + // ElastiCache SigV4 checks) when paired with the literal "test" secret and session + // token — never with Floci's own ambient secret, which those checks know nothing + // about and which would produce a credential pair nothing can verify. + env.add("AWS_ACCESS_KEY_ID=" + (hasOwnerAccountId ? ownerAccountId : (ak != null ? ak : "test"))); + env.add("AWS_SECRET_ACCESS_KEY=" + (hasOwnerAccountId ? "test" : (sk != null ? sk : "test"))); + env.add("AWS_SESSION_TOKEN=" + (hasOwnerAccountId ? "test" : (st != null ? st : "test"))); } env.add("FLOCI_HOSTNAME=" + URI.create(flociEndpoint).getHost()); env.add("FLOCI_ENDPOINT=" + flociEndpoint); diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.java index 517d63237a..39dee54c02 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4Validator.java @@ -101,6 +101,11 @@ public class SigV4Validator { String service = credParts[3]; String credentialScope = date + "/" + region + "/" + service + "/aws4_request"; + // Deliberately no fallback for a bare 12-digit account ID here: trusting an + // unregistered numeric access key paired with the well-known "test" secret would + // let any client forge an IAM-auth token for an arbitrary account and authenticate + // as any matching cache user. An unregistered key falls back to itself, unchanged + // (never a valid secret), so it always fails the signature check below. String secretKey = iamService.findSecretKey(accessKeyId).orElse(accessKeyId); String canonicalQueryString = Arrays.stream(rawPairs) 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.java index 7134a4337f..75f9ba72a3 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 @@ -256,12 +256,23 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { } env.addAll(awsEnv.sdkBaselineEnv(lambdaRegion, awsConfigPath.isPresent() ? Optional.of("/opt/aws-config") : Optional.empty(), - roleCredentials)); + roleCredentials, lambdaAccountId)); env.addAll(flociCaEnv(flociCaCert)); if (fn.getEnvironment() != null) { boolean hasExecutionRoleCredentials = roleCredentials.isPresent(); + boolean userDefinesFullCredentialTriad = definesFullCredentialTriad(fn.getEnvironment()); fn.getEnvironment().forEach((k, v) -> { - if (!hasExecutionRoleCredentials || !isAwsCredentialVariable(k)) { + if (isAwsCredentialVariable(k)) { + // Credential injection is all-or-nothing: a partial override (e.g. only + // AWS_ACCESS_KEY_ID set) must never join the baseline's other two values — + // that pairs a user-chosen key with the owner-account/execution-role secret + // and session token, a tuple nothing can verify. Only let the user's triad + // through when it is complete, and only when there is no execution role + // (which is already the authoritative credential source). + if (!hasExecutionRoleCredentials && userDefinesFullCredentialTriad) { + env.add(k + "=" + v); + } + } else { env.add(k + "=" + v); } }); @@ -557,12 +568,25 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { } } - private static boolean isAwsCredentialVariable(String name) { + public static boolean isAwsCredentialVariable(String name) { return "AWS_ACCESS_KEY_ID".equals(name) || "AWS_SECRET_ACCESS_KEY".equals(name) || "AWS_SESSION_TOKEN".equals(name); } + /** + * Whether a Lambda's own Environment config defines all three AWS credential variables, + * the only condition under which any of them may override the baseline env — a partial + * set must never leak through and split the baseline's credential tuple. Public: both the + * Docker and Kubernetes launchers append the function's Environment after the same baseline + * and must apply this rule identically. + */ + public static boolean definesFullCredentialTriad(java.util.Map environment) { + return environment.containsKey("AWS_ACCESS_KEY_ID") + && environment.containsKey("AWS_SECRET_ACCESS_KEY") + && environment.containsKey("AWS_SESSION_TOKEN"); + } + /** * Probes whether the handle's underlying container is still running. * diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java index 79c593faf7..4f4559c3e1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java @@ -191,10 +191,21 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { if (fn.getHandler() != null && !fn.getHandler().isBlank()) { env.add("_HANDLER=" + fn.getHandler()); } - env.addAll(awsEnv.sdkBaselineEnv(region, Optional.empty(), addressResolver.flociBaseUrl())); + env.addAll(awsEnv.sdkBaselineEnv(region, Optional.empty(), addressResolver.flociBaseUrl(), + Optional.empty(), AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId()))); env.addAll(ContainerLauncher.flociCaEnv(caCert)); if (fn.getEnvironment() != null) { - fn.getEnvironment().forEach((k, v) -> env.add(k + "=" + v)); + // Same all-or-nothing rule as ContainerLauncher: this launcher never has + // execution-role credentials, so the function's own Environment may only supply + // AWS credential vars when it defines the full triad — a partial set must never + // join the owner-account baseline and split its credential tuple. + boolean userDefinesFullCredentialTriad = + ContainerLauncher.definesFullCredentialTriad(fn.getEnvironment()); + fn.getEnvironment().forEach((k, v) -> { + if (!ContainerLauncher.isAwsCredentialVariable(k) || userDefinesFullCredentialTriad) { + env.add(k + "=" + v); + } + }); } var imageConfig = imagePackage diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java index 139be1ee11..c762d38af0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java @@ -101,6 +101,11 @@ public class RdsSigV4Validator { String service = credParts[3]; String credentialScope = date + "/" + region + "/" + service + "/aws4_request"; + // Deliberately no fallback for a bare 12-digit account ID here: trusting an + // unregistered numeric access key paired with the well-known "test" secret would + // let any client forge an IAM-auth token for an arbitrary account and authenticate + // as any matching database user. An unregistered key falls back to itself, unchanged + // (never a valid secret), so it always fails the signature check below. String secretKey = iamService.findSecretKey(accessKeyId).orElse(accessKeyId); // Canonical query string: sorted pairs, excluding X-Amz-Signature diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java index 0c2ff2f0e0..8a10ad82fc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java @@ -19,6 +19,7 @@ import java.security.MessageDigest; import java.util.ArrayList; import java.util.Comparator; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @Provider @@ -218,7 +219,18 @@ public class PreSignedUrlFilter implements ContainerRequestFilter { return LEGACY_SECRET_KEY; } if (iamService != null) { - return iamService.findSecretKey(accessKeyId).orElse(null); + Optional registered = iamService.findSecretKey(accessKeyId); + if (registered.isPresent()) { + return registered.get(); + } + // Deliberately no fallback for a bare 12-digit account ID here: AccountResolver + // reads a 12-digit access key ID as the request's account directly, so trusting an + // unregistered numeric key paired with the well-known "test" secret would let any + // client forge a signed request for an arbitrary account under S3 auth enforcement. + // A launched container's owning-account placeholder credentials (see + // LaunchedContainerAwsEnv) are therefore not honored by this enforced path either; + // they only work where no signature is required (auth enforcement disabled). + return null; } return null; } 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.java index a79d11cc50..863c559c02 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 @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.iam.model.SessionCreds; import org.junit.jupiter.api.Test; import java.util.List; +import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -123,4 +124,100 @@ class LaunchedContainerAwsEnvTest { assertEquals(1, env.stream().filter(e -> e.equals("FLOCI_HOSTNAME=host.docker.internal")).count()); assertTrue(env.contains("AWS_ENDPOINT_URL=https://host.docker.internal:4566")); } + + // --- ownerAccountId: a launched Lambda container that never assumes an execution role must + // resolve, on Floci's own side, to the function's real owning account rather than the literal + // "test" placeholder — otherwise AccountResolver falls back to the emulator's default + // (management) account and account-partitioned reads and writes collide or miss whenever the + // resource actually lives in a different account's partition. + + @Test + void ownerAccountIdWinsOverFlocisOwnAmbientAccessKeyId() { + // The regression case. Floci itself is very often started with AWS_ACCESS_KEY_ID set — + // the floci-lza image sets it unconditionally — and the server process's credentials say + // nothing about which account launched this container. Every other test here leaves the + // host env unset, so none of them would fail if this precedence were inverted. + LaunchedContainerAwsEnv awsEnv = awsEnvWithHostEnv("http://localhost:4566", + Map.of("AWS_ACCESS_KEY_ID", "test", "AWS_SECRET_ACCESS_KEY", "test")); + + List env = awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), Optional.empty(), "041922743467"); + + assertTrue(env.contains("AWS_ACCESS_KEY_ID=041922743467")); + } + + @Test + void ownerAccountIdForcesTestSecretEvenWithNonTestAmbientSecret() { + // The numeric owner-account access key is only ever validated by Floci's S3/RDS/ + // ElastiCache SigV4 checks when paired with the literal "test" secret (see + // LaunchedContainerAwsEnv's class javadoc and the matching validators). If Floci itself + // was started with a real, non-test AWS_SECRET_ACCESS_KEY (an exported key pair, + // aws-vault, a CI runner), that ambient secret must never be paired with the numeric + // owner-account key — the SDK would sign with a pair nothing can verify. + LaunchedContainerAwsEnv awsEnv = awsEnvWithHostEnv("http://localhost:4566", + Map.of("AWS_ACCESS_KEY_ID", "test", "AWS_SECRET_ACCESS_KEY", "AKIAREALAMBIENTSECRET", + "AWS_SESSION_TOKEN", "real-ambient-session-token")); + + List env = awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), Optional.empty(), "041922743467"); + + assertTrue(env.contains("AWS_ACCESS_KEY_ID=041922743467")); + assertTrue(env.contains("AWS_SECRET_ACCESS_KEY=test")); + assertTrue(env.contains("AWS_SESSION_TOKEN=test")); + } + + @Test + void injectsOwnerAccountIdAsAccessKeyWhenHostEnvNotSet() { + LaunchedContainerAwsEnv awsEnv = awsEnvWithHostEnv("http://localhost:4566", Map.of()); + + List env = awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), Optional.empty(), "041922743467"); + + assertTrue(env.contains("AWS_ACCESS_KEY_ID=041922743467")); + } + + @Test + void fallsBackToHostEnvWhenOwnerAccountIdIsNotTwelveDigits() { + LaunchedContainerAwsEnv awsEnv = awsEnvWithHostEnv("http://localhost:4566", + Map.of("AWS_ACCESS_KEY_ID", "AKIAHOSTKEY")); + + List env = awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), Optional.empty(), "not-an-account-id"); + + assertTrue(env.contains("AWS_ACCESS_KEY_ID=AKIAHOSTKEY")); + } + + @Test + void nullOwnerAccountIdFallsBackToPlaceholder() { + LaunchedContainerAwsEnv awsEnv = awsEnvWithHostEnv("http://localhost:4566", Map.of()); + + List env = awsEnv.sdkBaselineEnv("us-east-1", Optional.empty(), Optional.empty(), null); + + assertTrue(env.contains("AWS_ACCESS_KEY_ID=test")); + } + + @Test + void executionRoleCredentialsStillBeatOwnerAccountId() { + // A function that does assume a role has real credentials for it; the owning-account + // placeholder is only for the fall-through case. + LaunchedContainerAwsEnv awsEnv = awsEnvWithHostEnv("http://localhost:4566", Map.of()); + SessionCreds credentials = new SessionCreds("ASIAEXECUTIONROLE", "role-secret", "role-token"); + + List env = awsEnv.sdkBaselineEnv( + "us-east-1", Optional.empty(), Optional.of(credentials), "041922743467"); + + assertTrue(env.contains("AWS_ACCESS_KEY_ID=ASIAEXECUTIONROLE")); + } + + @Test + void mountedConfigDirIgnoresOwnerAccountId() { + LaunchedContainerAwsEnv awsEnv = awsEnvWithHostEnv("http://localhost:4566", Map.of()); + + List env = awsEnv.sdkBaselineEnv( + "us-east-1", Optional.of("/opt/aws-config"), Optional.empty(), "041922743467"); + + assertTrue(env.stream().noneMatch(e -> e.startsWith("AWS_ACCESS_KEY_ID="))); + } + + private LaunchedContainerAwsEnv awsEnvWithHostEnv(String baseUrl, Map hostEnv) { + ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class); + when(endpoint.baseUrl()).thenReturn(baseUrl); + return new LaunchedContainerAwsEnv(endpoint, hostEnv::get); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.java index 692f52c2be..57dc64adbd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/SigV4ValidatorTest.java @@ -116,6 +116,30 @@ class SigV4ValidatorTest { assertFalse(validator.validate(token, "cache-cluster-01", "default")); } + /** + * A bare 12-digit access key ID that isn't registered in IAM must be rejected like any + * other unknown key, not resolved to the well-known "test" secret. That fallback would let + * a client forge an IAM-auth token for any account number, signed with the public "test" + * secret, and authenticate as any matching cache user — a bypass of ElastiCache IAM + * authentication, which is only consulted when a caller has explicitly opted into it. + */ + @Test + void validateRejectsUnregisteredNumericAccessKeyId() throws Exception { + IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache"); + + SigV4Validator validator = new SigV4Validator(iamService); + String token = SigV4TokenTestHelper.createElastiCacheToken( + "cache-cluster-01", + "default", + "123456789012", + "test", + Instant.now().minusSeconds(60), + 900 + ); + + assertFalse(validator.validate(token, "cache-cluster-01", "default")); + } + @Test void validateRejectsTokenForWrongUser() throws Exception { IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache"); diff --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.java index 8ea5cb1e64..bde16eb0c8 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 @@ -345,10 +345,12 @@ class ContainerLauncherTest { } @Test - void launchFunction_fallsBackToTestCredentialsWhenEnvUnset() throws Exception { - // When System.getenv returns null for AWS vars, credentials should be test/test/test. - // Since we can't control System.getenv in unit tests, we verify the values are either - // from the environment or the "test" fallback — both are valid. + void launchFunction_injectsOwningAccountAsAccessKeyAndFallsBackForTheRest() throws Exception { + // The access key identifies the container's owning account to AccountResolver, so it is + // the function's resolved account (here the configured default, since this function has + // no ARN to derive one from) rather than the literal "test" placeholder. The secret and + // session token carry no account identity, so they still come from the host env or fall + // back to "test"; System.getenv can't be controlled here, so both are accepted. Path codePath = Files.createDirectory(tempDir.resolve("creds-fallback")); LambdaFunction fn = new LambdaFunction(); @@ -364,16 +366,45 @@ class ContainerLauncherTest { String secretKey = env.stream().filter(e -> e.startsWith("AWS_SECRET_ACCESS_KEY=")).findFirst().orElse(""); String sessionToken = env.stream().filter(e -> e.startsWith("AWS_SESSION_TOKEN=")).findFirst().orElse(""); - // Value should be either the host env var or "test" fallback - String expectedAk = System.getenv("AWS_ACCESS_KEY_ID") != null ? System.getenv("AWS_ACCESS_KEY_ID") : "test"; + // The owning account wins outright — including over a host env var, which describes the + // Floci server process and not the container it launched. String expectedSk = System.getenv("AWS_SECRET_ACCESS_KEY") != null ? System.getenv("AWS_SECRET_ACCESS_KEY") : "test"; String expectedSt = System.getenv("AWS_SESSION_TOKEN") != null ? System.getenv("AWS_SESSION_TOKEN") : "test"; - assertEquals("AWS_ACCESS_KEY_ID=" + expectedAk, accessKey); + assertEquals("AWS_ACCESS_KEY_ID=000000000000", accessKey); assertEquals("AWS_SECRET_ACCESS_KEY=" + expectedSk, secretKey); assertEquals("AWS_SESSION_TOKEN=" + expectedSt, sessionToken); } + @Test + void launchFunction_partialUserCredentialEnvironmentDoesNotSplitOwnerAccountTuple() throws Exception { + // A Lambda with no execution role falls onto the owner-account placeholder tuple. If the + // function's own Environment config defines only AWS_ACCESS_KEY_ID (no matching secret or + // session token), that partial value must not leak in and override just the access key — + // it would pair the user's key with the owner-account's "test" secret/token, a tuple + // nothing can verify. The injection must be all-or-nothing: since the function does not + // define the full triad, none of its credential vars should reach the container. + Path codePath = Files.createDirectory(tempDir.resolve("creds-partial")); + + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName("partial-creds-fn"); + fn.setRuntime("nodejs20.x"); + fn.setHandler("index.handler"); + fn.setCodeLocalPath(codePath.toString()); + fn.setFunctionArn("arn:aws:lambda:us-east-1:111122223333:function:partial-creds-fn"); + fn.setEnvironment(Map.of("AWS_ACCESS_KEY_ID", "user-partial-key")); + + launcher.launch(fn); + + List env = captureRealContainerSpec().env(); + assertEquals(1, env.stream().filter(e -> e.startsWith("AWS_ACCESS_KEY_ID=")).count(), + "the owner-account access key must not be joined by a second, user-supplied one"); + assertTrue(env.contains("AWS_ACCESS_KEY_ID=111122223333"), + "the owner-account access key must win when the function's own triad is incomplete"); + assertTrue(env.stream().noneMatch("AWS_ACCESS_KEY_ID=user-partial-key"::equals), + "a partial user-supplied access key must never override the owner-account baseline"); + } + @Test void launchFunction_injectsConfiguredDefaultRegionWhenArnMissing() throws Exception { Path codePath = Files.createDirectory(tempDir.resolve("region-default")); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java index 080225dfb0..9d904beaea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java @@ -32,6 +32,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.lenient; @@ -130,6 +131,48 @@ class KubernetesPodLauncherTest { }); } + @Test + void launchPassesTheFunctionsOwningAccountIntoTheBaselineAwsEnv() { + // A pod-launched Lambda is subject to the same placeholder-credential bug as a + // Docker-launched one: without the owning account it resolves to the emulator's + // default account and reads the wrong partition. + markPodPhaseInBackground("floci-lambda-my-fn-", "Running"); + var fn = function(); + fn.setAccountId("222222222222"); + fn.setFunctionArn("arn:aws:lambda:us-east-1:222222222222:function:my-fn"); + + launcher.launch(fn); + + verify(awsEnv).sdkBaselineEnv(eq("us-east-1"), eq(Optional.empty()), + eq("http://10.0.0.5:4566"), eq(Optional.empty()), eq("222222222222")); + } + + @Test + void launchDoesNotLetAPartialUserCredentialEnvironmentSplitTheBaselineTuple() { + // This launcher never has execution-role credentials, so every pod rides the + // owner-account/placeholder baseline. If the function's own Environment config defines + // only AWS_ACCESS_KEY_ID (no matching secret or session token), that partial value must + // not override just the baseline's access key and leave its secret/token in place. + markPodPhaseInBackground("floci-lambda-my-fn-", "Running"); + lenient().when(awsEnv.sdkBaselineEnv(anyString(), any(), anyString(), any(), anyString())) + .thenReturn(List.of( + "AWS_ACCESS_KEY_ID=000000000000", + "AWS_SECRET_ACCESS_KEY=test", + "AWS_SESSION_TOKEN=test")); + var fn = function(); + fn.setEnvironment(Map.of("AWS_ACCESS_KEY_ID", "user-partial-key")); + + launcher.launch(fn); + + var pod = client.pods().inNamespace("default").list().getItems().stream() + .filter(p -> p.getMetadata().getName().startsWith("floci-lambda-my-fn-")) + .findFirst().orElseThrow(); + var envVars = pod.getSpec().getContainers().getFirst().getEnv(); + assertThat(envVars).extracting(EnvVar::getName, EnvVar::getValue) + .contains(tuple("AWS_ACCESS_KEY_ID", "000000000000")) + .doesNotContain(tuple("AWS_ACCESS_KEY_ID", "user-partial-key")); + } + @Test void launchCreatesPodAndReturnsHandle() { markPodPhaseInBackground("floci-lambda-my-fn-", "Running"); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java index 5849c6f8ad..a059ff035d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java @@ -126,6 +126,31 @@ class RdsSigV4ValidatorTest { assertFalse(validator.validate(token, "admin")); } + /** + * A bare 12-digit access key ID that isn't registered in IAM must be rejected like any + * other unknown key, not resolved to the well-known "test" secret. That fallback would let + * a client forge an IAM-auth token for any account number, signed with the public "test" + * secret, and authenticate as any matching database user — a bypass of RDS IAM + * authentication, which is only consulted when a caller has explicitly opted into it. + */ + @Test + void validateRejectsUnregisteredNumericAccessKeyId() throws Exception { + IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds"); + + RdsSigV4Validator validator = new RdsSigV4Validator(iamService); + String token = SigV4TokenTestHelper.createRdsToken( + "db.example.local", + 5432, + "admin", + "123456789012", + "test", + Instant.now().minusSeconds(60), + 900 + ); + + assertFalse(validator.validate(token, "admin")); + } + @Test void validateRejectsTokenMissingDbUser() throws Exception { IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds"); diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilterTest.java index 89fdeb380e..d18b4c428e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilterTest.java @@ -1,13 +1,40 @@ package io.github.hectorvent.floci.services.s3; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.testutil.IamServiceTestHelper; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; import org.junit.jupiter.api.Test; +import java.lang.reflect.Method; + import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; class PreSignedUrlFilterTest { + /** + * A bare 12-digit access key ID that isn't registered in IAM must be rejected like any + * other unknown key, not resolved to the well-known "test" secret. That fallback would let + * a client sign an arbitrary account's X-Amz-Credential with the public "test" secret and + * have account resolution treat the forged value as the request's account — an + * authentication bypass under S3 auth enforcement (see AccountResolver, which reads a + * 12-digit access key ID as the account directly). + */ + private static String resolveSecretKey(PreSignedUrlFilter filter, String accessKeyId) throws Exception { + Method method = PreSignedUrlFilter.class.getDeclaredMethod("resolveSecretKey", String.class); + method.setAccessible(true); + return (String) method.invoke(filter, accessKeyId); + } + + @Test + void resolveSecretKeyRejectsUnregisteredNumericAccessKeyId() throws Exception { + IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDUNRELATED", "unrelated-secret"); + PreSignedUrlFilter filter = new PreSignedUrlFilter(null, null, iamService); + + assertNull(resolveSecretKey(filter, "123456789012")); + } + private static MultivaluedMap params() { return new MultivaluedHashMap<>(); }