mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(lambda): accept layer ARNs in GetLayerVersion (#8345)
GetLayerVersion took an unversioned layer ARN as a literal layer name and answered ResourceNotFoundException. It now resolves the ARN through the existing layer resolver, keeping its account and partition checks, and builds the archive URL from the layer's own Region. Both GetLayerVersion and GetLayerVersionByArn take their IAM resources from the generated request-resource table. The generator reads a name-or-ARN alternative on URI and query members, and fills an ARN variable from the integer shape named after it, so the layer version is read from the model. A REST route keeps its modeled operation when AWS authorizes it under another action name, and an ARN selector is checked on the stored version it resolves to, in that version's account and Region. The lookup tests share one layer archive fixture. Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Jackson Price <jxnprice@amazon.com> Co-authored-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
da23f42d11
commit
ade406bac2
19 files changed
+714
-59
No files matched your search
@@ -869,7 +869,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST;
|
||||
String servingScope = servingCredentialScope(claimedScope, ctx);
|
||||
if (rest) {
|
||||
return new ResolvedAuthorization(servingScope, routeAction(servingScope, ctx));
|
||||
return authorizationForRoute(servingScope, ctx);
|
||||
}
|
||||
String targetOperation = IamActionRegistry.targetOperation(ctx);
|
||||
String action = actionRegistry.resolve(servingScope, ctx);
|
||||
@@ -1011,16 +1011,21 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
.map(catalog::canonicalCredentialScope)
|
||||
.distinct()
|
||||
.sorted()
|
||||
.map(scope -> new ResolvedAuthorization(scope, routeAction(scope, ctx)))
|
||||
.map(scope -> authorizationForRoute(scope, ctx))
|
||||
.filter(authorization -> authorization.action() != null)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private ResolvedAuthorization authorizationForRoute(String scope, ContainerRequestContext ctx) {
|
||||
String action = routeAction(scope, ctx);
|
||||
return new ResolvedAuthorization(scope, action, actionRegistry.operationForRoute(scope, action, ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* The scope and action a request is authorized as, and the operation it calls as
|
||||
* {@code <namespace>:<Operation>}, which differs from the action for one AWS authorizes under another name.
|
||||
* A REST route maps straight to its action, which names the operation.
|
||||
* A modeled REST route retains its operation when AWS authorizes it under another action name.
|
||||
*/
|
||||
private record ResolvedAuthorization(String credentialScope, String action, String operation) {
|
||||
ResolvedAuthorization(String credentialScope, String action) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* The resources each operation's request names, for the namespaces whose ARNs {@code ResourceArnBuilder} does not
|
||||
@@ -97,14 +98,19 @@ final class RequestResourceMembers {
|
||||
* follows the one variable the format ends in with an id it mints, {@code /<id>}, which the format leaves out
|
||||
* (EventBridge's {@code connection/<name>/<id>}).
|
||||
*/
|
||||
record ArnFormat(String format, Pattern pattern, boolean unqualified, boolean minted) {
|
||||
record ArnFormat(String format, Pattern pattern, boolean unqualified, boolean minted, Pattern integers) {
|
||||
|
||||
ArnFormat(String format, Pattern pattern, boolean unqualified, boolean minted) {
|
||||
this(format, pattern, unqualified, minted, null);
|
||||
}
|
||||
|
||||
ArnFormat(String format, Pattern pattern, boolean unqualified) {
|
||||
this(format, pattern, unqualified, false);
|
||||
}
|
||||
|
||||
/** The ARN as its service checks it: an unqualified type's without the qualifier it may carry. */
|
||||
/** Normalize modeled integer variables and drop a qualifier only for an unqualified type. */
|
||||
String checked(String arn) {
|
||||
arn = normalizeIntegers(arn);
|
||||
if (!unqualified) {
|
||||
return arn;
|
||||
}
|
||||
@@ -119,6 +125,29 @@ final class RequestResourceMembers {
|
||||
return arn.substring(0, at);
|
||||
}
|
||||
|
||||
private String normalizeIntegers(String arn) {
|
||||
if (integers == null) {
|
||||
return arn;
|
||||
}
|
||||
Matcher values = integers.matcher(arn);
|
||||
if (!values.matches()) {
|
||||
return arn;
|
||||
}
|
||||
StringBuilder normalized = new StringBuilder();
|
||||
int at = 0;
|
||||
for (int group = 1; group <= values.groupCount(); group++) {
|
||||
String value = values.group(group);
|
||||
try {
|
||||
value = Long.toString(Long.parseLong(value));
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Keep invalid selectors unchanged for the service's normal validation.
|
||||
}
|
||||
normalized.append(arn, at, values.start(group)).append(value);
|
||||
at = values.end(group);
|
||||
}
|
||||
return normalized.append(arn.substring(at)).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether AWS owns the type's resources, its format's account being {@code aws}
|
||||
* ({@code arn:${Partition}:sso::aws:applicationProvider/...}), so an ARN of one names none of the caller's.
|
||||
@@ -284,6 +313,7 @@ final class RequestResourceMembers {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no operations");
|
||||
}
|
||||
Set<String> namespaces = Set.copyOf(document.path("namespaces").propertyStream().map(Map.Entry::getKey).toList());
|
||||
validateIntegerVariables(document.path("integerVariables"), document.path("arnFormats"));
|
||||
Map<String, Map<String, ArnFormat>> formats = new LinkedHashMap<>();
|
||||
document.path("arnFormats").properties().forEach(namespace -> {
|
||||
Set<String> unqualified = names(document.path("unqualified").path(namespace.getKey()));
|
||||
@@ -295,8 +325,9 @@ final class RequestResourceMembers {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + "'s "
|
||||
+ type.getKey() + " no ARN format");
|
||||
}
|
||||
Set<String> integers = names(document.path("integerVariables").path(namespace.getKey()).path(type.getKey()));
|
||||
types.put(type.getKey(), new ArnFormat(format, pattern(format), unqualified.contains(type.getKey()),
|
||||
minted.contains(type.getKey())));
|
||||
minted.contains(type.getKey()), integers.isEmpty() ? null : pattern(format, integers)));
|
||||
});
|
||||
formats.put(namespace.getKey(), Map.copyOf(types));
|
||||
});
|
||||
@@ -730,21 +761,49 @@ final class RequestResourceMembers {
|
||||
return new Member(outer.name(), outer.list(), arnMember(operation, path.substring(dot + 1)), outer.map());
|
||||
}
|
||||
|
||||
/**
|
||||
* What an ARN of the format matches: its literal parts, a partition, any Region and account, and anything for
|
||||
* each other variable but nothing.
|
||||
*/
|
||||
/** Reject integer metadata that does not identify a resource variable in a known ARN format. */
|
||||
private static void validateIntegerVariables(JsonNode integers, JsonNode formats) {
|
||||
if (integers.isMissingNode()) {
|
||||
return;
|
||||
}
|
||||
if (!integers.isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " integerVariables must be an object");
|
||||
}
|
||||
integers.properties().forEach(namespace -> {
|
||||
if (!namespace.getValue().isObject() || !formats.has(namespace.getKey())) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " integerVariables has no formats for " + namespace.getKey());
|
||||
}
|
||||
namespace.getValue().properties().forEach(type -> {
|
||||
String format = formats.path(namespace.getKey()).path(type.getKey()).asText("");
|
||||
Set<String> variables = VARIABLE.matcher(format).results().map(match -> match.group(1))
|
||||
.filter(name -> !Set.of("Partition", "Region", "Account").contains(name))
|
||||
.collect(Collectors.toSet());
|
||||
JsonNode names = type.getValue();
|
||||
if (!names.isArray() || names.isEmpty() || !names.valueStream().allMatch(
|
||||
name -> name.isTextual() && variables.contains(name.asText()))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " integerVariables names no variables for "
|
||||
+ namespace.getKey() + ":" + type.getKey());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static Pattern pattern(String format) {
|
||||
return pattern(format, Set.of());
|
||||
}
|
||||
|
||||
private static Pattern pattern(String format, Set<String> integers) {
|
||||
StringBuilder regex = new StringBuilder("^");
|
||||
Matcher variable = VARIABLE.matcher(format);
|
||||
int at = 0;
|
||||
while (variable.find()) {
|
||||
regex.append(Pattern.quote(format.substring(at, variable.start())));
|
||||
regex.append(switch (variable.group(1)) {
|
||||
String value = switch (variable.group(1)) {
|
||||
case "Partition" -> "[^:]+";
|
||||
case "Region", "Account" -> "[^:]*";
|
||||
default -> ".+";
|
||||
});
|
||||
};
|
||||
regex.append(integers.contains(variable.group(1)) ? "(" + value + ")" : value);
|
||||
at = variable.end();
|
||||
}
|
||||
return Pattern.compile(regex.append(Pattern.quote(format.substring(at))).append('$').toString());
|
||||
|
||||
@@ -704,7 +704,7 @@ public final class RequestResources {
|
||||
from.region().isEmpty() ? region : from.region(),
|
||||
from.accountId().isEmpty() ? accountId : from.accountId())), format,
|
||||
resource.types().getFirst(), filling.variables(), null, region), format.awsOwned(), partition,
|
||||
region, accountId, null);
|
||||
region, accountId, stored);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -872,10 +872,18 @@ public final class RequestResources {
|
||||
* the ARN's Region or the request's, whichever its handler acts on. An ARN with no account or Region keeps none,
|
||||
* and one of a type AWS owns ({@code awsOwned}) its account, {@code aws}, which is no caller's. One naming another
|
||||
* account whose resource {@code stored} says the service acts on there (an OAM sink a link is made to, a RAM
|
||||
* invitation sent to the caller) is that resource alone.
|
||||
* invitation sent to the caller) is that resource alone. When the service resolves the complete ARN to a stored
|
||||
* resource in its own coordinates, that stored ARN alone is checked.
|
||||
*/
|
||||
private static void addNamed(Set<String> arns, String arn, boolean awsOwned, String partition, String region,
|
||||
String accountId, StoredResourceArns stored) {
|
||||
if (stored != null) {
|
||||
Optional<String> resolved = stored.resolveStoredArn(arn);
|
||||
if (resolved.isPresent()) {
|
||||
arns.add(resolved.get());
|
||||
return;
|
||||
}
|
||||
}
|
||||
arns.add(arn);
|
||||
if (!AwsArnUtils.isArn(arn)) {
|
||||
return;
|
||||
|
||||
@@ -43,6 +43,15 @@ public interface StoredResourceArns {
|
||||
*/
|
||||
Optional<String> find(String type, List<String> names, String region);
|
||||
|
||||
/**
|
||||
* The resource resolved by an ARN in its own account and Region, without substituting the caller's
|
||||
* coordinates. Empty when the service has no such resource or does not resolve ARN selectors this way.
|
||||
* Used only for operations read by the generated request-resource table.
|
||||
*/
|
||||
default Optional<String> resolveStoredArn(String arn) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources the caller's resource named by {@code value} in {@code member}, as the table writes
|
||||
* the member's path, runs on, is in or reaches in the Region, which a request naming it acts on (the cluster or
|
||||
|
||||
@@ -743,6 +743,19 @@ public class IamActionRegistry {
|
||||
.map(IamRestRoutes.Match::labels).orElse(Map.of());
|
||||
}
|
||||
|
||||
/** Keep the modeled operation when AWS authorizes its route under a different action name. */
|
||||
public String operationForRoute(String credentialScope, String action, ContainerRequestContext ctx) {
|
||||
if (credentialScope == null || action == null) {
|
||||
return action;
|
||||
}
|
||||
String method = ctx.getMethod().toUpperCase();
|
||||
return restRoutes.operation(credentialScope, method, withoutInternalPrefix(ctx, routedPath(ctx)),
|
||||
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx))
|
||||
.filter(operation -> action.equals(IamAuthorizedActions.actionFor(credentialScope, operation, method)))
|
||||
.map(operation -> credentialScope + ":" + operation)
|
||||
.orElse(action);
|
||||
}
|
||||
|
||||
/** Member locations of a generated alternative route; absent entries keep the operation's model locations. */
|
||||
public static Map<String, String> routeMemberLocations(String operation, ContainerRequestContext ctx) {
|
||||
int separator = operation.indexOf(':');
|
||||
|
||||
@@ -97,7 +97,8 @@ public class LambdaLayerController {
|
||||
@Context UriInfo uriInfo) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
LambdaLayerVersion lv = layerService.getLayerVersion(region, layerName, versionNumber);
|
||||
return Response.ok(buildLayerVersionResponse(lv, region, uriInfo)).build();
|
||||
String layerRegion = AwsArnUtils.parse(lv.getLayerVersionArn()).region();
|
||||
return Response.ok(buildLayerVersionResponse(lv, layerRegion, uriInfo)).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
|
||||
@@ -8,6 +8,7 @@ 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;
|
||||
@@ -26,6 +27,7 @@ import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -33,7 +35,7 @@ import java.util.stream.Collectors;
|
||||
* Business logic for Lambda Layer management.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaLayerService {
|
||||
public class LambdaLayerService implements StoredResourceArns {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaLayerService.class);
|
||||
|
||||
@@ -99,6 +101,26 @@ public class LambdaLayerService {
|
||||
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) {
|
||||
if (!LAYER_VERSION_ARN.matcher(arn).matches()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
LambdaLayerVersion layer = resolveLayerByArn(arn);
|
||||
return layer == null ? Optional.empty() : Optional.of(layer.getLayerVersionArn());
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes a new layer version. Each call with the same layer name creates a new version.
|
||||
*/
|
||||
@@ -211,6 +233,9 @@ public class LambdaLayerService {
|
||||
* Returns information about a specific layer version.
|
||||
*/
|
||||
public LambdaLayerVersion getLayerVersion(String region, String layerName, long versionNumber) {
|
||||
if (AwsArnUtils.looksLikeArn(layerName)) {
|
||||
return getLayerVersionByArn(layerName + ":" + versionNumber);
|
||||
}
|
||||
return layerStore.get(region, layerName, versionNumber)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Layer version " + versionNumber + " for layer " + layerName + " not found.", 404));
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-14", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
|
||||
"namespaces": {"access-analyzer": ["accessanalyzer"], "account": ["account"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "ram": ["ram"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "route53": ["route53"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
|
||||
"namespaces": {"access-analyzer": ["accessanalyzer"], "account": ["account"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "lambda": ["lambda"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "ram": ["ram"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "route53": ["route53"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
|
||||
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "sts"],
|
||||
"notCovered": {"airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rules do not fill a name from, so nearly every operation's resource would be left open", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2-instance-connect": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticache": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, `environment/<application>/<name>`, while most of its requests name it by EnvironmentName or EnvironmentId alone, so reading it needs the stored environment those find", "elasticfilesystem": "REST: its requests namLine truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web"],
|
||||
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "account": {"account": "arn:${Partition}:account::${Account}:account", "accountInOrganization": "arn:${Partition}:account::${ManagementAccountId}:account/o-${OrganizationId}/${MemberAccountId}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudfront": {"anycast-ip-list": "arn:${Partition}:cloudfront::${Account}:anycast-ip-list/${Id}", "cache-policy": "arn:${Partition}:cloudfront::${Account}:cache-policy/${Id}", "connection-function": "arn:${Partition}:cloudfront::${Account}:connection-function/${Id}", "connection-group": "arn:${Partition}:cloudfront::${Account}:connection-group/${Id}", "continuous-deployment-policy": "arn:${Partition}:cloudfront::${Account}:continuous-deployment-policy/${Id}", "distribution": "arn:${Partition}:cloudfront::${Account}:distribution/${DistributionId}", "distribution-tenant": "arn:${Partition}:cloudfront::${Account}:distribution-tenant/${Id}", "field-level-encryption-config": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-config/${Id}", "field-level-encryption-profile": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-profile/${Id}", "function": "arn:${Partition}:cloudfront::${Account}:function/${Name}", "key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${Name}", "origin-access-control": "arn:${Partition}:cloudfront::${Account}:origin-access-control/${Id}", "origin-access-identity": "arn:${Partition}:cloudfront::${Account}:origin-access-identity/${Id}", "origin-request-policy": "arn:${Partition}:cloudfront::${Account}:origin-request-policy/${Id}", "realtime-log-config": "arn:${Partition}:cloudfront::${Account}:realtime-log-config/${Name}", "response-headers-policy": "arn:${Partition}:cloudfront::${Account}:response-headers-policy/${Id}", "streaming-distribution": "arn:${Partition}:cloudfront::${Account}:streaming-distribution/${DistributionId}", "trust-store": "arn:${Partition}:cloudfront::${Account}:trust-store/${Id}", "vpcorigin": "arn:${Partition}:cloudfront::${Account}:vpcorigin/${Id}"}, "cloudfront-keyvaluestore": {"key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${ResourceId}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Line truncated
|
||||
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "account": {"account": "arn:${Partition}:account::${Account}:account", "accountInOrganization": "arn:${Partition}:account::${ManagementAccountId}:account/o-${OrganizationId}/${MemberAccountId}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudfront": {"anycast-ip-list": "arn:${Partition}:cloudfront::${Account}:anycast-ip-list/${Id}", "cache-policy": "arn:${Partition}:cloudfront::${Account}:cache-policy/${Id}", "connection-function": "arn:${Partition}:cloudfront::${Account}:connection-function/${Id}", "connection-group": "arn:${Partition}:cloudfront::${Account}:connection-group/${Id}", "continuous-deployment-policy": "arn:${Partition}:cloudfront::${Account}:continuous-deployment-policy/${Id}", "distribution": "arn:${Partition}:cloudfront::${Account}:distribution/${DistributionId}", "distribution-tenant": "arn:${Partition}:cloudfront::${Account}:distribution-tenant/${Id}", "field-level-encryption-config": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-config/${Id}", "field-level-encryption-profile": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-profile/${Id}", "function": "arn:${Partition}:cloudfront::${Account}:function/${Name}", "key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${Name}", "origin-access-control": "arn:${Partition}:cloudfront::${Account}:origin-access-control/${Id}", "origin-access-identity": "arn:${Partition}:cloudfront::${Account}:origin-access-identity/${Id}", "origin-request-policy": "arn:${Partition}:cloudfront::${Account}:origin-request-policy/${Id}", "realtime-log-config": "arn:${Partition}:cloudfront::${Account}:realtime-log-config/${Name}", "response-headers-policy": "arn:${Partition}:cloudfront::${Account}:response-headers-policy/${Id}", "streaming-distribution": "arn:${Partition}:cloudfront::${Account}:streaming-distribution/${DistributionId}", "trust-store": "arn:${Partition}:cloudfront::${Account}:trust-store/${Id}", "vpcorigin": "arn:${Partition}:cloudfront::${Account}:vpcorigin/${Id}"}, "cloudfront-keyvaluestore": {"key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${ResourceId}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Line truncated
|
||||
"resourceTagKeys": {"ec2": {"application-status-check": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-block": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-manager-data-export": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-cancellation-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-modification-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "carrier-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "client-vpn-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "coip-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "customer-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "declarative-policies-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dedicated-host": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dhcp-options": ["aws:ResourceTag/", "ec2:ResourceTag/"], "egress-only-internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-gpu": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-ip": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-instance-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fpga-image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "host-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image-usage-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-snapshot-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-connect-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-event-window": ["aws:ResourceTag/", "ec2:ResourceTag/"], "internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-external-resource-verification-token": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-internet-registry-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-policy": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool-allocation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver-target": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv4pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv6pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "key-pair": ["aws:ResourceTag/", "ec2:ResourceTag/"], "launch-template": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-virtual-interface-group-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-vpc-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "mac-modification-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "natgateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-acl": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-path": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "outpost-lag": ["aws:ResourceTag/", "ec2:ResourceTag/"], "placement-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "prefix-list": ["aws:ResourceTag/", "ec2:ResourceTag/"], "replace-root-volume-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "reserved-instances": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-peer": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-network": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-subnet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group-rule": ["aws:ResourceTag/", "ec2:ResourceTag/"], "snapshot": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-fleet-request": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-instances-request": ["aws:ResourceTag/", "Line truncated
|
||||
"unqualified": {"ssm": ["parameter"], "states": ["statemachine"]},
|
||||
"unqualified": {"lambda": ["function"], "ssm": ["parameter"], "states": ["statemachine"]},
|
||||
"mintedIds": {"events": ["api-destination", "connection"]},
|
||||
"integerVariables": {"lambda": {"layerVersion": ["LayerVersion"]}},
|
||||
"forwardedActions": {"kms:Decrypt": {"type": "key", "format": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "viaService": "kms:ViaService"}},
|
||||
"operations": {
|
||||
"access-analyzer:ApplyArchiveRule": {"action": "access-analyzer:ApplyArchiveRule", "types": ["Analyzer"], "resources": [{"types": ["Analyzer"], "arn": "analyzerArn"}]},
|
||||
@@ -2557,6 +2558,8 @@
|
||||
"kinesisanalytics:UntagResource": {"action": "kinesisanalytics:UntagResource", "types": ["application"], "resources": [{"types": ["application"], "arn": "ResourceARN"}]},
|
||||
"kinesisanalytics:UpdateApplication": {"action": "kinesisanalytics:UpdateApplication", "types": ["application"], "resources": [{"type": "application", "fill": {"ApplicationName": "ApplicationName"}}]},
|
||||
"kinesisanalytics:UpdateApplicationMaintenanceConfiguration": {"action": "kinesisanalytics:UpdateApplicationMaintenanceConfiguration", "types": ["application"], "resources": [{"type": "application", "fill": {"ApplicationName": "ApplicationName"}}]},
|
||||
"lambda:GetLayerVersion": {"action": "lambda:GetLayerVersion", "types": ["layerVersion"], "resources": [{"type": "layerVersion", "fill": {"LayerName": "LayerName", "LayerVersion": "VersionNumber"}, "arnOf": {"LayerName": "layer"}}], "located": {"LayerName": "{LayerName}", "VersionNumber": "{VersionNumber}"}},
|
||||
"lambda:GetLayerVersionByArn": {"action": "lambda:GetLayerVersion", "types": ["layerVersion"], "resources": [{"types": ["layerVersion"], "arn": "Arn"}], "located": {"Arn": "?Arn"}},
|
||||
"logs:CreateDelivery": {"action": "logs:CreateDelivery", "types": ["delivery", "delivery-destination", "delivery-source"], "resources": [{"types": ["delivery", "delivery-destination", "delivery-source"], "arn": "deliveryDestinationArn"}, {"type": "delivery", "fill": {}, "made": true}, {"type": "delivery-source", "fill": {"DeliverySourceName": "deliverySourceName"}}]},
|
||||
"logs:DeleteDelivery": {"action": "logs:DeleteDelivery", "types": ["delivery"], "resources": [{"type": "delivery", "fill": {}, "find": ["id"]}]},
|
||||
"logs:DeleteDeliveryDestination": {"action": "logs:DeleteDeliveryDestination", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "name"}}]},
|
||||
|
||||
@@ -96,6 +96,7 @@ class IamEnforcementFilterTest {
|
||||
iamService = mock(IamService.class);
|
||||
evaluator = mock(IamPolicyEvaluator.class);
|
||||
actionRegistry = mock(IamActionRegistry.class);
|
||||
when(actionRegistry.operationForRoute(any(), any(), any())).thenAnswer(inv -> inv.getArgument(1));
|
||||
arnBuilder = mock(ResourceArnBuilder.class);
|
||||
requestContext = new RequestContext();
|
||||
conditionContextResolver = mock(IamConditionContextResolver.class);
|
||||
|
||||
@@ -42,6 +42,35 @@ class RequestResourceMembersTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void modeledIntegerArnVariablesNormalizeOnlyTheirOwnValues() throws Exception {
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree("""
|
||||
{
|
||||
"namespaces": {"example": ["example"]},
|
||||
"arnFormats": {"example": {
|
||||
"version": "arn:${Partition}:example:${Region}:${Account}:item:${Name}:${Version}"
|
||||
}},
|
||||
"integerVariables": {"example": {"version": ["Version"]}},
|
||||
"operations": {"example:Read": {"resources": []}}
|
||||
}
|
||||
""");
|
||||
ArnFormat format = parse(document.toString()).formats().get("example").get("version");
|
||||
String prefix = "arn:aws-cn:example:cn-north-1:000000000001:item:001:";
|
||||
assertEquals(prefix + "1", format.checked(prefix + "01"));
|
||||
assertEquals(prefix + "1", format.checked(prefix + "+1"));
|
||||
for (String invalid : List.of("latest", "*", "9223372036854775808")) {
|
||||
assertEquals(prefix + invalid, format.checked(prefix + invalid));
|
||||
}
|
||||
for (String invalid : List.of("[]", "{\"unknown\":{\"version\":[\"Version\"]}}",
|
||||
"{\"example\":{\"unknown\":[\"Version\"]}}", "{\"example\":{\"version\":[\"Account\"]}}",
|
||||
"{\"example\":{\"version\":\"Version\"}}", "{\"example\":{\"version\":[1]}}")) {
|
||||
ObjectNode changed = document.deepCopy();
|
||||
changed.set("integerVariables", MAPPER.readTree(invalid));
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> parse(changed.toString()));
|
||||
assertTrue(failure.getMessage().contains("integerVariables"), failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedIdTargetsValidateTheirMemberWireNameAndDiscriminators() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
@@ -124,7 +153,7 @@ class RequestResourceMembersTest {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
assertTrue(table.namespaces().containsAll(List.of("cognito-idp", "ecr", "elasticloadbalancing", "states")));
|
||||
assertTrue(table.handBuilt().contains("lambda"));
|
||||
assertEquals(Set.of("dynamodb", "logs"), table.namespaces().stream().filter(table.handBuilt()::contains)
|
||||
assertEquals(Set.of("dynamodb", "lambda", "logs"), table.namespaces().stream().filter(table.handBuilt()::contains)
|
||||
.collect(Collectors.toSet()));
|
||||
Set<String> logsDelivery = Stream.of("PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource",
|
||||
"DescribeDeliverySources", "PutDeliveryDestination", "GetDeliveryDestination",
|
||||
@@ -133,6 +162,8 @@ class RequestResourceMembersTest {
|
||||
.map(operation -> "logs:" + operation).collect(Collectors.toSet());
|
||||
Set<String> expected = new HashSet<>(logsDelivery);
|
||||
expected.add("logs:PutDestination");
|
||||
expected.add("lambda:GetLayerVersion");
|
||||
expected.add("lambda:GetLayerVersionByArn");
|
||||
// What AWS was measured to check where the Service Reference lists no resource type (MEASURED).
|
||||
expected.add("dynamodb:ListTables");
|
||||
assertEquals(expected, table.operations().keySet().stream()
|
||||
|
||||
@@ -1431,6 +1431,27 @@ class RequestResourcesTest {
|
||||
return RequestResources.created(operation, request, "aws", "us-east-1", "000000000000");
|
||||
}
|
||||
|
||||
@Test
|
||||
void layerArnLookupsUseTheStoredCoordinatesAndNumericVersion() {
|
||||
String layer = "arn:aws:lambda:us-west-2:000000000000:layer:shared";
|
||||
String version = layer + ":1";
|
||||
StoredResourceArns stored = mock(StoredResourceArns.class);
|
||||
when(stored.resolveStoredArn(version)).thenReturn(Optional.of(version));
|
||||
ContainerRequestContext request = rest("GET", null, Map.of());
|
||||
Map<String, String> labels = Map.of("LayerName", layer, "VersionNumber", "01");
|
||||
|
||||
assertEquals(List.of(version), RequestResources.of("lambda:GetLayerVersion", request,
|
||||
"aws", "us-east-1", "000000000000", stored, labels));
|
||||
assertEquals(List.of(version), RequestResources.of("lambda:GetLayerVersionByArn",
|
||||
rest("GET", null, Map.of("Arn", layer + ":01")), "aws", "us-east-1",
|
||||
"000000000000", stored, Map.of()));
|
||||
|
||||
when(stored.resolveStoredArn(version)).thenReturn(Optional.empty());
|
||||
assertEquals(List.of(version, "arn:aws:lambda:us-east-1:000000000000:layer:shared:1"),
|
||||
RequestResources.of("lambda:GetLayerVersion", request, "aws", "us-east-1",
|
||||
"000000000000", stored, labels));
|
||||
}
|
||||
|
||||
private static List<String> of(String operation, ContainerRequestContext request) {
|
||||
return RequestResources.of(operation, request, "aws", "us-east-1", "000000000000");
|
||||
}
|
||||
|
||||
@@ -509,6 +509,24 @@ class IamActionRegistryTest {
|
||||
assertEquals("lambda:ListLayers", lambdaAction("GET", "/2018-10-31/layers"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestOperationRetainsItsModeledNameWhenItsAuthorizedActionDiffers() {
|
||||
MultivaluedHashMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.putSingle("find", "LayerVersion");
|
||||
ContainerRequestContext byArn = mockCtx("GET", "/2018-10-31/layers",
|
||||
query, MediaType.APPLICATION_JSON_TYPE, "{}");
|
||||
String action = registry.resolveRoute("lambda", byArn);
|
||||
assertEquals("lambda:GetLayerVersion", action);
|
||||
assertEquals("lambda:GetLayerVersionByArn", registry.operationForRoute("lambda", action, byArn));
|
||||
|
||||
ContainerRequestContext named = mockCtx("GET", "/2018-10-31/layers/shared/versions/1",
|
||||
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}");
|
||||
assertEquals("lambda:GetLayerVersion",
|
||||
registry.operationForRoute("lambda", registry.resolveRoute("lambda", named), named));
|
||||
assertEquals("lambda:ListLayers", registry.operationForRoute("lambda", "lambda:ListLayers", byArn));
|
||||
assertNull(registry.operationForRoute("lambda", null, byArn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulerAndPipesTaggingIsCheckedOnBothTagRoutes() {
|
||||
for (String scope : List.of("scheduler", "pipes")) {
|
||||
|
||||
@@ -2176,26 +2176,31 @@ class ResourceArnBuilderTest {
|
||||
for (String path : new String[] {"/2018-10-31/layers/my-layer/versions/3",
|
||||
"/2018-10-31/layers/my-layer/versions/3/policy",
|
||||
"/2018-10-31/layers/my-layer/versions/3/policy/statement-1"}) {
|
||||
String operation = path.endsWith("/statement-1") ? "RemoveLayerVersionPermission"
|
||||
: path.endsWith("/policy") ? "GetLayerVersionPolicy" : "GetLayerVersion";
|
||||
when(ctx.getMethod()).thenReturn(operation.startsWith("Remove") ? "DELETE" : "GET");
|
||||
request(path);
|
||||
assertEquals(version, builder.build("lambda", ctx, "us-east-1", ACCOUNT), path);
|
||||
assertEquals(version, layerResource(operation, "us-east-1"), path);
|
||||
}
|
||||
// Lambda looks a layer named by an ARN up by that name as given, not as the layer the ARN names, so
|
||||
// the layer of that name is the one checked.
|
||||
// GetLayerVersion accepts an unversioned ARN and checks the version that it names.
|
||||
String named = "arn:aws:lambda:us-east-1:000000000000:layer:my-layer";
|
||||
when(ctx.getMethod()).thenReturn("GET");
|
||||
request("/2018-10-31/layers/" + named + "/versions/3");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:" + named + ":3",
|
||||
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
assertEquals(version, layerResource("GetLayerVersion", "us-east-1"));
|
||||
// GetLayerVersionByArn reads the version its Arn names.
|
||||
request("/2018-10-31/layers");
|
||||
queryParams.putSingle("find", "LayerVersion");
|
||||
queryParams.putSingle("Arn", version);
|
||||
assertEquals(version, builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
assertEquals(version, layerResource("GetLayerVersionByArn", "us-east-1"));
|
||||
queryParams.clear();
|
||||
// Listing layers, a layer's versions or configs, and creating a config, name no resource.
|
||||
for (String path : new String[] {"/2018-10-31/layers", "/2018-10-31/layers/my-layer/versions",
|
||||
"/2020-04-22/code-signing-configs"}) {
|
||||
request(path);
|
||||
assertEquals("*", builder.build("lambda", ctx, "us-east-1", ACCOUNT), path);
|
||||
String operation = path.endsWith("/versions") ? "ListLayerVersions" : "ListLayers";
|
||||
assertEquals("*", path.contains("/layers")
|
||||
? layerResource(operation, "us-east-1")
|
||||
: builder.build("lambda", ctx, "us-east-1", ACCOUNT), path);
|
||||
}
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
request("/2020-04-22/code-signing-configs");
|
||||
@@ -2203,7 +2208,7 @@ class ResourceArnBuilderTest {
|
||||
// PublishLayerVersion makes a version of the layer, so it is checked against the layer.
|
||||
request("/2018-10-31/layers/my-layer/versions");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer",
|
||||
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
layerResource("PublishLayerVersion", "us-east-1"));
|
||||
// A function's own settings, such as its concurrency or versions, are checked against the function.
|
||||
request("/2015-03-31/functions/my-function/versions");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
|
||||
@@ -2214,6 +2219,31 @@ class ResourceArnBuilderTest {
|
||||
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"aws,us-west-2,us-east-1", "aws-cn,cn-northwest-1,cn-north-1",
|
||||
"aws-us-gov,us-gov-east-1,us-gov-west-1"})
|
||||
void lambdaLayerArnLookupKeepsItsCoordinatesAndNormalizesTheVersion(
|
||||
String partition, String layerRegion, String requestRegion) {
|
||||
String layer = "arn:" + partition + ":lambda:" + layerRegion + ":111122223333:layer:shared";
|
||||
when(ctx.getMethod()).thenReturn("GET");
|
||||
request("/2018-10-31/layers/" + layer.replace(":", "%3A") + "/versions/01");
|
||||
|
||||
assertEquals(layer + ":1", layerResource("GetLayerVersion", requestRegion));
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherLayerRoutesKeepTheirLiteralNameResource() {
|
||||
String layer = "arn:aws:lambda:us-west-2:111122223333:layer:shared";
|
||||
String expected = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":layer:" + layer + ":1";
|
||||
when(ctx.getMethod()).thenReturn("DELETE");
|
||||
request("/2018-10-31/layers/" + layer + "/versions/01");
|
||||
assertEquals(expected, layerResource("DeleteLayerVersion", "us-east-1"));
|
||||
|
||||
when(ctx.getMethod()).thenReturn("GET");
|
||||
request("/2018-10-31/layers/" + layer + "/versions/01/policy");
|
||||
assertEquals(expected, layerResource("GetLayerVersionPolicy", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLayerVersionIsReadAsLambdaReadsItsNameAndNumber() {
|
||||
// Lambda parses the version number, so 01 is version 1, and the router keeps an encoded / inside the
|
||||
@@ -2221,21 +2251,26 @@ class ResourceArnBuilderTest {
|
||||
when(ctx.getMethod()).thenReturn("GET");
|
||||
request("/2018-10-31/layers/my-layer/versions/01");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer:1",
|
||||
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
layerResource("GetLayerVersion", "us-east-1"));
|
||||
request("/2018-10-31/layers/my%2Flayer/versions/3/policy");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my/layer:3",
|
||||
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
layerResource("GetLayerVersionPolicy", "us-east-1"));
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
request("/2018-10-31/layers/my%2Flayer/versions");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my/layer",
|
||||
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
layerResource("PublishLayerVersion", "us-east-1"));
|
||||
// GetLayerVersionByArn parses the number the same way.
|
||||
when(ctx.getMethod()).thenReturn("GET");
|
||||
request("/2018-10-31/layers");
|
||||
queryParams.putSingle("find", "LayerVersion");
|
||||
queryParams.putSingle("Arn", "arn:aws:lambda:us-east-1:000000000000:layer:my-layer:01");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer:1",
|
||||
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
|
||||
layerResource("GetLayerVersionByArn", "us-east-1"));
|
||||
}
|
||||
|
||||
private String layerResource(String operation, String region) {
|
||||
return builder.buildResources("lambda", "lambda:" + operation, ctx, region, ACCOUNT,
|
||||
AwsRegions.partitionFor(region)).getFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+36
-20
@@ -6,12 +6,10 @@ import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.floci.aws.services.lambda.LambdaLayerFixtures.layerArchive;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
@@ -29,16 +27,6 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
|
||||
private static final String LAYER_NAME = "by-arn-layer";
|
||||
|
||||
private static String layerZipBase64() throws Exception {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
||||
zos.putNextEntry(new ZipEntry("python/shared.py"));
|
||||
zos.write("VALUE = 1".getBytes());
|
||||
zos.closeEntry();
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(baos.toByteArray());
|
||||
}
|
||||
|
||||
private static String publishLayer() throws Exception {
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
@@ -50,7 +38,7 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
"Description": "resolved by arn",
|
||||
"LicenseInfo": "Apache-2.0"
|
||||
}
|
||||
""".formatted(layerZipBase64()))
|
||||
""".formatted(Base64.getEncoder().encodeToString(layerArchive())))
|
||||
.when()
|
||||
.post("/2018-10-31/layers/" + LAYER_NAME + "/versions")
|
||||
.then()
|
||||
@@ -178,7 +166,7 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
@Order(8)
|
||||
void arnNamingAnotherAccountDoesNotResolveTheCallersOwnLayer() throws Exception {
|
||||
String arn = publishLayer();
|
||||
// Same region, name and version — only the account differs. The lookup is keyed within
|
||||
@@ -207,7 +195,7 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
@Order(9)
|
||||
void arnInAnotherPartitionIsRejected() throws Exception {
|
||||
String arn = publishLayer();
|
||||
// Same account, region, name and version - only the partition differs. Measured against
|
||||
@@ -236,7 +224,7 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
@Order(10)
|
||||
void listLayersStillWorksWithoutFind() throws Exception {
|
||||
publishLayer();
|
||||
|
||||
@@ -250,7 +238,7 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
@Order(11)
|
||||
void unknownFindValueFallsThroughToListLayers() throws Exception {
|
||||
publishLayer();
|
||||
|
||||
@@ -266,7 +254,7 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
@Order(12)
|
||||
void findMatchIsCaseSensitive() {
|
||||
// Also measured: only the exact string dispatches; other casings are ListLayers calls,
|
||||
// which is why an Arn alongside them is simply ignored rather than resolved.
|
||||
@@ -282,10 +270,38 @@ class LambdaGetLayerVersionByArnIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void getLayerVersionAcceptsTheUnversionedLayerArn() throws Exception {
|
||||
String versionArn = publishLayer();
|
||||
String layerArn = versionArn.substring(0, versionArn.lastIndexOf(':'));
|
||||
String version = versionArn.substring(versionArn.lastIndexOf(':') + 1);
|
||||
String expectedHash = given()
|
||||
.queryParam("find", "LayerVersion").queryParam("Arn", versionArn)
|
||||
.get("/2018-10-31/layers")
|
||||
.then().statusCode(200).extract().path("Content.CodeSha256");
|
||||
|
||||
given().pathParam("layer", layerArn).pathParam("version", version)
|
||||
.get("/2018-10-31/layers/{layer}/versions/{version}")
|
||||
.then().statusCode(200)
|
||||
.body("LayerVersionArn", equalTo(versionArn))
|
||||
.body("Content.CodeSha256", equalTo(expectedHash));
|
||||
given().pathParam("layer", layerArn.replace(":000000000000:", ":017000801446:"))
|
||||
.pathParam("version", version)
|
||||
.get("/2018-10-31/layers/{layer}/versions/{version}")
|
||||
.then().statusCode(404);
|
||||
given().pathParam("layer", layerArn).pathParam("version", "999999")
|
||||
.get("/2018-10-31/layers/{layer}/versions/{version}")
|
||||
.then().statusCode(404);
|
||||
given().pathParam("layer", versionArn).pathParam("version", version)
|
||||
.get("/2018-10-31/layers/{layer}/versions/{version}")
|
||||
.then().statusCode(400);
|
||||
}
|
||||
|
||||
// ── cleanup ───────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
@Order(14)
|
||||
void cleanup_deletePublishedVersions() {
|
||||
List<Integer> versions = given()
|
||||
.when()
|
||||
|
||||
@@ -4,11 +4,26 @@ import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.lambda.model.LambdaLayerVersion;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public final class LambdaLayerFixtures {
|
||||
private LambdaLayerFixtures() {}
|
||||
|
||||
public static byte[] layerArchive() throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
|
||||
zip.putNextEntry(new ZipEntry("python/shared.py"));
|
||||
zip.write("VALUE = 1".getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
public static LambdaLayerService accountScopedService(
|
||||
String defaultAccount, String region, Map<String, LambdaLayerVersion> layersByAccount) {
|
||||
AccountAwareStorageBackend<LambdaLayerVersion> storage = AccountAwareStorageBackend.inMemory(defaultAccount);
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
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 org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
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.layerArchive;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class LambdaLayerNameArnIamIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "741681410004";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"us-east-1,false", "us-east-1,true", "cn-north-1,false", "cn-north-1,true",
|
||||
"us-gov-west-1,false", "us-gov-west-1,true"})
|
||||
void nameAndArnLookupsHonorScopedAllowAndExplicitDeny(String region, boolean arnSelector) throws Exception {
|
||||
verifyLayerPermissions(Region.of(region), Region.of(region), arnSelector);
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossRegionArnLookupChecksTheStoredLayerVersion() throws Exception {
|
||||
verifyLayerPermissions(Region.US_WEST_2, Region.US_EAST_1, true);
|
||||
}
|
||||
|
||||
private void verifyLayerPermissions(Region layerRegion, Region requestRegion, boolean arnSelector) throws Exception {
|
||||
String name = "layer-iam-" + UUID.randomUUID();
|
||||
byte[] archive = layerArchive();
|
||||
PublishLayerVersionResponse published;
|
||||
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, layerRegion, endpoint)) {
|
||||
published = owner.publishLayerVersion(request -> request.layerName(name)
|
||||
.content(content -> content.zipFile(SdkBytes.fromByteArray(archive))));
|
||||
}
|
||||
cleanup.register(() -> {
|
||||
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, layerRegion, endpoint)) {
|
||||
owner.deleteLayerVersion(request -> request.layerName(name).versionNumber(published.version()));
|
||||
}
|
||||
});
|
||||
|
||||
String user = "layer-reader-" + UUID.randomUUID();
|
||||
String authorization = auth(ACCOUNT, requestRegion.id(), "iam");
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, user);
|
||||
String selector = arnSelector ? published.layerArn() : name;
|
||||
String resource = published.layerVersionArn();
|
||||
try (LambdaClient reader = AwsTestClients.create(LambdaClient.builder(),
|
||||
credentials.accessKeyId(), credentials.secretAccessKey(), requestRegion, endpoint)) {
|
||||
policy(authorization, user, """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "lambda:GetLayerVersion",
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Action": "lambda:GetLayerVersion",
|
||||
"Resource": "%s"
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(resource));
|
||||
denied(reader, selector, published.version());
|
||||
deniedByArn(reader, resource);
|
||||
|
||||
policy(authorization, user, allow(resource));
|
||||
assertEquals(resource, reader.getLayerVersion(request -> request.layerName(selector)
|
||||
.versionNumber(published.version())).layerVersionArn());
|
||||
assertEquals(resource, reader.getLayerVersionByArn(request -> request.arn(resource)).layerVersionArn());
|
||||
|
||||
policy(authorization, user, allow(resource + "-other"));
|
||||
denied(reader, selector, published.version());
|
||||
deniedByArn(reader, resource);
|
||||
}
|
||||
}
|
||||
|
||||
private void policy(String authorization, String user, String document) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, user, "layer-access", document);
|
||||
}
|
||||
|
||||
private static String allow(String resource) {
|
||||
return """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "lambda:GetLayerVersion",
|
||||
"Resource": "%s"
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(resource);
|
||||
}
|
||||
|
||||
private static void denied(LambdaClient client, String selector, long version) {
|
||||
LambdaException denied = assertThrows(LambdaException.class, () -> client.getLayerVersion(request -> request
|
||||
.layerName(selector).versionNumber(version)));
|
||||
assertEquals(403, denied.statusCode());
|
||||
assertTrue(denied.awsErrorDetails().errorCode().contains("AccessDenied"));
|
||||
}
|
||||
|
||||
private static void deniedByArn(LambdaClient client, String arn) {
|
||||
LambdaException denied = assertThrows(LambdaException.class,
|
||||
() -> client.getLayerVersionByArn(request -> request.arn(arn)));
|
||||
assertEquals(403, denied.statusCode());
|
||||
assertTrue(denied.awsErrorDetails().errorCode().contains("AccessDenied"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package io.floci.aws.services.lambda;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.lambda.LambdaClient;
|
||||
import software.amazon.awssdk.services.lambda.model.GetLayerVersionResponse;
|
||||
import software.amazon.awssdk.services.lambda.model.LambdaException;
|
||||
import software.amazon.awssdk.services.lambda.model.PublishLayerVersionResponse;
|
||||
import software.amazon.awssdk.services.lambda.model.ResourceNotFoundException;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.services.lambda.LambdaLayerFixtures.layerArchive;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class LambdaLayerNameArnIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "741681410002";
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"us-east-1", "cn-north-1", "us-gov-west-1"})
|
||||
void nameAndUnversionedArnReturnTheSameArchive(String region) throws Exception {
|
||||
byte[] archive = layerArchive();
|
||||
String name = "layer-name-arn-" + UUID.randomUUID();
|
||||
try (LambdaClient client = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.of(region))) {
|
||||
PublishLayerVersionResponse published = client.publishLayerVersion(request -> request
|
||||
.layerName(name).content(content -> content.zipFile(SdkBytes.fromByteArray(archive))));
|
||||
try {
|
||||
GetLayerVersionResponse byName = client.getLayerVersion(request -> request
|
||||
.layerName(name).versionNumber(published.version()));
|
||||
GetLayerVersionResponse byArn = client.getLayerVersion(request -> request
|
||||
.layerName(published.layerArn()).versionNumber(published.version()));
|
||||
|
||||
assertEquals(published.layerVersionArn(), byArn.layerVersionArn());
|
||||
assertEquals(byName.content().codeSha256(), byArn.content().codeSha256());
|
||||
assertEquals(Base64.getEncoder().encodeToString(
|
||||
MessageDigest.getInstance("SHA-256").digest(archive)), byArn.content().codeSha256());
|
||||
assertArrayEquals(archive, given().urlEncodingEnabled(false).get(byArn.content().location())
|
||||
.then().statusCode(200).extract().asByteArray());
|
||||
} finally {
|
||||
client.deleteLayerVersion(request -> request.layerName(name).versionNumber(published.version()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void arnLookupKeepsTheStoredArchiveRegion() throws Exception {
|
||||
byte[] archive = layerArchive();
|
||||
String name = "layer-region-arn-" + UUID.randomUUID();
|
||||
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_WEST_2);
|
||||
LambdaClient reader = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_EAST_1)) {
|
||||
PublishLayerVersionResponse published = owner.publishLayerVersion(request -> request
|
||||
.layerName(name).content(content -> content.zipFile(SdkBytes.fromByteArray(archive))));
|
||||
try {
|
||||
GetLayerVersionResponse result = reader.getLayerVersion(request -> request
|
||||
.layerName(published.layerArn()).versionNumber(published.version()));
|
||||
|
||||
assertEquals(published.layerVersionArn(), result.layerVersionArn());
|
||||
assertTrue(result.content().location().contains(LambdaService.tasksBucketName("us-west-2")));
|
||||
assertArrayEquals(archive, given().urlEncodingEnabled(false).get(result.content().location())
|
||||
.then().statusCode(200).extract().asByteArray());
|
||||
} finally {
|
||||
owner.deleteLayerVersion(request -> request.layerName(name).versionNumber(published.version()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidArnSelectorsCannotSubstituteTheCallersLayer() throws Exception {
|
||||
String name = "layer-invalid-arn-" + UUID.randomUUID();
|
||||
byte[] archive = layerArchive();
|
||||
try (LambdaClient client = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_EAST_1)) {
|
||||
PublishLayerVersionResponse published = client.publishLayerVersion(request -> request
|
||||
.layerName(name).content(content -> content.zipFile(SdkBytes.fromByteArray(archive))));
|
||||
try {
|
||||
String foreignAccount = published.layerArn().replace(ACCOUNT, "741681410003");
|
||||
assertThrows(ResourceNotFoundException.class, () -> client.getLayerVersion(request -> request
|
||||
.layerName(foreignAccount).versionNumber(published.version())));
|
||||
assertThrows(ResourceNotFoundException.class, () -> client.getLayerVersion(request -> request
|
||||
.layerName(published.layerArn()).versionNumber(999999L)));
|
||||
LambdaException versioned = assertThrows(LambdaException.class,
|
||||
() -> client.getLayerVersion(request -> request
|
||||
.layerName(published.layerVersionArn()).versionNumber(published.version())));
|
||||
assertEquals(400, versioned.statusCode());
|
||||
String foreignPartition = published.layerArn().replace("arn:aws:", "arn:aws-cn:");
|
||||
LambdaException partition = assertThrows(LambdaException.class,
|
||||
() -> client.getLayerVersion(request -> request
|
||||
.layerName(foreignPartition).versionNumber(published.version())));
|
||||
assertEquals(400, partition.statusCode());
|
||||
assertEquals(published.layerVersionArn(), client.getLayerVersion(request -> request
|
||||
.layerName(published.layerArn()).versionNumber(published.version())).layerVersionArn());
|
||||
} finally {
|
||||
client.deleteLayerVersion(request -> request.layerName(name).versionNumber(published.version()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,10 @@ Beyond the members' names, botocore's shapes and documentation say what a member
|
||||
- a member whose documentation says its service uses its default for a request leaving it out ("If you do not
|
||||
specify a cluster, the default cluster is assumed") names that default then (`defaults`), when it fills the one
|
||||
variable of that type's format, rather than naming nothing.
|
||||
A URI or query member can carry the same name-or-ARN alternative as a body member. An integer shape
|
||||
whose name matches an otherwise unfilled ARN variable (optionally ending in `Number`) supplies that variable.
|
||||
`integerVariables` records these numeric identifiers so the reader canonicalizes leading zeroes even when the
|
||||
request gives the whole ARN; string identifiers retain their spelling.
|
||||
What a request names, this file alone says. A service only looks up what it holds where an entry asks it to
|
||||
(`StoredResourceArns`): the resource the members a `find` gives name, the ones a `through` member reaches, and the
|
||||
resource its handler uses for a member left out (Athena's `primary` workgroup, EventBridge's `default` bus, ECS's
|
||||
@@ -270,6 +274,10 @@ READ_IN_HAND_BUILT: dict[str, str] = {
|
||||
READ_IN_HAND_BUILT["logs:PutDestination"] = (
|
||||
"CloudWatch Logs destination creation names the destination by destinationName, which ResourceArnBuilder "
|
||||
"reads from the generated request-resource table")
|
||||
for operation in ("GetLayerVersion", "GetLayerVersionByArn"):
|
||||
READ_IN_HAND_BUILT[f"lambda:{operation}"] = (
|
||||
"Lambda layer lookups name the version through modeled path and query members; "
|
||||
"other Lambda resources retain their existing builders")
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
# MEASURED: what AWS was measured to check where neither botocore nor the Service Reference says it.
|
||||
@@ -1220,7 +1228,8 @@ def located_members(models: dict[str, dict], operation: str) -> dict[str, str]:
|
||||
continue
|
||||
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
|
||||
where = _located(member)
|
||||
if where is None or _strings(model, model["shapes"][member["shape"]]) != "":
|
||||
shape = model["shapes"][member["shape"]]
|
||||
if where is None or (_strings(model, shape) != "" and shape["type"] not in ("integer", "long")):
|
||||
continue
|
||||
if found.setdefault(name, where) != where:
|
||||
raise ValueError(f"{operation}'s {name} is {found[name]} in one client and {where} in {client}")
|
||||
@@ -1318,7 +1327,7 @@ def name_or_arn_members(models: dict[str, dict], operation: str) -> dict[str, st
|
||||
if spec is None or "input" not in spec or not READ_PROTOCOLS & _protocols(model):
|
||||
continue
|
||||
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
|
||||
if member.get("location") not in BODY_LOCATIONS:
|
||||
if member.get("location") not in BODY_LOCATIONS and _located(member) is None:
|
||||
continue
|
||||
shape = model["shapes"][member["shape"]]
|
||||
word = _name_or_arn(shape)
|
||||
@@ -1371,14 +1380,22 @@ def _documented_name_or_arn(documentation: str | None) -> str | None:
|
||||
|
||||
def _name_or_arn(shape: dict) -> str | None:
|
||||
"""The resource type word of the ARN a string shape's pattern takes before a name; None for another shape."""
|
||||
match = NAME_OR_ARN_RE.match(shape.get("pattern") or "") if shape["type"] == "string" else None
|
||||
return match.group(1) if match else None
|
||||
if shape["type"] != "string":
|
||||
return None
|
||||
pattern = shape.get("pattern") or ""
|
||||
match = NAME_OR_ARN_RE.match(pattern)
|
||||
if match:
|
||||
return match.group(1)
|
||||
alternative = re.fullmatch(r"\(arn:.*:([A-Za-z][A-Za-z0-9-]*)[:/](.+)\)\|(.+)", pattern)
|
||||
if alternative and alternative.group(2) == alternative.group(3):
|
||||
return alternative.group(1)
|
||||
return None
|
||||
|
||||
|
||||
def named_by(word: str, formats: dict[str, str]) -> str | None:
|
||||
"""The type whose ARN format's resource is the word and one variable (`event-bus/${EventBusName}`)."""
|
||||
found = [kind for kind, arn in formats.items()
|
||||
if re.fullmatch(r"arn:\$\{Partition}:[^:]*:[^:]*:[^:]*:" + re.escape(word) + r"/\$\{\w+}", arn)]
|
||||
if re.fullmatch(r"arn:\$\{Partition}:[^:]*:[^:]*:[^:]*:" + re.escape(word) + r"[:/]\$\{\w+}", arn)]
|
||||
return found[0] if len(found) == 1 else None
|
||||
|
||||
|
||||
@@ -1451,6 +1468,8 @@ def structure_account_members(models: dict[str, dict], operation: str, types: li
|
||||
accounts = [name for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items()
|
||||
if member.get("location") in BODY_LOCATIONS and re.search(r"account$", name, re.IGNORECASE)
|
||||
and model["shapes"][member["shape"]]["type"] == "string"]
|
||||
if not accounts:
|
||||
continue
|
||||
for kind in types:
|
||||
structures = [shape for name, shape in model["shapes"].items()
|
||||
if shape.get("type") == "structure" and stem(name) == stem(kind)]
|
||||
@@ -2104,6 +2123,7 @@ def read_resources(operation: str, types: list[str], formats: dict[str, str], mo
|
||||
types, members, through_members(models, formats))
|
||||
resources = with_documented(operation, types, formats, models, resources)
|
||||
resources = with_typed_targets(resources, formats, typed_target_fields(models, name))
|
||||
resources = with_integer_members(resources, formats, models, name)
|
||||
optional = optional_members(models, name)
|
||||
resources = with_absent_arn(resources, formats, optional)
|
||||
resources = with_absent_account(resources, formats, account_members(models, name), optional)
|
||||
@@ -2159,6 +2179,41 @@ def with_typed_targets(resources: list[dict], formats: dict[str, str], typed: di
|
||||
return found
|
||||
|
||||
|
||||
def integer_members(models: dict[str, dict], operation: str) -> dict[str, str]:
|
||||
"""Unambiguous integer request members keyed by their shape name without a trailing Number."""
|
||||
candidates: dict[str, set[str]] = {}
|
||||
for model in models.values():
|
||||
spec = model["operations"].get(operation, {})
|
||||
if "input" not in spec or _reading(model) is None:
|
||||
continue
|
||||
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
|
||||
shape = model["shapes"][member["shape"]]
|
||||
if shape["type"] not in ("integer", "long"):
|
||||
continue
|
||||
if member.get("location") not in BODY_LOCATIONS and _located(member) is None:
|
||||
continue
|
||||
variable = member["shape"].removesuffix("Number")
|
||||
candidates.setdefault(variable, set()).add(name)
|
||||
return {variable: next(iter(names)) for variable, names in candidates.items() if len(names) == 1}
|
||||
|
||||
|
||||
def with_integer_members(resources: list[dict], formats: dict[str, str], models: dict[str, dict],
|
||||
operation: str) -> list[dict]:
|
||||
"""Fill an otherwise unnamed ARN variable from the integer shape bearing its name."""
|
||||
members = integer_members(models, operation)
|
||||
result = []
|
||||
for resource in resources:
|
||||
if "fill" not in resource or resource.get("find"):
|
||||
result.append(resource)
|
||||
continue
|
||||
variables = set(VARIABLE_RE.findall(formats[resource["type"]])) - KNOWN_VARIABLES
|
||||
fill = dict(resource["fill"])
|
||||
for variable in sorted(variables & members.keys()):
|
||||
fill.setdefault(variable, members[variable])
|
||||
result.append(dict(resource, fill=dict(sorted(fill.items()))))
|
||||
return result
|
||||
|
||||
|
||||
def with_enum_named(operation: str, resources: list[dict], formats: dict[str, str],
|
||||
models: dict[str, dict]) -> list[dict]:
|
||||
"""The resources, a variable no member fills of a type named by its variables `fixed` to the one value of an enum
|
||||
@@ -2607,11 +2662,35 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
|
||||
"resourceTagKeys": resource_tag_keys(documents),
|
||||
"unqualified": unqualified,
|
||||
"mintedIds": minted,
|
||||
"integerVariables": integer_variables(operations, namespaces, data),
|
||||
"forwardedActions": forwarded,
|
||||
"operations": operations,
|
||||
}
|
||||
|
||||
|
||||
def integer_variables(operations: dict[str, dict], namespaces: dict[str, list[str]],
|
||||
data: Path) -> dict[str, dict[str, list[str]]]:
|
||||
"""ARN variables filled by integer shapes, also normalized when a request supplies the whole ARN."""
|
||||
found: dict[str, dict[str, set[str]]] = {}
|
||||
loaded: dict[str, dict[str, dict]] = {}
|
||||
for operation, entry in operations.items():
|
||||
if not any(resource.get("fill") for resource in entry["resources"]):
|
||||
continue
|
||||
namespace, name = operation.split(":", 1)
|
||||
if namespace not in loaded:
|
||||
loaded[namespace] = load_models(data, set(namespaces[namespace]))
|
||||
members = integer_members(loaded[namespace], name)
|
||||
for resource in entry["resources"]:
|
||||
for variable, member in resource.get("fill", {}).items():
|
||||
if members.get(variable) == member:
|
||||
types = found.setdefault(namespace, {})
|
||||
types.setdefault(resource["type"], set()).add(variable)
|
||||
result = {}
|
||||
for namespace, types in sorted(found.items()):
|
||||
result[namespace] = {kind: sorted(variables) for kind, variables in sorted(types.items())}
|
||||
return result
|
||||
|
||||
|
||||
def unqualified_types(formats: dict[str, dict[str, str]], operations: dict[str, dict],
|
||||
namespaces: dict[str, list[str]], data: Path) -> dict[str, list[str]]:
|
||||
"""The types of each namespace whose ARN a request may give with a qualifier, one more `:<name>` past its format,
|
||||
@@ -2711,7 +2790,7 @@ def render(document: dict) -> str:
|
||||
"""The document with one operation to a line."""
|
||||
lines = ["{"]
|
||||
for key in ("_source", "namespaces", "handBuilt", "notCovered", "otherNamespaces", "arnFormats", "resourceTagKeys",
|
||||
"unqualified", "mintedIds", "forwardedActions"):
|
||||
"unqualified", "mintedIds", "integerVariables", "forwardedActions"):
|
||||
lines.append(f' "{key}": {json.dumps(document[key])},')
|
||||
lines.append(' "operations": {')
|
||||
operations = list(document["operations"].items())
|
||||
@@ -2755,6 +2834,19 @@ def validate(document: dict) -> list[str]:
|
||||
return ["arnFormats is not an ARN format for each resource type of namespaces the file reads"]
|
||||
if list(operations) != sorted(operations):
|
||||
problems.append("operations is not sorted")
|
||||
integers = document.get("integerVariables", {})
|
||||
if not isinstance(integers, dict):
|
||||
return ["integerVariables is not an object"]
|
||||
for namespace, types in integers.items():
|
||||
if namespace not in formats or not isinstance(types, dict):
|
||||
return [f"integerVariables has no resource formats for {namespace}"]
|
||||
for kind, variables in types.items():
|
||||
available = set(VARIABLE_RE.findall(formats[namespace].get(kind, ""))) - KNOWN_VARIABLES
|
||||
if not isinstance(variables, list) or not variables or not all(
|
||||
isinstance(variable, str) and variable in available for variable in variables):
|
||||
return [f"integerVariables names no ARN variables for {namespace}:{kind}"]
|
||||
if variables != sorted(set(variables)):
|
||||
return [f"integerVariables repeats or misorders variables for {namespace}:{kind}"]
|
||||
tag_keys = document.get("resourceTagKeys", {})
|
||||
if not isinstance(tag_keys, dict) or any(
|
||||
not isinstance(kinds, dict) or any(kind not in formats.get(namespace, {})
|
||||
@@ -2975,6 +3067,9 @@ def _created_problems(operation: str, created: object, types: set[str], formats:
|
||||
def derive(document: dict, data: Path) -> list[str]:
|
||||
"""Where the resources the file gives differ from what botocore gives for its types and formats."""
|
||||
problems: list[str] = []
|
||||
integers = integer_variables(document["operations"], document["namespaces"], data)
|
||||
if document.get("integerVariables", {}) != integers:
|
||||
problems.append(f"integerVariables differ from botocore: expected {json.dumps(integers)}")
|
||||
unqualified = unqualified_types(document["arnFormats"], document["operations"], document["namespaces"], data)
|
||||
if document["unqualified"] != unqualified:
|
||||
problems.append(f"the file checks {json.dumps(document['unqualified'])} without a qualifier, the reference "
|
||||
|
||||
@@ -383,6 +383,56 @@ def write_models(root, models: dict[str, dict]):
|
||||
(directory / "service-2.json").write_text(json.dumps(value), encoding="utf-8")
|
||||
|
||||
|
||||
def test_rest_arn_alternatives_and_integer_shapes_fill_versioned_resources(isolated, tmp_path):
|
||||
formats = {
|
||||
"product": "arn:${Partition}:svc:${Region}:${Account}:product:${ProductName}",
|
||||
"productVersion": "arn:${Partition}:svc:${Region}:${Account}:product:${ProductName}:${ProductVersion}",
|
||||
}
|
||||
api = model({"GetProductVersion": {"ProductName": "ProductName", "VersionNumber": "ProductVersionNumber"},
|
||||
"GetProductVersionByArn": {"Arn": "String"}}, "rest-json")
|
||||
api["shapes"]["ProductName"] = {
|
||||
"type": "string", "pattern": "(arn:(aws[a-z-]*)?:svc:[a-z0-9-]+:[0-9]{12}:product:[a-z]+)|[a-z]+"}
|
||||
api["shapes"]["ProductVersionNumber"] = {"type": "long"}
|
||||
api["shapes"]["GetProductVersionIn"]["required"] = ["ProductName", "VersionNumber"]
|
||||
api["operations"]["GetProductVersion"]["http"] = {
|
||||
"method": "GET", "requestUri": "/products/{ProductName}/versions/{VersionNumber}"}
|
||||
for name, member in api["shapes"]["GetProductVersionIn"]["members"].items():
|
||||
member.update(location="uri", locationName=name)
|
||||
api["operations"]["GetProductVersionByArn"]["http"] = {"method": "GET", "requestUri": "/products"}
|
||||
api["shapes"]["GetProductVersionByArnIn"]["members"]["Arn"].update(location="querystring", locationName="Arn")
|
||||
write_models(tmp_path, {"svc": api})
|
||||
documents = [reference("svc", {"GetProductVersion": ["productVersion"],
|
||||
"GetProductVersionByArn": ["productVersion"]}, formats)]
|
||||
document = r.build(documents, "test", tmp_path, "botocore test")
|
||||
entry = document["operations"]["svc:GetProductVersion"]
|
||||
assert entry["resources"] == [{
|
||||
"type": "productVersion", "fill": {"ProductName": "ProductName", "ProductVersion": "VersionNumber"},
|
||||
"arnOf": {"ProductName": "product"}}]
|
||||
assert entry["located"] == {"ProductName": "{ProductName}", "VersionNumber": "{VersionNumber}"}
|
||||
assert document["operations"]["svc:GetProductVersionByArn"]["resources"] == [
|
||||
{"types": ["productVersion"], "arn": "Arn"}]
|
||||
assert document["integerVariables"] == {"svc": {"productVersion": ["ProductVersion"]}}
|
||||
assert r.validate(document) == []
|
||||
assert r.derive(document, tmp_path) == []
|
||||
document["integerVariables"] = {}
|
||||
assert any("integerVariables differ from botocore" in problem for problem in r.derive(document, tmp_path))
|
||||
document["integerVariables"] = {"svc": {"productVersion": ["Account"]}}
|
||||
assert r.validate(document) == ["integerVariables names no ARN variables for svc:productVersion"]
|
||||
|
||||
|
||||
def test_numeric_shapes_do_not_guess_between_members_or_accept_floats():
|
||||
api = model({"UpdateThing": {"MinCapacity": "Capacity", "MaxCapacity": "Capacity",
|
||||
"Weight": "WeightNumber"}})
|
||||
api["shapes"]["Capacity"] = {"type": "integer"}
|
||||
api["shapes"]["WeightNumber"] = {"type": "double"}
|
||||
assert r.integer_members({"svc": api}, "UpdateThing") == {}
|
||||
|
||||
|
||||
def test_an_arn_alternative_requires_the_same_name_pattern():
|
||||
shape = {"type": "string", "pattern": "(arn:aws:svc:us-east-1:123456789012:thing:[a-z]+)|[0-9]+"}
|
||||
assert r._name_or_arn(shape) is None
|
||||
|
||||
|
||||
DOCUMENTS = [reference("svc", {"GetThing": ["thing"], "ListThings": []}, {"thing": FORMATS["thing"]}),
|
||||
reference("other", {"Op": ["x"]}, {"x": "arn:${Partition}:other:::x"}),
|
||||
reference("later", {"Op": ["y"]}, {"y": "arn:${Partition}:later:::y"})]
|
||||
@@ -927,7 +977,10 @@ def test_the_vendored_file_is_well_formed():
|
||||
for operation, entry in operations.items() if operation.startswith("events:")
|
||||
and "endpoint" in json.dumps(entry) for resource in entry["resources"])
|
||||
# A state machine's version or alias is checked on the state machine.
|
||||
assert document["unqualified"] == {"ssm": ["parameter"], "states": ["statemachine"]}
|
||||
assert document["unqualified"] == {"lambda": ["function"], "ssm": ["parameter"], "states": ["statemachine"]}
|
||||
assert document["integerVariables"] == {"lambda": {"layerVersion": ["LayerVersion"]}}
|
||||
assert {operation for operation in operations if operation.startswith("lambda:")} == {
|
||||
"lambda:GetLayerVersion", "lambda:GetLayerVersionByArn"}
|
||||
# A listener is made under a load balancer, and a rule under a listener.
|
||||
assert operations["elasticloadbalancing:CreateListener"]["creates"] == [
|
||||
{"type": f"listener/{kind}", "parent": f"loadbalancer/{kind}/", "arn": "LoadBalancerArn"}
|
||||
|
||||
Reference in new issue
Block a user