mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user