mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lambda): accept layer ARNs when deleting versions (#8409)
* fix(lambda): accept layer ARNs when deleting versions * test(lambda): share layer publication cleanup * test(iam): include layer deletion in the resource inventory * fix(lambda): read Lambda's IAM resources whole from the generated table
This commit is contained in:
1 parent
ce25aa0247
commit
b8014cbd4e
22 files changed
+1219
-906
No files matched your search
@@ -20,6 +20,7 @@ import io.floci.aws.services.iam.ResourceArnBuilder;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.iam.model.IamUser;
|
||||
import io.floci.aws.services.lambdaweb.LambdaWebService;
|
||||
import io.floci.aws.services.lambdaweb.model.WebFunctionEndpoint;
|
||||
import io.floci.aws.services.s3.S3ConditionKeys;
|
||||
import io.floci.aws.services.s3.S3ControlTagConditionKeys;
|
||||
import io.floci.aws.services.s3.S3ObjectActions;
|
||||
@@ -609,25 +610,28 @@ public class IamConditionContextResolver {
|
||||
.forEach(value -> putIfPresent(conditions, REQUEST_AUTH_TYPE, value));
|
||||
}
|
||||
if (RequestConditionKeys.takes(action, RESOURCE_AUTH_TYPE)) {
|
||||
putIfPresent(conditions, RESOURCE_AUTH_TYPE, storedAuthType(ctx));
|
||||
putIfPresent(conditions, RESOURCE_AUTH_TYPE, storedAuthType(action, ctx));
|
||||
}
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
private String storedAuthType(ContainerRequestContext ctx) {
|
||||
/** The authType of the web function endpoint the request names, as the request resources read it. */
|
||||
private String storedAuthType(String action, ContainerRequestContext ctx) {
|
||||
if (!lambdaWebService.isResolvable()) {
|
||||
return null;
|
||||
}
|
||||
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
|
||||
String endpointArn = ResourceArnBuilder.webFunctionArn(ctx.getUriInfo().getPath(), region,
|
||||
requestContext.getAccountId());
|
||||
String endpointArn = RequestResources.of(action, ctx, regionResolver.partitionForRegion(region), region,
|
||||
requestContext.getAccountId(), null, IamActionRegistry.pathLabels("lambda", ctx)).stream()
|
||||
.filter(arn -> arn.contains("/endpoint/")).findFirst().orElse("");
|
||||
int child = endpointArn.lastIndexOf("/endpoint/");
|
||||
if (child < 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return lambdaWebService.get().getEndpoint(region, endpointArn.substring(0, child),
|
||||
endpointArn.substring(child + "/endpoint/".length())).authType;
|
||||
WebFunctionEndpoint endpoint = lambdaWebService.get().getEndpoint(region, endpointArn.substring(0, child),
|
||||
endpointArn.substring(child + "/endpoint/".length()));
|
||||
return endpoint == null ? null : endpoint.authType;
|
||||
} catch (AwsException expected) {
|
||||
// The handler refuses the same names, so the key is only left out, as for a missing endpoint on AWS.
|
||||
return null;
|
||||
|
||||
@@ -61,7 +61,7 @@ final class RequestResourceMembers {
|
||||
private static final Set<String> ARN_KEYS = Set.of("types", "arn", "made", "endpoint");
|
||||
/** The keys of a resource whose format's variables members fill, or its service finds by them. */
|
||||
private static final Set<String> FILL_KEYS = Set.of("type", "fill", "when", "unless", "arnOf", "account", "fixed",
|
||||
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault", "defaults");
|
||||
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault", "defaults", "partialArn");
|
||||
/** The keys of a resource named through a member naming another of its service's own: it is read no other way. */
|
||||
private static final Set<String> THROUGH_KEYS = Set.of("types", "through", "when", "endpoint");
|
||||
/** The keys of a resource its service acts on for a request naming none of it: it is read no other way. */
|
||||
@@ -221,13 +221,25 @@ final class RequestResourceMembers {
|
||||
* variable that is the one of another type's format names that type's default when the request leaves it out
|
||||
* ({@code defaults}, the member mapped to the type), which the service gives: an ECS service of a request with no
|
||||
* {@code cluster} is on the default cluster. One member of {@code find} may be a list, each of whose values the
|
||||
* service finds (ECS's {@code taskDefinitions[]}).
|
||||
* service finds (ECS's {@code taskDefinitions[]}). A
|
||||
* {@code partialArn} type's members may give its ARN with the leading parts left out, its account and resource
|
||||
* ({@code 123456789012:function:my-function}) or its Region too, which the reader completes in the request's
|
||||
* partition, and Region where the value leaves that out.
|
||||
*/
|
||||
record Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
|
||||
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault,
|
||||
Map<String, String> defaults) {
|
||||
Map<String, String> defaults, boolean partialArn) {
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
|
||||
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault,
|
||||
Map<String, String> defaults) {
|
||||
this(types, arn, fill, when, unless, arnOf, account, fixed, made, find, endpoint, through, byDefault,
|
||||
whenDefault, unlessDefault, defaults, false);
|
||||
}
|
||||
|
||||
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
|
||||
@@ -684,9 +696,15 @@ final class RequestResourceMembers {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " takes " + type + "'s account for " + operation
|
||||
+ " from " + account.name() + ", no member of one account or a type of none");
|
||||
}
|
||||
boolean partialArn = resource.has("partialArn");
|
||||
if (partialArn && (!resource.path("partialArn").isBoolean() || !resource.path("partialArn").booleanValue()
|
||||
|| fill.isEmpty())) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + type + " for " + operation
|
||||
+ " from a partial ARN " + resource.path("partialArn") + ", not true for a type its members fill");
|
||||
}
|
||||
return new Resource(List.of(type), null, Map.copyOf(fill), when, unless, Map.copyOf(arnOf), account,
|
||||
Map.copyOf(fixed), made, List.copyOf(find), endpoint, null, byDefault, whenDefault, unlessDefault,
|
||||
defaults(operation, type, resource.path("defaults"), fill, formats));
|
||||
defaults(operation, type, resource.path("defaults"), fill, formats), partialArn);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -47,6 +47,8 @@ public final class RequestResources {
|
||||
|
||||
private static final Pattern VARIABLE = Pattern.compile("\\$\\{(\\w+)}");
|
||||
private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
|
||||
/** An ARN without its leading {@code arn:<partition>:<service>:}, its Region optional: {@code 123456789012:function:f}. */
|
||||
private static final Pattern PARTIAL_ARN = Pattern.compile("(?:([a-z]{2}(?:-[a-z0-9]+)+-\\d+):)?(\\d{12}):(.+)");
|
||||
private static final String WITHOUT_LEADING_SLASH = "WithoutLeadingSlash";
|
||||
|
||||
/** Values for a type's variables, and the ARN whose account and Region the resource they name is in, if any. */
|
||||
@@ -639,6 +641,8 @@ public final class RequestResources {
|
||||
.map(value -> variable.getKey().endsWith(WITHOUT_LEADING_SLASH)
|
||||
? asVariable(variable.getKey(), value)
|
||||
: withoutTypePath(value, resource.types().getFirst()))
|
||||
.map(value -> resource.partialArn() ? completed(value, variable.getValue(), resource, formats,
|
||||
format, partition, region, accountId) : value)
|
||||
.toList();
|
||||
// An element of a list naming no resource names its service's default (a PutEvents entry with no bus).
|
||||
if (variable.getValue().eachElement() && stored != null && resource.fill().size() == 1) {
|
||||
@@ -714,6 +718,39 @@ public final class RequestResources {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The value of a member of a {@code partialArn} type as an ARN: one giving its account and resource
|
||||
* ({@code 123456789012:function:my-function}), or its Region too, completed in the request's partition and, where
|
||||
* it leaves the Region out, the request's; one giving the resource alone ({@code function:my-function}) in the
|
||||
* caller's account too; as given otherwise, a name or a whole ARN. A member that may give the ARN of another type
|
||||
* ({@code arnOf}) is completed as that type's.
|
||||
*/
|
||||
static String completed(String value, RequestResourceMembers.Member member,
|
||||
RequestResourceMembers.Resource resource,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats,
|
||||
RequestResourceMembers.ArnFormat format, String partition, String region,
|
||||
String accountId) {
|
||||
RequestResourceMembers.ArnFormat named = arnOf(resource, member.path(), formats);
|
||||
RequestResourceMembers.ArnFormat type = named == null ? format : named;
|
||||
String[] parts = type.format().split(":", 6);
|
||||
int variable = parts.length < 6 ? -1 : parts[5].indexOf("${");
|
||||
if (variable <= 0) {
|
||||
return value;
|
||||
}
|
||||
String word = parts[5].substring(0, variable);
|
||||
Matcher partial = PARTIAL_ARN.matcher(value);
|
||||
String arn;
|
||||
if (partial.matches() && partial.group(3).startsWith(word)) {
|
||||
arn = new AwsArnUtils.Arn(partition, parts[2], partial.group(1) == null ? region : partial.group(1),
|
||||
partial.group(2), partial.group(3)).toString();
|
||||
} else if (value.startsWith(word) && value.length() > word.length()) {
|
||||
arn = new AwsArnUtils.Arn(partition, parts[2], region, accountId, value).toString();
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
return type.pattern().matcher(arn).matches() ? arn : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as the variable takes it: a variable named for leaving out the leading {@code /} takes a Parameter
|
||||
* Store name without the whitespace around it, which a put drops, and without one leading {@code /}, as an SSM
|
||||
|
||||
@@ -18,9 +18,6 @@ import io.floci.aws.services.cloudwatch.logs.LogGroupTagTarget;
|
||||
import io.floci.aws.services.eks.EksController;
|
||||
import io.floci.aws.services.eks.EksService;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import io.floci.aws.services.lambda.LambdaArnUtils;
|
||||
import io.floci.aws.services.lambda.durable.DurableTokens;
|
||||
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.floci.aws.services.s3.S3ControlArnUtils;
|
||||
import io.floci.aws.services.s3.S3ObjectKeys;
|
||||
import io.floci.aws.services.s3.S3ResourceArns;
|
||||
@@ -47,7 +44,6 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -88,8 +84,6 @@ public class ResourceArnBuilder {
|
||||
* which IamService itself does not depend on, and a direct injection would close that loop.
|
||||
*/
|
||||
private final Instance<IamService> iamService;
|
||||
/** Looked up lazily for the same reason, to read the image a MicroVM runs. */
|
||||
private final Instance<LambdaMicrovmsService> microvmsService;
|
||||
/** Looked up lazily for the same reason, to read the ARN an EKS cluster or what it holds is stored under. */
|
||||
private final Instance<EksService> eksService;
|
||||
/** Looked up lazily for the same reason, to resolve a key named by an id, an alias or an ARN to its stored ARN. */
|
||||
@@ -108,14 +102,12 @@ public class ResourceArnBuilder {
|
||||
|
||||
@Inject
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<LambdaMicrovmsService> microvmsService,
|
||||
Instance<EksService> eksService,
|
||||
Instance<KmsService> kmsService,
|
||||
Instance<StoredResourceArns> storedResourceArns,
|
||||
CurrentVertxRequest currentVertxRequest) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.iamService = iamService;
|
||||
this.microvmsService = microvmsService;
|
||||
this.eksService = eksService;
|
||||
this.kmsService = kmsService;
|
||||
this.storedResourceArns = storedResourceArns;
|
||||
@@ -123,30 +115,21 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<LambdaMicrovmsService> microvmsService,
|
||||
Instance<EksService> eksService,
|
||||
Instance<KmsService> kmsService,
|
||||
Instance<StoredResourceArns> storedResourceArns) {
|
||||
this(objectMapper, iamService, microvmsService, eksService, kmsService,
|
||||
storedResourceArns, null);
|
||||
this(objectMapper, iamService, eksService, kmsService, storedResourceArns, null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<LambdaMicrovmsService> microvmsService,
|
||||
Instance<EksService> eksService,
|
||||
Instance<KmsService> kmsService) {
|
||||
this(objectMapper, iamService, microvmsService, eksService, kmsService, null);
|
||||
this(objectMapper, iamService, eksService, kmsService, null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<LambdaMicrovmsService> microvmsService,
|
||||
Instance<EksService> eksService) {
|
||||
this(objectMapper, iamService, microvmsService, eksService, null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<LambdaMicrovmsService> microvmsService) {
|
||||
this(objectMapper, iamService, microvmsService, null);
|
||||
this(objectMapper, iamService, eksService, null);
|
||||
}
|
||||
|
||||
ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
|
||||
@@ -162,7 +145,7 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
|
||||
ResourceArnBuilder(ObjectMapper objectMapper, CurrentVertxRequest currentVertxRequest) {
|
||||
this(objectMapper, null, null, null, null, null, currentVertxRequest);
|
||||
this(objectMapper, null, null, null, null, currentVertxRequest);
|
||||
}
|
||||
|
||||
public String build(String credentialScope, ContainerRequestContext ctx,
|
||||
@@ -203,7 +186,6 @@ public class ResourceArnBuilder {
|
||||
: IamActionRegistry.decodedPath(ctx);
|
||||
return switch (credentialScope) {
|
||||
case "s3" -> buildS3Resources(operation, path, ctx, region);
|
||||
case "lambda" -> List.of(buildLambdaArn(path, ctx, region, accountId));
|
||||
case "sqs" -> List.of(buildSqsArn(ctx, region, accountId));
|
||||
case "sns" -> List.of(buildSnsArn(ctx, region, accountId));
|
||||
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
|
||||
@@ -951,281 +933,6 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Lambda ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The function a Lambda request acts on, as an IAM policy names it. An invoke runs the function
|
||||
* in the account and Region its full or partial ARN names, so it is evaluated against that
|
||||
* function, and against the version or alias it names in the function name or in
|
||||
* {@code Qualifier}, since Lambda authorizes a qualified call against the qualified ARN (Lambda
|
||||
* Developer Guide, "Referencing functions in the Resource section of policies"). The reads
|
||||
* {@link #readsInTheAccountItNames} names act in the account a qualified ARN names too. Every
|
||||
* other route acts on the caller's own function of that name, whatever account an ARN names.
|
||||
* Those are evaluated unqualified, because not every one of them acts on the qualifier it is
|
||||
* given.
|
||||
*/
|
||||
private String buildLambdaArn(String path, ContainerRequestContext ctx, String region, String accountId) {
|
||||
String webFunctionArn = webFunctionArn(path, region, accountId);
|
||||
if (webFunctionArn != null) {
|
||||
return webFunctionArn;
|
||||
}
|
||||
String microvmArn = microvmArn(path, ctx, region, accountId);
|
||||
if (microvmArn != null) {
|
||||
return microvmArn;
|
||||
}
|
||||
// TagResource, ListTags and UntagResource name the tagged function, image or other resource by its ARN.
|
||||
if (path.startsWith("/2017-03-31/tags/")) {
|
||||
return lambdaTaggedArn(path.substring("/2017-03-31/tags/".length()), accountId);
|
||||
}
|
||||
String executionArn = durableExecutionArn(path);
|
||||
if (executionArn == null) {
|
||||
executionArn = durableCallbackExecutionArn(path);
|
||||
}
|
||||
if (executionArn != null) {
|
||||
return executionArn;
|
||||
}
|
||||
String childArn = lambdaChildArn(path, ctx, region, accountId);
|
||||
if (childArn != null) {
|
||||
return childArn;
|
||||
}
|
||||
// path: /2015-03-31/functions/name or similar
|
||||
String name = extractSegmentAfter(path, "functions");
|
||||
if (name == null) {
|
||||
return createdFunctionArn(path, ctx, region, accountId);
|
||||
}
|
||||
if (path.endsWith("/code-signing-config")) {
|
||||
return codeSigningFunctionArn(name, region, accountId);
|
||||
}
|
||||
boolean qualifiedTarget = path.endsWith("/functions/" + name + "/invocations")
|
||||
|| path.endsWith("/functions/" + name + "/response-streaming-invocations")
|
||||
|| path.endsWith("/functions/" + name + "/provisioned-concurrency");
|
||||
try {
|
||||
if (!qualifiedTarget) {
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(name);
|
||||
boolean namedAccount = readsInTheAccountItNames(path, name, ref, ctx);
|
||||
return AwsArnUtils.Arn.of("lambda",
|
||||
namedAccount ? ref.region() : region,
|
||||
namedAccount ? ref.account() : accountId,
|
||||
"function:" + ref.name()).toString();
|
||||
}
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolveWithQualifier(
|
||||
name, ctx.getUriInfo().getQueryParameters().getFirst("Qualifier"));
|
||||
String resource = ref.qualifier() != null
|
||||
? "function:" + ref.name() + ":" + ref.qualifier()
|
||||
: "function:" + ref.name();
|
||||
return AwsArnUtils.Arn.of("lambda",
|
||||
ref.region() != null ? ref.region() : region,
|
||||
ref.account() != null ? ref.account() : accountId,
|
||||
resource).toString();
|
||||
} catch (AwsException e) {
|
||||
// A reference Lambda refuses, which its handler answers with a 400 before acting on anything.
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString();
|
||||
}
|
||||
}
|
||||
|
||||
/** Code-signing attachment routes use Lambda's broader NamespacedFunctionName shape. */
|
||||
private static String codeSigningFunctionArn(String name, String region, String accountId) {
|
||||
try {
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolveNamespacedFunctionName(name);
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + ref.name()).toString();
|
||||
} catch (AwsException e) {
|
||||
// A reference Lambda refuses, which its handler answers with a 400 before acting on anything.
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The function {@code CreateFunction} makes, which its body names, in the caller's account and Region, as
|
||||
* every route but an invoke acts there: the Service Reference gives it the {@code function} resource, so
|
||||
* its own action, and the tagging action its tags need, are checked on that function. {@code *} for any
|
||||
* other route that names no function.
|
||||
*/
|
||||
private String createdFunctionArn(String path, ContainerRequestContext ctx, String region, String accountId) {
|
||||
if (!"POST".equalsIgnoreCase(ctx.getMethod()) || !"/2015-03-31/functions".equals(path)) {
|
||||
return "*";
|
||||
}
|
||||
JsonNode body = readJsonBody(ctx);
|
||||
JsonNode name = body == null ? null : body.get("FunctionName");
|
||||
if (name == null || !name.isTextual() || name.asText().isEmpty()) {
|
||||
return "*";
|
||||
}
|
||||
try {
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId,
|
||||
"function:" + LambdaArnUtils.resolve(name.asText()).name()).toString();
|
||||
} catch (AwsException e) {
|
||||
// A name Lambda refuses, which its handler answers with a 400 before creating anything.
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name.asText()).toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource of a Lambda event source mapping, code signing config or layer route, as the Service
|
||||
* Reference gives it. A mapping is looked up by its UUID, a config by the id that ends its ARN and a
|
||||
* layer version by its layer's name as given, an ARN included, and its number, each in the request's
|
||||
* account and Region, so that is the resource checked. A layer route's path is split as the router
|
||||
* splits it, before decoding, so an encoded {@code /} stays inside the layer's name, and its version
|
||||
* number is read as Lambda parses it, so {@code 01} is version 1. {@code PublishLayerVersion} is checked
|
||||
* against the layer and {@code GetLayerVersionByArn} against the version its {@code Arn} names, its
|
||||
* number read the same way. Listing configs, layers or a layer's versions, and creating a config, name
|
||||
* no resource, so they are {@code *}. Null for every other Lambda route.
|
||||
*/
|
||||
private static String lambdaChildArn(String path, ContainerRequestContext ctx, String region, String accountId) {
|
||||
String mapping = segmentAfterPrefix(path, "/2015-03-31/event-source-mappings/");
|
||||
if (mapping != null) {
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, "event-source-mapping:" + mapping).toString();
|
||||
}
|
||||
if (path.startsWith("/2020-04-22/code-signing-configs")) {
|
||||
String config = segmentAfterPrefix(path, "/2020-04-22/code-signing-configs/");
|
||||
return config == null ? "*"
|
||||
: AwsArnUtils.Arn.of("lambda", region, accountId,
|
||||
"code-signing-config:" + trailingName(config)).toString();
|
||||
}
|
||||
if (path.equals("/2018-10-31/layers")) {
|
||||
String arn = ctx.getUriInfo().getQueryParameters().getFirst("Arn");
|
||||
boolean byArn = "LayerVersion".equals(ctx.getUriInfo().getQueryParameters().getFirst("find"));
|
||||
return byArn && AwsArnUtils.isArnFor(arn, "lambda") ? layerVersionArn(arn) : "*";
|
||||
}
|
||||
String layers = "/2018-10-31/layers/";
|
||||
if (!path.startsWith(layers)) {
|
||||
return null;
|
||||
}
|
||||
String raw = IamActionRegistry.rawPath(ctx);
|
||||
if (!raw.startsWith(layers)) {
|
||||
return "*";
|
||||
}
|
||||
String[] segments = raw.substring(layers.length()).split("/");
|
||||
if (segments.length < 2 || !"versions".equals(segments[1])) {
|
||||
return "*";
|
||||
}
|
||||
String layer = "layer:" + pathSegment(segments[0]);
|
||||
if (segments.length == 2) {
|
||||
return "POST".equalsIgnoreCase(ctx.getMethod())
|
||||
? AwsArnUtils.Arn.of("lambda", region, accountId, layer).toString() : "*";
|
||||
}
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId,
|
||||
layer + ":" + layerVersion(pathSegment(segments[2]))).toString();
|
||||
}
|
||||
|
||||
/** A layer version ARN, its version number written as Lambda parses it. */
|
||||
private static String layerVersionArn(String arn) {
|
||||
int colon = arn.lastIndexOf(':');
|
||||
return arn.substring(0, colon + 1) + layerVersion(arn.substring(colon + 1));
|
||||
}
|
||||
|
||||
/** A layer version number as Lambda parses it, so {@code 01} is 1; as given when it is no number. */
|
||||
private static String layerVersion(String version) {
|
||||
try {
|
||||
return Long.toString(Long.parseLong(version));
|
||||
} catch (NumberFormatException e) {
|
||||
return version;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A path segment as sent, decoded as a path parameter is: a {@code +} stays a {@code +}. A malformed
|
||||
* escape is kept as sent.
|
||||
*/
|
||||
private static String pathSegment(String raw) {
|
||||
try {
|
||||
return URLDecoder.decode(raw.replace("+", "%2B"), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource of a Lambda MicroVM or network connector route, as the Service Reference gives it:
|
||||
* {@code microvm-image:<name>} for an action on an image, its versions and builds, and
|
||||
* {@code network-connector:<id>} for one on a connector. An identifier given as an ARN is taken for
|
||||
* its trailing name, in the request's account and Region, since that is the resource the service
|
||||
* looks up and acts on, whatever account or Region the ARN names. {@code RunMicrovm} is checked
|
||||
* against the image its {@code imageIdentifier} names, read the same way, an action on a running
|
||||
* MicroVM against the image that MicroVM runs, and a managed image's versions against the managed
|
||||
* image. Creating an image or a connector, listing them and listing MicroVMs name no resource, so
|
||||
* they are {@code *}, as is a MicroVM the account does not hold. Null for every other Lambda route.
|
||||
*/
|
||||
private String microvmArn(String path, ContainerRequestContext ctx, String region, String accountId) {
|
||||
if (path.startsWith("/2025-09-09/")) {
|
||||
String image = segmentAfterPrefix(path, "/2025-09-09/microvm-images/");
|
||||
if (image != null) {
|
||||
return microvmImageArn(region, accountId, image);
|
||||
}
|
||||
String managed = segmentAfterPrefix(path, "/2025-09-09/managed-microvm-images/");
|
||||
if (managed != null) {
|
||||
return LambdaMicrovmsService.namesManagedImage(managed)
|
||||
? LambdaMicrovmsService.managedImageArn(region) : "*";
|
||||
}
|
||||
String microvm = segmentAfterPrefix(path, "/2025-09-09/microvms/");
|
||||
if (microvm != null) {
|
||||
return runningMicrovmImageArn(region, microvm);
|
||||
}
|
||||
if (path.equals("/2025-09-09/microvms") && "POST".equalsIgnoreCase(ctx.getMethod())) {
|
||||
JsonNode body = readJsonBody(ctx);
|
||||
String identifier = body == null ? null : body.path("imageIdentifier").asText(null);
|
||||
return identifier == null || identifier.isBlank() ? "*" : microvmImageArn(region, accountId, identifier);
|
||||
}
|
||||
return "*";
|
||||
}
|
||||
if (path.startsWith("/2026-04-04/")) {
|
||||
String connector = segmentAfterPrefix(path, "/2026-04-04/network-connectors/");
|
||||
return connector == null ? "*"
|
||||
: AwsArnUtils.Arn.of("lambda", region, accountId,
|
||||
"network-connector:" + trailingName(connector)).toString();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String microvmImageArn(String region, String accountId, String identifier) {
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, "microvm-image:" + trailingName(identifier)).toString();
|
||||
}
|
||||
|
||||
/** The image the caller's MicroVM runs, or {@code *} when the account holds no such MicroVM to act on. */
|
||||
private String runningMicrovmImageArn(String region, String microvmId) {
|
||||
if (microvmsService == null) {
|
||||
return "*";
|
||||
}
|
||||
return microvmsService.get().findMicrovm(region, microvmId)
|
||||
.map(vm -> vm.imageArn)
|
||||
.filter(arn -> arn != null && !arn.isBlank())
|
||||
.orElse("*");
|
||||
}
|
||||
|
||||
/** An identifier's name: an ARN's part after its last {@code :}, as the MicroVM service unwraps it. */
|
||||
private static String trailingName(String identifier) {
|
||||
return AwsArnUtils.looksLikeArn(identifier) ? identifier.substring(identifier.lastIndexOf(':') + 1) : identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource a Lambda tag route acts on, from the ARN it names. Tagging looks a function up by the
|
||||
* ARN's Region and name, and a MicroVM image or network connector by the ARN's Region and trailing
|
||||
* name, in the caller's own account whatever account the ARN names, so that resource is the one
|
||||
* checked. The MicroVM tag handler takes only a Lambda ARN naming an image or a connector with no
|
||||
* version, so the target is read through {@link LambdaMicrovmsService#taggedResource}, as it reads it.
|
||||
* Any other ARN, an event source mapping's included, has to name its resource exactly or is
|
||||
* refused, so it is checked as written.
|
||||
*/
|
||||
private static String lambdaTaggedArn(String tagged, String accountId) {
|
||||
// The image or connector LambdaMicrovmsService tags: the caller's own, in the ARN's Region.
|
||||
Optional<String> microvmResource = LambdaMicrovmsService.taggedResource(tagged);
|
||||
if (microvmResource.isPresent()) {
|
||||
String region = AwsArnUtils.parse(tagged).region();
|
||||
if (!region.isBlank()) {
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, microvmResource.get()).toString();
|
||||
}
|
||||
}
|
||||
if (!AwsArnUtils.looksLikeArn(tagged)) {
|
||||
return "*";
|
||||
}
|
||||
try {
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(tagged);
|
||||
return ref.qualifier() != null ? tagged
|
||||
: AwsArnUtils.Arn.of("lambda", ref.region(), accountId, "function:" + ref.name()).toString();
|
||||
} catch (AwsException e) {
|
||||
// Not a function ARN Lambda takes, which it tags only when the ARN names the resource exactly.
|
||||
return tagged;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource of an Aurora DSQL route, as the Service Authorization Reference names it: the cluster
|
||||
* a cluster route names, the stream a stream route names (its cluster, to create or list streams), or
|
||||
@@ -1448,6 +1155,18 @@ public class ResourceArnBuilder {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A path segment as sent, decoded as a path parameter is: a {@code +} stays a {@code +}. A malformed
|
||||
* escape is kept as sent.
|
||||
*/
|
||||
private static String pathSegment(String raw) {
|
||||
try {
|
||||
return URLDecoder.decode(raw.replace("+", "%2B"), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
/** The path segment right after {@code prefix}, or null when the path doesn't start with it or names none. */
|
||||
private static String segmentAfterPrefix(String path, String prefix) {
|
||||
if (!path.startsWith(prefix)) {
|
||||
@@ -1459,95 +1178,6 @@ public class ResourceArnBuilder {
|
||||
return segment.isEmpty() ? null : segment;
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource of a Lambda Web Functions route. An action on a revision or an endpoint is evaluated
|
||||
* against that child's ARN; an action on the function, a create of a revision or endpoint, the list of
|
||||
* either, and the tag and resource-policy routes against the function's (Lambda Developer Guide,
|
||||
* "Lambda Web Function permissions"). ListWebFunctions, GetWebAccountSettings and CreateWebFunction
|
||||
* name no resource. Null for every other Lambda route.
|
||||
*/
|
||||
public static String webFunctionArn(String path, String region, String accountId) {
|
||||
if (!path.startsWith("/2025-03-07/")) {
|
||||
return null;
|
||||
}
|
||||
String rest = path.substring("/2025-03-07/".length());
|
||||
if (rest.startsWith("tags/") || rest.startsWith("resource-policy/")) {
|
||||
String arn = rest.substring(rest.indexOf('/') + 1);
|
||||
return AwsArnUtils.looksLikeArn(arn) ? arn : "*";
|
||||
}
|
||||
if (!rest.startsWith("web-functions/")) {
|
||||
return "*";
|
||||
}
|
||||
List<String> segments = new ArrayList<>(List.of(rest.substring("web-functions/".length()).split("/")));
|
||||
if (segments.isEmpty() || segments.getFirst().isEmpty()) {
|
||||
return "*";
|
||||
}
|
||||
String functionArn;
|
||||
if (AwsArnUtils.looksLikeArn(segments.getFirst()) && segments.size() > 1) {
|
||||
// A function ARN carries one slash: arn:...:web-function/<name>.
|
||||
functionArn = segments.get(0) + "/" + segments.get(1);
|
||||
segments.subList(0, 2).clear();
|
||||
} else {
|
||||
functionArn = AwsArnUtils.Arn.of("lambda", region, accountId,
|
||||
"web-function/" + segments.getFirst()).toString();
|
||||
segments.removeFirst();
|
||||
}
|
||||
if (segments.size() >= 2 && ("revisions".equals(segments.get(0)) || "endpoints".equals(segments.get(0)))) {
|
||||
String child = "revisions".equals(segments.get(0)) ? "revision" : "endpoint";
|
||||
String id = String.join("/", segments.subList(1, segments.size()));
|
||||
if (AwsArnUtils.looksLikeArn(id) && id.contains("/" + child + "/")) {
|
||||
// A revision or endpoint ARN ends in its id: arn:...:web-function/<name>/revision/<id>.
|
||||
id = id.substring(id.lastIndexOf('/') + 1);
|
||||
}
|
||||
return functionArn + "/" + child + "/" + id;
|
||||
}
|
||||
return functionArn;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code GetFunction}, {@code GetFunctionConfiguration} and {@code ListDurableExecutionsByFunction}
|
||||
* read a function named by a qualified full ARN in the account the ARN names, where the version or
|
||||
* alias is resolved ({@code LambdaService.getFunction(region, name, qualifier)}). Unqualified, or
|
||||
* by partial ARN, they read the caller's own function of that name, as every other route acts.
|
||||
*/
|
||||
private static boolean readsInTheAccountItNames(String path, String name,
|
||||
LambdaArnUtils.ResolvedFunctionRef ref,
|
||||
ContainerRequestContext ctx) {
|
||||
if (!"GET".equals(ctx.getMethod()) || !AwsArnUtils.looksLikeArn(name)) {
|
||||
return false;
|
||||
}
|
||||
String route = path.substring(path.indexOf("/functions/" + name) + "/functions/".length() + name.length());
|
||||
if (!route.isEmpty() && !route.equals("/configuration") && !route.equals("/durable-executions")) {
|
||||
return false;
|
||||
}
|
||||
String qualifier = ctx.getUriInfo().getQueryParameters().getFirst("Qualifier");
|
||||
return ref.qualifier() != null || (qualifier != null && !qualifier.isBlank());
|
||||
}
|
||||
|
||||
/** Durable execution actions are authorized against the execution ARN, which carries the version. */
|
||||
private static String durableExecutionArn(String path) {
|
||||
String prefix = "/durable-executions/";
|
||||
int executions = path.indexOf(prefix);
|
||||
if (executions < 0) {
|
||||
return null;
|
||||
}
|
||||
Matcher matcher = LambdaArnUtils.DURABLE_EXECUTION_ARN.matcher(path.substring(executions + prefix.length()));
|
||||
return matcher.lookingAt() ? matcher.group() : null;
|
||||
}
|
||||
|
||||
/** A callback id carries its execution ARN, so the callback actions are authorized against that execution. */
|
||||
private static String durableCallbackExecutionArn(String path) {
|
||||
String prefix = "/durable-execution-callbacks/";
|
||||
int callbacks = path.indexOf(prefix);
|
||||
int action = path.lastIndexOf('/');
|
||||
if (callbacks < 0 || action <= callbacks + prefix.length()) {
|
||||
return null;
|
||||
}
|
||||
return DurableTokens.callbackExecutionArn(path.substring(callbacks + prefix.length(), action))
|
||||
.filter(arn -> LambdaArnUtils.DURABLE_EXECUTION_ARN.matcher(arn).matches())
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
// ── Bedrock ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -2099,16 +1729,6 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
private String extractSegmentAfter(String path, String segment) {
|
||||
String marker = "/" + segment + "/";
|
||||
int idx = path.indexOf(marker);
|
||||
if (idx < 0) return null;
|
||||
String after = path.substring(idx + marker.length());
|
||||
// take only the first segment (stop at next /)
|
||||
int slash = after.indexOf('/');
|
||||
return slash > 0 ? after.substring(0, slash) : after;
|
||||
}
|
||||
|
||||
// ── STS ─────────────────────────────────────────────────────────────────────
|
||||
/**
|
||||
* Uses the serving operation, as {@link #buildLogResources} does: {@code AssumeRole} is
|
||||
|
||||
@@ -8,7 +8,6 @@ import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.SignedMarkers;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.lambda.model.LambdaLayerVersion;
|
||||
import io.floci.aws.services.lambda.zip.DeploymentPackage;
|
||||
import io.floci.aws.services.lambda.zip.ZipExtractor;
|
||||
@@ -35,7 +34,7 @@ import java.util.stream.Collectors;
|
||||
* Business logic for Lambda Layer management.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaLayerService implements StoredResourceArns {
|
||||
public class LambdaLayerService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaLayerService.class);
|
||||
|
||||
@@ -101,19 +100,8 @@ public class LambdaLayerService implements StoredResourceArns {
|
||||
this.s3Service = s3Service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "lambda";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
// Layer version selectors supply the complete identifier, so no generated suffix needs a lookup.
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> resolveStoredArn(String arn) {
|
||||
/** The caller's stored layer version a layer version ARN selects; empty for another ARN or no such version. */
|
||||
public Optional<String> storedLayerVersionArn(String arn) {
|
||||
if (!LAYER_VERSION_ARN.matcher(arn).matches()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -340,11 +328,14 @@ public class LambdaLayerService implements StoredResourceArns {
|
||||
* Deletes a specific layer version.
|
||||
*/
|
||||
public void deleteLayerVersion(String region, String layerName, long versionNumber) {
|
||||
LambdaLayerVersion lv = layerStore.get(region, layerName, versionNumber).orElse(null);
|
||||
LambdaLayerVersion lv = AwsArnUtils.looksLikeArn(layerName)
|
||||
? findLayerVersionByArn(layerName + ":" + versionNumber)
|
||||
: layerStore.get(region, layerName, versionNumber).orElse(null);
|
||||
if (lv == null) {
|
||||
// AWS returns 204 even if the layer version doesn't exist
|
||||
return;
|
||||
}
|
||||
String layerRegion = AwsArnUtils.parse(lv.getLayerVersionArn()).region();
|
||||
|
||||
// Delete the extracted code from disk
|
||||
if (lv.getCodeLocalPath() != null) {
|
||||
@@ -352,9 +343,9 @@ public class LambdaLayerService implements StoredResourceArns {
|
||||
deleteDirectory(codePath);
|
||||
}
|
||||
|
||||
layerStore.delete(region, layerName, versionNumber);
|
||||
deleteLayerArchive(region, lv);
|
||||
LOG.infov("Deleted layer version: {0} v{1} in region {2}", layerName, versionNumber, region);
|
||||
layerStore.delete(layerRegion, lv.getLayerName(), versionNumber);
|
||||
deleteLayerArchive(layerRegion, lv);
|
||||
LOG.infov("Deleted layer version: {0} v{1} in region {2}", lv.getLayerName(), versionNumber, layerRegion);
|
||||
}
|
||||
|
||||
private void deleteLayerArchive(String region, LambdaLayerVersion lv) {
|
||||
@@ -377,6 +368,15 @@ public class LambdaLayerService implements StoredResourceArns {
|
||||
* answers them.
|
||||
*/
|
||||
public LambdaLayerVersion getLayerVersionByArn(String layerVersionArn) {
|
||||
LambdaLayerVersion lv = findLayerVersionByArn(layerVersionArn);
|
||||
if (lv == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"The resource you requested does not exist.", 404);
|
||||
}
|
||||
return lv;
|
||||
}
|
||||
|
||||
private LambdaLayerVersion findLayerVersionByArn(String layerVersionArn) {
|
||||
if (layerVersionArn == null || layerVersionArn.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(
|
||||
SmithyValidationErrors.notNull("arn"));
|
||||
@@ -397,12 +397,7 @@ public class LambdaLayerService implements StoredResourceArns {
|
||||
// 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",
|
||||
"The resource you requested does not exist.", 404);
|
||||
}
|
||||
return lv;
|
||||
return resolveLayerByArn(layerVersionArn);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.lambda.durable.DurableTokens;
|
||||
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What IAM asks Lambda of the resources a request names: the stored layer version a layer version ARN selects, the
|
||||
* image the caller's MicroVM runs, which the Service Reference checks an action on a running MicroVM on, and the
|
||||
* durable execution a callback belongs to, which Lambda authorizes a callback request against.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaStoredResourceArns implements StoredResourceArns {
|
||||
|
||||
private final LambdaLayerService layers;
|
||||
private final Instance<LambdaMicrovmsService> microvms;
|
||||
|
||||
@Inject
|
||||
public LambdaStoredResourceArns(LambdaLayerService layers, Instance<LambdaMicrovmsService> microvms) {
|
||||
this.layers = layers;
|
||||
this.microvms = microvms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "lambda";
|
||||
}
|
||||
|
||||
/** Lambda mints no id into an ARN a request names by its name, so there is nothing to find. */
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** The caller's stored layer version a layer version ARN selects, its number written as Lambda parses it. */
|
||||
@Override
|
||||
public Optional<String> resolveStoredArn(String arn) {
|
||||
return layers.storedLayerVersionArn(arn);
|
||||
}
|
||||
|
||||
/**
|
||||
* The image of the caller's MicroVM a {@code microvmIdentifier} names, and the durable execution of the callback a
|
||||
* {@code CallbackId} names; empty when the caller has no such MicroVM, or the id names no callback.
|
||||
*/
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
return switch (member) {
|
||||
case "microvmIdentifier" -> microvms.isResolvable()
|
||||
? microvms.get().findMicrovm(region, value).map(vm -> vm.imageArn)
|
||||
.filter(arn -> !arn.isBlank()).map(List::of).orElse(List.of())
|
||||
: List.of();
|
||||
case "CallbackId" -> DurableTokens.callbackExecutionArn(value).map(List::of).orElse(List.of());
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user