fix(lambda): enforce function policies on cross-account calls (#5476)

Under IAM enforcement, a caller whose own policy allowed lambda:InvokeFunction could invoke
another account's function by ARN even when that function's policy granted nothing, and
RotateSecret could be pointed at another account's function the same way. Three things combined:
there was no resource-policy provider for Lambda, so the call was judged as same-account; the
function name was cut at its first colon, so an ARN was evaluated as function:arn in the caller's
account, where no Allow or Deny written for the function could match; and the invoke followed the
account in the ARN.

- LambdaResourcePolicyProvider supplies a function's policy statements and the account its ARN
  names, also when the function has no policy, so a call to another account's function needs that
  function's policy to allow the caller as well as the caller's own policy. It is keyed on the
  ARN, so RotateSecret's check on its rotation function, made under the secretsmanager scope,
  sees it too.
- ResourceArnBuilder evaluates each call against the function it acts on. An invoke runs in the
  account and Region a full or partial ARN names, as the version or alias it names in the function
  name or in Qualifier, since Lambda authorizes a qualified call against the qualified ARN.
  GetFunction, GetFunctionConfiguration and ListDurableExecutionsByFunction read a qualified full
  ARN in the account it names, so they are evaluated there too, and a read of another account's
  function needs its policy as on AWS. Every other route acts on the caller's own function of that
  name, so it is evaluated against that function, unqualified because not all of their handlers
  act on the qualifier.
- An invoke by partial ARN runs in the account it names, as one by full ARN already did.
- RotateSecret looks its function up where the rotation runs it: in the ARN's account, and as the
  version or alias the ARN names.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-11 21:47:27 -05:00
1 parent 23c6666a51
commit 6d7d85f0f8
13 files changed
+827 -24

No files matched your search

@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
@@ -78,7 +79,7 @@ public class ResourceArnBuilder {
String path = ctx.getUriInfo().getPath();
return switch (credentialScope) {
case "s3" -> List.of(buildS3Arn(path, region));
case "lambda" -> List.of(buildLambdaArn(path, region, accountId));
case "lambda" -> List.of(buildLambdaArn(path, ctx, region, accountId));
case "sqs" -> List.of(buildSqsArn(ctx, region, accountId));
case "sns" -> List.of(buildSnsArn(ctx, region, accountId));
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
@@ -541,7 +542,19 @@ public class ResourceArnBuilder {
}
// ── Lambda ──────────────────────────────────────────────────────────────────
private String buildLambdaArn(String path, String region, String accountId) {
/**
* The function a Lambda request acts on, as an IAM policy names it. An invoke runs the function
* in the account and Region its full or partial ARN names, so it is evaluated against that
* function, and against the version or alias it names in the function name or in
* {@code Qualifier}, since Lambda authorizes a qualified call against the qualified ARN (Lambda
* Developer Guide, "Referencing functions in the Resource section of policies"). The reads
* {@link #readsInTheAccountItNames} names act in the account a qualified ARN names too. Every
* other route acts on the caller's own function of that name, whatever account an ARN names.
* Those are evaluated unqualified, because not every one of them acts on the qualifier it is
* given.
*/
private String buildLambdaArn(String path, ContainerRequestContext ctx, String region, String accountId) {
String executionArn = durableExecutionArn(path);
if (executionArn == null) {
executionArn = durableCallbackExecutionArn(path);
@@ -552,10 +565,49 @@ public class ResourceArnBuilder {
// path: /2015-03-31/functions/name or similar
String name = extractSegmentAfter(path, "functions");
if (name == null) return "*";
// strip qualifier if present
int colon = name.indexOf(':');
if (colon > 0) name = name.substring(0, colon);
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString();
boolean invoke = path.endsWith("/functions/" + name + "/invocations");
try {
if (!invoke) {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(name);
boolean namedAccount = readsInTheAccountItNames(path, name, ref, ctx);
return AwsArnUtils.Arn.of("lambda",
namedAccount ? ref.region() : region,
namedAccount ? ref.account() : accountId,
"function:" + ref.name()).toString();
}
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolveWithQualifier(
name, ctx.getUriInfo().getQueryParameters().getFirst("Qualifier"));
String resource = ref.qualifier() != null
? "function:" + ref.name() + ":" + ref.qualifier()
: "function:" + ref.name();
return AwsArnUtils.Arn.of("lambda",
ref.region() != null ? ref.region() : region,
ref.account() != null ? ref.account() : accountId,
resource).toString();
} catch (AwsException e) {
// A reference Lambda refuses, which its handler answers with a 400 before acting on anything.
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString();
}
}
/**
* {@code GetFunction}, {@code GetFunctionConfiguration} and {@code ListDurableExecutionsByFunction}
* read a function named by a qualified full ARN in the account the ARN names, where the version or
* alias is resolved ({@code LambdaService.getFunction(region, name, qualifier)}). Unqualified, or
* by partial ARN, they read the caller's own function of that name, as every other route acts.
*/
private static boolean readsInTheAccountItNames(String path, String name,
LambdaArnUtils.ResolvedFunctionRef ref,
ContainerRequestContext ctx) {
if (!"GET".equals(ctx.getMethod()) || !name.startsWith("arn:")) {
return false;
}
String route = path.substring(path.indexOf("/functions/" + name) + "/functions/".length() + name.length());
if (!route.isEmpty() && !route.equals("/configuration") && !route.equals("/durable-executions")) {
return false;
}
String qualifier = ctx.getUriInfo().getQueryParameters().getFirst("Qualifier");
return ref.qualifier() != null || (qualifier != null && !qualifier.isBlank());
}
/** Durable execution actions are authorized against the execution ARN, which carries the version. */
@@ -0,0 +1,81 @@
package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Supplies Lambda function policies to the IAM policy evaluation pipeline, together with the account
* that owns the function.
*
* <p>The owner is the account in the function ARN, and it is returned even when the function has no
* policy or does not exist: a call to another account's function is then judged as cross-account,
* which needs the function policy to allow the caller as well as the caller's own policy (Lambda
* Developer Guide, function URLs: "If the principal making the request is in a different account,
* then the principal must have both an identity-based policy ... and permissions granted to them in
* a resource-based policy").
*
* <p>All of a function's statements are returned, its own and those of its versions and aliases. Each
* statement's {@code Resource} names the function, version or alias it was added to, so matching it
* against the ARN the call names is what scopes it: a grant on an alias covers calls to that alias
* only, and one on the function does not cover a qualified call (Lambda Developer Guide, "Referencing
* functions in the Resource section of policies").
*
* <p>Keyed on the ARN rather than the request's credential scope, because a function is also the
* second resource of calls signed for another service: {@code RotateSecret} checks
* {@code lambda:InvokeFunction} on its rotation function under the {@code secretsmanager} scope.
*/
@ApplicationScoped
public class LambdaResourcePolicyProvider implements ResourcePolicyProvider {
private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
/** A function, version or alias, or a durable execution under one: the name is group 1. */
private static final Pattern FUNCTION_RESOURCE = Pattern.compile("function:([^:/]+)(?:[:/].*)?");
private final LambdaService lambdaService;
private final ObjectMapper objectMapper;
@Inject
public LambdaResourcePolicyProvider(LambdaService lambdaService, ObjectMapper objectMapper) {
this.lambdaService = lambdaService;
this.objectMapper = objectMapper;
}
@Override
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
if (!AwsArnUtils.isArnFor(resourceArn, "lambda")) {
return List.of();
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
Matcher function = FUNCTION_RESOURCE.matcher(arn.resource());
if (!function.matches() || !ACCOUNT_ID.matcher(arn.accountId()).matches()) {
return List.of();
}
List<Map<String, Object>> statements =
lambdaService.policyStatements(arn.accountId(), arn.region(), function.group(1));
return List.of(new ResourcePolicy(policyDocument(statements), arn.accountId()));
}
private String policyDocument(List<Map<String, Object>> statements) {
if (statements.isEmpty()) {
return null;
}
Map<String, Object> policy = new LinkedHashMap<>();
policy.put("Version", "2012-10-17");
policy.put("Statement", statements);
try {
return objectMapper.writeValueAsString(policy);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not serialize the function policy", e);
}
}
}
@@ -1232,9 +1232,10 @@ public class LambdaService implements ResourceProvider {
String name = ref.name();
String qualifier = ref.qualifier();
LambdaFunction fn;
if (functionName.startsWith("arn:")) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(functionName);
fn = targetResolver.resolveInvokeTargetForAccount(arn.accountId(), region, name, qualifier);
// A full or partial ARN names its account, which is where the function runs and what IAM
// enforcement authorized the call against.
if (ref.account() != null) {
fn = targetResolver.resolveInvokeTargetForAccount(ref.account(), region, name, qualifier);
} else {
fn = targetResolver.resolveInvokeTarget(region, name, qualifier);
}
@@ -3731,6 +3732,40 @@ public class LambdaService implements ResourceProvider {
}
}
/**
* Every statement in the resource-based policies of a function in {@code accountId}: the
* function's own and those of each of its versions and aliases, which each statement's
* {@code Resource} tells apart. Read under the lock the policy mutations hold, so a statement
* being added or removed is seen whole or not at all. Empty when the function does not exist or
* has no policy.
*/
public List<Map<String, Object>> policyStatements(String accountId, String region, String functionName) {
Optional<LambdaFunction> observed = functionStore.getForAccount(accountId, region, functionName);
if (observed.isEmpty()) {
return List.of();
}
synchronized (lockForPolicyMutation(observed.get().getFunctionArn())) {
return functionStore.getForAccount(accountId, region, functionName)
.map(fn -> fn.getPolicies().stream()
.<Map<String, Object>>map(LinkedHashMap::new)
.toList())
.orElse(List.of());
}
}
/**
* Reads the function, version or alias a full ARN names, in the ARN's own account and Region,
* where an invoke of that ARN runs it. {@link #getFunction(String, String)} reads a name in the
* caller's account, which for another account's ARN is a different function or none.
*/
public LambdaFunction getFunctionByArn(String functionArn) {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionArn);
if (ref.region() == null || ref.account() == null) {
throw new AwsException("InvalidParameterValueException", "Not a function ARN: " + functionArn, 400);
}
return targetResolver.resolveReadTargetForAccount(ref.account(), ref.region(), ref.name(), ref.qualifier());
}
/**
* Puts a previously captured policy statement back. Used to compensate when a replacement fails
* after the original was removed: it takes the stored statement shape rather than an
@@ -1149,10 +1149,11 @@ public class SecretsManagerService implements ResourceProvider {
// A function that cannot be found is reported the way AWS reports it, AccessDeniedException with
// HTTP 400; any other reference Lambda refuses is an invalid RotationLambdaARN. Either way the
// secret is left as it was.
// secret is left as it was. The function is looked up where the rotation will invoke it: in the
// ARN's account, and as the version or alias the ARN names.
if (!serviceManaged && lambdaService != null) {
try {
lambdaService.getFunction(region, functionArn);
lambdaService.getFunctionByArn(functionArn);
} catch (AwsException e) {
if (e.getHttpStatus() == 404) {
throw new AwsException("AccessDeniedException",