fix(lambda): resolve layer version ARNs by account (#2948)

* fix(lambda): resolve layer version ARNs by account

Layer resolution dropped the ARN's account segment, so an ARN naming another
account resolved inside the caller's own partition. Two consequences, filed
separately as #2813 and #2809.

A foreign ARN whose layer name and version happened to match one of the
caller's own resolved to that layer: the function recorded an ARN it was not
using, and the launcher mounted different content at /opt than
GetFunctionConfiguration reported. resolveLayerByArn now scopes the lookup to
the caller's account and partition, so a foreign ARN is a miss.

A foreign ARN that matched nothing was rejected outright, which no AWS-managed
public layer can ever satisfy: Powertools, the AppConfig extension and
Datadog-published layers all live in AWS-owned accounts, and every Terraform
stack attaching one failed at CreateFunction. Validation now applies the
eager existence check only to the caller's own account and records a foreign
ARN unresolved, warning that its content is not mounted.

Measured against the live service in ap-southeast-1:

  CreateFunction, foreign ARN matching an own layer name/version
    -> AccessDeniedException, not a substitution
  CreateFunction, AWS-managed Powertools layer
    -> 201, ARN echoed verbatim on GetFunctionConfiguration
  CreateFunction, missing layer in the caller's own account
    -> InvalidParameterValueException: Layer version ... does not exist.

The own-account message and status are unchanged, matching that third case
exactly. The AccessDenied case is a known divergence: Floci implements no
layer permissions, so it cannot tell a public layer from one the caller has no
policy for, and accepts both.

Closes #2813
Closes #2809

* fix(lambda): reject foreign-partition layer ARNs when attaching them

GetLayerVersionByArn already answers a non-aws partition with
InvalidParameterValueException, but CreateFunction and
UpdateFunctionConfiguration accepted the same ARN and persisted it, so a
function could carry a layer Floci's own lookup path calls invalid.

Partitions are isolated, so no resource policy can ever make a cn or
gov layer readable from the aws partition. That is what separates it
from a foreign account, where a policy can, and where AWS-managed public
layers live. Foreign accounts stay accepted; foreign partitions now
reject with the message GetLayerVersionByArn already uses.

Measured on CreateFunction in ap-southeast-1: a cross-partition layer
ARN and a foreign-account layer ARN both fail with AccessDeniedException,
so the live service does not distinguish them at this call. The split
here is Floci's, on reachability grounds, and is documented as such.

* fix(lambda): gate foreign-account layer ARNs behind a config flag

Review asked for the accept-foreign-ARN behaviour to be opt-in rather than the
default, on both PRs' reasoning that it broadens what CreateFunction accepts
beyond AWS. It is now floci.services.lambda.accept-external-layer-arns, default
false, env FLOCI_SERVICES_LAMBDA_ACCEPT_EXTERNAL_LAYER_ARNS.

Off, a layer ARN naming another account is refused. On, it is recorded on the
function verbatim and its content is not mounted, which is what a stack
attaching Powertools or the AppConfig extension needs. A same-account ARN is
unaffected either way: a missing layer is still the eager
InvalidParameterValueException.

The refusal is AccessDeniedException, 403, not the InvalidParameterValueException
this branch previously used for the partition case. That was the second review
finding: the live probe in this PR measured CreateFunction returning
AccessDeniedException for a cross-partition ARN and the identical
AccessDeniedException for a same-partition foreign account, so reporting a
different error class than what was measured was an observable divergence
presented as parity. Both now report what AWS reported.

Cross-partition stays refused with the flag on. Partitions are isolated, so no
resource policy can make an aws-cn layer readable from aws, and
GetLayerVersionByArn already calls such an ARN invalid.

Negative control, with the default flipped to true and the tests kept:

  LambdaLayerArnAccountIntegrationTest
    foreignAccountArnIsDeniedByDefaultAndTheFunctionIsNotCreated
    updateFunctionConfigurationIsDeniedAndLeavesTheExistingLayerInPlace
  Tests run: 7, Failures: 2

Also moves the two generic ARN ownership checks this branch was adding into
AwsArnUtils as isForeignPartition and isForeignAccount, so the layer code keeps
only the layer-shaped part. Review noted RdsService.targetGroupBelongsTo already
carries its own copy and asked not to land a further one. The existing RDS, EKS
and EC2 copies are deliberately left alone; this only avoids adding another.
This commit is contained in:
Brian Taylor authored and GitHub committed 2026-09-13 00:19:37 -04:00
1 parent 27def6079d
commit 24a8c8440b
9 files changed
+631 -25

No files matched your search

@@ -0,0 +1,64 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Ownership predicates for a parsed ARN. Both are generic on purpose: RdsService already carries
* its own copy of the same two checks inside targetGroupBelongsTo, and Lambda layer resolution
* needs them too, so the resource-shaped part stays with the caller and only these live here.
*/
class AwsArnOwnershipTest {
private static final String LOCAL = "000000000000";
private static AwsArnUtils.Arn arn(String value) {
return AwsArnUtils.parse(value);
}
@Test
void awsPartitionIsNotForeign() {
assertFalse(AwsArnUtils.isForeignPartition(
arn("arn:aws:lambda:us-east-1:000000000000:layer:l:1")));
}
@Test
void otherPartitionsAreForeign() {
assertTrue(AwsArnUtils.isForeignPartition(
arn("arn:aws-cn:lambda:cn-north-1:000000000000:layer:l:1")));
assertTrue(AwsArnUtils.isForeignPartition(
arn("arn:aws-us-gov:lambda:us-gov-west-1:000000000000:layer:l:1")));
}
@Test
void anEmptyPartitionIsNotForeign() {
assertFalse(AwsArnUtils.isForeignPartition(arn("arn::lambda:us-east-1:000000000000:layer:l:1")));
}
@Test
void theCallersOwnAccountIsNotForeign() {
assertFalse(AwsArnUtils.isForeignAccount(
arn("arn:aws:lambda:us-east-1:000000000000:layer:l:1"), LOCAL));
}
@Test
void anotherAccountIsForeign() {
assertTrue(AwsArnUtils.isForeignAccount(
arn("arn:aws:lambda:us-east-1:017000801446:layer:l:1"), LOCAL));
}
@Test
void anEmptyAccountIsNotForeign() {
// AWS-managed layers use arn:aws:lambda:::awslayer:<name>, which names no account and is
// not somebody else's resource.
assertFalse(AwsArnUtils.isForeignAccount(arn("arn:aws:lambda:::awslayer:AWSLambda-Python"), LOCAL));
}
@Test
void nullIsNotForeign() {
assertFalse(AwsArnUtils.isForeignPartition(null));
assertFalse(AwsArnUtils.isForeignAccount(null, LOCAL));
}
}
@@ -0,0 +1,157 @@
package io.github.hectorvent.floci.services.lambda;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
/**
* {@code floci.services.lambda.accept-external-layer-arns} turned on.
*
* <p>The default refuses every foreign-account layer ARN, because Floci has no layer permission
* model and so cannot tell an AWS-managed public layer from a private one that AWS would refuse.
* A stack attaching Powertools, the AppConfig extension or a vendor-published layer needs the
* permissive answer, which is what this flag selects: the ARN is recorded verbatim and its
* content is never mounted.
*
* <p>Cross-partition stays refused even here. Partitions are isolated, so no resource policy can
* make an {@code aws-cn} layer readable from {@code aws}, and {@code GetLayerVersionByArn} calls
* such an ARN invalid outright.
*/
@QuarkusTest
@TestProfile(LambdaExternalLayerArnAcceptedIntegrationTest.AcceptExternalLayerArnsProfile.class)
class LambdaExternalLayerArnAcceptedIntegrationTest {
private static final String POWERTOOLS_ARN =
"arn:aws:lambda:us-east-1:017000801446:layer:AWSLambdaPowertoolsPythonV3-python313-arm64:36";
private static String zipBase64(String path, String content) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry(path));
zos.write(content.getBytes());
zos.closeEntry();
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
private static void createFunction(String name, String layerArn, int expectedStatus) throws Exception {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"Runtime": "python3.12",
"Role": "arn:aws:iam::000000000000:role/r",
"Handler": "handler.handler",
"Code": { "ZipFile": "%s" },
"Layers": ["%s"]
}
""".formatted(name, zipBase64("handler.py", "def handler(e, c): return {}"), layerArn))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(expectedStatus);
}
@Test
void awsManagedLayerArnIsAcceptedAndEchoedVerbatim() throws Exception {
createFunction("ext-layer-managed", POWERTOOLS_ARN, 201);
given()
.when()
.get("/2015-03-31/functions/ext-layer-managed")
.then()
.statusCode(200)
.body("Configuration.Layers", hasSize(1))
.body("Configuration.Layers[0].Arn", equalTo(POWERTOOLS_ARN));
given()
.when()
.delete("/2015-03-31/functions/ext-layer-managed")
.then()
.statusCode(204);
}
@Test
void updateFunctionConfigurationAcceptsAForeignAccountArn() throws Exception {
createFunction("ext-layer-update", POWERTOOLS_ARN, 201);
String other = "arn:aws:lambda:us-east-1:017000801446:layer:AWSLambdaPowertoolsPythonV3-python313-arm64:37";
given()
.contentType("application/json")
.body("""
{
"Layers": ["%s"]
}
""".formatted(other))
.when()
.put("/2015-03-31/functions/ext-layer-update/configuration")
.then()
.statusCode(200)
.body("Layers", hasSize(1))
.body("Layers[0].Arn", equalTo(other));
given()
.when()
.delete("/2015-03-31/functions/ext-layer-update")
.then()
.statusCode(204);
}
@Test
void foreignPartitionArnIsStillRejected() throws Exception {
createFunction("ext-layer-foreign-partition",
"arn:aws-cn:lambda:cn-north-1:123456789012:layer:probe:1", 403);
given()
.when()
.get("/2015-03-31/functions/ext-layer-foreign-partition")
.then()
.statusCode(404);
}
@Test
void missingLayerInTheCallersOwnAccountIsStillRejected() throws Exception {
// The flag only relaxes foreign ARNs. A typo in the caller's own account is still the
// eager InvalidParameterValueException AWS gives, which is the case #2813 relies on.
given()
.contentType("application/json")
.body("""
{
"FunctionName": "ext-layer-typo",
"Runtime": "python3.12",
"Role": "arn:aws:iam::000000000000:role/r",
"Handler": "handler.handler",
"Code": { "ZipFile": "%s" },
"Layers": ["arn:aws:lambda:us-east-1:000000000000:layer:no-such-layer:1"]
}
""".formatted(zipBase64("handler.py", "def handler(e, c): return {}")))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
public static final class AcceptExternalLayerArnsProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.lambda.accept-external-layer-arns", "true",
"quarkus.http.test-port", "4588",
"floci.port", "4588",
"floci.base-url", "http://localhost:4588");
}
}
}
@@ -0,0 +1,242 @@
package io.github.hectorvent.floci.services.lambda;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Layer version ARNs carry an account, and resolution has to honour it.
*
* <p>Measured against the live service in ap-southeast-1. An ARN in another account whose layer
* name and version match one of the caller's own is {@code AccessDeniedException}, never a
* substitution; a cross-partition ARN is the same {@code AccessDeniedException}; and only a
* missing layer in the caller's own account is
* {@code InvalidParameterValueException: Layer version ... does not exist.}
*
* <p>This class covers the default configuration, which answers every foreign ARN the way AWS
* answers a non-public one. {@code floci.services.lambda.accept-external-layer-arns} relaxes that
* for same-partition ARNs, covered by {@link LambdaExternalLayerArnAcceptedIntegrationTest}.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class LambdaLayerArnAccountIntegrationTest {
private static final String LAYER_NAME = "arn-account-layer";
private static final String LOCAL_ACCOUNT = "000000000000";
private static final String FOREIGN_ACCOUNT = "017000801446";
private static final String POWERTOOLS_ARN =
"arn:aws:lambda:us-east-1:017000801446:layer:AWSLambdaPowertoolsPythonV3-python313-arm64:36";
@Inject
LambdaLayerService layerService;
private static String zipBase64(String path, String content) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
zos.putNextEntry(new ZipEntry(path));
zos.write(content.getBytes());
zos.closeEntry();
}
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
private static String publishLayer() throws Exception {
return given()
.contentType("application/json")
.body("""
{
"Content": { "ZipFile": "%s" },
"CompatibleRuntimes": ["python3.12"]
}
""".formatted(zipBase64("python/shared.py", "VALUE = 1")))
.when()
.post("/2018-10-31/layers/" + LAYER_NAME + "/versions")
.then()
.statusCode(201)
.extract().path("LayerVersionArn");
}
private static void createFunction(String name, String layerArn, int expectedStatus) throws Exception {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "%s",
"Runtime": "python3.12",
"Role": "arn:aws:iam::000000000000:role/r",
"Handler": "handler.handler",
"Code": { "ZipFile": "%s" },
"Layers": ["%s"]
}
""".formatted(name, zipBase64("handler.py", "def handler(e, c): return {}"), layerArn))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(expectedStatus);
}
@Test
@Order(1)
void foreignAccountArnDoesNotResolveToTheCallersOwnSameNamedLayer() throws Exception {
String ownArn = publishLayer();
assertNotNull(layerService.resolveLayerByArn(ownArn),
"the caller's own layer must still resolve by its own ARN");
String foreignArn = ownArn.replace(":" + LOCAL_ACCOUNT + ":", ":" + FOREIGN_ACCOUNT + ":");
assertNull(layerService.resolveLayerByArn(foreignArn),
"an ARN naming another account must not resolve to the caller's same-named layer");
}
@Test
@Order(2)
void foreignPartitionArnDoesNotResolveToTheLocalLayer() throws Exception {
String ownArn = publishLayer();
assertNull(layerService.resolveLayerByArn(ownArn.replace("arn:aws:", "arn:aws-cn:")),
"an ARN in another partition must not resolve to the local layer");
}
@Test
@Order(2)
void foreignPartitionArnIsRejectedWhenAttachedToAFunction() throws Exception {
// The live probe returns AccessDeniedException for a cross-partition ARN, identical to
// the foreign-account case, so this reports what was measured rather than reusing
// GetLayerVersionByArn's InvalidParameterValueException. Nothing is persisted either way.
String arn = "arn:aws-cn:lambda:cn-north-1:123456789012:layer:probe:1";
createFunction("arn-account-foreign-partition", arn, 403);
given()
.when()
.get("/2015-03-31/functions/arn-account-foreign-partition")
.then()
.statusCode(404);
}
@Test
@Order(3)
void foreignAccountArnIsDeniedByDefaultAndTheFunctionIsNotCreated() throws Exception {
// Floci cannot tell a public layer from a private one without a layer permission model,
// so the default gives the answer AWS gives to everything but a public layer.
given()
.contentType("application/json")
.body("""
{
"FunctionName": "arn-account-managed",
"Runtime": "python3.12",
"Role": "arn:aws:iam::000000000000:role/r",
"Handler": "handler.handler",
"Code": { "ZipFile": "%s" },
"Layers": ["%s"]
}
""".formatted(zipBase64("handler.py", "def handler(e, c): return {}"), POWERTOOLS_ARN))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(403)
.body("__type", equalTo("AccessDeniedException"))
.body("message", equalTo(
"User is not authorized to perform: lambda:GetLayerVersion on resource: "
+ POWERTOOLS_ARN + " because no resource-based policy allows the"
+ " lambda:GetLayerVersion action"));
given()
.when()
.get("/2015-03-31/functions/arn-account-managed")
.then()
.statusCode(404);
}
@Test
@Order(4)
void missingLayerInTheCallersOwnAccountIsStillRejected() throws Exception {
given()
.contentType("application/json")
.body("""
{
"FunctionName": "arn-account-typo",
"Runtime": "python3.12",
"Role": "arn:aws:iam::000000000000:role/r",
"Handler": "handler.handler",
"Code": { "ZipFile": "%s" },
"Layers": ["arn:aws:lambda:us-east-1:000000000000:layer:no-such-layer:1"]
}
""".formatted(zipBase64("handler.py", "def handler(e, c): return {}")))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"))
.body("message", equalTo(
"Layer version arn:aws:lambda:us-east-1:000000000000:layer:no-such-layer:1"
+ " does not exist."));
}
@Test
@Order(5)
void updateFunctionConfigurationIsDeniedAndLeavesTheExistingLayerInPlace() throws Exception {
String ownArn = publishLayer();
createFunction("arn-account-update", ownArn, 201);
given()
.contentType("application/json")
.body("""
{
"Layers": ["%s"]
}
""".formatted(POWERTOOLS_ARN))
.when()
.put("/2015-03-31/functions/arn-account-update/configuration")
.then()
.statusCode(403)
.body("__type", equalTo("AccessDeniedException"));
// A refused update must not have partially applied: the original layer is still attached.
given()
.when()
.get("/2015-03-31/functions/arn-account-update")
.then()
.statusCode(200)
.body("Configuration.Layers", hasSize(1))
.body("Configuration.Layers[0].Arn", equalTo(ownArn));
given()
.when()
.delete("/2015-03-31/functions/arn-account-update")
.then()
.statusCode(204);
}
// Cleanup: every version this class published, so a sibling class sees no leftovers.
@Test
@Order(20)
void cleanup_deleteLayerVersions() {
for (int version = 1; version <= 3; version++) {
given()
.when()
.delete("/2018-10-31/layers/" + LAYER_NAME + "/versions/" + version)
.then()
.statusCode(204);
}
given()
.when()
.get("/2018-10-31/layers/" + LAYER_NAME + "/versions")
.then()
.statusCode(200)
.body("LayerVersions", hasSize(0));
}
}