fix(iam): check CloudWatch Logs requests on the resources they name, from the generated table (#9088)

CloudWatch Logs was built by hand: ResourceArnBuilder built a group or
stream ARN for six operations and resolved the tag operations' ARN
itself, every other Logs operation was checked on *, and only the
vended-log delivery operations and PutDestination were read from the
request resources table, through READ_IN_HAND_BUILT. logs moves from
HAND_BUILT to NAMESPACES, so the table gives each of its 118
operations the log group, stream, destination or delivery resource its
request names, from botocore and the Service Reference: PutLogEvents,
FilterLogEvents, metric and subscription filters, StartQuery and the
other operations on a group or stream are checked on it, no longer on
*. READ_IN_HAND_BUILT, whose only entries were Logs', goes with its
checks and tests. ResourceArnBuilder's buildLogResources and the
filter's Logs case go; the tagged CreateLogGroup check reads the
table's bare group ARN, which the evaluator already matches with or
without the trailing :* for the group's management actions.
CloudWatchLogsStoredResourceArns answers the stored tags of a log
group, a destination and the delivery family; IamConditionContextResolver
keeps only the request tags of Logs' create and tag calls. Log group
tag writes give the group a new map under the lock creating and
deleting a group take, so one racing a delete cannot put the group
back, and its tags field is volatile. Only Logs' operations change in
the table.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-20 16:21:08 -04:00
1 parent 751f84079f
commit 3027145979
18 files changed
+424 -407

No files matched your search

+26 -23
View File
@@ -2332,8 +2332,7 @@ requests retain HTTP 403 XML `AccessDenied` responses, except SNS's, which retur
action is denied. The routed protocol determines the status, not just the request's content type.
A request is checked against the resources it names. Floci builds their ARNs itself for S3,
DynamoDB, SSM, KMS, IAM, API Gateway
and CloudWatch Logs. For Secrets Manager, Elastic Load Balancing, ECR,
DynamoDB, SSM, KMS, IAM and API Gateway. For Secrets Manager, Elastic Load Balancing, ECR,
Step Functions, EventBridge, EventBridge Scheduler, Amazon Cognito user pools and identity pools, Amazon Data Firehose, Cloud
Map, ACM, CodePipeline, CodeBuild, Amazon Managed Service for Apache Flink (Kinesis Data Analytics v2),
Application Auto Scaling, AWS Budgets, Cost and Usage Reports, Service Quotas, Amazon Textract, Amazon Translate, Amazon Athena,
@@ -2341,7 +2340,7 @@ AWS Data Exports, AWS Pricing Calculator, Cost Explorer, CloudTrail, Global Acce
Timestream for InfluxDB, Amazon Redshift, the Amazon Redshift Data API, AWS Payment Cryptography, AWS DataSync, Amazon EMR,
Amazon Rekognition, IAM Identity Center, Amazon Inspector, Amazon Macie, AWS Fault Injection Service, AWS Resource
Access Manager, CloudWatch Observability Access Manager, AWS Resource Explorer, AWS Account Management, AWS Control
Catalog, Amazon OpenSearch Service, IAM Access Analyzer, AWS Security Hub, Amazon GuardDuty, Lambda, AWS Glue, Amazon SQS, Amazon SNS, Amazon Kinesis Data Streams, Amazon EventBridge Pipes, Aurora DSQL, STS, Amazon EKS and AWS Resource Groups they come from a table generated from AWS's Service Reference and botocore, `src/main/resources/aws/iam-request-resources.json`, which gives each
Catalog, Amazon OpenSearch Service, IAM Access Analyzer, AWS Security Hub, Amazon GuardDuty, Lambda, AWS Glue, Amazon SQS, Amazon SNS, Amazon Kinesis Data Streams, Amazon EventBridge Pipes, Aurora DSQL, STS, Amazon EKS, AWS Resource Groups and Amazon CloudWatch Logs they come from a table generated from AWS's Service Reference and botocore, `src/main/resources/aws/iam-request-resources.json`, which gives each
operation's action, the resource types that action acts on with their ARN formats, and the request
members that name them: a member holding a resource's ARN, which counts when it matches the format
of a type the action acts on, or members filling the variables of a type's format. Nothing in it is
@@ -3088,19 +3087,22 @@ These identities always bypass enforcement (backward-compatible defaults):
| No `Authorization` header | **Rejected** for a JSON, CBOR or Query management call, unless AWS serves the operation without credentials. Allowed for a REST request such as a health check (see [Unsigned requests](#unsigned-requests)) |
| Unresolvable IAM action for the request | Allowed — unknown mappings are permissive |
**CloudWatch Logs streams.** `logs:CreateLogStream` and `logs:DeleteLogStream` evaluate the
specific log-stream ARN, so policies can allow or deny one stream within a group. Their
`aws:ResourceTag/<key>` conditions read the owning log group's current tags in the request's
account and region. Both stream operations check the documented group and stream name constraints
**CloudWatch Logs streams.** `logs:CreateLogStream`, `logs:DeleteLogStream`, `logs:PutLogEvents` and
`logs:GetLogEvents` are checked on the log-stream ARN their group and stream names give, from the generated
table, so policies can allow or deny one stream within a group. A stream ARN carries no
`aws:ResourceTag/<key>`: Floci holds no tags on a stream, and nothing AWS publishes gives a stream its group's.
`CreateLogStream` and `DeleteLogStream` check the documented group and stream name constraints
before changing storage, preventing delimiter aliases from targeting another stream.
These checks also apply to deletion: legacy streams with names containing `:` or `*` cannot be
deleted through `DeleteLogStream`. Existing stored names are not automatically migrated.
**CloudWatch Logs groups.** `CreateLogGroup`, `DeleteLogGroup`, `PutRetentionPolicy` and
`DeleteRetentionPolicy` accept policy resources naming the selected group with a bare ARN
or its legacy `:*` form. Both forms participate in each statement, including explicit denies
and `NotResource`, without bypassing session, boundary or SCP ceilings. The three operations on
existing groups read that group's resource tags; creation uses the request's `tags` for
**CloudWatch Logs groups.** An operation on a log group, `FilterLogEvents`, `DescribeLogStreams`, metric and
subscription filters and `StartQuery` among them, is checked on the group's bare ARN, as the Service Reference
formats a log group, from the generated table. `CreateLogGroup`, `DeleteLogGroup`, `PutRetentionPolicy`,
`DeleteRetentionPolicy` and `TagLogGroup` also accept policy resources naming the selected group with its legacy
`:*` form. Both forms participate in each statement, including explicit denies
and `NotResource`, without bypassing session, boundary or SCP ceilings. An operation on an
existing group reads that group's resource tags; creation uses the request's `tags` for
`aws:RequestTag/<key>` and `aws:TagKeys`. Tagged creation additionally requires either
`logs:TagResource` on the bare group ARN or `logs:TagLogGroup` on either group ARN form.
The group name constraints apply before mutation, and deletion preserves streams and filters
@@ -3108,22 +3110,24 @@ whose stored group identity belongs to another historical group. These four oper
or `*` in a group name. Historical names remain taggable through the ARN tagging APIs below;
they cannot be newly created or deleted through the group lifecycle APIs. Stored names are not migrated.
**CloudWatch Logs ARN tagging.** For log groups, `logs:TagResource`, `logs:UntagResource`
and `logs:ListTagsForResource` evaluate the group's ARN without a trailing `:*`. The ARN must
**CloudWatch Logs ARN tagging.** `logs:TagResource`, `logs:UntagResource` and
`logs:ListTagsForResource` are checked on the ARN their `resourceArn` carries, from the generated table, for each
type the Service Reference gives them: a log group, a destination, a delivery source, a delivery destination or a
delivery. For a log group the ARN must
identify a group in the request's account, region and partition; a different owner or resource
kind returns `ResourceNotFoundException` without reading or changing a local group's tags.
All three actions use the group's existing `aws:ResourceTag/<key>` conditions. `TagResource`
All three actions use the resource's existing `aws:ResourceTag/<key>` conditions. `TagResource`
also provides `aws:RequestTag/<key>` and `aws:TagKeys`; `UntagResource` provides `aws:TagKeys`.
An unauthorized request cannot partially add or remove tags. These ownership checks also apply
when IAM enforcement is disabled. Shared tag mutations reject storage aliases whose stored group
name differs from the requested name, without migrating historical records.
This support covers log groups. Tagging destinations and other CloudWatch Logs resource types
remains unsupported. Plain-name inputs are used literally, including incomplete prefixes such as
The tag handlers also take a plain group name, used literally, including incomplete prefixes such as
`arn:archive`; arbitrary `:log-group:` substrings never select a different group. Structurally complete
ARNs take precedence over plain-name interpretation and must identify a local group. A trailing `:*`
is accepted on a canonical local group ARN. These compatibility forms are not a claim that AWS accepts
them for these APIs. Other Logs actions retain their existing wildcard resource evaluation.
them for these APIs, and authorization reads `resourceArn` as AWS does: a plain name names nothing the
table reads, so the call is checked on `*`, and a group ARN with a trailing `:*` is checked as written.
**CloudWatch Logs account policies.** `PutAccountPolicy` also needs the action for the type of
policy it creates, checked against `*` like `logs:PutAccountPolicy` itself: `logs:PutDataProtectionPolicy`
@@ -3503,9 +3507,7 @@ floci populates:
`ResourceId.N` or `InstanceId.N`), and for `s3:GetBucketTagging`, `s3:DeleteBucket` and the
`s3:PutBucketTagging` that `DeleteBucketTagging` is checked as (the bucket). A request naming several EC2 resources is evaluated
once per resource and denied when any of them fails the condition, as on AWS.
`logs:CreateLogStream`, `logs:DeleteLogStream`, `logs:TagResource`, `logs:UntagResource`,
`logs:ListTagsForResource`, `logs:DeleteLogGroup`, `logs:PutRetentionPolicy` and
`logs:DeleteRetentionPolicy` use the owning log group's tags. Any other ARN a request is checked on
Any other ARN a request is checked on
takes the resource-tag keys the generated `resourceTagKeys` table in `iam-request-resources.json` gives
its type (`aws:ResourceTag/`, `secretsmanager:ResourceTag/`), which `regen_iam_request_resources.py`
reads from the Service Reference for every namespace it reads, valued from the tags the type's service
@@ -3538,8 +3540,9 @@ floci populates:
Load Balancing for its load balancers, target groups, listeners and rules and its Classic Load Balancers, SQS for its
queues, SNS for its topics, Kinesis Data Streams for its streams and consumers, EventBridge Pipes for its pipes,
Aurora DSQL for its clusters, EKS for its clusters, node groups, Fargate profiles, add-ons, Pod Identity
associations and access entries and Resource Groups for its groups. Tag keys differing only in case are one condition
key holding every value.
associations and access entries, Resource Groups for its groups and CloudWatch Logs for its log groups,
destinations, delivery sources, delivery destinations and deliveries. Tag keys differing only in case are one
condition key holding every value.
- EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and
`ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the
key names, an ARN for a key the Service Reference types as one. `resourceKeys` in
@@ -5,10 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
import io.floci.aws.services.cloudwatch.logs.LogGroupTagTarget;
import io.floci.aws.services.dynamodb.DynamoDbConditionKeys;
import io.floci.aws.services.dynamodb.DynamoDbFacade;
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
@@ -111,8 +107,6 @@ public class IamConditionContextResolver {
private final Instance<DynamoDbFacade> dynamoDbFacade;
private final Instance<Ec2Service> ec2Service;
private final Instance<S3Service> s3Service;
private final Instance<CloudWatchLogsService> logsService;
private final Instance<CloudWatchLogsCrossAccountService> crossAccountService;
private final Instance<IamService> iamService;
private final Instance<LambdaWebService> lambdaWebService;
private final Instance<RequestConditionSpelling> requestConditionSpellings;
@@ -132,8 +126,6 @@ public class IamConditionContextResolver {
public IamConditionContextResolver(Instance<DynamoDbFacade> dynamoDbFacade,
Instance<Ec2Service> ec2Service,
Instance<S3Service> s3Service,
Instance<CloudWatchLogsService> logsService,
Instance<CloudWatchLogsCrossAccountService> crossAccountService,
Instance<IamService> iamService,
Instance<LambdaWebService> lambdaWebService,
Instance<RequestConditionSpelling> requestConditionSpellings,
@@ -143,7 +135,7 @@ public class IamConditionContextResolver {
EmulatorConfig config,
CurrentVertxRequest currentVertxRequest,
ResolvedServiceCatalog serviceCatalog) {
this(dynamoDbFacade, ec2Service, s3Service, logsService, crossAccountService, iamService,
this(dynamoDbFacade, ec2Service, s3Service, iamService,
lambdaWebService, requestConditionSpellings, storedResourceArns, requestContext, regionResolver,
config, currentVertxRequest, serviceCatalog, Clock.systemUTC());
}
@@ -151,8 +143,6 @@ public class IamConditionContextResolver {
IamConditionContextResolver(Instance<DynamoDbFacade> dynamoDbFacade,
Instance<Ec2Service> ec2Service,
Instance<S3Service> s3Service,
Instance<CloudWatchLogsService> logsService,
Instance<CloudWatchLogsCrossAccountService> crossAccountService,
Instance<IamService> iamService,
Instance<LambdaWebService> lambdaWebService,
Instance<RequestConditionSpelling> requestConditionSpellings,
@@ -165,8 +155,6 @@ public class IamConditionContextResolver {
this.dynamoDbFacade = dynamoDbFacade;
this.ec2Service = ec2Service;
this.s3Service = s3Service;
this.logsService = logsService;
this.crossAccountService = crossAccountService;
this.iamService = iamService;
this.lambdaWebService = lambdaWebService;
this.requestConditionSpellings = requestConditionSpellings;
@@ -298,81 +286,35 @@ public class IamConditionContextResolver {
};
}
/** Logs tag operations and group mutations use the handler's resource and request scope. */
/**
* The tags a CloudWatch Logs call asks to attach or remove, read as its handler reads them: a tagged
* {@code CreateLogGroup}'s and a {@code TagResource}'s {@code tags} as {@code aws:RequestTag/<key>} and
* {@code aws:TagKeys}, an {@code UntagResource}'s {@code tagKeys} as {@code aws:TagKeys}. The tags of what the
* request names come from Logs' {@link StoredResourceArns}, as for every namespace the table reads.
*/
private Map<String, List<String>> logsConditionContext(String action, ContainerRequestContext ctx) {
if (!("logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action)
|| LogGroupTagTarget.supports(action) || "logs:CreateLogGroup".equals(action) || "logs:DeleteLogGroup".equals(action)
|| "logs:PutRetentionPolicy".equals(action) || "logs:DeleteRetentionPolicy".equals(action))) {
if (!("logs:CreateLogGroup".equals(action) || "logs:TagResource".equals(action)
|| "logs:UntagResource".equals(action))) {
return null;
}
JsonNode body = bufferedJsonBody(ctx);
if (body == null) {
return null;
}
if ("logs:CreateLogGroup".equals(action)) {
JsonNode tags = body.path("tags");
if (!tags.isObject() || tags.isEmpty()) {
return null;
}
Map<String, List<String>> conditions = new LinkedHashMap<>();
List<String> keys = new ArrayList<>();
tags.properties().forEach(entry -> {
keys.add(entry.getKey());
conditions.put("aws:RequestTag/" + entry.getKey(), List.of(entry.getValue().asText()));
});
conditions.put("aws:TagKeys", keys);
return conditions;
}
boolean direct = LogGroupTagTarget.supports(action);
boolean destination = direct && CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn(
body.path("resourceArn").asText());
if (destination ? !crossAccountService.isResolvable() : !logsService.isResolvable()) {
return null;
}
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
Map<String, List<String>> conditions = new LinkedHashMap<>();
if ("logs:TagResource".equals(action) && body.path("tags").isObject()) {
List<String> keys = new ArrayList<>();
body.path("tags").fields().forEachRemaining(entry -> {
List<String> keys = new ArrayList<>();
if ("logs:UntagResource".equals(action)) {
body.path("tagKeys").forEach(key -> keys.add(key.asText()));
} else if (body.path("tags").isObject()) {
body.path("tags").properties().forEach(entry -> {
keys.add(entry.getKey());
conditions.put(REQUEST_TAG_PREFIX + entry.getKey(), List.of(entry.getValue().asText()));
});
if (!keys.isEmpty()) {
conditions.put("aws:TagKeys", keys);
}
} else if ("logs:UntagResource".equals(action)) {
List<String> keys = new ArrayList<>();
body.path("tagKeys").forEach(key -> keys.add(key.asText()));
if (!keys.isEmpty()) {
conditions.put("aws:TagKeys", keys);
}
}
if (direct && CloudWatchLogsDeliveryService.isDeliveryResourceArn(body.path("resourceArn").asText())) {
// A delivery source, destination or delivery: its request tags apply, its own tags are not read.
return conditions.isEmpty() ? null : conditions;
if (!keys.isEmpty()) {
conditions.put("aws:TagKeys", keys);
}
Map<String, String> tags;
try {
if (destination) {
tags = crossAccountService.get().listDestinationTags(body.path("resourceArn").asText(), region);
} else {
String group = direct ? logsService.get().resolveTagTarget(body.path("resourceArn").asText(), region).name()
: body.path("logGroupName").asText();
tags = logsService.get().listTagsLogGroup(group, region);
}
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
// Leave the handler to report a missing resource; unexpected lookup errors must not hide a deny.
return conditions.isEmpty() ? null : conditions;
}
if (tags == null || tags.isEmpty()) {
return conditions.isEmpty() ? null : conditions;
}
tags.forEach((key, value) -> conditions.put(RESOURCE_TAG_PREFIX + key,
List.of(value == null ? "" : value)));
return conditions;
return conditions.isEmpty() ? null : conditions;
}
/** The condition key whose value a delegation can decide rather than the request. */
@@ -649,17 +649,17 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
// Tagged group creation requires either tagging permission, using the same resolved
// caller (including session, boundary and SCP ceilings) as the primary operation.
// caller (including session, boundary and SCP ceilings) as the primary operation, on the
// group the table checks the create on; the evaluator matches TagLogGroup's policies on it
// with or without the trailing :* as it does the create's.
if ("logs:CreateLogGroup".equals(action) && conditionContext != null
&& !conditionContext.getOrDefault("aws:TagKeys", List.of()).isEmpty()) {
String groupResource = resources.getFirst();
String taggingResource = groupResource.substring(0, groupResource.length() - 2);
String taggingResource = resources.getFirst();
Map<String, List<String>> taggingContext = IamConditionContextResolver.withGlobalContext(
conditionContext, taggingResource, region, accountId, accountId);
Map<String, List<String>> groupContext = IamConditionContextResolver.withGlobalContext(
conditionContext, groupResource, region, accountId, accountId);
if (evaluator.evaluate(caller, null, "logs:TagResource", taggingResource, taggingContext) == Decision.DENY
&& evaluator.evaluate(caller, null, "logs:TagLogGroup", groupResource, groupContext) == Decision.DENY) {
&& evaluator.evaluate(caller, null, "logs:TagLogGroup", taggingResource, taggingContext)
== Decision.DENY) {
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}",
akid, "logs:TagResource", taggingResource);
ctx.abortWith(accessDeniedForRequest("logs:TagResource", credentialScope, ctx, taggingResource));
@@ -1801,16 +1801,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
/**
* Logs, Secrets Manager and KMS targets depend on the serving operation and the request's partition; API
* Gateway's path ARNs on the request's partition, which that service mints them in; and the targets of a
* namespace the table of request resources reads on {@code operation}, the one the request is dispatched as (see
* {@link RequestResources}).
* KMS targets depend on the serving operation and the request's partition; API Gateway's path ARNs on the
* request's partition, which that service mints them in; and the targets of a namespace the table of request
* resources reads on {@code operation}, the one the request is dispatched as (see {@link RequestResources}).
*/
private List<String> targetResources(String credentialScope, String action, String operation,
ContainerRequestContext ctx, String region, String accountId) {
if ("logs".equals(credentialScope)) {
return arnBuilder.buildLogResources(action, ctx, region, accountId, requestPartition());
}
if ("kms".equals(credentialScope)) {
return arnBuilder.buildKmsResources(action, ctx, region, accountId, requestPartition());
}
@@ -61,9 +61,11 @@ import java.util.Optional;
* group, a listener, a rule or a Classic Load Balancer; SQS, for the tags of a queue; SNS, for the tags of a topic;
* Kinesis Data Streams, for the tags of a stream or a consumer; EventBridge Pipes, for the tags of a pipe; Aurora DSQL,
* for the tags of a cluster; EKS, for the tags of a cluster, a node group, a Fargate profile, an add-on, a Pod Identity
* association or an access entry; Resource Groups, for the tags of a group); looked up lazily by
* {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for
* the namespace a request or an ARN is of, so IAM never depends on that service directly.</p>
* association or an access entry; Resource Groups, for the tags of a group; CloudWatch Logs, for a delivery, the
* delivery destinations of a delivery source and the tags of a log group, a destination, a delivery source, a
* delivery destination or a delivery); looked up lazily by {@code ResourceArnBuilder} and
* {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for the namespace a request or an
* ARN is of, so IAM never depends on that service directly.</p>
*
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
* {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone
@@ -454,18 +454,34 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {
return LogGroupTagTarget.resolve(resourceArn, region, regionResolver.getAccountId(), regionResolver.getPartition());
}
/**
* Gives the group a new map holding its tags and {@code tags}, under the lock creating and deleting a group take,
* so a tag call never puts back a group a delete has removed.
*/
public void tagLogGroup(String groupName, Map<String, String> tags, String region) {
String key = groupKey(region, groupName);
LogGroup group = requireNamedLogGroup(region, groupName);
group.getTags().putAll(tags);
groupStore.put(key, group);
synchronized (metricFilterStore) {
String key = groupKey(region, groupName);
LogGroup group = requireNamedLogGroup(region, groupName);
Map<String, String> merged = new HashMap<>(group.getTags() != null ? group.getTags() : Map.of());
merged.putAll(tags);
group.setTags(merged);
groupStore.put(key, group);
}
}
/**
* Gives the group a new map holding its tags but {@code tagKeys}, under the lock creating and deleting a group
* take, so an untag call never puts back a group a delete has removed.
*/
public void untagLogGroup(String groupName, List<String> tagKeys, String region) {
String key = groupKey(region, groupName);
LogGroup group = requireNamedLogGroup(region, groupName);
tagKeys.forEach(group.getTags()::remove);
groupStore.put(key, group);
synchronized (metricFilterStore) {
String key = groupKey(region, groupName);
LogGroup group = requireNamedLogGroup(region, groupName);
Map<String, String> remaining = new HashMap<>(group.getTags() != null ? group.getTags() : Map.of());
tagKeys.forEach(remaining::remove);
group.setTags(remaining);
groupStore.put(key, group);
}
}
/**
@@ -499,6 +515,18 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {
return group.getTags();
}
/**
* The tags of the log group named {@code name} in {@code region} of {@code accountId}, read in place where its tag
* handlers read; none when that account holds no such group. Tag calls give the group a new map one at a time, so
* the read is of one whole set.
*/
Map<String, String> groupTagsInAccount(String accountId, String region, String name) {
return getForAccount(groupStore, accountId, groupKey(region, name))
.filter(stored -> name.equals(stored.getLogGroupName()))
.map(LogGroup::getTags)
.orElse(Map.of());
}
// ──────────────────────────── Log Streams ────────────────────────────
public void createLogStream(String groupName, String streamName, String region) {
@@ -1,31 +1,46 @@
package io.floci.aws.services.cloudwatch.logs;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* What IAM asks CloudWatch Logs of the resources a request names: the caller's delivery of the id it was created
* with, and the delivery destinations the deliveries from a delivery source send to, which the Service Reference
* checks a {@code DeleteDeliverySource} on.
* with, the delivery destinations the deliveries from a delivery source send to, which the Service Reference
* checks a {@code DeleteDeliverySource} on, and the tags of a log group, a destination or a delivery source,
* delivery destination or delivery.
*/
@ApplicationScoped
public class CloudWatchLogsStoredResourceArns implements StoredResourceArns {
private static final String NAMESPACE = "logs";
private static final String LOG_GROUP = "log-group:";
private static final String ALL_STREAMS = ":*";
private final CloudWatchLogsService logs;
private final CloudWatchLogsCrossAccountService destinations;
private final CloudWatchLogsDeliveryService deliveries;
private final RegionResolver regionResolver;
@Inject
public CloudWatchLogsStoredResourceArns(CloudWatchLogsDeliveryService deliveries) {
public CloudWatchLogsStoredResourceArns(CloudWatchLogsService logs, CloudWatchLogsCrossAccountService destinations,
CloudWatchLogsDeliveryService deliveries, RegionResolver regionResolver) {
this.logs = logs;
this.destinations = destinations;
this.deliveries = deliveries;
this.regionResolver = regionResolver;
}
@Override
public String namespace() {
return "logs";
return NAMESPACE;
}
/** The ARN of the caller's delivery of the id {@code names} gives, as the service stored it; empty for none. */
@@ -46,4 +61,45 @@ public class CloudWatchLogsStoredResourceArns implements StoredResourceArns {
public List<String> through(String member, String value, String region) {
return "name".equals(member) ? deliveries.destinationArnsFrom(value, region) : List.of();
}
/**
* The tags of the log group, destination, delivery source, delivery destination or delivery whose ARN is
* {@code arn}, in the request's account, where the tag handlers read: an ARN of another account names none, and
* neither does a log stream's, Floci holding no tags on a stream. A log group is read in place by the name its ARN
* gives, a trailing {@code :*} dropped as its tag handlers drop it, in the ARN's Region. A resource Floci does not
* hold has none; any other failure of the lookup is thrown, so it cannot pass for a resource without tags. A tag
* without a value reads as an empty one.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, NAMESPACE)) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String account = regionResolver.getAccountId();
String region = parsed.region();
if (!parsed.accountId().equals(account) || region.isBlank()) {
return Map.of();
}
String resource = parsed.resource();
if (resource.startsWith(LOG_GROUP)) {
String name = resource.substring(LOG_GROUP.length());
name = name.endsWith(ALL_STREAMS) ? name.substring(0, name.length() - ALL_STREAMS.length()) : name;
return name.isEmpty() || name.indexOf(':') >= 0 ? Map.of()
: StoredResourceArns.withEmptyValues(logs.groupTagsInAccount(account, region, name));
}
try {
if (CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn(arn)) {
return StoredResourceArns.withEmptyValues(destinations.listDestinationTags(arn, region));
}
if (deliveries.isDeliveryArn(arn, region)) {
return StoredResourceArns.withEmptyValues(deliveries.listTags(arn, region));
}
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
}
return Map.of();
}
}
@@ -16,7 +16,7 @@ public class LogGroup {
private Integer retentionInDays;
private boolean deletionProtectionEnabled;
private String kmsKeyId;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
public LogGroup() {}
@@ -12,9 +12,6 @@ import io.floci.aws.core.common.ServicePrincipals;
import io.floci.aws.core.common.SigV4CredentialScope;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.common.auth.SigV4Canonicalization;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService;
import io.floci.aws.services.cloudwatch.logs.LogGroupTagTarget;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.s3.S3ControlArnUtils;
import io.floci.aws.services.s3.S3ObjectKeys;
@@ -218,43 +215,6 @@ public class ResourceArnBuilder {
return null;
}
/** Uses the serving operation and the same raw names as the handler. */
public List<String> buildLogResources(String action, ContainerRequestContext ctx,
String region, String accountId, String partition) {
// Operations the vendored table reads take their resources from it.
if (RequestResources.reads(action)) {
return namedResources("logs", action, ctx, region, accountId, partition);
}
boolean stream = "logs:CreateLogStream".equals(action) || "logs:DeleteLogStream".equals(action);
boolean group = switch (action) {
case "logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy",
"logs:DeleteRetentionPolicy" -> true;
default -> false;
};
if (!stream && !group && !LogGroupTagTarget.supports(action)) {
return List.of("*");
}
JsonNode body = readJsonBody(ctx);
if (body == null) {
return List.of("*");
}
if (LogGroupTagTarget.supports(action)) {
String resourceArn = body.path("resourceArn").asText();
// A delivery source, destination or delivery is tagged through the same operations.
if (CloudWatchLogsDeliveryService.isDeliveryResourceArn(resourceArn)) {
return List.of(resourceArn);
}
if (CloudWatchLogsCrossAccountService.isCrossAccountDestinationArn(resourceArn)) {
return List.of(resourceArn);
}
return List.of(LogGroupTagTarget.resolve(resourceArn, region, accountId, partition).arn());
}
String name = body.path("logGroupName").asText();
String resource = "log-group:" + name + (stream
? ":log-stream:" + body.path("logStreamName").asText() : ":*");
return List.of(new AwsArnUtils.Arn(partition, "logs", region, accountId, resource).toString());
}
// ── IAM ─────────────────────────────────────────────────────────────────────
/** A stored entity's ARN and path, the two things a target ARN is built from. */
@@ -1,7 +1,7 @@
{
"_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-20", "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"], "cloudformation": ["cloudcontrol", "cloudformation"], "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"], "dsql": ["dsql"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-containers": ["emr-containers"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "glue": ["glue"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "pipes": ["pipes"], "quicksight": ["quicksight"], "ram": ["ram"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "resource-groups": ["resource-groups"], "route53": ["route53"], "s3tables": ["s3tables"], "s3vectors": ["s3vectors"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sns": ["sns"], "sqs": ["sqs"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "sts": ["sts"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
"handBuilt": ["apigateway", "bedrock", "dynamodb", "iam", "kms", "logs", "s3"],
"handBuilt": ["apigateway", "bedrock", "dynamodb", "iam", "kms", "s3"],
"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", "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 name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST rLine truncated
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "apiportal", "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", "bcm-data-hub", "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", "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", "osm", "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}"}, "cloudformation": {"changeset": "arn:${Partition}:cloudformation:${Region}:${Account}:changeSet/${ChangeSetName}/${Id}", "generatedtemplate": "arn:${Partition}:cloudformation:${Region}:${Account}:generatedTemplate/${Id}", "resourcescan": "arn:${Partition}:cloudformation:${Region}:${Account}:resourceScan/${Id}", "stack": "arn:${Partition}:cloudformation:${Region}:${Account}:stack/${StackName}/${Id}", "stackset": "arn:${Partition}:cloudformation:${Region}:${Account}:stackset/${StackSetName}:${Id}", "stackset-target": "arn:${Partition}:cloudformation:${Region}:${Account}:stackset-target/${StackSetTarget}", "type": "arn:${Partition}:cloudformation:${Region}:${Account}:type/resource/${Type}", "typeHook": "arn:${Partition}:cloudformation:${Region}:${Account}:type/hook/${Type}"}, "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:$Line truncated
@@ -3319,20 +3319,124 @@
"lambda:UpdateRuntimeVersion": {"action": "lambda:UpdateRuntimeVersion", "types": ["runtimeVersion"], "resources": []},
"lambda:UpdateWebFunctionEndpoint": {"action": "lambda:UpdateWebFunctionEndpoint", "types": ["webFunctionEndpoint"], "resources": [{"type": "webFunctionEndpoint", "fill": {"EndpointName": "endpointName", "FunctionName": "functionName"}, "arnOf": {"functionName": "webFunction"}}], "located": {"endpointName": "{endpointName}", "functionName": "{functionName}"}},
"lambda:UploadFunction": {"action": "lambda:UploadFunction", "types": [], "resources": []},
"logs:AssociateKmsKey": {"action": "logs:AssociateKmsKey", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:AssociateSourceToS3TableIntegration": {"action": "logs:AssociateSourceToS3TableIntegration", "types": [], "resources": []},
"logs:CancelExportTask": {"action": "logs:CancelExportTask", "types": [], "resources": []},
"logs:CancelImportTask": {"action": "logs:CancelImportTask", "types": [], "resources": []},
"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:CreateExportTask": {"action": "logs:CreateExportTask", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:CreateImportTask": {"action": "logs:CreateImportTask", "types": [], "resources": []},
"logs:CreateLogAnomalyDetector": {"action": "logs:CreateLogAnomalyDetector", "types": ["log-group"], "resources": [{"types": ["log-group"], "arn": "logGroupArnList[]"}]},
"logs:CreateLogGroup": {"action": "logs:CreateLogGroup", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:CreateLogStream": {"action": "logs:CreateLogStream", "types": ["log-stream"], "resources": [{"type": "log-stream", "fill": {"LogGroupName": "logGroupName", "LogStreamName": "logStreamName"}}]},
"logs:CreateLookupTable": {"action": "logs:CreateLookupTable", "types": ["lookup-table"], "resources": [{"type": "lookup-table", "fill": {"LookupTableName": "lookupTableName"}}]},
"logs:CreateScheduledQuery": {"action": "logs:CreateScheduledQuery", "types": ["scheduled-query"], "resources": [{"types": ["scheduled-query"], "arn": "executionRoleArn"}, {"type": "scheduled-query", "fill": {}, "find": ["name"]}]},
"logs:DeleteAccountPolicy": {"action": "logs:DeleteAccountPolicy", "types": [], "resources": []},
"logs:DeleteDataProtectionPolicy": {"action": "logs:DeleteDataProtectionPolicy", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"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"}}]},
"logs:DeleteDeliveryDestinationPolicy": {"action": "logs:DeleteDeliveryDestinationPolicy", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "deliveryDestinationName"}}]},
"logs:DeleteDeliverySource": {"action": "logs:DeleteDeliverySource", "types": ["delivery-destination"], "resources": [{"types": ["delivery-destination"], "through": "name"}]},
"logs:DeleteDestination": {"action": "logs:DeleteDestination", "types": ["destination"], "resources": [{"type": "destination", "fill": {"DestinationName": "destinationName"}}]},
"logs:DeleteIndexPolicy": {"action": "logs:DeleteIndexPolicy", "types": [], "resources": []},
"logs:DeleteIntegration": {"action": "logs:DeleteIntegration", "types": [], "resources": []},
"logs:DeleteLogAnomalyDetector": {"action": "logs:DeleteLogAnomalyDetector", "types": ["anomaly-detector"], "resources": [{"types": ["anomaly-detector"], "arn": "anomalyDetectorArn"}]},
"logs:DeleteLogGroup": {"action": "logs:DeleteLogGroup", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DeleteLogStream": {"action": "logs:DeleteLogStream", "types": ["log-stream"], "resources": [{"type": "log-stream", "fill": {"LogGroupName": "logGroupName", "LogStreamName": "logStreamName"}}]},
"logs:DeleteLookupTable": {"action": "logs:DeleteLookupTable", "types": ["lookup-table"], "resources": [{"types": ["lookup-table"], "arn": "lookupTableArn"}]},
"logs:DeleteMetricFilter": {"action": "logs:DeleteMetricFilter", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DeleteQueryDefinition": {"action": "logs:DeleteQueryDefinition", "types": [], "resources": []},
"logs:DeleteResourcePolicy": {"action": "logs:DeleteResourcePolicy", "types": [], "resources": []},
"logs:DeleteRetentionPolicy": {"action": "logs:DeleteRetentionPolicy", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DeleteScheduledQuery": {"action": "logs:DeleteScheduledQuery", "types": ["scheduled-query"], "resources": [{"type": "scheduled-query", "fill": {"ScheduledQueryId": "identifier"}}]},
"logs:DeleteSubscriptionFilter": {"action": "logs:DeleteSubscriptionFilter", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DeleteSyslogConfiguration": {"action": "logs:DeleteSyslogConfiguration", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:DeleteTransformer": {"action": "logs:DeleteTransformer", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:DescribeAccountPolicies": {"action": "logs:DescribeAccountPolicies", "types": [], "resources": []},
"logs:DescribeConfigurationTemplates": {"action": "logs:DescribeConfigurationTemplates", "types": [], "resources": []},
"logs:DescribeDeliveries": {"action": "logs:DescribeDeliveries", "types": [], "resources": []},
"logs:DescribeDeliveryDestinations": {"action": "logs:DescribeDeliveryDestinations", "types": [], "resources": []},
"logs:DescribeDeliverySources": {"action": "logs:DescribeDeliverySources", "types": [], "resources": []},
"logs:DescribeDestinations": {"action": "logs:DescribeDestinations", "types": [], "resources": []},
"logs:DescribeExportTasks": {"action": "logs:DescribeExportTasks", "types": [], "resources": []},
"logs:DescribeFieldIndexes": {"action": "logs:DescribeFieldIndexes", "types": [], "resources": []},
"logs:DescribeImportTaskBatches": {"action": "logs:DescribeImportTaskBatches", "types": [], "resources": []},
"logs:DescribeImportTasks": {"action": "logs:DescribeImportTasks", "types": [], "resources": []},
"logs:DescribeIndexPolicies": {"action": "logs:DescribeIndexPolicies", "types": [], "resources": []},
"logs:DescribeLogGroups": {"action": "logs:DescribeLogGroups", "types": [], "resources": []},
"logs:DescribeLogStreams": {"action": "logs:DescribeLogStreams", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DescribeLookupTables": {"action": "logs:DescribeLookupTables", "types": [], "resources": []},
"logs:DescribeMetricFilters": {"action": "logs:DescribeMetricFilters", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DescribeQueries": {"action": "logs:DescribeQueries", "types": [], "resources": []},
"logs:DescribeQueryDefinitions": {"action": "logs:DescribeQueryDefinitions", "types": [], "resources": []},
"logs:DescribeResourcePolicies": {"action": "logs:DescribeResourcePolicies", "types": [], "resources": []},
"logs:DescribeSubscriptionFilters": {"action": "logs:DescribeSubscriptionFilters", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DisassociateKmsKey": {"action": "logs:DisassociateKmsKey", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:DisassociateSourceFromS3TableIntegration": {"action": "logs:DisassociateSourceFromS3TableIntegration", "types": [], "resources": []},
"logs:FilterLogEvents": {"action": "logs:FilterLogEvents", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:GetDataProtectionPolicy": {"action": "logs:GetDataProtectionPolicy", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:GetDelivery": {"action": "logs:GetDelivery", "types": ["delivery"], "resources": [{"type": "delivery", "fill": {}, "find": ["id"]}]},
"logs:GetDeliveryDestination": {"action": "logs:GetDeliveryDestination", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "name"}}]},
"logs:GetDeliveryDestinationPolicy": {"action": "logs:GetDeliveryDestinationPolicy", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "deliveryDestinationName"}}]},
"logs:GetDeliverySource": {"action": "logs:GetDeliverySource", "types": ["delivery-source"], "resources": [{"type": "delivery-source", "fill": {"DeliverySourceName": "name"}}]},
"logs:GetIntegration": {"action": "logs:GetIntegration", "types": [], "resources": []},
"logs:GetLogAnomalyDetector": {"action": "logs:GetLogAnomalyDetector", "types": ["anomaly-detector"], "resources": [{"types": ["anomaly-detector"], "arn": "anomalyDetectorArn"}]},
"logs:GetLogEvents": {"action": "logs:GetLogEvents", "types": ["log-stream"], "resources": [{"type": "log-stream", "fill": {"LogGroupName": "logGroupName", "LogStreamName": "logStreamName"}, "unless": {"logGroupName": [null]}}]},
"logs:GetLogFields": {"action": "logs:GetLogFields", "types": [], "resources": []},
"logs:GetLogGroupFields": {"action": "logs:GetLogGroupFields", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:GetLogObject": {"action": "logs:GetLogObject", "types": [], "resources": []},
"logs:GetLogRecord": {"action": "logs:GetLogRecord", "types": ["log-group"], "resources": []},
"logs:GetLookupTable": {"action": "logs:GetLookupTable", "types": ["lookup-table"], "resources": [{"types": ["lookup-table"], "arn": "lookupTableArn"}]},
"logs:GetQueryResults": {"action": "logs:GetQueryResults", "types": ["log-group"], "resources": []},
"logs:GetScheduledQuery": {"action": "logs:GetScheduledQuery", "types": ["scheduled-query"], "resources": [{"type": "scheduled-query", "fill": {"ScheduledQueryId": "identifier"}}]},
"logs:GetScheduledQueryHistory": {"action": "logs:GetScheduledQueryHistory", "types": ["scheduled-query"], "resources": [{"type": "scheduled-query", "fill": {"ScheduledQueryId": "identifier"}}]},
"logs:GetStorageTierPolicy": {"action": "logs:GetStorageTierPolicy", "types": [], "resources": []},
"logs:GetTransformer": {"action": "logs:GetTransformer", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:ListAggregateLogGroupSummaries": {"action": "logs:ListAggregateLogGroupSummaries", "types": [], "resources": []},
"logs:ListAnomalies": {"action": "logs:ListAnomalies", "types": ["anomaly-detector"], "resources": [{"types": ["anomaly-detector"], "arn": "anomalyDetectorArn"}, {"type": "anomaly-detector", "fill": {}, "when": {"anomalyDetectorArn": [null]}, "default": true}]},
"logs:ListIntegrations": {"action": "logs:ListIntegrations", "types": [], "resources": []},
"logs:ListLogAnomalyDetectors": {"action": "logs:ListLogAnomalyDetectors", "types": ["anomaly-detector"], "resources": [{"types": ["anomaly-detector"], "arn": "filterLogGroupArn"}]},
"logs:ListLogGroups": {"action": "logs:ListLogGroups", "types": [], "resources": []},
"logs:ListLogGroupsForQuery": {"action": "logs:ListLogGroupsForQuery", "types": [], "resources": []},
"logs:ListScheduledQueries": {"action": "logs:ListScheduledQueries", "types": [], "resources": []},
"logs:ListSourcesForS3TableIntegration": {"action": "logs:ListSourcesForS3TableIntegration", "types": [], "resources": []},
"logs:ListSyslogConfigurations": {"action": "logs:ListSyslogConfigurations", "types": [], "resources": []},
"logs:ListTagsForResource": {"action": "logs:ListTagsForResource", "types": ["anomaly-detector", "delivery", "delivery-destination", "delivery-source", "destination", "log-group", "lookup-table"], "resources": [{"types": ["anomaly-detector", "delivery", "delivery-destination", "delivery-source", "destination", "log-group", "lookup-table"], "arn": "resourceArn"}]},
"logs:ListTagsLogGroup": {"action": "logs:ListTagsLogGroup", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:PutAccountPolicy": {"action": "logs:PutAccountPolicy", "types": [], "resources": []},
"logs:PutBearerTokenAuthentication": {"action": "logs:PutBearerTokenAuthentication", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:PutDataProtectionPolicy": {"action": "logs:PutDataProtectionPolicy", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:PutDeliveryDestination": {"action": "logs:PutDeliveryDestination", "types": ["delivery-destination"], "resources": [{"types": ["delivery-destination"], "arn": "deliveryDestinationConfiguration.destinationResourceArn"}, {"types": ["delivery-destination"], "arn": "roleArn"}, {"type": "delivery-destination", "fill": {"DeliveryDestinationName": "name"}}]},
"logs:PutDeliveryDestinationPolicy": {"action": "logs:PutDeliveryDestinationPolicy", "types": ["delivery-destination"], "resources": [{"type": "delivery-destination", "fill": {"DeliveryDestinationName": "deliveryDestinationName"}}]},
"logs:PutDeliverySource": {"action": "logs:PutDeliverySource", "types": ["delivery-source"], "resources": [{"types": ["delivery-source"], "arn": "resourceArn"}, {"type": "delivery-source", "fill": {"DeliverySourceName": "name"}}]},
"logs:PutDestination": {"action": "logs:PutDestination", "types": ["destination"], "resources": [{"types": ["destination"], "arn": "roleArn"}, {"types": ["destination"], "arn": "targetArn"}, {"type": "destination", "fill": {"DestinationName": "destinationName"}}]},
"logs:PutDestinationPolicy": {"action": "logs:PutDestinationPolicy", "types": ["destination"], "resources": [{"type": "destination", "fill": {"DestinationName": "destinationName"}}]},
"logs:PutIndexPolicy": {"action": "logs:PutIndexPolicy", "types": [], "resources": []},
"logs:PutIntegration": {"action": "logs:PutIntegration", "types": [], "resources": []},
"logs:PutLogEvents": {"action": "logs:PutLogEvents", "types": ["log-stream"], "resources": [{"type": "log-stream", "fill": {"LogGroupName": "logGroupName", "LogStreamName": "logStreamName"}}]},
"logs:PutLogGroupDeletionProtection": {"action": "logs:PutLogGroupDeletionProtection", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:PutMetricFilter": {"action": "logs:PutMetricFilter", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:PutQueryDefinition": {"action": "logs:PutQueryDefinition", "types": [], "resources": []},
"logs:PutResourcePolicy": {"action": "logs:PutResourcePolicy", "types": [], "resources": []},
"logs:PutRetentionPolicy": {"action": "logs:PutRetentionPolicy", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:PutStorageTierPolicy": {"action": "logs:PutStorageTierPolicy", "types": [], "resources": []},
"logs:PutSubscriptionFilter": {"action": "logs:PutSubscriptionFilter", "types": ["destination", "log-group"], "resources": [{"types": ["destination", "log-group"], "arn": "destinationArn"}, {"types": ["destination", "log-group"], "arn": "roleArn"}, {"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:PutSyslogConfiguration": {"action": "logs:PutSyslogConfiguration", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:PutTransformer": {"action": "logs:PutTransformer", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifier"}}]},
"logs:StartLiveTail": {"action": "logs:StartLiveTail", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupIdentifiers[]"}}]},
"logs:StartQuery": {"action": "logs:StartQuery", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:StopQuery": {"action": "logs:StopQuery", "types": [], "resources": []},
"logs:TagLogGroup": {"action": "logs:TagLogGroup", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:TagResource": {"action": "logs:TagResource", "types": ["anomaly-detector", "delivery", "delivery-destination", "delivery-source", "destination", "log-group", "lookup-table", "scheduled-query"], "resources": [{"types": ["anomaly-detector", "delivery", "delivery-destination", "delivery-source", "destination", "log-group", "lookup-table", "scheduled-query"], "arn": "resourceArn"}]},
"logs:TestMetricFilter": {"action": "logs:TestMetricFilter", "types": [], "resources": []},
"logs:TestTransformer": {"action": "logs:TestTransformer", "types": [], "resources": []},
"logs:UntagLogGroup": {"action": "logs:UntagLogGroup", "types": ["log-group"], "resources": [{"type": "log-group", "fill": {"LogGroupName": "logGroupName"}}]},
"logs:UntagResource": {"action": "logs:UntagResource", "types": ["anomaly-detector", "delivery", "delivery-destination", "delivery-source", "destination", "log-group", "lookup-table", "scheduled-query"], "resources": [{"types": ["anomaly-detector", "delivery", "delivery-destination", "delivery-source", "destination", "log-group", "lookup-table", "scheduled-query"], "arn": "resourceArn"}]},
"logs:UpdateAnomaly": {"action": "logs:UpdateAnomaly", "types": ["anomaly-detector"], "resources": [{"types": ["anomaly-detector"], "arn": "anomalyDetectorArn"}, {"types": ["anomaly-detector"], "through": "anomalyId"}]},
"logs:UpdateDeliveryConfiguration": {"action": "logs:UpdateDeliveryConfiguration", "types": ["delivery", "delivery-destination", "delivery-source"], "resources": [{"type": "delivery", "fill": {}, "find": ["id"]}]},
"logs:UpdateLogAnomalyDetector": {"action": "logs:UpdateLogAnomalyDetector", "types": ["anomaly-detector"], "resources": [{"types": ["anomaly-detector"], "arn": "anomalyDetectorArn"}]},
"logs:UpdateLookupTable": {"action": "logs:UpdateLookupTable", "types": ["lookup-table"], "resources": [{"types": ["lookup-table"], "arn": "lookupTableArn"}]},
"logs:UpdateScheduledQuery": {"action": "logs:UpdateScheduledQuery", "types": ["scheduled-query"], "resources": [{"types": ["scheduled-query"], "arn": "executionRoleArn"}, {"type": "scheduled-query", "fill": {"ScheduledQueryId": "identifier"}}]},
"macie2:AcceptInvitation": {"action": "macie2:AcceptInvitation", "types": [], "resources": []},
"macie2:BatchGetCustomDataIdentifiers": {"action": "macie2:BatchGetCustomDataIdentifiers", "types": ["CustomDataIdentifier"], "resources": [{"type": "CustomDataIdentifier", "fill": {"ResourceId": "ids[]"}}]},
"macie2:BatchUpdateAutomatedDiscoveryAccounts": {"action": "macie2:BatchUpdateAutomatedDiscoveryAccounts", "types": [], "resources": []},
@@ -3,8 +3,6 @@ package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
import io.floci.aws.services.dynamodb.DynamoDbFacade;
import io.floci.aws.services.dynamodb.DynamoDbService;
import io.floci.aws.services.dynamodb.backend.NativeDynamoDbBackend;
@@ -61,7 +59,6 @@ import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -77,8 +74,6 @@ class IamConditionContextResolverTest {
private Instance<DynamoDbFacade> dynamoDbFacadeInstance;
private Ec2Service ec2Service;
private S3Service s3Service;
private CloudWatchLogsService logsService;
private CloudWatchLogsCrossAccountService crossAccountService;
private IamService iamService;
private LambdaWebService lambdaWebService;
private RequestContext requestContext;
@@ -123,14 +118,6 @@ class IamConditionContextResolverTest {
Instance<S3Service> s3ServiceInstance = mock(Instance.class);
when(s3ServiceInstance.isResolvable()).thenReturn(true);
when(s3ServiceInstance.get()).thenReturn(s3Service);
logsService = mock(CloudWatchLogsService.class);
Instance<CloudWatchLogsService> logsServiceInstance = mock(Instance.class);
when(logsServiceInstance.isResolvable()).thenReturn(true);
when(logsServiceInstance.get()).thenReturn(logsService);
crossAccountService = mock(CloudWatchLogsCrossAccountService.class);
Instance<CloudWatchLogsCrossAccountService> crossAccountServiceInstance = mock(Instance.class);
when(crossAccountServiceInstance.isResolvable()).thenReturn(true);
when(crossAccountServiceInstance.get()).thenReturn(crossAccountService);
iamService = mock(IamService.class);
Instance<IamService> iamServiceInstance = mock(Instance.class);
when(iamServiceInstance.isResolvable()).thenReturn(true);
@@ -152,8 +139,7 @@ class IamConditionContextResolverTest {
ServiceCatalog catalog = new ServiceCatalog(List.of(dynamo));
when(serviceCatalog.matchTarget(any())).thenAnswer(call -> catalog.matchTarget(call.getArgument(0)));
resolver = new IamConditionContextResolver(
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance,
crossAccountServiceInstance, iamServiceInstance,
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, iamServiceInstance,
lambdaWebServiceInstance, spellings(new ShapeNamingSpelling()), mock(Instance.class),
requestContext, new RegionResolver("us-east-1", "123456789012"), config,
null, serviceCatalog);
@@ -247,43 +233,26 @@ class IamConditionContextResolverTest {
assertNull(resolver.resolve("sts", "sts:GetCallerIdentity", formRequest("Action=GetCallerIdentity")));
}
/** A Logs create or tag call carries the tags it asks to attach or remove; what it names carries its own. */
@Test
void logStreamTagsUseRawParentNameAndRequestRegion() throws Exception {
void aLogsTagCallCarriesTheTagsItAsksToAttachOrRemove() throws Exception {
ContainerRequestContext request = mock(ContainerRequestContext.class);
String group = "\"resourceArn\":\"arn:aws:logs:us-east-1:123456789012:log-group:app\"";
when(request.getProperty("floci.bufferedJsonBody"))
.thenReturn(mapper.readTree("{\"logGroupName\":\" group \",\"logStreamName\":42}"));
when(logsService.listTagsLogGroup(" group ", "eu-west-1")).thenReturn(Map.of("team", "blue"));
requestContext.setRegion("eu-west-1");
for (String action : List.of("logs:CreateLogStream", "logs:DeleteLogStream")) {
assertEquals(Map.of("aws:ResourceTag/team", List.of("blue")), resolver.resolve("logs", action, request));
}
requestContext.setRegion(null);
when(logsService.listTagsLogGroup(" group ", "us-east-1")).thenReturn(Map.of("team", "red"));
assertEquals(Map.of("aws:ResourceTag/team", List.of("red")),
resolver.resolve("logs", "logs:CreateLogStream", request));
}
@Test
void missingLogGroupTagsDoNotReplaceTheHandlersMissingResourceError() throws Exception {
ContainerRequestContext request = mock(ContainerRequestContext.class);
when(request.getProperty("floci.bufferedJsonBody")).thenReturn(mapper.readTree("{\"logGroupName\":42}"));
when(logsService.listTagsLogGroup("42", "us-east-1"))
.thenThrow(new AwsException("ResourceNotFoundException", "missing", 400));
assertNull(resolver.resolve("logs", "logs:DeleteLogStream", request));
}
@Test
void unexpectedLogGroupLookupFailuresCannotEraseTagDenies() throws Exception {
ContainerRequestContext request = mock(ContainerRequestContext.class);
when(request.getProperty("floci.bufferedJsonBody")).thenReturn(mapper.readTree("{\"logGroupName\":\"group\"}"));
AwsException failure = new AwsException("InternalFailure", "storage unavailable", 500);
when(logsService.listTagsLogGroup("group", "us-east-1")).thenThrow(failure);
assertSame(failure, assertThrows(AwsException.class,
() -> resolver.resolve("logs", "logs:CreateLogStream", request)));
IllegalStateException unexpected = new IllegalStateException("unavailable");
doThrow(unexpected).when(logsService).listTagsLogGroup("group", "us-east-1");
assertSame(unexpected, assertThrows(IllegalStateException.class,
() -> resolver.resolve("logs", "logs:DeleteLogStream", request)));
.thenReturn(mapper.readTree("{" + group + ",\"tags\":{\"team\":\"blue\"}}"));
assertEquals(Map.of("aws:RequestTag/team", List.of("blue"), "aws:TagKeys", List.of("team")),
resolver.resolve("logs", "logs:TagResource", request));
when(request.getProperty("floci.bufferedJsonBody"))
.thenReturn(mapper.readTree("{" + group + ",\"tagKeys\":[\"team\"]}"));
assertEquals(Map.of("aws:TagKeys", List.of("team")), resolver.resolve("logs", "logs:UntagResource", request));
when(request.getProperty("floci.bufferedJsonBody"))
.thenReturn(mapper.readTree("{\"logGroupName\":\"app\",\"tags\":{\"team\":\"red\"}}"));
assertEquals(Map.of("aws:RequestTag/team", List.of("red"), "aws:TagKeys", List.of("team")),
resolver.resolve("logs", "logs:CreateLogGroup", request));
when(request.getProperty("floci.bufferedJsonBody"))
.thenReturn(mapper.readTree("{\"logGroupName\":\"app\",\"logStreamName\":\"s\"}"));
assertNull(resolver.resolve("logs", "logs:CreateLogGroup", request));
assertNull(resolver.resolve("logs", "logs:CreateLogStream", request));
}
/** A form request whose body can be read again, as a real request's restored stream can. */
@@ -866,7 +835,7 @@ class IamConditionContextResolverTest {
@SuppressWarnings("unchecked")
private IamConditionContextResolver resolverAt(Instant now) {
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class),
spellings(), mock(Instance.class), requestContext, new RegionResolver("us-east-1", "123456789012"),
config, null,
serviceCatalog, Clock.fixed(now, ZoneOffset.UTC));
@@ -878,7 +847,7 @@ class IamConditionContextResolverTest {
Instance<StoredResourceArns> instance = mock(Instance.class);
when(instance.iterator()).thenAnswer(invocation -> List.of(stored).iterator());
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class),
spellings(), instance, requestContext, new RegionResolver("us-east-1", "123456789012"), config,
null, serviceCatalog, Clock.systemUTC());
}
@@ -18,7 +18,6 @@ import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -164,21 +163,14 @@ class RequestResourceMembersTest {
assertTrue(table.namespaces().containsAll(List.of("cognito-idp", "ecr", "elasticloadbalancing", "states")));
assertTrue(table.namespaces().contains("lambda"));
assertFalse(table.handBuilt().contains("lambda"));
assertEquals(Set.of("dynamodb", "logs"), table.namespaces().stream().filter(table.handBuilt()::contains)
assertFalse(table.handBuilt().contains("logs"));
assertEquals(Set.of("dynamodb"), table.namespaces().stream().filter(table.handBuilt()::contains)
.collect(Collectors.toSet()));
Set<String> logsDelivery = Stream.of("PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource",
"DescribeDeliverySources", "PutDeliveryDestination", "GetDeliveryDestination",
"DeleteDeliveryDestination", "DescribeDeliveryDestinations", "CreateDelivery", "GetDelivery",
"UpdateDeliveryConfiguration", "DeleteDelivery", "DescribeDeliveries")
.map(operation -> "logs:" + operation).collect(Collectors.toSet());
Set<String> expected = new HashSet<>(logsDelivery);
expected.add("logs:PutDestination");
// 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()
assertEquals(Set.of("dynamodb:ListTables"), table.operations().keySet().stream()
.filter(operation -> table.handBuilt().contains(operation.substring(0, operation.indexOf(':'))))
.collect(Collectors.toSet()),
"only the operations listed to read override hand-built operations");
"only what MEASURED gives is read in a hand-built namespace");
assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains));
assertTrue(table.operations().containsKey("rds:CreateDBParameterGroup"));
assertTrue(table.operations().containsKey("rds:CreateDBProxy"));
@@ -152,7 +152,7 @@ class DynamoDbFacadeTest {
RequestContext requestContext = new RequestContext();
requestContext.setRegion(OTHER_REGION);
IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb,
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), requestContext,
new RegionResolver(OTHER_REGION, "000000000000"),
@@ -123,11 +123,18 @@ class LogsArnTagAuthorizationIntegrationTest {
assertTags(local, expectedTags(action));
}
/**
* A plain name where AWS takes an ARN names nothing the generated table reads, so the call is checked on
* {@code *}; the handler still reads it as the literal name of a historical group.
*/
@ParameterizedTest
@ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"})
void incompleteArnPrefixRemainsALiteralLegacyName(String action) {
String name = historicalGroupNamed("arn:archive-" + UUID.randomUUID(), Map.of("team", "blue"));
String caller = user(statement("Allow", "logs:" + action, arn(name)));
String scoped = user(statement("Allow", "logs:" + action, arn(name)));
invoke(scoped, action, name).statusCode(400).body(containsString("AccessDeniedException"));
assertTags(name, Map.of("team", "blue"));
String caller = user(statement("Allow", "logs:" + action, "*"));
assertSuccess(invoke(caller, action, name), action);
assertTags(name, expectedTags(action));
}
@@ -69,49 +69,20 @@ class LogsStreamAuthorizationIntegrationTest {
assertPresent(group, "selected", action.equals("CreateLogStream"));
}
/**
* A stream carries no resource tags: Floci holds none on a stream, and nothing AWS publishes gives a stream its
* group's, so a condition on the group's tags matches no stream call.
*/
@ParameterizedTest
@ValueSource(strings = {"CreateLogStream", "DeleteLogStream"})
void groupTagDenyPreventsMutationEvenWithWildcardAllow(String action) {
String group = group(Map.of("protected", "true"));
void aStreamCallCarriesNoTagsOfItsGroup(String action) {
String group = group(Map.of("team", "blue"));
prepare(action, group, "selected");
String caller = user(policy("Allow", action, "*", "") + ","
+ policy("Deny", action, "*",
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/protected\":\"true\"}}"));
String caller = user(policy("Allow", action, "*",
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}"));
stream(caller, action, group, "selected").statusCode(400)
.body(containsString("AccessDeniedException"));
assertPresent(group, "selected", action.equals("DeleteLogStream"));
if (action.equals("DeleteLogStream")) {
assertEvent(group, "selected");
}
for (Map<String, String> tags : List.of(Map.of("protected", "false"), Map.<String, String>of())) {
String allowed = group(tags);
prepare(action, allowed, "selected");
stream(caller, action, allowed, "selected").statusCode(200);
assertPresent(allowed, "selected", action.equals("CreateLogStream"));
}
}
@ParameterizedTest
@ValueSource(strings = {"CreateLogStream", "DeleteLogStream"})
void resourceTagAllowReadsTheOwningGroup(String action) {
String group = group(Map.of("team", "blue"));
String other = group(Map.of("team", "red"));
String untagged = group(Map.of());
prepare(action, group, "selected");
prepare(action, other, "selected");
prepare(action, untagged, "selected");
String caller = user(policy("Allow", action, "*",
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}"));
stream(caller, action, other, "selected").statusCode(400)
.body(containsString("AccessDeniedException"));
assertPresent(other, "selected", action.equals("DeleteLogStream"));
stream(caller, action, untagged, "selected").statusCode(400)
.body(containsString("AccessDeniedException"));
assertPresent(untagged, "selected", action.equals("DeleteLogStream"));
stream(caller, action, group, "selected").statusCode(200);
assertPresent(group, "selected", action.equals("CreateLogStream"));
}
@ParameterizedTest
@@ -144,36 +115,72 @@ class LogsStreamAuthorizationIntegrationTest {
assertPresent(group, "42", action.equals("DeleteLogStream"));
}
/** A group call reads the tags of the group of its name in the request's own account and Region. */
@ParameterizedTest
@ValueSource(strings = {"CreateLogStream", "DeleteLogStream"})
@ValueSource(strings = {"PutRetentionPolicy", "DescribeLogStreams"})
void sameNamedGroupsKeepTheirAccountAndRegionTags(String action) {
String group = "logs-stream-scope-" + UUID.randomUUID();
String group = "logs-group-scope-" + UUID.randomUUID();
String otherAccount = "222222222222";
String otherRegion = "eu-west-1";
createGroup(ACCOUNT, REGION, group, Map.of("team", "blue"));
createGroup(ACCOUNT, otherRegion, group, Map.of("team", "red"));
createGroup(otherAccount, REGION, group, Map.of("team", "red"));
if (action.equals("DeleteLogStream")) {
for (String[] scope : List.of(new String[]{ACCOUNT, REGION}, new String[]{ACCOUNT, otherRegion},
new String[]{otherAccount, REGION})) {
call(endpoint.getPort(), scope[0], scope[1], "CreateLogStream",
Map.of("logGroupName", group, "logStreamName", "selected")).statusCode(200);
}
}
Map<String, ?> body = action.equals("PutRetentionPolicy")
? Map.of("logGroupName", group, "retentionInDays", 7) : Map.of("logGroupName", group);
String statements = policy("Allow", action, "*",
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}");
String caller = user(statements);
String otherCaller = user(otherAccount, statements);
call(endpoint.getPort(), caller, otherRegion, action,
Map.of("logGroupName", group, "logStreamName", "selected"))
call(endpoint.getPort(), caller, otherRegion, action, body)
.statusCode(400).body(containsString("AccessDeniedException"));
call(endpoint.getPort(), otherCaller, REGION, action,
Map.of("logGroupName", group, "logStreamName", "selected"))
call(endpoint.getPort(), otherCaller, REGION, action, body)
.statusCode(400).body(containsString("AccessDeniedException"));
assertPresent(ACCOUNT, otherRegion, group, "selected", action.equals("DeleteLogStream"));
assertPresent(otherAccount, REGION, group, "selected", action.equals("DeleteLogStream"));
stream(caller, action, group, "selected").statusCode(200);
assertPresent(group, "selected", action.equals("CreateLogStream"));
call(endpoint.getPort(), caller, REGION, action, body).statusCode(200);
}
/** Writing and reading a stream's events is checked on the stream the request names, as the table reads it. */
@ParameterizedTest
@ValueSource(strings = {"PutLogEvents", "GetLogEvents"})
void aStreamsEventsAreCheckedOnTheStreamTheRequestNames(String action) {
String group = group(Map.of());
for (String name : List.of("selected", "other")) {
stream(ACCOUNT, "CreateLogStream", group, name).statusCode(200);
}
String caller = user(policy("Allow", action, streamArn(group, "selected"), ""));
call(endpoint.getPort(), caller, action, events(action, group, "other"))
.statusCode(400).body(containsString("AccessDeniedException"));
call(endpoint.getPort(), caller, action, events(action, group, "selected")).statusCode(200);
}
/** A call on a log group is checked on the group the request names, as the table reads it, not on {@code *}. */
@ParameterizedTest
@ValueSource(strings = {"FilterLogEvents", "DescribeLogStreams", "PutMetricFilter", "PutSubscriptionFilter"})
void aGroupCallIsCheckedOnTheGroupTheRequestNames(String action) {
String group = group(Map.of());
String other = group(Map.of());
String caller = user(policy("Allow", action,
"arn:aws:logs:" + REGION + ":" + ACCOUNT + ":log-group:" + group, ""));
call(endpoint.getPort(), caller, action, groupCall(action, other))
.statusCode(400).body(containsString("AccessDeniedException"));
call(endpoint.getPort(), caller, action, groupCall(action, group)).statusCode(200);
}
private static Map<String, ?> events(String action, String group, String stream) {
return action.equals("PutLogEvents")
? Map.of("logGroupName", group, "logStreamName", stream, "logEvents",
List.of(Map.of("timestamp", System.currentTimeMillis(), "message", "written")))
: Map.of("logGroupName", group, "logStreamName", stream);
}
private static Map<String, ?> groupCall(String action, String group) {
return switch (action) {
case "PutMetricFilter" -> Map.of("logGroupName", group, "filterName", "errors", "filterPattern", "ERROR",
"metricTransformations", List.of(Map.of("metricName", "Errors", "metricNamespace", "App",
"metricValue", "1")));
case "PutSubscriptionFilter" -> Map.of("logGroupName", group, "filterName", "ship", "filterPattern", "",
"destinationArn", "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:ship");
default -> Map.of("logGroupName", group);
};
}
@ParameterizedTest
@@ -198,8 +205,7 @@ class LogsStreamAuthorizationIntegrationTest {
}
}
String resource = "arn:aws:logs:" + region + ":" + ACCOUNT + ":log-group:" + group + ":log-stream:selected";
String caller = user(policy("Allow", action, resource,
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}"));
String caller = user(policy("Allow", action, resource, ""));
given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1")
.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
.queryParam("X-Amz-Credential", caller + "/20261015/" + region + "/logs/aws4_request")
@@ -241,8 +247,7 @@ class LogsStreamAuthorizationIntegrationTest {
}
String resource = "arn:aws:logs:" + selectedRegion + ":" + account
+ ":log-group:" + group + ":log-stream:selected";
String caller = user(account, policy("Allow", action, resource,
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}"));
String caller = user(account, policy("Allow", action, resource, ""));
RequestSpecification request = given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1")
.queryParam("X-Amz-Credential", caller + "/20261015/" + remote + "/logs/aws4_request")
.queryParam("X-Amz-Signature", "abc")
@@ -266,8 +271,7 @@ class LogsStreamAuthorizationIntegrationTest {
seedHistoricalStream(protectedGroup, "s");
assertPresent(protectedGroup, "s", true);
assertEvent(protectedGroup, "s");
String caller = user(policy("Allow", "DeleteLogStream", exactGrant ? streamArn(group, "x::s") : "*",
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}"));
String caller = user(policy("Allow", "DeleteLogStream", exactGrant ? streamArn(group, "x::s") : "*", ""));
Response response = stream(caller, "DeleteLogStream", group, "x::s").extract().response();
assertAll("reject storage alias and retain historical stream and event",
() -> response.then().statusCode(400).body(containsString("InvalidParameterException")),
@@ -81,9 +81,8 @@ class LogsUnknownRegionAuthorizationIntegrationTest {
}
@ParameterizedTest
@CsvSource({"CreateLogStream,false,false", "DeleteLogStream,false,false", "CreateLogStream,true,false",
"DeleteLogStream,true,false", "DeleteLogStream,false,true"})
void optedInRegionLabelsCannotAliasHistoricalGroupNames(String action, boolean conditional, boolean streamAlias) {
@CsvSource({"CreateLogStream,false", "DeleteLogStream,false", "DeleteLogStream,true"})
void optedInRegionLabelsCannotAliasHistoricalGroupNames(String action, boolean streamAlias) {
int port = endpoint.getPort();
String group = "logs-region-alias-" + UUID.randomUUID();
String historical = streamAlias ? group : "x::" + group;
@@ -106,13 +105,12 @@ class LogsUnknownRegionAuthorizationIntegrationTest {
}
}
assertPresent(port, REGION, historical, historicalStream, delete);
String condition = conditional ? ",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}" : "";
String resources = "[\"arn:aws:logs:" + aliasRegion + ":" + ACCOUNT + ":log-group:" + group
+ ":log-stream:s\",\"arn:aws:logs:" + validUnknownRegion + ":" + ACCOUNT
+ ":log-group:" + group + ":log-stream:s\"]";
String caller = LogsAuthorizationFixtures.user(cleanup, port, ACCOUNT, "logs-region-alias-", "streams",
"{\"Effect\":\"Allow\",\"Action\":\"logs:" + action
+ "\",\"Resource\":" + resources + condition + "}");
+ "\",\"Resource\":" + resources + "}");
Response response = call(port, caller, aliasRegion, action,
Map.of("logGroupName", group, "logStreamName", "s"));
assertAll("preserve stored identity across an opted-in region delimiter",
@@ -906,54 +906,66 @@ class ResourceArnBuilderTest {
"us-east-1", ACCOUNT, "aws"));
}
/** A stream call is checked on the stream its group and stream names name, read raw, in the request's partition. */
@Test
void logStreamTargetsUseTheServingActionAndRequestPartition() {
for (String action : List.of("logs:CreateLogStream", "logs:DeleteLogStream")) {
void logStreamTargetsAreTheStreamTheRequestNamesFromTheTable() {
for (String action : List.of("logs:CreateLogStream", "logs:DeleteLogStream", "logs:PutLogEvents")) {
for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) {
String partition = AwsRegions.partitionFor(region);
setJsonBody("{\"logGroupName\":\" /group \",\"logStreamName\":42}");
when(ctx.getHeaderString("X-Amz-Target")).thenReturn("Logs_20140328.DeleteLogGroup");
assertEquals(List.of("arn:" + AwsRegions.partitionFor(region)
+ ":logs:" + region + ":123456789012:log-group: /group :log-stream:42"),
builder.buildLogResources(action, ctx, region, "123456789012", AwsRegions.partitionFor(region)));
assertEquals(List.of("arn:" + partition + ":logs:" + region + ":" + ACCOUNT
+ ":log-group: /group :log-stream:42"),
builder.buildResources("logs", action, ctx, region, ACCOUNT, partition));
}
}
}
/**
* A group call is checked on the group its name names, as the Service Reference formats a log group, with no
* trailing {@code :*}; the evaluator matches a policy naming the group with one for the group's own management
* actions ({@code LogGroupArnPolicyCompatibilityTest}).
*/
@Test
void logGroupTargetsUseTheServingActionAndRequestPartition() {
void logGroupTargetsAreTheGroupTheRequestNamesFromTheTable() {
for (String action : List.of("logs:CreateLogGroup", "logs:DeleteLogGroup", "logs:PutRetentionPolicy",
"logs:DeleteRetentionPolicy")) {
"logs:DeleteRetentionPolicy", "logs:TagLogGroup", "logs:FilterLogEvents", "logs:DescribeLogStreams",
"logs:PutMetricFilter", "logs:StartQuery")) {
for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) {
String partition = AwsRegions.partitionFor(region);
setJsonBody("{\"logGroupName\":42}");
when(ctx.getHeaderString("X-Amz-Target")).thenReturn("Logs_20140328.DeleteLogStream");
assertEquals(List.of("arn:" + AwsRegions.partitionFor(region)
+ ":logs:" + region + ":123456789012:log-group:42:*"),
builder.buildLogResources(action, ctx, region, "123456789012", AwsRegions.partitionFor(region)));
assertEquals(List.of("arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":log-group:42"),
builder.buildResources("logs", action, ctx, region, ACCOUNT, partition));
}
}
// A request naming no group names nothing the table reads.
setJsonBody("{}");
assertEquals(List.of("*"), builder.buildResources("logs", "logs:FilterLogEvents", ctx, "us-east-1", ACCOUNT,
"aws"));
}
/** A subscription filter is checked on its group, and on its destination when that is a Logs destination. */
@Test
void subscriptionFilterTargetsAreItsGroupAndALogsDestination() {
String prefix = "arn:aws:logs:us-east-1:" + ACCOUNT + ":";
setJsonBody("{\"logGroupName\":\"app\",\"destinationArn\":\"arn:aws:lambda:us-east-1:" + ACCOUNT
+ ":function:ship\"}");
assertEquals(List.of(prefix + "log-group:app"),
builder.buildResources("logs", "logs:PutSubscriptionFilter", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"logGroupName\":\"app\",\"destinationArn\":\"" + prefix + "destination:central\"}");
assertEquals(List.of(prefix + "destination:central", prefix + "log-group:app"),
builder.buildResources("logs", "logs:PutSubscriptionFilter", ctx, "us-east-1", ACCOUNT, "aws"));
}
@Test
void directLogTagTargetsUseBareArnAndServingAction() {
void logTagTargetsAreTheArnTheRequestCarries() {
for (String action : List.of("logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource")) {
for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1", "custom-region-1")) {
String partition = AwsRegions.partitionFor(region);
String arn = "arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":log-group:group";
setJsonBody("{\"resourceArn\":\"" + arn + "\"}");
when(ctx.getHeaderString("X-Amz-Target")).thenReturn("Logs_20140328.DeleteLogGroup");
assertEquals(List.of(arn), builder.buildLogResources(action, ctx, region, ACCOUNT, partition));
}
}
}
@Test
void destinationTagTargetsUseDestinationArn() {
for (String action : List.of("logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource")) {
for (String region : List.of("us-east-1", "cn-north-1", "us-gov-west-1")) {
String partition = AwsRegions.partitionFor(region);
String arn = "arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":destination:central";
setJsonBody("{\"resourceArn\":\"" + arn + "\"}");
assertEquals(List.of(arn), builder.buildLogResources(action, ctx, region, ACCOUNT, partition));
for (String resource : List.of("log-group:group", "destination:central")) {
String arn = "arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":" + resource;
setJsonBody("{\"resourceArn\":\"" + arn + "\"}");
assertEquals(List.of(arn), builder.buildResources("logs", action, ctx, region, ACCOUNT, partition));
}
}
}
}
@@ -963,15 +975,16 @@ class ResourceArnBuilderTest {
void putDestinationTargetsTheDestinationItNames(String partition, String region) {
setJsonBody("{\"destinationName\":\"central\"}");
assertEquals(List.of("arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":destination:central"),
builder.buildLogResources("logs:PutDestination", ctx, region, ACCOUNT, partition));
builder.buildResources("logs", "logs:PutDestination", ctx, region, ACCOUNT, partition));
String targetArn = "arn:" + partition + ":kinesis:" + region + ":" + ACCOUNT + ":stream/central";
String roleArn = "arn:" + partition + ":iam::" + ACCOUNT + ":role/logs-delivery";
setJsonBody("{\"destinationName\":\"central\",\"targetArn\":\"" + targetArn
+ "\",\"roleArn\":\"" + roleArn + "\"}");
assertEquals(List.of("arn:" + partition + ":logs:" + region + ":" + ACCOUNT + ":destination:central"),
builder.buildLogResources("logs:PutDestination", ctx, region, ACCOUNT, partition));
builder.buildResources("logs", "logs:PutDestination", ctx, region, ACCOUNT, partition));
setJsonBody("{}");
assertEquals(List.of("*"), builder.buildLogResources("logs:PutDestination", ctx, region, ACCOUNT, partition));
assertEquals(List.of("*"),
builder.buildResources("logs", "logs:PutDestination", ctx, region, ACCOUNT, partition));
}
@Test
@@ -987,51 +1000,43 @@ class ResourceArnBuilderTest {
.thenThrow(new AwsException("ResourceNotFoundException", "Delivery not found", 400));
when(deliveries.destinationArnsFrom("bus-source", "us-east-1"))
.thenReturn(List.of(prefix + "delivery-destination:bus-logs"));
ResourceArnBuilder builder = reading(new CloudWatchLogsStoredResourceArns(deliveries));
ResourceArnBuilder builder = reading(new CloudWatchLogsStoredResourceArns(null, null, deliveries, null));
for (String action : List.of("logs:PutDeliverySource", "logs:GetDeliverySource")) {
setJsonBody("{\"name\":\"bus-source\"}");
assertEquals(List.of(prefix + "delivery-source:bus-source"),
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
builder.buildResources("logs", action, ctx, "us-east-1", ACCOUNT, "aws"));
}
setJsonBody("{\"name\":\"bus-source\"}");
assertEquals(List.of(prefix + "delivery-destination:bus-logs"),
builder.buildLogResources("logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT, "aws"));
builder.buildResources("logs", "logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT, "aws"));
// A source with no deliveries reaches no destination, so the request names none of its resource type.
setJsonBody("{\"name\":\"idle-source\"}");
assertEquals(List.of("*"), builder.buildLogResources("logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT,
"aws"));
assertEquals(List.of("*"),
builder.buildResources("logs", "logs:DeleteDeliverySource", ctx, "us-east-1", ACCOUNT, "aws"));
for (String action : List.of("logs:PutDeliveryDestination", "logs:GetDeliveryDestination",
"logs:DeleteDeliveryDestination")) {
setJsonBody("{\"name\":\"bus-logs\"}");
assertEquals(List.of(prefix + "delivery-destination:bus-logs"),
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
builder.buildResources("logs", action, ctx, "us-east-1", ACCOUNT, "aws"));
}
for (String action : List.of("logs:GetDelivery", "logs:DeleteDelivery", "logs:UpdateDeliveryConfiguration")) {
setJsonBody("{\"id\":\"AbCdEfGh12345678\"}");
assertEquals(List.of(prefix + "delivery:AbCdEfGh12345678"),
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
builder.buildResources("logs", action, ctx, "us-east-1", ACCOUNT, "aws"));
// One it holds none of has its id open.
setJsonBody("{\"id\":\"gone\"}");
assertEquals(List.of(prefix + "delivery:*"),
builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
builder.buildResources("logs", action, ctx, "us-east-1", ACCOUNT, "aws"));
}
setJsonBody("{\"deliverySourceName\":\"bus-source\",\"deliveryDestinationArn\":\""
+ prefix + "delivery-destination:bus-logs\"}");
assertEquals(List.of(prefix + "delivery-destination:bus-logs", prefix + "delivery:*",
prefix + "delivery-source:bus-source"),
builder.buildLogResources("logs:CreateDelivery", ctx, "us-east-1", ACCOUNT, "aws"));
builder.buildResources("logs", "logs:CreateDelivery", ctx, "us-east-1", ACCOUNT, "aws"));
for (String action : List.of("logs:DescribeDeliverySources", "logs:DescribeDeliveryDestinations",
"logs:DescribeDeliveries")) {
setJsonBody("{}");
assertEquals(List.of("*"), builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
}
}
@Test
void excludedLogsActionsKeepWildcardResources() {
for (String action : List.of("logs:PutLogEvents")) {
setJsonBody("{\"logGroupName\":\"group\",\"logStreamName\":\"stream\"}");
assertEquals(List.of("*"), builder.buildLogResources(action, ctx, "us-east-1", ACCOUNT, "aws"));
assertEquals(List.of("*"), builder.buildResources("logs", action, ctx, "us-east-1", ACCOUNT, "aws"));
}
}
+10 -36
View File
@@ -96,10 +96,8 @@ of its own name with that action's resource types when the reference has that ac
the reference lists one client's operations per namespace, and
OpenSearch Service's are the `es` client's alone, while the `opensearch` client's are named after `es` actions.
Every operation in `NAMESPACES` is read, whether Floci serves it or not. In a namespace in `HAND_BUILT`, whose
other operations keep their existing resource builders, so are the operations `READ_IN_HAND_BUILT` lists, which
follow the rule unchanged: a family of a hand-built namespace whose requests name their resources the
way the rule reads them. `HAND_BUILT` are the namespaces `ResourceArnBuilder` builds resources for itself, and
Every operation in `NAMESPACES` is read, whether Floci serves it or not. `HAND_BUILT` are the namespaces
`ResourceArnBuilder` builds resources for itself, whose operations are read only where `MEASURED` gives them, and
`NOT_COVERED` the ones Floci serves that are not read yet, each with its reason;
`RequestResourceNamespacesIntegrationTest` fails for a served namespace in none of the three.
`ID_TARGETS` is Floci's coverage of id-list namespaces, the types of each it reads by id (EC2's instances and
@@ -298,24 +296,10 @@ NAMESPACES = ("access-analyzer", "account", "acm", "application-autoscaling", "a
"rekognition", "resource-explorer-2", "route53", "s3tables", "s3vectors", "servicediscovery",
"servicequotas", "ssm", "sso", "states", "textract", "timestream-influxdb", "translate", "signer", "xray",
"securityhub", "guardduty", "secretsmanager", "scheduler", "lambda", "cloudformation", "glue",
"sqs", "sns", "kinesis", "pipes", "dsql", "sts", "eks", "resource-groups")
"sqs", "sns", "kinesis", "pipes", "dsql", "sts", "eks", "resource-groups", "logs")
# The namespaces whose resources ResourceArnBuilder builds itself.
HAND_BUILT = ("apigateway", "bedrock", "dynamodb", "iam", "kms", "logs", "s3")
# Operations of a namespace in `HAND_BUILT` read from the reference all the same, each with its reason.
_LOGS_DELIVERY = ("CloudWatch Logs vended-log delivery: its requests name a delivery source, destination or delivery "
"by the member the rule reads, while ResourceArnBuilder keeps building the log group and stream ARNs")
READ_IN_HAND_BUILT: dict[str, str] = {
f"logs:{operation}": _LOGS_DELIVERY
for operation in ("PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource", "DescribeDeliverySources",
"PutDeliveryDestination", "GetDeliveryDestination", "DeleteDeliveryDestination",
"DescribeDeliveryDestinations", "CreateDelivery", "GetDelivery", "UpdateDeliveryConfiguration",
"DeleteDelivery", "DescribeDeliveries")
}
READ_IN_HAND_BUILT["logs:PutDestination"] = (
"CloudWatch Logs destination creation names the destination by destinationName, which ResourceArnBuilder "
"reads from the generated request-resource table")
HAND_BUILT = ("apigateway", "bedrock", "dynamodb", "iam", "kms", "s3")
# ---------------------------------------------------------------------------------------------------------------------
# MEASURED: what AWS was measured to check where neither botocore nor the Service Reference says it.
@@ -3471,24 +3455,15 @@ def _with_resource_types(documents: list[dict]) -> set[str]:
def reads(operation: str) -> bool:
"""Read whole namespaces, and in a namespace otherwise built by hand the operations `READ_IN_HAND_BUILT` lists
and those `MEASURED` gives."""
"""Read whole namespaces, and in a namespace otherwise built by hand the operations `MEASURED` gives."""
namespace = namespace_of(operation)
return namespace in NAMESPACES or namespace in HAND_BUILT and (operation in READ_IN_HAND_BUILT
or operation in MEASURED)
return namespace in NAMESPACES or namespace in HAND_BUILT and operation in MEASURED
def _check_overrides(covered: dict[str, dict]) -> None:
"""Every operation `READ_IN_HAND_BUILT` lists or `MEASURED` gives is one the file reads, and no namespace is in
two places."""
stale = [f"READ_IN_HAND_BUILT names {operation}, which the reference does not give" for operation in READ_IN_HAND_BUILT
if operation not in covered]
stale += [f"MEASURED gives {operation}, which the file does not read" for operation in MEASURED
if operation not in covered]
stale += [f"MEASURED gives {operation}, which READ_IN_HAND_BUILT reads by the rules" for operation in MEASURED
if operation in READ_IN_HAND_BUILT]
stale += [f"READ_IN_HAND_BUILT names {operation}, outside HAND_BUILT" for operation in READ_IN_HAND_BUILT
if namespace_of(operation) not in HAND_BUILT]
"""Every operation `MEASURED` gives is one the file reads, and no namespace is in two places."""
stale = [f"MEASURED gives {operation}, which the file does not read" for operation in MEASURED
if operation not in covered]
for left, right in (("NAMESPACES", "HAND_BUILT"), ("NAMESPACES", "NOT_COVERED"), ("HAND_BUILT", "NOT_COVERED")):
stale += [f"{namespace} is in both {left} and {right}"
for namespace in sorted(set(globals()[left]) & set(globals()[right]))]
@@ -3952,8 +3927,7 @@ def verify_against(vendored: dict, upstream: dict[str, dict], formats: dict[str,
untrue.append(f"AWS no longer gives {namespace}'s {', '.join(changed)} the ARN format the file does")
added = sorted(operation for operation in upstream
if namespace_of(operation) in vendored["namespaces"]
and (namespace_of(operation) not in vendored["handBuilt"] or operation in READ_IN_HAND_BUILT
or operation in MEASURED)
and (namespace_of(operation) not in vendored["handBuilt"] or operation in MEASURED)
and operation not in vendored["operations"])
return untrue, added
@@ -370,7 +370,6 @@ def isolated(monkeypatch):
monkeypatch.setattr(r, "NAMESPACES", ("svc",))
monkeypatch.setattr(r, "HAND_BUILT", ("hand",))
monkeypatch.setattr(r, "NOT_COVERED", {"later": "a later batch"})
monkeypatch.setattr(r, "READ_IN_HAND_BUILT", {})
monkeypatch.setattr(r, "MEASURED", {})
monkeypatch.setattr(r, "STATEMENT_SOURCES", {})
return monkeypatch
@@ -1141,28 +1140,6 @@ def test_the_vendored_file_is_well_formed():
"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}}
def test_hand_built_operations_listed_to_read_follow_the_rule(isolated, tmp_path):
isolated.setattr(r, "READ_IN_HAND_BUILT", {"hand:GetThing": "a family the rule reads"})
documents = DOCUMENTS + [reference("hand", {"GetThing": ["thing"], "PutThing": ["thing"]},
{"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"})]
hand = model({"GetThing": {"ThingName": "String"}, "PutThing": {"ThingName": "String"}})
hand["metadata"]["endpointPrefix"] = "hand"
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}), "hand": hand})
document = r.build(documents, "test", tmp_path, "botocore test")
assert document["operations"]["hand:GetThing"] == {
"action": "hand:GetThing", "types": ["thing"], "resources": [{"type": "thing", "fill": {"ThingName": "ThingName"}}]}
assert "hand:PutThing" not in document["operations"]
assert r.reads("hand:GetThing") and not r.reads("hand:PutThing")
assert r.validate(document) == []
def test_operations_listed_to_read_must_exist_and_be_hand_built(isolated, tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
isolated.setattr(r, "READ_IN_HAND_BUILT", {"hand:Gone": "no longer there"})
with pytest.raises(ValueError, match="READ_IN_HAND_BUILT names hand:Gone, which the reference does not give"):
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
MEASURED_FORMATS = {"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"}
PROBED = "real AWS probes in https://example.com/probes accept an allow and enforce a deny on thing/*"