mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambda): serve layer version permissions and read them as the layer's resource policy (#9764)
AddLayerVersionPermission, RemoveLayerVersionPermission and GetLayerVersionPolicy had no handler, so a layer's owner
could not grant another account, an organization or everyone lambda:GetLayerVersion on one of its versions, as the
Lambda Developer Guide says it must ("To use a layer in another account, the owner of that account must grant your
account permission in a resource-based policy").
LambdaLayerPolicyService keeps a layer version's statements with the version, in the order they were added, each
granting lambda:GetLayerVersion to an account (written as its root ARN), to everyone, or to an organization
(aws:PrincipalOrgID), with a revision each change renews. Its answers are AWS's, as the aws-emulator evaluation
suite records them: a statement id already in the policy is a ResourceConflictException that leaves the revision as
it was; a RevisionId other than the latest a PreconditionFailedException, before anything changes; an OrganizationId
with an account principal an InvalidParameterValueException; a policy past 20480 characters a
PolicyLengthExceededException; the model's constraints a ValidationException in member order; and a version that
never had a policy and one whose every statement was removed answer differently ("No policy is associated with the
given resource." and "Layer version ... does not have any resource policy.").
LambdaResourcePolicyProvider now returns a layer version's policy, owned by the account in its ARN, so under IAM
enforcement a caller in another account is refused lambda:GetLayerVersion on it until its owner grants that account.
Reading another account's layer once granted is not served yet: GetLayerVersionByArn still resolves a layer only in
the caller's own account.
This commit is contained in:
1 parent
0722c64a1f
commit
2efd250432
11 files changed
+851
-18
No files matched your search
@@ -33,7 +33,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*`, `/tag/*` | REST JSON | 30 |
|
||||
| [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 54 |
|
||||
| [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 |
|
||||
| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 69 |
|
||||
| [Lambda](lambda.md) | `/2015-03-31/functions/...` + `/2025-12-01/durable-executions/...` | REST JSON | 72 |
|
||||
| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 23 |
|
||||
| [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 |
|
||||
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 102 |
|
||||
|
||||
+20
-4
@@ -53,6 +53,9 @@ Floci Lambda runs your function code locally inside real Docker containers - clo
|
||||
| `ListLayerVersions` | List the versions of a layer, optionally by runtime and architecture |
|
||||
| `ListLayers` | List layers with their newest version, optionally by runtime and architecture |
|
||||
| `DeleteLayerVersion` | Delete a layer version |
|
||||
| `AddLayerVersionPermission` | Grant an account, an organization or everyone `lambda:GetLayerVersion` on a layer version |
|
||||
| `GetLayerVersionPolicy` | Get a layer version's resource-based policy and its revision |
|
||||
| `RemoveLayerVersionPermission` | Remove a statement from a layer version's policy |
|
||||
| `ListTags` | List tags on a function or event source mapping |
|
||||
| `TagResource` | Tag a function or event source mapping |
|
||||
| `UntagResource` | Untag a function or event source mapping |
|
||||
@@ -611,6 +614,23 @@ A layer ARN outside the caller's partition is refused whatever that setting says
|
||||
isolated, so no resource policy can ever make such a layer readable, and `GetLayerVersionByArn`
|
||||
rejects one outright with `InvalidParameterValueException: Invalid layer version ...`.
|
||||
|
||||
**Layer permissions:** `AddLayerVersionPermission`, `GetLayerVersionPolicy` and
|
||||
`RemoveLayerVersionPermission` keep a layer version's resource-based policy, the statements granting
|
||||
`lambda:GetLayerVersion` to an account (written as its root ARN), to everyone (`*`), or to an
|
||||
organization (`*` with `OrganizationId`, as `aws:PrincipalOrgID`), each with a revision that a
|
||||
`RevisionId` must match. The answers are AWS's own: a statement id already in the policy is a
|
||||
`ResourceConflictException` that leaves the revision as it was, a stale `RevisionId` a
|
||||
`PreconditionFailedException`, an organization with an account principal an
|
||||
`InvalidParameterValueException`, a policy past 20480 characters a `PolicyLengthExceededException`,
|
||||
and a version that never had a policy and one whose every statement was removed answer
|
||||
`GetLayerVersionPolicy` differently ("No policy is associated with the given resource." and "Layer
|
||||
version ... does not have any resource policy."). The policy goes with the version when it is deleted.
|
||||
Under IAM enforcement it is the version's resource policy, owned by the account in its ARN, so a caller
|
||||
in another account is refused `lambda:GetLayerVersion` on it until the owner grants that account, as
|
||||
AWS's "the owner of that account must grant your account permission in a resource-based policy" says.
|
||||
Reading another account's layer version once granted is not served yet: `GetLayerVersionByArn` still
|
||||
resolves a layer only in the caller's own account.
|
||||
|
||||
## Provisioned concurrency
|
||||
|
||||
Published versions with `SnapStart.ApplyOn=PublishedVersions` reject provisioned concurrency
|
||||
@@ -699,10 +719,6 @@ For a longer drain, explicitly stop with the larger timeout and then start Floci
|
||||
|
||||
## Not Implemented
|
||||
|
||||
These AWS Lambda operations have no handler in Floci. Calls will return `404` or an error:
|
||||
|
||||
- Layer permissions (`AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`)
|
||||
|
||||
Code signing enforcement is not emulated: an attached configuration never gates a deployment.
|
||||
The attachment lifecycle is supported for `$LATEST`: `PutFunctionCodeSigningConfig` attaches or
|
||||
replaces a configuration, `GetFunctionCodeSigningConfig` reads it,
|
||||
|
||||
@@ -34,6 +34,9 @@ import java.util.Map;
|
||||
* DeleteLayerVersion: DELETE /2018-10-31/layers/{LayerName}/versions/{VersionNumber}
|
||||
* ListLayers: GET /2018-10-31/layers
|
||||
* GetLayerVersionByArn: GET /2018-10-31/layers?find=LayerVersion&Arn={arn}
|
||||
* AddLayerVersionPermission: POST /2018-10-31/layers/{LayerName}/versions/{VersionNumber}/policy
|
||||
* GetLayerVersionPolicy: GET /2018-10-31/layers/{LayerName}/versions/{VersionNumber}/policy
|
||||
* RemoveLayerVersionPermission: DELETE /2018-10-31/layers/{LayerName}/versions/{VersionNumber}/policy/{StatementId}
|
||||
*/
|
||||
@Path("/2018-10-31")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -44,16 +47,19 @@ public class LambdaLayerController {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final LambdaLayerService layerService;
|
||||
private final LambdaLayerPolicyService policyService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final PreSignedUrlGenerator presignGenerator;
|
||||
|
||||
@Inject
|
||||
public LambdaLayerController(ObjectMapper objectMapper,
|
||||
LambdaLayerService layerService,
|
||||
LambdaLayerPolicyService policyService,
|
||||
RegionResolver regionResolver,
|
||||
PreSignedUrlGenerator presignGenerator) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.layerService = layerService;
|
||||
this.policyService = policyService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.presignGenerator = presignGenerator;
|
||||
}
|
||||
@@ -111,6 +117,48 @@ public class LambdaLayerController {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/layers/{layerName}/versions/{versionNumber}/policy")
|
||||
public Response addLayerVersionPermission(@PathParam("layerName") String layerName,
|
||||
@PathParam("versionNumber") long versionNumber,
|
||||
@QueryParam("RevisionId") String revisionId,
|
||||
@Context HttpHeaders headers,
|
||||
Map<String, Object> request) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
LambdaLayerPolicyService.Added added = policyService.addLayerVersionPermission(region, layerName,
|
||||
versionNumber, request, revisionId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("Statement", added.statement());
|
||||
root.put("RevisionId", added.revisionId());
|
||||
return Response.status(201).entity(root).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/layers/{layerName}/versions/{versionNumber}/policy")
|
||||
public Response getLayerVersionPolicy(@PathParam("layerName") String layerName,
|
||||
@PathParam("versionNumber") long versionNumber,
|
||||
@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
LambdaLayerPolicyService.Policy policy = policyService.getLayerVersionPolicy(region, layerName,
|
||||
versionNumber);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("Policy", policy.policy());
|
||||
root.put("RevisionId", policy.revisionId());
|
||||
return Response.ok(root).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/layers/{layerName}/versions/{versionNumber}/policy/{statementId}")
|
||||
public Response removeLayerVersionPermission(@PathParam("layerName") String layerName,
|
||||
@PathParam("versionNumber") long versionNumber,
|
||||
@PathParam("statementId") String statementId,
|
||||
@QueryParam("RevisionId") String revisionId,
|
||||
@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
policyService.removeLayerVersionPermission(region, layerName, versionNumber, statementId, revisionId);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
/**
|
||||
* ListLayers, and GetLayerVersionByArn when {@code find=LayerVersion}. AWS gives the two
|
||||
* actions the same method and path, and JAX-RS cannot route on a query parameter. The match
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.services.lambda.model.LambdaLayerVersion;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The resource-based policy of a Lambda layer version: AddLayerVersionPermission, RemoveLayerVersionPermission and
|
||||
* GetLayerVersionPolicy, through which a layer's owner grants other accounts, an organization or everyone
|
||||
* {@code lambda:GetLayerVersion} on one of its versions ("To use a layer in another account, the owner of that account
|
||||
* must grant your account permission in a resource-based policy", Lambda Developer Guide). The statements are kept
|
||||
* with the version, in the order they were added, and go with it when it is deleted.
|
||||
*
|
||||
* <p>The refusals are AWS's own, as its fidelity checks record them (aws/aws-emulator-evaluation-suite,
|
||||
* {@code behavioral/lambda/check_layer_permission_lifecycle.py} and its neighbours): a version that never had a policy
|
||||
* and one whose every statement was removed answer GetLayerVersionPolicy differently, a statement id already in the
|
||||
* policy is a conflict that leaves the revision as it was, and a revision id other than the policy's latest is refused
|
||||
* before anything changes.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaLayerPolicyService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaLayerPolicyService.class);
|
||||
|
||||
/** The botocore model's constraints on the request members, which the service checks in member order. */
|
||||
private static final String STATEMENT_ID_PATTERN = "([a-zA-Z0-9-_]+)";
|
||||
private static final int STATEMENT_ID_MAX_LENGTH = 100;
|
||||
private static final String ACTION_PATTERN = "lambda:GetLayerVersion";
|
||||
private static final int ACTION_MAX_LENGTH = 22;
|
||||
private static final String PRINCIPAL_PATTERN = "\\d{12}|\\*|arn:(aws[a-zA-Z-]*):iam::\\d{12}:root";
|
||||
private static final String ORGANIZATION_ID_PATTERN = "o-[a-z0-9]{10,32}";
|
||||
private static final int ORGANIZATION_ID_MAX_LENGTH = 34;
|
||||
private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
|
||||
/** The size a layer version's policy may reach, as AWS's PolicyLengthExceededException names it. */
|
||||
static final int POLICY_SIZE_LIMIT = 20480;
|
||||
|
||||
private static final String NO_POLICY = "No policy is associated with the given resource.";
|
||||
private static final String STALE_REVISION = "The Revision Id provided does not match the latest Revision Id. "
|
||||
+ "Call the GetLayerPolicy API to retrieve the latest Revision Id";
|
||||
|
||||
private final LambdaLayerService layerService;
|
||||
private final LambdaLayerStore layerStore;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public LambdaLayerPolicyService(LambdaLayerService layerService, LambdaLayerStore layerStore,
|
||||
RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this.layerService = layerService;
|
||||
this.layerStore = layerStore;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/** A statement added to a version's policy, as JSON, and the policy's new revision. */
|
||||
public record Added(String statement, String revisionId) {
|
||||
}
|
||||
|
||||
/** A version's policy, as JSON, and its revision. */
|
||||
public record Policy(String policy, String revisionId) {
|
||||
}
|
||||
|
||||
public Added addLayerVersionPermission(String region, String layerName, long versionNumber,
|
||||
Map<String, Object> request, String revisionId) {
|
||||
String statementId = text(request, "StatementId");
|
||||
String action = text(request, "Action");
|
||||
String principal = text(request, "Principal");
|
||||
String organizationId = text(request, "OrganizationId");
|
||||
List<String> violations = new ArrayList<>();
|
||||
violation(violations, "statementId", statementId, STATEMENT_ID_PATTERN, STATEMENT_ID_MAX_LENGTH, true);
|
||||
violation(violations, "action", action, ACTION_PATTERN, ACTION_MAX_LENGTH, true);
|
||||
violation(violations, "principal", principal, PRINCIPAL_PATTERN, Integer.MAX_VALUE, true);
|
||||
violation(violations, "organizationId", organizationId, ORGANIZATION_ID_PATTERN,
|
||||
ORGANIZATION_ID_MAX_LENGTH, false);
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(violations);
|
||||
}
|
||||
if (organizationId != null && !"*".equals(principal)) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"If organization id is specified then principal should be *", 400);
|
||||
}
|
||||
LambdaLayerVersion found = version(region, layerName, versionNumber);
|
||||
synchronized (lock(found)) {
|
||||
LambdaLayerVersion version = version(region, layerName, versionNumber);
|
||||
requireRevision(version, revisionId);
|
||||
List<Map<String, Object>> statements = version.getPolicy() == null ? new ArrayList<>()
|
||||
: new ArrayList<>(version.getPolicy());
|
||||
if (statements.stream().anyMatch(statement -> statementId.equals(statement.get("Sid")))) {
|
||||
throw new AwsException("ResourceConflictException", "The statement id (" + statementId
|
||||
+ ") provided already exists. Please provide a new statement id, or remove the existing "
|
||||
+ "statement.", 409);
|
||||
}
|
||||
Map<String, Object> statement = statement(version, statementId, action, principal, organizationId);
|
||||
statements.add(statement);
|
||||
int size = json(document(statements)).length();
|
||||
if (size > POLICY_SIZE_LIMIT) {
|
||||
throw new AwsException("PolicyLengthExceededException", "The final policy size (" + size
|
||||
+ ") is bigger than the limit (" + POLICY_SIZE_LIMIT + ").", 400);
|
||||
}
|
||||
version.setPolicy(statements);
|
||||
version.setPolicyRevisionId(UUID.randomUUID().toString());
|
||||
save(version);
|
||||
LOG.infov("Added permission {0} to layer version {1}", statementId, version.getLayerVersionArn());
|
||||
return new Added(json(statement), version.getPolicyRevisionId());
|
||||
}
|
||||
}
|
||||
|
||||
/** The version's policy and the revision it was written with, read under the lock its writers hold. */
|
||||
public Policy getLayerVersionPolicy(String region, String layerName, long versionNumber) {
|
||||
LambdaLayerVersion found = version(region, layerName, versionNumber);
|
||||
synchronized (lock(found)) {
|
||||
LambdaLayerVersion version = version(region, layerName, versionNumber);
|
||||
if (version.getPolicy() == null) {
|
||||
throw new AwsException("ResourceNotFoundException", NO_POLICY, 404);
|
||||
}
|
||||
if (version.getPolicy().isEmpty()) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Layer version " + version.getLayerVersionArn() + " does not have any resource policy.", 404);
|
||||
}
|
||||
return new Policy(json(document(version.getPolicy())), version.getPolicyRevisionId());
|
||||
}
|
||||
}
|
||||
|
||||
public void removeLayerVersionPermission(String region, String layerName, long versionNumber, String statementId,
|
||||
String revisionId) {
|
||||
LambdaLayerVersion found = version(region, layerName, versionNumber);
|
||||
synchronized (lock(found)) {
|
||||
LambdaLayerVersion version = version(region, layerName, versionNumber);
|
||||
if (version.getPolicy() == null || version.getPolicy().isEmpty()) {
|
||||
throw new AwsException("ResourceNotFoundException", NO_POLICY, 404);
|
||||
}
|
||||
requireRevision(version, revisionId);
|
||||
List<Map<String, Object>> statements = new ArrayList<>(version.getPolicy());
|
||||
if (!statements.removeIf(statement -> Objects.equals(statementId, statement.get("Sid")))) {
|
||||
throw new AwsException("ResourceNotFoundException", NO_POLICY, 404);
|
||||
}
|
||||
version.setPolicy(statements);
|
||||
version.setPolicyRevisionId(UUID.randomUUID().toString());
|
||||
save(version);
|
||||
LOG.infov("Removed permission {0} from layer version {1}", statementId, version.getLayerVersionArn());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements of the policy of the layer version {@code layerVersionArn} names, in the account and Region the
|
||||
* ARN names; empty for a version with none, or none stored.
|
||||
*/
|
||||
public List<Map<String, Object>> policyStatements(String layerVersionArn) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(layerVersionArn);
|
||||
String[] parts = arn.resource().split(":");
|
||||
if (parts.length != 3 || !"layer".equals(parts[0])) {
|
||||
return List.of();
|
||||
}
|
||||
long number;
|
||||
try {
|
||||
number = Long.parseLong(parts[2]);
|
||||
} catch (NumberFormatException e) {
|
||||
return List.of();
|
||||
}
|
||||
return layerStore.getForAccount(arn.accountId(), arn.region(), parts[1], number)
|
||||
.map(LambdaLayerVersion::getPolicy)
|
||||
.orElse(List.of());
|
||||
}
|
||||
|
||||
/** The caller's layer version the name or ARN and the number select, refused as AWS refuses a missing one. */
|
||||
private LambdaLayerVersion version(String region, String layerName, long versionNumber) {
|
||||
try {
|
||||
return layerService.getLayerVersion(region, layerName, versionNumber);
|
||||
} catch (AwsException e) {
|
||||
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
String layerArn = AwsArnUtils.looksLikeArn(layerName) ? layerName
|
||||
: AwsArnUtils.Arn.of("lambda", region, regionResolver.getAccountId(), "layer:" + layerName)
|
||||
.toString();
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Layer version " + layerArn + ":" + versionNumber + " does not exist.", 404);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireRevision(LambdaLayerVersion version, String revisionId) {
|
||||
if (revisionId != null && !revisionId.equals(version.getPolicyRevisionId())) {
|
||||
throw new AwsException("PreconditionFailedException", STALE_REVISION, 412);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> statement(LambdaLayerVersion version, String statementId, String action,
|
||||
String principal, String organizationId) {
|
||||
Map<String, Object> statement = new LinkedHashMap<>();
|
||||
statement.put("Sid", statementId);
|
||||
statement.put("Effect", "Allow");
|
||||
statement.put("Principal", principal(principal, AwsArnUtils.parse(version.getLayerVersionArn()).region()));
|
||||
statement.put("Action", action);
|
||||
statement.put("Resource", version.getLayerVersionArn());
|
||||
if (organizationId != null) {
|
||||
statement.put("Condition", Map.of("StringEquals", Map.of("aws:PrincipalOrgID", organizationId)));
|
||||
}
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement's Principal as AWS writes it: an account as that account's root ARN, an ARN as itself, both under
|
||||
* {@code AWS}, and {@code *} as given.
|
||||
*/
|
||||
private Object principal(String principal, String region) {
|
||||
if (ACCOUNT_ID.matcher(principal).matches()) {
|
||||
String partition = regionResolver.partitionForRegion(region);
|
||||
return Map.of("AWS", AwsArnUtils.Arn.global(partition, "iam", principal, "root").toString());
|
||||
}
|
||||
return "*".equals(principal) ? principal : Map.of("AWS", principal);
|
||||
}
|
||||
|
||||
private static Map<String, Object> document(List<Map<String, Object>> statements) {
|
||||
Map<String, Object> document = new LinkedHashMap<>();
|
||||
document.put("Version", "2012-10-17");
|
||||
document.put("Id", "default");
|
||||
document.put("Statement", statements);
|
||||
return document;
|
||||
}
|
||||
|
||||
private void save(LambdaLayerVersion version) {
|
||||
layerStore.save(AwsArnUtils.parse(version.getLayerVersionArn()).region(), version);
|
||||
}
|
||||
|
||||
/**
|
||||
* The version's lock, which its deletion holds too ({@link LambdaLayerService#versionLock}): each change re-reads
|
||||
* the version under it, so a version deleted meanwhile is refused as missing rather than saved back.
|
||||
*/
|
||||
private Object lock(LambdaLayerVersion version) {
|
||||
return layerService.versionLock(version.getLayerVersionArn());
|
||||
}
|
||||
|
||||
private String json(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Could not serialize the layer version policy", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String text(Map<String, Object> request, String member) {
|
||||
Object value = request == null ? null : request.get(member);
|
||||
return value instanceof String s ? s : null;
|
||||
}
|
||||
|
||||
private static void violation(List<String> violations, String path, String value, String pattern, int maxLength,
|
||||
boolean required) {
|
||||
if (value == null) {
|
||||
if (required) {
|
||||
violations.add(SmithyValidationErrors.notNull(path));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (value.length() > maxLength) {
|
||||
violations.add(SmithyValidationErrors.lengthOutOfRange(path, value, 1, maxLength));
|
||||
}
|
||||
if (!Pattern.compile(pattern).matcher(value).matches()) {
|
||||
violations.add(SmithyValidationErrors.pattern(path, value, pattern));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -82,6 +83,8 @@ public class LambdaLayerService {
|
||||
"arn:aws-us-gov:greengrass:::runtime/function/executable"); // partition-literal: the Runtime enum lists these three ids verbatim
|
||||
|
||||
private final LambdaLayerStore layerStore;
|
||||
/** The lock of each layer version, keyed by its ARN ({@link #versionLock}). */
|
||||
private final Map<String, Object> versionLocks = new ConcurrentHashMap<>();
|
||||
private final ZipExtractor zipExtractor;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -325,7 +328,16 @@ public class LambdaLayerService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a specific layer version.
|
||||
* The lock a layer version's deletion and the changes and reads of its resource-based policy
|
||||
* ({@link LambdaLayerPolicyService}) share: a permission added while the version is deleted cannot save it back,
|
||||
* and a policy is read with the revision it was written with.
|
||||
*/
|
||||
public Object versionLock(String layerVersionArn) {
|
||||
return versionLocks.computeIfAbsent(layerVersionArn, key -> new Object());
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a specific layer version, holding its lock ({@link #versionLock}) while it goes.
|
||||
*/
|
||||
public void deleteLayerVersion(String region, String layerName, long versionNumber) {
|
||||
LambdaLayerVersion lv = AwsArnUtils.looksLikeArn(layerName)
|
||||
@@ -336,15 +348,16 @@ public class LambdaLayerService {
|
||||
return;
|
||||
}
|
||||
String layerRegion = AwsArnUtils.parse(lv.getLayerVersionArn()).region();
|
||||
synchronized (versionLock(lv.getLayerVersionArn())) {
|
||||
// Delete the extracted code from disk
|
||||
if (lv.getCodeLocalPath() != null) {
|
||||
Path codePath = Path.of(lv.getCodeLocalPath());
|
||||
deleteDirectory(codePath);
|
||||
}
|
||||
|
||||
// Delete the extracted code from disk
|
||||
if (lv.getCodeLocalPath() != null) {
|
||||
Path codePath = Path.of(lv.getCodeLocalPath());
|
||||
deleteDirectory(codePath);
|
||||
layerStore.delete(layerRegion, lv.getLayerName(), versionNumber);
|
||||
deleteLayerArchive(layerRegion, lv);
|
||||
}
|
||||
|
||||
layerStore.delete(layerRegion, lv.getLayerName(), versionNumber);
|
||||
deleteLayerArchive(layerRegion, lv);
|
||||
LOG.infov("Deleted layer version: {0} v{1} in region {2}", lv.getLayerName(), versionNumber, layerRegion);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,10 @@ import java.util.regex.Pattern;
|
||||
* only, and one on the function does not cover a qualified call (Lambda Developer Guide, "Referencing
|
||||
* functions in the Resource section of policies").
|
||||
*
|
||||
* <p>A layer version's policy is its own, the statements its owner added with AddLayerVersionPermission, owned by the
|
||||
* account in the layer version ARN, and returned as a function's is: "To use a layer in another account, the owner of
|
||||
* that account must grant your account permission in a resource-based policy" (Lambda Developer Guide).
|
||||
*
|
||||
* <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.
|
||||
@@ -40,13 +44,18 @@ 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:([^:/]+)(?:[:/].*)?");
|
||||
/** A layer version: its layer's name and its number. */
|
||||
private static final Pattern LAYER_VERSION_RESOURCE = Pattern.compile("layer:[a-zA-Z0-9-_]+:\\d+");
|
||||
|
||||
private final LambdaService lambdaService;
|
||||
private final LambdaLayerPolicyService layerPolicies;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public LambdaResourcePolicyProvider(LambdaService lambdaService, ObjectMapper objectMapper) {
|
||||
public LambdaResourcePolicyProvider(LambdaService lambdaService, LambdaLayerPolicyService layerPolicies,
|
||||
ObjectMapper objectMapper) {
|
||||
this.lambdaService = lambdaService;
|
||||
this.layerPolicies = layerPolicies;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@@ -56,8 +65,15 @@ public class LambdaResourcePolicyProvider implements ResourcePolicyProvider {
|
||||
return List.of();
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
|
||||
if (!ACCOUNT_ID.matcher(arn.accountId()).matches()) {
|
||||
return List.of();
|
||||
}
|
||||
if (LAYER_VERSION_RESOURCE.matcher(arn.resource()).matches()) {
|
||||
return List.of(new ResourcePolicy(policyDocument(layerPolicies.policyStatements(resourceArn)),
|
||||
arn.accountId()));
|
||||
}
|
||||
Matcher function = FUNCTION_RESOURCE.matcher(arn.resource());
|
||||
if (!function.matches() || !ACCOUNT_ID.matcher(arn.accountId()).matches()) {
|
||||
if (!function.matches()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Map<String, Object>> statements =
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Represents a single published version of a Lambda layer.
|
||||
@@ -25,10 +26,24 @@ public class LambdaLayerVersion {
|
||||
private String codeSha256;
|
||||
private String codeLocalPath;
|
||||
private boolean archiveStored;
|
||||
/**
|
||||
* The statements of the version's resource-based policy, in the order they were added: null for a version no
|
||||
* permission was ever added to, empty for one whose every statement was removed, which Lambda tells apart ("No
|
||||
* policy is associated with the given resource." against "Layer version ... does not have any resource policy.").
|
||||
*/
|
||||
private List<Map<String, Object>> policy;
|
||||
/** The policy's revision, new on each change of it; null for a version no permission was ever added to. */
|
||||
private String policyRevisionId;
|
||||
|
||||
public LambdaLayerVersion() {
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getPolicy() { return policy; }
|
||||
public void setPolicy(List<Map<String, Object>> policy) { this.policy = policy; }
|
||||
|
||||
public String getPolicyRevisionId() { return policyRevisionId; }
|
||||
public void setPolicyRevisionId(String policyRevisionId) { this.policyRevisionId = policyRevisionId; }
|
||||
|
||||
public boolean isArchiveStored() { return archiveStored; }
|
||||
public void setArchiveStored(boolean archiveStored) { this.archiveStored = archiveStored; }
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.lambda.model.LambdaLayerVersion;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static io.floci.aws.services.lambda.LambdaLayerFixtures.layer;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* A layer version's deletion and the changes and reads of its policy hold one lock: a permission waiting while its
|
||||
* version is deleted is refused as missing rather than saving the version back, deletion waits for a change in
|
||||
* progress, and a policy is read with the revision it was written with. The test thread holds the lock itself, which
|
||||
* it may take again, and the other call is seen waiting on it before the test thread goes on.
|
||||
*/
|
||||
class LambdaLayerPolicyServiceTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String NAME = "shared";
|
||||
private static final String ARN = "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":layer:" + NAME + ":1";
|
||||
|
||||
private LambdaLayerStore store;
|
||||
private LambdaLayerService layers;
|
||||
private LambdaLayerPolicyService policies;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AccountAwareStorageBackend<LambdaLayerVersion> storage = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
storage.putForAccount(ACCOUNT, "layer::" + REGION + "::" + NAME + "::1", layer(ACCOUNT, REGION, NAME, 1));
|
||||
store = new LambdaLayerStore(storage);
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
|
||||
layers = new LambdaLayerService(store, null, null, regionResolver, null);
|
||||
policies = new LambdaLayerPolicyService(layers, store, regionResolver, new ObjectMapper());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVersionDeletedWhileAPermissionWaitsIsRefusedAsMissingAndNotSavedBack() throws Exception {
|
||||
AtomicReference<Object> outcome = new AtomicReference<>();
|
||||
Thread adding = new Thread(() -> outcome.set(attempt(() -> policies.addLayerVersionPermission(REGION, NAME, 1,
|
||||
grant("share"), null))));
|
||||
synchronized (layers.versionLock(ARN)) {
|
||||
adding.start();
|
||||
awaitBlocked(adding);
|
||||
layers.deleteLayerVersion(REGION, NAME, 1);
|
||||
}
|
||||
adding.join(TimeUnit.SECONDS.toMillis(10));
|
||||
|
||||
AwsException refused = assertInstanceOf(AwsException.class, outcome.get());
|
||||
assertEquals("Layer version " + ARN + " does not exist.", refused.getMessage());
|
||||
assertTrue(store.get(REGION, NAME, 1).isEmpty(), "the deleted version was saved back");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletionWaitsForAPolicyChangeInProgress() throws Exception {
|
||||
Thread deleting = new Thread(() -> layers.deleteLayerVersion(REGION, NAME, 1));
|
||||
synchronized (layers.versionLock(ARN)) {
|
||||
deleting.start();
|
||||
awaitBlocked(deleting);
|
||||
policies.addLayerVersionPermission(REGION, NAME, 1, grant("share"), null);
|
||||
assertTrue(store.get(REGION, NAME, 1).isPresent());
|
||||
}
|
||||
deleting.join(TimeUnit.SECONDS.toMillis(10));
|
||||
|
||||
assertTrue(store.get(REGION, NAME, 1).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyIsReadWithTheRevisionItWasWrittenWith() throws Exception {
|
||||
policies.addLayerVersionPermission(REGION, NAME, 1, grant("first"), null);
|
||||
AtomicReference<Object> outcome = new AtomicReference<>();
|
||||
Thread reading = new Thread(() -> outcome.set(attempt(() -> policies.getLayerVersionPolicy(REGION, NAME, 1))));
|
||||
String latest;
|
||||
synchronized (layers.versionLock(ARN)) {
|
||||
reading.start();
|
||||
awaitBlocked(reading);
|
||||
latest = policies.addLayerVersionPermission(REGION, NAME, 1, grant("second"), null).revisionId();
|
||||
}
|
||||
reading.join(TimeUnit.SECONDS.toMillis(10));
|
||||
|
||||
LambdaLayerPolicyService.Policy read = assertInstanceOf(LambdaLayerPolicyService.Policy.class, outcome.get());
|
||||
assertEquals(latest, read.revisionId());
|
||||
assertTrue(read.policy().contains("\"second\""), read.policy());
|
||||
}
|
||||
|
||||
private static Map<String, Object> grant(String statementId) {
|
||||
return Map.of("StatementId", statementId, "Action", "lambda:GetLayerVersion", "Principal", "111122223333");
|
||||
}
|
||||
|
||||
private static Object attempt(Supplier<Object> call) {
|
||||
try {
|
||||
return call.get();
|
||||
} catch (RuntimeException e) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits until the thread is waiting to take a lock, failing if it ends or ten seconds pass first. */
|
||||
private static void awaitBlocked(Thread thread) {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (thread.getState() != Thread.State.BLOCKED) {
|
||||
if (!thread.isAlive() || System.nanoTime() > deadline) {
|
||||
fail("the call did not wait for the layer version's lock (" + thread.getState() + ")");
|
||||
}
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
}
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.lambda.model.AddLayerVersionPermissionRequest;
|
||||
import software.amazon.awssdk.services.lambda.model.AddLayerVersionPermissionResponse;
|
||||
import software.amazon.awssdk.services.lambda.model.GetLayerVersionPolicyResponse;
|
||||
import software.amazon.awssdk.services.lambda.model.LambdaException;
|
||||
import software.amazon.awssdk.services.lambda.model.PublishLayerVersionResponse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static io.floci.aws.services.lambda.LambdaLayerFixtures.publishLayerVersion;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A layer version's resource-based policy, as AWS's own fidelity checks record it (aws/aws-emulator-evaluation-suite,
|
||||
* {@code behavioral/lambda/check_layer_permission_lifecycle.py},
|
||||
* {@code check_layer_permission_revisionid_precondition.py},
|
||||
* {@code check_add_layer_version_permission_organization_id_requires_wildcard_principal_rejected.py},
|
||||
* {@code check_add_layer_permission_policy_length_exceeded.py}, and the CloudFormation
|
||||
* {@code check_deploy_lambda_layerversionpermission_principal_malformed_rejected.py}): each refusal's code and
|
||||
* message, and the statement as AWS writes it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class LambdaLayerVersionPermissionIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void aPermissionIsAddedReadAndRemovedAsAwsAnswersEachStep() throws Exception {
|
||||
try (LambdaClient lambda = client()) {
|
||||
PublishLayerVersionResponse layer = publish(lambda);
|
||||
String name = name(layer);
|
||||
long version = layer.version();
|
||||
|
||||
refused("ResourceNotFoundException", "No policy is associated with the given resource.",
|
||||
() -> lambda.getLayerVersionPolicy(r -> r.layerName(name).versionNumber(version)));
|
||||
|
||||
AddLayerVersionPermissionResponse added = grant(lambda, name, version, "share", ACCOUNT, r -> { });
|
||||
JsonNode statement = JSON.readTree(added.statement());
|
||||
assertEquals("share", statement.get("Sid").asText());
|
||||
assertEquals("Allow", statement.get("Effect").asText());
|
||||
assertEquals("arn:aws:iam::" + ACCOUNT + ":root", statement.get("Principal").get("AWS").asText());
|
||||
assertEquals("lambda:GetLayerVersion", statement.get("Action").asText());
|
||||
assertEquals(layer.layerVersionArn(), statement.get("Resource").asText());
|
||||
|
||||
GetLayerVersionPolicyResponse policy = lambda.getLayerVersionPolicy(r -> r.layerName(name)
|
||||
.versionNumber(version));
|
||||
assertEquals("share", JSON.readTree(policy.policy()).get("Statement").get(0).get("Sid").asText());
|
||||
assertEquals(added.revisionId(), policy.revisionId());
|
||||
|
||||
// A statement id already in the policy is a conflict, and leaves the revision as it was.
|
||||
refused("ResourceConflictException", "The statement id (share) provided already exists. Please provide a "
|
||||
+ "new statement id, or remove the existing statement.",
|
||||
() -> grant(lambda, name, version, "share", ACCOUNT, r -> { }));
|
||||
assertEquals(added.revisionId(), lambda.getLayerVersionPolicy(r -> r.layerName(name)
|
||||
.versionNumber(version)).revisionId());
|
||||
|
||||
lambda.removeLayerVersionPermission(r -> r.layerName(name).versionNumber(version).statementId("share")
|
||||
.revisionId(added.revisionId()));
|
||||
refused("ResourceNotFoundException", "Layer version " + layer.layerVersionArn()
|
||||
+ " does not have any resource policy.",
|
||||
() -> lambda.getLayerVersionPolicy(r -> r.layerName(name).versionNumber(version)));
|
||||
refused("ResourceNotFoundException", "No policy is associated with the given resource.",
|
||||
() -> lambda.removeLayerVersionPermission(r -> r.layerName(name).versionNumber(version)
|
||||
.statementId("share")));
|
||||
// The freed statement id can be added again.
|
||||
assertEquals("share", JSON.readTree(grant(lambda, name, version, "share", ACCOUNT, r -> { })
|
||||
.statement()).get("Sid").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRevisionIdOtherThanThePoliciesLatestIsRefusedBeforeAnythingChanges() throws Exception {
|
||||
String stale = "The Revision Id provided does not match the latest Revision Id. Call the GetLayerPolicy "
|
||||
+ "API to retrieve the latest Revision Id";
|
||||
try (LambdaClient lambda = client()) {
|
||||
PublishLayerVersionResponse layer = publish(lambda);
|
||||
String name = name(layer);
|
||||
long version = layer.version();
|
||||
String first = grant(lambda, name, version, "first", ACCOUNT, r -> { }).revisionId();
|
||||
|
||||
refused("PreconditionFailedException", stale, () -> grant(lambda, name, version, "second", ACCOUNT,
|
||||
r -> r.revisionId("00000000-0000-0000-0000-000000000000")));
|
||||
String second = grant(lambda, name, version, "second", ACCOUNT, r -> r.revisionId(first)).revisionId();
|
||||
assertNotEquals(first, second);
|
||||
|
||||
refused("PreconditionFailedException", stale, () -> lambda.removeLayerVersionPermission(r -> r
|
||||
.layerName(name).versionNumber(version).statementId("first").revisionId(first)));
|
||||
assertEquals(2, statements(lambda, name, version).size());
|
||||
lambda.removeLayerVersionPermission(r -> r.layerName(name).versionNumber(version).statementId("first")
|
||||
.revisionId(second));
|
||||
assertEquals("second", statements(lambda, name, version).get(0).get("Sid").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOrganizationIsGrantedOnlyToEveryPrincipal() throws Exception {
|
||||
try (LambdaClient lambda = client()) {
|
||||
PublishLayerVersionResponse layer = publish(lambda);
|
||||
String name = name(layer);
|
||||
long version = layer.version();
|
||||
|
||||
refused("InvalidParameterValueException", "If organization id is specified then principal should be *",
|
||||
() -> grant(lambda, name, version, "org-account", ACCOUNT,
|
||||
r -> r.organizationId("o-abcdefghij")));
|
||||
JsonNode statement = JSON.readTree(grant(lambda, name, version, "org", "*",
|
||||
r -> r.organizationId("o-abcdefghij")).statement());
|
||||
assertEquals("*", statement.get("Principal").asText());
|
||||
assertEquals("o-abcdefghij",
|
||||
statement.get("Condition").get("StringEquals").get("aws:PrincipalOrgID").asText());
|
||||
assertEquals(1, statements(lambda, name, version).size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrincipalOutsideTheModelsPatternIsAValidationError() throws Exception {
|
||||
try (LambdaClient lambda = client()) {
|
||||
PublishLayerVersionResponse layer = publish(lambda);
|
||||
refused("ValidationException", "1 validation error detected: Value 'not-an-account' at 'principal' "
|
||||
+ "failed to satisfy constraint: Member must satisfy regular expression pattern: "
|
||||
+ "\\d{12}|\\*|arn:(aws[a-zA-Z-]*):iam::\\d{12}:root",
|
||||
() -> grant(lambda, name(layer), layer.version(), "bad", "not-an-account", r -> { }));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVersionThatDoesNotExistIsNamedByItsArn() throws Exception {
|
||||
try (LambdaClient lambda = client()) {
|
||||
PublishLayerVersionResponse layer = publish(lambda);
|
||||
String missing = layer.layerArn() + ":" + (layer.version() + 7);
|
||||
refused("ResourceNotFoundException", "Layer version " + missing + " does not exist.",
|
||||
() -> lambda.getLayerVersionPolicy(r -> r.layerName(name(layer))
|
||||
.versionNumber(layer.version() + 7)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyGrowingPastItsLimitIsRefusedAndKeepsWhatItHad() throws Exception {
|
||||
try (LambdaClient lambda = client()) {
|
||||
PublishLayerVersionResponse layer = publish(lambda);
|
||||
String name = name(layer);
|
||||
long version = layer.version();
|
||||
int added = 0;
|
||||
LambdaException refused = null;
|
||||
while (refused == null && added < 500) {
|
||||
String id = "statement-" + added;
|
||||
try {
|
||||
grant(lambda, name, version, id, ACCOUNT, r -> { });
|
||||
added++;
|
||||
} catch (LambdaException e) {
|
||||
refused = e;
|
||||
}
|
||||
}
|
||||
assertEquals("PolicyLengthExceededException", refused.awsErrorDetails().errorCode());
|
||||
String message = refused.awsErrorDetails().errorMessage();
|
||||
assertTrue(message.startsWith("The final policy size (")
|
||||
&& message.endsWith(") is bigger than the limit (20480)."), message);
|
||||
assertEquals(added, statements(lambda, name, version).size());
|
||||
}
|
||||
}
|
||||
|
||||
private LambdaClient client() {
|
||||
return AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_EAST_1, endpoint);
|
||||
}
|
||||
|
||||
private PublishLayerVersionResponse publish(LambdaClient lambda) throws Exception {
|
||||
return publishLayerVersion(lambda, "layer-policy-" + UUID.randomUUID().toString().substring(0, 8), ACCOUNT,
|
||||
Region.US_EAST_1, endpoint, cleanup);
|
||||
}
|
||||
|
||||
private static String name(PublishLayerVersionResponse layer) {
|
||||
return layer.layerArn().substring(layer.layerArn().lastIndexOf(':') + 1);
|
||||
}
|
||||
|
||||
private static AddLayerVersionPermissionResponse grant(
|
||||
LambdaClient lambda, String name, long version, String statementId, String principal,
|
||||
Consumer<AddLayerVersionPermissionRequest.Builder> more) {
|
||||
return lambda.addLayerVersionPermission(r -> {
|
||||
r.layerName(name).versionNumber(version).statementId(statementId).action("lambda:GetLayerVersion")
|
||||
.principal(principal);
|
||||
more.accept(r);
|
||||
});
|
||||
}
|
||||
|
||||
private static JsonNode statements(LambdaClient lambda, String name, long version) throws Exception {
|
||||
return JSON.readTree(lambda.getLayerVersionPolicy(r -> r.layerName(name).versionNumber(version)).policy())
|
||||
.get("Statement");
|
||||
}
|
||||
|
||||
private static void refused(String code, String message, Runnable call) {
|
||||
LambdaException e = assertThrows(LambdaException.class, call::run);
|
||||
assertEquals(code, e.awsErrorDetails().errorCode());
|
||||
assertEquals(message, e.awsErrorDetails().errorMessage());
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.lambda.model.LambdaException;
|
||||
import software.amazon.awssdk.services.lambda.model.PublishLayerVersionResponse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.services.lambda.LambdaLayerFixtures.publishLayerVersion;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A layer version's policy is what lets another account read it: "To use a layer in another account, the owner of
|
||||
* that account must grant your account permission in a resource-based policy" (Lambda Developer Guide, adding layers).
|
||||
* A caller in another account whose own policy allows {@code lambda:GetLayerVersion} is refused it on the owner's
|
||||
* version until the owner grants that account, after which IAM no longer refuses it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class LambdaLayerVersionPolicyIamIntegrationTest {
|
||||
|
||||
private static final String OWNER = "741681410004";
|
||||
private static final String READER = "100000000012";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void anotherAccountReadsALayerVersionOnlyOnceItsOwnerGrantsIt() throws Exception {
|
||||
String name = "shared-layer-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), OWNER, Region.US_EAST_1, endpoint)) {
|
||||
PublishLayerVersionResponse layer = publishLayerVersion(owner, name, OWNER, Region.US_EAST_1, endpoint,
|
||||
cleanup);
|
||||
String user = "layer-reader-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String authorization = auth(READER, "iam");
|
||||
UserCredentials reader = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, user);
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, user, "read-layers", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"lambda:GetLayerVersion",
|
||||
"Resource":"*"}]}""");
|
||||
try (LambdaClient other = AwsTestClients.create(LambdaClient.builder(), reader.accessKeyId(),
|
||||
reader.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
LambdaException refused = assertThrows(LambdaException.class,
|
||||
() -> other.getLayerVersionByArn(r -> r.arn(layer.layerVersionArn())));
|
||||
assertEquals(403, refused.statusCode());
|
||||
assertTrue(refused.awsErrorDetails().errorMessage().contains("lambda:GetLayerVersion"),
|
||||
refused.awsErrorDetails().errorMessage());
|
||||
|
||||
owner.addLayerVersionPermission(r -> r.layerName(name).versionNumber(layer.version())
|
||||
.statementId("reader").action("lambda:GetLayerVersion").principal(READER));
|
||||
int status;
|
||||
try {
|
||||
other.getLayerVersionByArn(r -> r.arn(layer.layerVersionArn()));
|
||||
status = 200;
|
||||
} catch (LambdaException e) {
|
||||
status = e.statusCode();
|
||||
}
|
||||
assertNotEquals(403, status, "IAM still refuses the account the layer's owner granted");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,13 +22,41 @@ class LambdaResourcePolicyProviderTest {
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private LambdaService lambdaService;
|
||||
private LambdaLayerPolicyService layerPolicies;
|
||||
private LambdaResourcePolicyProvider provider;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaService = mock(LambdaService.class);
|
||||
when(lambdaService.policyStatements(OWNER, "us-east-1", "my-function")).thenReturn(List.of());
|
||||
provider = new LambdaResourcePolicyProvider(lambdaService, objectMapper);
|
||||
layerPolicies = mock(LambdaLayerPolicyService.class);
|
||||
provider = new LambdaResourcePolicyProvider(lambdaService, layerPolicies, objectMapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* A layer version's policy is the statements its owner added, owned by the account in its ARN, so a call from
|
||||
* another account is judged against them: "the owner of that account must grant your account permission in a
|
||||
* resource-based policy". A version with none still names its owner.
|
||||
*/
|
||||
@Test
|
||||
void aLayerVersionsPolicyIsItsOwnersStatements() throws Exception {
|
||||
String layerVersion = "arn:aws:lambda:us-east-1:" + OWNER + ":layer:shared:3";
|
||||
Map<String, Object> grant = Map.of("Sid", "share", "Effect", "Allow",
|
||||
"Principal", Map.of("AWS", "arn:aws:iam::444455556666:root"),
|
||||
"Action", "lambda:GetLayerVersion", "Resource", layerVersion);
|
||||
when(layerPolicies.policyStatements(layerVersion)).thenReturn(List.of(grant));
|
||||
when(layerPolicies.policyStatements("arn:aws:lambda:us-east-1:" + OWNER + ":layer:shared:4"))
|
||||
.thenReturn(List.of());
|
||||
|
||||
List<ResourcePolicy> policies = provider.getResourcePolicies("lambda", layerVersion);
|
||||
|
||||
JsonNode statements = objectMapper.readTree(policies.getFirst().policyDocument()).get("Statement");
|
||||
assertEquals("share", statements.get(0).get("Sid").asText());
|
||||
assertEquals(OWNER, policies.getFirst().ownerAccountId());
|
||||
List<ResourcePolicy> unshared = provider.getResourcePolicies("lambda",
|
||||
"arn:aws:lambda:us-east-1:" + OWNER + ":layer:shared:4");
|
||||
assertNull(unshared.getFirst().policyDocument());
|
||||
assertEquals(OWNER, unshared.getFirst().ownerAccountId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,10 +95,14 @@ class LambdaResourcePolicyProviderTest {
|
||||
assertEquals(OWNER, policies.getFirst().ownerAccountId());
|
||||
}
|
||||
|
||||
/**
|
||||
* A layer version has a policy of its own ({@link #aLayerVersionsPolicyIsItsOwnersStatements}); a layer does not.
|
||||
*/
|
||||
@Test
|
||||
void resourcesThatAreNotFunctionsAreLeftToOtherProviders() {
|
||||
void resourcesThatAreNotFunctionsOrLayerVersionsAreLeftToOtherProviders() {
|
||||
assertTrue(provider.getResourcePolicies("lambda", "*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("lambda", "arn:aws:lambda:us-east-1:" + OWNER + ":layer:my-layer:1").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("lambda", "arn:aws:lambda:us-east-1:" + OWNER + ":layer:my-layer")
|
||||
.isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("lambda",
|
||||
"arn:aws:lambda:us-east-1:" + OWNER + ":event-source-mapping:fa123456-14a1-4fd2-9fec-83de64ad683d").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("s3", "arn:aws:s3:::bucket/key").isEmpty());
|
||||
|
||||
Reference in new issue
Block a user