mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
27def6079d
commit
24a8c8440b
9 files changed
+631
-25
No files matched your search
+28
-7
@@ -200,13 +200,34 @@ architecture. `Marker` is opaque and signed with a key generated at startup, so
|
||||
edited or previous-run token is rejected with `InvalidParameterValueException` rather than
|
||||
applied as a cursor. One divergence: a parameter sent with an empty value
|
||||
(`?CompatibleRuntime=`) is treated as absent rather than rejected, because RESTEasy binds an
|
||||
empty query value as null. `CreateFunction`/`UpdateFunctionConfiguration`
|
||||
validate each `Layers` ARN eagerly against that storage, matching real AWS - an unresolvable ARN
|
||||
is rejected with `InvalidParameterValueException`, not silently accepted. Only resolves layers
|
||||
published into this same local Floci instance; a real AWS-owned layer ARN (e.g. the AWS AppConfig
|
||||
Extension or a Datadog-published layer) can never resolve here, since there's no mechanism in
|
||||
Floci for fetching real AWS content - publish your own copy of the layer's content locally under
|
||||
a name you control and reference that ARN instead.
|
||||
empty query value as null. Resolution honours the ARN's
|
||||
account and partition: an ARN naming another account resolves to nothing rather than to a
|
||||
same-named layer of the caller's own, matching the live service, which answers that case with
|
||||
`AccessDeniedException` and never substitutes. `CreateFunction`/`UpdateFunctionConfiguration`
|
||||
validate each `Layers` ARN in the caller's own account eagerly against that storage, matching
|
||||
real AWS - an unresolvable one is rejected with `InvalidParameterValueException: Layer version
|
||||
... does not exist.`, not silently accepted.
|
||||
|
||||
An ARN naming another account or another partition is answered on the live service by the layer's
|
||||
resource policy: an AWS-managed public layer resolves, and everything else is
|
||||
`AccessDeniedException`. Measured on `CreateFunction` in ap-southeast-1, a foreign-account ARN and
|
||||
a cross-partition ARN return the same `AccessDeniedException`, so Floci returns that for both.
|
||||
Floci implements no layer permissions and cannot fetch real AWS content, so it cannot tell a
|
||||
public layer from a private one; refusing is the faithful default, being the answer AWS gives to
|
||||
every foreign ARN except a public one.
|
||||
|
||||
Set `floci.services.lambda.accept-external-layer-arns: true`
|
||||
(`FLOCI_SERVICES_LAMBDA_ACCEPT_EXTERNAL_LAYER_ARNS`) to record a same-partition foreign ARN on the
|
||||
function instead of refusing it, which is what a stack attaching Powertools, the AppConfig
|
||||
extension or a vendor-published layer needs. The trade is explicit: with it on, Floci also accepts
|
||||
an ARN AWS would refuse with `AccessDeniedException`, so a typo or a private third-party layer
|
||||
passes here and fails on deploy. The content is never mounted at `/opt` either way, and a warning
|
||||
is logged at attach time and again at invoke; publish your own copy of the content locally under a
|
||||
name you control if the handler needs it at runtime.
|
||||
|
||||
A layer ARN outside the `aws` partition is refused whatever that setting says. Partitions are
|
||||
isolated, so no resource policy can ever make such a layer readable, and `GetLayerVersionByArn`
|
||||
rejects one outright with `InvalidParameterValueException: Invalid layer version ...`.
|
||||
|
||||
## Not Implemented
|
||||
|
||||
|
||||
@@ -2147,6 +2147,28 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
Optional<List<String>> extraHosts();
|
||||
|
||||
/**
|
||||
* Accept a {@code Layers} ARN naming another account, recording it on the function
|
||||
* without mounting its content. Off by default, because it broadens what CreateFunction
|
||||
* and UpdateFunctionConfiguration accept beyond what AWS does.
|
||||
*
|
||||
* <p>On the live service a foreign-account layer resolves through its resource policy:
|
||||
* an AWS-managed public layer succeeds, and everything else is AccessDeniedException.
|
||||
* Floci implements no layer permissions, so it cannot tell those apart. The default
|
||||
* answers both the way AWS answers the second, which is the faithful choice for a
|
||||
* compatibility layer. Turn this on to attach public layers such as Powertools, the
|
||||
* AppConfig extension or a vendor-published layer, at the cost of also accepting an
|
||||
* ARN AWS would refuse. The content is never fetched either way, so a function whose
|
||||
* behaviour depends on the layer will not run correctly here.
|
||||
*
|
||||
* <p>A layer ARN outside the {@code aws} partition is rejected regardless: partitions
|
||||
* are isolated, so no resource policy can make one readable.
|
||||
*
|
||||
* Env var: FLOCI_SERVICES_LAMBDA_ACCEPT_EXTERNAL_LAYER_ARNS
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean acceptExternalLayerArns();
|
||||
|
||||
/**
|
||||
* Concurrent executions ceiling applied per region. AWS Lambda's
|
||||
* "account-level" concurrency is in fact a per-region quota (default 1000);
|
||||
|
||||
@@ -129,6 +129,36 @@ public final class AwsArnUtils {
|
||||
return isArn(value) && value.split(":", 6)[2].equals(service);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the ARN names a partition other than {@code aws}, the only one Floci emulates.
|
||||
* An empty partition field is not foreign: callers that omit it are naming a local
|
||||
* resource.
|
||||
*
|
||||
* <p>Deliberately a literal {@code aws} rather than {@link #PARTITION_REGEX}. That constant
|
||||
* exists to recognise a legal ARN in any partition; this asks the opposite question, whether
|
||||
* the ARN names a partition this emulator can serve, and the answer is only ever the
|
||||
* commercial one.
|
||||
*/
|
||||
public static boolean isForeignPartition(Arn arn) {
|
||||
if (arn == null) {
|
||||
return false;
|
||||
}
|
||||
String partition = arn.partition();
|
||||
return partition != null && !partition.isEmpty() && !"aws".equals(partition);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the ARN names an account other than {@code localAccountId}. An empty account
|
||||
* field is not foreign: several AWS ARN forms omit it for a resource the caller owns.
|
||||
*/
|
||||
public static boolean isForeignAccount(Arn arn, String localAccountId) {
|
||||
if (arn == null) {
|
||||
return false;
|
||||
}
|
||||
String account = arn.accountId();
|
||||
return account != null && !account.isEmpty() && !account.equals(localAccountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an SQS ARN to a queue URL using the given base URL.
|
||||
* Example: arn:aws:sqs:us-east-1:000000000000:my-queue → http://localhost:4566/000000000000/my-queue
|
||||
|
||||
@@ -454,24 +454,15 @@ public class LambdaLayerService {
|
||||
+ " constraint: Member must satisfy regular expression pattern: "
|
||||
+ LAYER_VERSION_ARN_PATTERN, 400);
|
||||
}
|
||||
// resolveLayerByArn keys on region/name/version within the caller's own partition, so an
|
||||
// ARN naming another account would otherwise resolve to the caller's same-named layer.
|
||||
// No layer here can be shared cross-account (layer permissions are unimplemented), so a
|
||||
// foreign account is always a miss; this is where sharing would hook in if that changes.
|
||||
// resolveLayerByArn also drops the partition, so an ARN naming another one would
|
||||
// otherwise resolve to the local layer under a foreign-partition ARN. Floci emulates
|
||||
// the aws partition; the live service rejects the others outright.
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(layerVersionArn);
|
||||
if (parsed.partition() != null && !parsed.partition().isEmpty()
|
||||
&& !"aws".equals(parsed.partition())) {
|
||||
// Floci emulates the aws partition; the live service rejects the others outright, and
|
||||
// with a different error than an unresolvable ARN, so this precedes the lookup.
|
||||
if (AwsArnUtils.isForeignPartition(AwsArnUtils.parse(layerVersionArn))) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Invalid layer version " + layerVersionArn, 400);
|
||||
}
|
||||
String requestedAccount = AwsArnUtils.accountOrDefault(layerVersionArn, null);
|
||||
if (requestedAccount != null && !requestedAccount.equals(regionResolver.getAccountId())) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The resource you requested does not exist.", 404);
|
||||
}
|
||||
// A foreign account is a miss rather than a substitution: resolveLayerByArn scopes the
|
||||
// lookup to the caller's own account. This is where cross-account sharing would hook in
|
||||
// if layer permissions were ever implemented.
|
||||
LambdaLayerVersion lv = resolveLayerByArn(layerVersionArn);
|
||||
if (lv == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
@@ -496,6 +487,9 @@ public class LambdaLayerService {
|
||||
if (resourceParts.length < 3 || !"layer".equals(resourceParts[0])) {
|
||||
return null;
|
||||
}
|
||||
if (isForeignLayerArn(arn)) {
|
||||
return null;
|
||||
}
|
||||
String region = arn.region();
|
||||
String layerName = resourceParts[1];
|
||||
long version;
|
||||
@@ -507,6 +501,52 @@ public class LambdaLayerService {
|
||||
return layerStore.get(region, layerName, version).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the ARN is a well-formed layer version ARN naming an account or partition other
|
||||
* than the caller's, so Floci cannot decide whether it exists. On the live service such a
|
||||
* layer resolves through its resource policy, measured against ap-southeast-1: an ARN in
|
||||
* another account whose name and version match a layer of the caller's own is
|
||||
* {@code AccessDeniedException}, never a substitution. Floci has no layer permission model
|
||||
* (see the Not Implemented list), so it treats every foreign ARN as unknowable rather than
|
||||
* resolving it inside the caller's own partition.
|
||||
*/
|
||||
public boolean isForeignLayerArn(String layerVersionArn) {
|
||||
AwsArnUtils.Arn arn = parseLayerVersionArn(layerVersionArn);
|
||||
if (arn == null) {
|
||||
return false;
|
||||
}
|
||||
return isForeignLayerArn(arn);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the ARN is a well-formed layer version ARN outside the {@code aws} partition.
|
||||
* Partitions are isolated, so such a layer is unreachable rather than merely unreadable, and
|
||||
* {@link #getLayerVersionByArn} already rejects it outright. Attaching one to a function has
|
||||
* to reject too, or Floci would persist an ARN its own lookup path calls invalid.
|
||||
*/
|
||||
public boolean isForeignPartitionLayerArn(String layerVersionArn) {
|
||||
return AwsArnUtils.isForeignPartition(parseLayerVersionArn(layerVersionArn));
|
||||
}
|
||||
|
||||
private AwsArnUtils.Arn parseLayerVersionArn(String layerVersionArn) {
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(layerVersionArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
String[] resourceParts = arn.resource().split(":");
|
||||
if (resourceParts.length < 3 || !"layer".equals(resourceParts[0])) {
|
||||
return null;
|
||||
}
|
||||
return arn;
|
||||
}
|
||||
|
||||
private boolean isForeignLayerArn(AwsArnUtils.Arn arn) {
|
||||
return AwsArnUtils.isForeignPartition(arn)
|
||||
|| AwsArnUtils.isForeignAccount(arn, regionResolver.getAccountId());
|
||||
}
|
||||
|
||||
private byte[] resolveLayerContent(Map<String, Object> content) {
|
||||
String zipFileBase64 = (String) content.get("ZipFile");
|
||||
if (zipFileBase64 != null) {
|
||||
|
||||
@@ -234,13 +234,42 @@ public class LambdaService implements ResourceProvider {
|
||||
// content mounted, which is correct AWS-parity behavior for a layer deleted *after* being
|
||||
// attached (AWS doesn't re-validate on every invoke either), but was previously the only
|
||||
// signal at all for a bad ARN, even a typo caught at attach time on real AWS.
|
||||
//
|
||||
// An ARN naming another account or another partition is answered on the live service by the
|
||||
// layer's resource policy: a public layer resolves, and everything else is
|
||||
// AccessDeniedException. Measured on CreateFunction in ap-southeast-1, a foreign-account ARN
|
||||
// and a cross-partition ARN return the same AccessDeniedException, so Floci returns that for
|
||||
// both rather than inventing a distinction the API does not make.
|
||||
//
|
||||
// Floci implements no layer permissions, so it cannot tell a public layer from a private one
|
||||
// and cannot fetch either one's content. Refusing is the faithful default: it is the answer
|
||||
// AWS gives to every foreign ARN except a public layer. floci.services.lambda
|
||||
// .accept-external-layer-arns records a same-partition foreign ARN unresolved instead, which
|
||||
// is what a stack attaching Powertools or the AppConfig extension needs. Cross-partition
|
||||
// stays refused even then, because partitions are isolated and no policy can reach across
|
||||
// one, and because GetLayerVersionByArn already calls such an ARN invalid.
|
||||
private void validateLayersResolvable(List<String> layerArns) {
|
||||
if (layerArns == null || layerService == null) return;
|
||||
for (String arn : layerArns) {
|
||||
if (layerService.resolveLayerByArn(arn) == null) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Layer version " + arn + " does not exist.", 400);
|
||||
if (layerService.resolveLayerByArn(arn) != null) {
|
||||
continue;
|
||||
}
|
||||
if (layerService.isForeignLayerArn(arn)) {
|
||||
boolean acceptable = !layerService.isForeignPartitionLayerArn(arn)
|
||||
&& config != null
|
||||
&& config.services().lambda().acceptExternalLayerArns();
|
||||
if (!acceptable) {
|
||||
throw new AwsException("AccessDeniedException",
|
||||
"User is not authorized to perform: lambda:GetLayerVersion on resource: "
|
||||
+ arn + " because no resource-based policy allows the"
|
||||
+ " lambda:GetLayerVersion action", 403);
|
||||
}
|
||||
LOG.warnv("Layer {0} belongs to another account; recorded on the function but its"
|
||||
+ " content will not be mounted at /opt", arn);
|
||||
continue;
|
||||
}
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"Layer version " + arn + " does not exist.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -291,6 +291,7 @@ floci:
|
||||
container-idle-timeout-seconds: 300
|
||||
region-concurrency-limit: 1000
|
||||
unreserved-concurrency-min: 100
|
||||
accept-external-layer-arns: false # FLOCI_SERVICES_LAMBDA_ACCEPT_EXTERNAL_LAYER_ARNS - accept a Layers ARN from another account (content is never mounted). AWS answers these through the layer resource policy, which Floci does not model, so the default refuses them like AWS refuses a non-public one. Turn on to attach public layers such as Powertools.
|
||||
# aws-config-path: # Host path to bind-mount (read-only) at /opt/aws-config for real credential discovery
|
||||
# extra-hosts: # Extra /etc/hosts entries for Lambda containers, "hostname:ip" ("host-gateway" allowed as ip)
|
||||
# container-name-prefix: floci # FLOCI_SERVICES_LAMBDA_CONTAINER_NAME_PREFIX — base name prefix for spawned containers and code volumes ([A-Za-z0-9][A-Za-z0-9_.-]*; invalid values fall back to "floci")
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
+157
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+242
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user