mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(lambda): resolve launched-container placeholder creds to the owning account (#2657)
* fix(lambda): resolve launched-container placeholder creds to the function's owning account A Lambda that never assumes an execution role falls through to placeholder credentials, and the literal AWS_ACCESS_KEY_ID=test that ContainerLauncher then injected is not a 12-digit account ID, so AccountResolver resolved every such container to the emulator's default (management) account regardless of which account actually owns the function. Account-partitioned reads and writes then collide or miss whenever the real resource lives elsewhere -- observed as five accounts' LoggingStack custom resources simultaneously colliding on one AWSServiceRoleForAutoscaling during an LZA Stage 1 run, and non-deterministically, since account IDs are re-minted every pipeline run. sdkBaselineEnv now takes the workload's owning account and injects it as the placeholder access key. It wins over Floci's own ambient AWS_ACCESS_KEY_ID: the server process's credentials describe the server, not a container it launches, and a deployment that exports AWS_ACCESS_KEY_ID (the floci-lza image sets it unconditionally) would otherwise make the owning-account branch dead code. Mounted ~/.aws and real execution-role credentials still take precedence, and launch paths that don't know the owning account are unaffected. Recovered from 092cb16a5 + d25f1cefc, re-derived onto upstream's current shape: the fork's 3-arg overload would collide with upstream's flociEndpoint overload, so the account rides on the injectedCredentials-carrying signatures instead, and ContainerLauncher passes the lambdaAccountId it already resolves. The host env lookup moved behind a package-private seam so the precedence is actually testable -- the fork's own regression test asserted it without ever forcing the host env to be set, and so could not have failed. Drops the branch's local-only issues/*.md ledger entry and scripts/describe-sg-as.sh diagnostic. * fix(lambda): pass the owning account into Kubernetes-launched Lambda pods too The pod launcher builds the same baseline AWS environment as the Docker one and so had the same defect: a Lambda that never assumes an execution role fell through to the "test" placeholder access key and resolved to the emulator's default account. It already derives the owning account for its layer downloads, so it now passes it to sdkBaselineEnv as well. ECS, MWAA and Flink container managers deliberately stay on the account-less overload -- those workloads have no owning Lambda function to derive one from. * fix(lambda): resolve owning-account placeholder AKID to the test secret in SigV4 validation sdkBaselineEnv gives a Lambda without an execution role and a known owning account that account ID (a bare 12-digit string) as AWS_ACCESS_KEY_ID, paired with the "test" placeholder secret. Floci's own SigV4 validators for S3 presigned URLs, ElastiCache IAM auth, and RDS IAM auth look up the secret for an unregistered access key and previously fell back to either null or the access key itself, which only coincidentally matched when both sides were the literal "test"/"test" pair. Once the access key became a 12-digit account ID instead, the fallback no longer matched the "test" secret the client actually signed with, and every such presigned URL or IAM auth token failed validation. Each validator's fallback now recognizes a bare 12-digit access key specifically as this placeholder and expects the "test" secret for it, while any other unregistered access key keeps its prior behavior (InvalidAccessKeyId for S3, signature mismatch for ElastiCache/RDS) so a genuinely unknown key is still rejected. * fix(lambda): force test secret and session token on the owner-account placeholder path The owner-account AKID branch in LaunchedContainerAwsEnv still paired the numeric owner-account access key with Floci's own ambient AWS_SECRET_ACCESS_KEY when one was set. The S3, RDS, and ElastiCache SigV4 validators only accept a numeric access key paired with the literal "test" secret, so a non-test ambient secret produced a credential pair nothing could verify, breaking presigned URLs and IAM-auth tokens. Force the secret and session token to "test" whenever the owner-account AKID wins, and scope the ambient-credential-forwarding warning to the branch where it actually forwards them. * fix(security): reject unregistered numeric access keys in SigV4 validators The S3 presigned-URL filter, RDS SigV4 validator, and ElastiCache SigV4 validator each treated any unregistered 12-digit access key ID as a valid credential when paired with the literal "test" secret. Since AccountResolver reads a 12-digit access key ID as the request's account directly, this let a client forge a signed request or IAM-auth token for an arbitrary account number using the well-known "test" secret, bypassing S3 auth enforcement and RDS/ElastiCache IAM authentication for any matching database or cache user. Remove the numeric-access-key fallback from all three validators; an unregistered key is rejected the same way any other unknown key is. This narrows the owner-account placeholder credentials added for launched Lambdas to paths that don't require a real signature check; ledgered in issues/ for a follow-up that mints real per-account session credentials instead. * fix(lambda): reject partial user credential overrides on the placeholder path Both the Docker and Kubernetes launchers appended a Lambda's own Environment config after the owner-account/placeholder AWS credential baseline. When the function defined only a subset of AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/ AWS_SESSION_TOKEN, that partial value overrode just its own key in the baseline tuple, pairing a user-chosen value with the owner-account's other credential parts -- a combination no SigV4 validator accepts and which could resolve requests to the wrong account. Credential injection from a function's Environment is now all-or-nothing: only a fully-specified triad is allowed to override the baseline; anything less is dropped so the baseline stays intact.
This commit is contained in:
1 parent
e9a379b37a
commit
be892864db
12 files changed
+373
-22
No files matched your search
+56
-9
@@ -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<String> 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<String> 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<String> sdkBaselineEnv(String region, Optional<String> awsConfigMountDir,
|
||||
Optional<SessionCreds> 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<String> sdkBaselineEnv(String region, Optional<String> awsConfigMountDir,
|
||||
String flociEndpoint, Optional<SessionCreds> injectedCredentials) {
|
||||
return sdkBaselineEnv(region, awsConfigMountDir, flociEndpoint, injectedCredentials, null);
|
||||
}
|
||||
|
||||
/** Full variant, additionally taking the workload's owning account. */
|
||||
public List<String> sdkBaselineEnv(String region, Optional<String> awsConfigMountDir,
|
||||
String flociEndpoint, Optional<SessionCreds> injectedCredentials,
|
||||
String ownerAccountId) {
|
||||
var env = new ArrayList<String>();
|
||||
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);
|
||||
|
||||
+5
@@ -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)
|
||||
|
||||
+27
-3
@@ -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<String, String> 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.
|
||||
*
|
||||
|
||||
+13
-2
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<String> 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;
|
||||
}
|
||||
|
||||
+97
@@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String, String> hostEnv) {
|
||||
ContainerReachableEndpoint endpoint = mock(ContainerReachableEndpoint.class);
|
||||
when(endpoint.baseUrl()).thenReturn(baseUrl);
|
||||
return new LaunchedContainerAwsEnv(endpoint, hostEnv::get);
|
||||
}
|
||||
}
|
||||
+24
@@ -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");
|
||||
|
||||
+38
-7
@@ -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<String> 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"));
|
||||
|
||||
+43
@@ -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");
|
||||
|
||||
+25
@@ -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");
|
||||
|
||||
@@ -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<String, String> params() {
|
||||
return new MultivaluedHashMap<>();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user