From 215e37eb484e9da43f66330a29cb94d338f31777 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:10:24 -0400 Subject: [PATCH] fix(cloudtrail): name S3 denials as CloudTrail records the operation's data event (#9460) IamEnforcementFilter named the CloudTrail data event of a denied S3 request from a hand-written table keyed by the IAM action, so a request checked under another operation's action took that operation's name: HeadBucket was recorded as ListObjects, CopyObject, UploadPart and UploadPartCopy as PutObject, GetObjectTorrent as GetObject, ListBuckets as a data event, and ListObjectVersions, ListParts, DeleteObjects, AbortMultipartUpload and the legal hold and retention calls were not recorded. A denial is now recorded under the data event of the operation the request matched, from src/main/resources/aws/cloudtrail-s3-data-events.json, which tools/aws/regen_cloudtrail_s3_data_events.py generates from botocore's S3 model, the S3 user guide's data events table and its sentence naming the event a call is recorded with (vendored by tools/aws/fetch_cloudtrail_s3_data_events.py), and AWS's S3 service reference. An operation the table for general purpose buckets lists is recorded under its name or the one the guide gives it (PutObjectRetention as PutObjectLockRetention), a versioned one under the version-less name the table lists (ListObjectsV2 as ListObjects), and an operation it does not list records no data event. readOnly is the service reference's, by the reading iam-action-resources.json's readOnlyActions are vendored by, in place of CloudTrailService's hand-written list. The IAM data drift workflow runs on a pull request touching any of the six new files, so the online check covers a change to the table alone. --- .github/workflows/iam-data-drift.yml | 6 + Makefile | 38 +++- docs/services/cloudtrail.md | 29 ++- .../aws/core/common/IamEnforcementFilter.java | 82 ++----- .../cloudtrail/CloudTrailService.java | 15 +- .../aws/services/cloudtrail/S3DataEvents.java | 76 +++++++ .../aws/cloudtrail-s3-data-events.json | 148 ++++++++++++ .../core/common/IamEnforcementFilterTest.java | 57 +++-- .../common/IamEnforcementFilterUnitTest.java | 131 +---------- .../CloudTrailSelectorMatchingTest.java | 10 +- .../services/cloudtrail/S3DataEventsTest.java | 58 +++++ tools/aws/fetch_cloudtrail_s3_data_events.py | 136 +++++++++++ tools/aws/regen_cloudtrail_s3_data_events.py | 214 ++++++++++++++++++ .../sources/cloudtrail-s3-data-events.json | 142 ++++++++++++ .../test_fetch_cloudtrail_s3_data_events.py | 58 +++++ tools/aws/test_iam_data_verify.py | 9 +- .../test_regen_cloudtrail_s3_data_events.py | 106 +++++++++ 17 files changed, 1078 insertions(+), 237 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/cloudtrail/S3DataEvents.java create mode 100644 src/main/resources/aws/cloudtrail-s3-data-events.json create mode 100644 src/test/java/io/floci/aws/services/cloudtrail/S3DataEventsTest.java create mode 100644 tools/aws/fetch_cloudtrail_s3_data_events.py create mode 100644 tools/aws/regen_cloudtrail_s3_data_events.py create mode 100644 tools/aws/sources/cloudtrail-s3-data-events.json create mode 100644 tools/aws/test_fetch_cloudtrail_s3_data_events.py create mode 100644 tools/aws/test_regen_cloudtrail_s3_data_events.py diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index dd8a1162c2..6addc42d20 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -76,6 +76,12 @@ on: - 'src/main/resources/aws/rest-routes.json' - 'tools/aws/regen_rest_routes.py' - 'tools/aws/test_regen_rest_routes.py' + - 'src/main/resources/aws/cloudtrail-s3-data-events.json' + - 'tools/aws/sources/cloudtrail-s3-data-events.json' + - 'tools/aws/fetch_cloudtrail_s3_data_events.py' + - 'tools/aws/test_fetch_cloudtrail_s3_data_events.py' + - 'tools/aws/regen_cloudtrail_s3_data_events.py' + - 'tools/aws/test_regen_cloudtrail_s3_data_events.py' - 'tools/aws/regen_partitions.py' - 'tools/aws/regen_query_services.py' - '.github/workflows/iam-data-drift.yml' diff --git a/Makefile b/Makefile index 99a0304a93..a093c85db5 100644 --- a/Makefile +++ b/Makefile @@ -65,6 +65,10 @@ # src/main/resources/aws/iam-cloudtrail-shapes.json, how a CloudTrail record names and types an IAM # call's members and errors, is generated from botocore's IAM model by # tools/aws/regen_iam_cloudtrail_shapes.py. +# src/main/resources/aws/cloudtrail-s3-data-events.json, the name CloudTrail records each S3 data event +# under and whether it is read-only, is generated from botocore's S3 model, the S3 user guide's data +# events table, which tools/aws/fetch_cloudtrail_s3_data_events.py vendors, and AWS's S3 service +# reference by tools/aws/regen_cloudtrail_s3_data_events.py (make cloudtrail-s3-data-events-sync). PYTHON ?= python3 @@ -108,7 +112,8 @@ PREFIX ?= $(HOME)/.local iam-passed-network-connectors-check iam-passed-network-connectors-verify \ iam-passed-network-connectors-test iam-tag-on-create-sync iam-tag-on-create-check \ iam-tag-on-create-verify iam-tag-on-create-test iam-request-resources-sync iam-request-resources-check \ - iam-request-resources-verify iam-request-resources-test iam-data-verify + iam-request-resources-verify iam-request-resources-test iam-data-verify \ + cloudtrail-s3-data-events-sync cloudtrail-s3-data-events-check cloudtrail-s3-data-events-verify help: ## List the targets below @grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}' @@ -537,6 +542,7 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo " Run 'make aws-data-sync' and commit the result."; \ exit 1; \ } + @$(MAKE) --no-print-directory cloudtrail-s3-data-events-check @$(MAKE) --no-print-directory iam-passed-roles-check @$(MAKE) --no-print-directory iam-passed-network-connectors-check @$(MAKE) --no-print-directory iam-tag-on-create-check @@ -649,12 +655,16 @@ IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json tools/aws/sources/iam-identifiers.json tools/aws/fetch_iam_identifiers.py tools/aws/test_fetch_iam_identifiers.py \ tools/aws/sources/required-resource-types.json tools/aws/fetch_required_resource_types.py \ tools/aws/test_fetch_required_resource_types.py +CLOUDTRAIL_S3_DATA_EVENTS_PATHS := src/main/resources/aws/cloudtrail-s3-data-events.json \ + tools/aws/sources/cloudtrail-s3-data-events.json tools/aws/fetch_cloudtrail_s3_data_events.py \ + tools/aws/test_fetch_cloudtrail_s3_data_events.py tools/aws/regen_cloudtrail_s3_data_events.py \ + tools/aws/test_regen_cloudtrail_s3_data_events.py iam-data-verify: ## CI gate (online): every vendored IAM file must still match AWS; CHANGED="" checks only the ones they cover @# Every check runs even when an earlier one fails, so one file's drift cannot hide another's @# state. Sequential steps in CI stop at the first failure, which once left the action @# resource gate unexercised while the namespace list was stale. - @namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; conditionkeys=0; s3control=0; requestkeys=0; routes=0; \ + @namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; conditionkeys=0; s3control=0; requestkeys=0; routes=0; cloudtrail=0; \ changed="$(strip $(CHANGED))"; \ if [ -n "$(CHANGED_FILE)" ]; then changed=$$(cat "$(CHANGED_FILE)") || exit 1; fi; \ covers() { \ @@ -699,9 +709,13 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A if covers "$(DOCUMENTED_ROUTES_PATHS)" "the REST routes AWS documents for endpoints botocore does not model"; then \ $(MAKE) --no-print-directory documented-routes-verify || routes=$$?; \ fi; \ + if covers "$(CLOUDTRAIL_S3_DATA_EVENTS_PATHS)" "the names CloudTrail records S3 data events under"; then \ + $(MAKE) --no-print-directory cloudtrail-s3-data-events-verify || cloudtrail=$$?; \ + fi; \ if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ] \ || [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ] || [ $$dynamodb -ne 0 ] \ - || [ $$conditionkeys -ne 0 ] || [ $$s3control -ne 0 ] || [ $$requestkeys -ne 0 ] || [ $$routes -ne 0 ]; then \ + || [ $$conditionkeys -ne 0 ] || [ $$s3control -ne 0 ] || [ $$requestkeys -ne 0 ] || [ $$routes -ne 0 ] \ + || [ $$cloudtrail -ne 0 ]; then \ echo ""; \ echo "error: vendored IAM data does not match upstream:"; \ if [ $$namespaces -ne 0 ]; then \ @@ -730,6 +744,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A if [ $$s3control -ne 0 ]; then echo " the S3 Control tag condition key table"; fi; \ if [ $$requestkeys -ne 0 ]; then echo " the request condition key table"; fi; \ if [ $$routes -ne 0 ]; then echo " the REST routes AWS documents, see its message above"; fi; \ + if [ $$cloudtrail -ne 0 ]; then echo " the names CloudTrail records S3 data events under, see its message above"; fi; \ exit 1; \ fi @@ -975,3 +990,20 @@ documented-routes-sync: ## Read the REST routes AWS documents for endpoints boto $(PYTHON) tools/aws/regen_rest_routes.py --fetch-documented documented-routes-verify: ## CI gate (online): the vendored documented REST routes must still be the ones AWS's pages give $(PYTHON) tools/aws/regen_rest_routes.py --verify + +cloudtrail-s3-data-events-sync: ## Regenerate src/main/resources/aws/cloudtrail-s3-data-events.json (online; commit the result) + $(PYTHON) tools/aws/regen_cloudtrail_s3_data_events.py + +cloudtrail-s3-data-events-check: ## CI gate (offline): the vendored S3 data event names must be botocore's and the vendored page's + @$(PYTHON) tools/aws/regen_cloudtrail_s3_data_events.py --check || { \ + echo ""; \ + echo "error: src/main/resources/aws/cloudtrail-s3-data-events.json is out of date."; \ + echo " Run 'make cloudtrail-s3-data-events-sync' and commit the result."; \ + exit 1; \ + } + +cloudtrail-s3-data-events-verify: ## CI gate (online): the S3 data event names and read-only flags must still be what AWS gives + @status=0; \ + $(PYTHON) tools/aws/fetch_cloudtrail_s3_data_events.py --verify || status=1; \ + $(PYTHON) tools/aws/regen_cloudtrail_s3_data_events.py --verify || status=1; \ + exit $$status diff --git a/docs/services/cloudtrail.md b/docs/services/cloudtrail.md index fe0170cd79..3655392e4c 100644 --- a/docs/services/cloudtrail.md +++ b/docs/services/cloudtrail.md @@ -78,17 +78,24 @@ Both success and `AwsException` paths emit; the latter populates `errorCode` / `errorMessage` (`NoSuchKey`, `NoSuchBucketPolicy`, etc.). If `floci.services.iam.enforcement-enabled` is set, IAM-deny responses also -emit records with `errorCode: "AccessDenied"`, named after the operation that -was refused. Besides the ops above, that covers the object ACL and tagging -operations, `PutObjectRetention`, `GetObjectAttributes`, and the `POST` -operations `CreateMultipartUpload`, `CompleteMultipartUpload`, `RestoreObject` -and `SelectObjectContent`. A `POST` is named from the request's -sub-resource, since `CreateMultipartUpload` and `CompleteMultipartUpload` are -both checked as `s3:PutObject` and `SelectObjectContent` as `s3:GetObject`. A request -refused for a permission it needs besides its own, such as -`s3:PutObjectTagging` for an upload that sets tags, is recorded as the -operation. A browser `POST` upload, whose credential is in its form fields, is -recorded as `PostObject` when IAM refuses it. +emit records with `errorCode: "AccessDenied"`, for every operation CloudTrail +records as a data event on an object of a general purpose bucket, named as +CloudTrail names it and marked `readOnly` as it does. The operations, their +names and their flags come from `src/main/resources/aws/cloudtrail-s3-data-events.json`, +which `make cloudtrail-s3-data-events-sync` generates from botocore's S3 model, +the S3 user guide's [data events table](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cloudtrail-logging-s3-info.html) +(vendored by `tools/aws/fetch_cloudtrail_s3_data_events.py`) and AWS's S3 service +reference. A request is named after the operation it matched, so `HeadBucket`, +`CopyObject`, `UploadPart` and `CreateMultipartUpload` are recorded as themselves +although they are checked as `s3:ListBucket` or `s3:PutObject`. `ListObjectsV2` +is recorded as `ListObjects`, the only name the guide lists for a general +purpose bucket, and `PutObjectRetention` as `PutObjectLockRetention`, as the +guide says. A request refused for a permission it needs besides its own, such +as `s3:PutObjectTagging` for an upload that sets tags, is recorded as the +operation. An operation CloudTrail records as a management event, such as +`ListBuckets` or `GetBucketPolicy`, is not recorded as a data event. A browser +`POST` upload, whose credential is in its form fields, is recorded as +`PostObject` when IAM refuses it. ## IAM Coverage diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 54e033a5b0..c20c97f632 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RequestOperationResolver.ResolvedOperation; import io.floci.aws.services.cloudtrail.CloudTrailService; +import io.floci.aws.services.cloudtrail.S3DataEvents; import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsController; import io.floci.aws.services.iam.AccessDeniedMessages; import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType; @@ -118,6 +119,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { /** AWS's wording for a signature that does not follow its format. */ private static final String INCOMPLETE_SIGNATURE = "The request signature does not conform to AWS standards."; + // The operation the request was matched to ("s3:ListObjectsV2"), which names the CloudTrail event of a denial. + static final String RESOLVED_OPERATION_PROPERTY = "floci.iam.resolvedOperation"; /** The IAM User Guide's "Troubleshoot SigV4" wording for an empty header. */ private static final String EMPTY_AUTHORIZATION = "Authorization header cannot be empty."; @@ -405,6 +408,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { // alias would resolve to no action and be allowed through without any policy check. String claimedScope = catalog.canonicalCredentialScope(rawScope); ResolvedOperation resolvedOperation = operationResolver.resolve(auth, claimedScope, ctx, resourceInfo); + ctx.setProperty(RESOLVED_OPERATION_PROPERTY, resolvedOperation.operation()); String credentialScope = resolvedOperation.credentialScope(); String action = resolvedOperation.action(); if (IamActionRegistry.takenByDocumentedRoute(credentialScope, ctx)) { @@ -1283,8 +1287,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { ? refusalMessage(caller, caller.principalArn(), akid, accountId, resourceOwnerAccountId, action, resource, resourcePolicyDecision, effectiveContext) : null; - emitS3DenialIfApplicable(akid, operationAction, resource, ctx, region, - s3Message != null ? s3Message : accessDeniedMessage(action)); + if (s3Request) { + emitS3DenialIfApplicable(akid, resource, ctx, region, s3Message); + } abortIamAware(ctx, s3Message != null ? s3XmlAccessDenied(s3Message, formatS3ResourcePath(resource)) : accessDeniedForRequest(action, credentialScope, ctx, resource), @@ -1730,25 +1735,24 @@ public class IamEnforcementFilter implements ContainerRequestFilter { /** * Best-effort CloudTrail emission for S3 access denials. Without this hook, * denied requests get aborted before {@code S3Controller}'s try/catch sees - * them, so denials would never appear in CloudTrail logs — leaving a major - * gap vs. real AWS for downstream audit ingestion. Failures here never - * propagate (the deny response is the load-bearing behavior). + * them, so denials would never appear in CloudTrail logs, leaving a major + * gap vs. real AWS for downstream audit ingestion. A denial is recorded under the data event the + * request's matched operation is recorded as ({@link S3DataEvents}), and not at all for an operation + * CloudTrail records no data event for. Failures here never propagate (the deny response is the + * load-bearing behavior). */ - private void emitS3DenialIfApplicable(String akid, String action, String resource, - ContainerRequestContext ctx, String region, + private void emitS3DenialIfApplicable(String akid, String resource, ContainerRequestContext ctx, String region, String denyMessage) { + String operation = ctx.getProperty(RESOLVED_OPERATION_PROPERTY) instanceof String resolved ? resolved : null; try { - if (action == null || !action.startsWith("s3:")) { + if (operation == null || !operation.startsWith("s3:")) { return; } - String eventName = mapS3ActionToEventName(action, ctx.getMethod(), - ctx.getUriInfo().getQueryParameters().keySet()); - if (eventName != null) { - emitS3Denial(akid, eventName, resource, region, denyMessage); - } + S3DataEvents.forOperation(operation.substring("s3:".length())) + .ifPresent(event -> emitS3Denial(akid, event.name(), resource, region, denyMessage)); } catch (RuntimeException e) { // The request is refused either way; a record that could not be written is logged, not raised. - LOG.warnv(e, "CloudTrail denial emission failed for {0} on {1}", action, resource); + LOG.warnv(e, "CloudTrail denial emission failed for {0} on {1}", operation, resource); } } @@ -1814,56 +1818,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } } - // Package-private for unit testing. - static String mapS3ActionToEventName(String action, String httpMethod, Set queryParameters) { - if (action == null) return null; - // Action set sourced from IamActionRegistry — see that file for any - // additions. HEAD on an object is bucketed under s3:GetObject by the - // registry, so we distinguish via httpMethod. The GetObjectAttributes actions - // are the operation its own check refuses. - if ("POST".equalsIgnoreCase(httpMethod)) { - return postObjectEventName(action, queryParameters); - } - return switch (action) { - case "s3:GetObject", "s3:GetObjectVersion" -> - "HEAD".equalsIgnoreCase(httpMethod) ? "HeadObject" : "GetObject"; - case "s3:PutObject" -> "PutObject"; - case "s3:PutObjectRetention" -> "PutObjectRetention"; - case "s3:GetObjectAttributes", "s3:GetObjectVersionAttributes" -> "GetObjectAttributes"; - case "s3:DeleteObject", "s3:DeleteObjectVersion" -> "DeleteObject"; - case "s3:ListBucket" -> "ListObjects"; - case "s3:ListAllMyBuckets" -> "ListBuckets"; - case "s3:GetObjectAcl", "s3:GetObjectVersionAcl" -> "GetObjectAcl"; - case "s3:PutObjectAcl", "s3:PutObjectVersionAcl" -> "PutObjectAcl"; - case "s3:GetObjectTagging", "s3:GetObjectVersionTagging" -> "GetObjectTagging"; - case "s3:PutObjectTagging", "s3:PutObjectVersionTagging" -> "PutObjectTagging"; - case "s3:DeleteObjectTagging", "s3:DeleteObjectVersionTagging" -> "DeleteObjectTagging"; - default -> null; - }; - } - - /** - * The operation a denied POST on an object names. Its action alone is not enough: CreateMultipartUpload - * and CompleteMultipartUpload are both checked as {@code s3:PutObject}, and SelectObjectContent as - * {@code s3:GetObject}. The sub-resource that chose the action in {@code IamActionRegistry} names the - * operation, and {@code ?uploads}, which S3Controller runs ahead of an {@code uploadId}, makes a - * request naming both a create. A POST naming none gets no name rather than a wrong one. - */ - private static String postObjectEventName(String action, Set queryParameters) { - return switch (action) { - case "s3:PutObject" -> { - if (queryParameters.contains("uploads")) { - yield "CreateMultipartUpload"; - } - yield queryParameters.contains("uploadId") ? "CompleteMultipartUpload" : null; - } - case "s3:RestoreObject" -> queryParameters.contains("restore") ? "RestoreObject" : null; - case "s3:GetObject", "s3:GetObjectVersion" -> - queryParameters.contains("select") ? "SelectObjectContent" : null; - default -> null; - }; - } - /** * The targets of a request, which the table of request resources reads on {@code operation}, the one the request * is dispatched as, for a namespace it reads (see {@link RequestResources}). diff --git a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java index 3e41af5ace..c55ecf968f 100644 --- a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java @@ -1061,16 +1061,13 @@ public class CloudTrailService implements StoredResourceArns, Resettable { return key.startsWith(configKeyPart); } - // Package-private for unit testing. A read-only event is one that doesn't change a resource, so - // SelectObjectContent is one although it is sent as a POST. + /** + * Whether CloudTrail records the S3 data event of the name read-only, as {@link S3DataEvents} gives it: one whose + * operation changes nothing, so SelectObjectContent is one although it is sent as a POST. Package-private for unit + * testing. + */ static boolean isReadOnlyEvent(String eventName) { - if (eventName == null) return true; - return switch (eventName) { - case "GetObject", "HeadObject", "ListObjects", "ListObjectsV2", - "GetObjectAcl", "GetObjectTagging", "GetObjectAttributes", "ListMultipartUploads", - "GetObjectAnnotation", "ListObjectAnnotations", "SelectObjectContent" -> true; - default -> false; - }; + return eventName == null || S3DataEvents.isReadOnly(eventName); } /** diff --git a/src/main/java/io/floci/aws/services/cloudtrail/S3DataEvents.java b/src/main/java/io/floci/aws/services/cloudtrail/S3DataEvents.java new file mode 100644 index 0000000000..db673b9333 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudtrail/S3DataEvents.java @@ -0,0 +1,76 @@ +package io.floci.aws.services.cloudtrail; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.VendoredResources; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * The S3 operations CloudTrail records as data events, read once from the vendored + * {@code aws/cloudtrail-s3-data-events.json}: for each, the name its event is recorded under and whether it is + * recorded read-only. + * + *

The file is generated by {@code tools/aws/regen_cloudtrail_s3_data_events.py} from botocore's S3 model, the S3 + * user guide's data events table for objects in general purpose buckets, which + * {@code tools/aws/fetch_cloudtrail_s3_data_events.py} vendors, and AWS's S3 service reference. An operation is recorded + * under its own name, the one the guide gives its call ({@code PutObjectRetention} as + * {@code PutObjectLockRetention}), or the version-less one the guide lists for it ({@code ListObjectsV2} as + * {@code ListObjects}), and is read-only when none of the actions it is authorized with changes anything. An + * operation the file does not list is not a data event. {@code make aws-data-check} fails when it is stale. + * + *

A missing or malformed resource is a build defect, not a runtime condition, so loading fails with + * {@link IllegalStateException}. + */ +public final class S3DataEvents { + + static final String RESOURCE_NAME = "aws/cloudtrail-s3-data-events.json"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** The name CloudTrail records an S3 operation's data event under, and whether it records it read-only. */ + public record Event(String name, boolean readOnly) { + } + + private static final class Holder { + static final S3DataEvents EVENTS = VendoredResources.read(RESOURCE_NAME, "CloudTrail S3 data events", + in -> new S3DataEvents(MAPPER.readTree(in))); + } + + private final Map byOperation = new HashMap<>(); + private final Map readOnlyByName = new HashMap<>(); + + S3DataEvents(JsonNode file) { + JsonNode events = file.path("dataEvents"); + if (!events.isObject() || events.isEmpty()) { + throw new IllegalStateException(RESOURCE_NAME + " carries no dataEvents"); + } + events.properties().forEach(entry -> { + JsonNode name = entry.getValue().path("eventName"); + JsonNode readOnly = entry.getValue().path("readOnly"); + if (!name.isTextual() || !readOnly.isBoolean()) { + throw new IllegalStateException(RESOURCE_NAME + " gives " + entry.getKey() + + " no eventName or no readOnly flag"); + } + Event event = new Event(name.asText(), readOnly.asBoolean()); + byOperation.put(entry.getKey(), event); + Boolean recorded = readOnlyByName.putIfAbsent(event.name(), event.readOnly()); + if (recorded != null && recorded != event.readOnly()) { + throw new IllegalStateException(RESOURCE_NAME + " records " + event.name() + + " both read-only and not"); + } + }); + } + + /** The data event CloudTrail records the S3 operation as; empty for one it does not record as a data event. */ + public static Optional forOperation(String operation) { + return operation == null ? Optional.empty() : Optional.ofNullable(Holder.EVENTS.byOperation.get(operation)); + } + + /** Whether CloudTrail records the S3 data event of the name read-only; false for a name the file does not list. */ + public static boolean isReadOnly(String eventName) { + return Holder.EVENTS.readOnlyByName.getOrDefault(eventName, false); + } +} diff --git a/src/main/resources/aws/cloudtrail-s3-data-events.json b/src/main/resources/aws/cloudtrail-s3-data-events.json new file mode 100644 index 0000000000..8ff8011876 --- /dev/null +++ b/src/main/resources/aws/cloudtrail-s3-data-events.json @@ -0,0 +1,148 @@ +{ + "_source": { + "botocore": "botocore 1.44.9 (installed package)", + "page": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/cloudtrail-logging-s3-info.html", + "reference": "https://servicereference.us-east-1.amazonaws.com/v1/s3/s3.json", + "generator": "tools/aws/regen_cloudtrail_s3_data_events.py", + "note": "Each S3 operation CloudTrail records as a data event on an AWS::S3::Object, with the event name it is recorded under and whether it is recorded read-only. `unmodeled` lists the APIs the guide names that botocore models no operation for." + }, + "dataEvents": { + "AbortMultipartUpload": { + "eventName": "AbortMultipartUpload", + "readOnly": false + }, + "CompleteMultipartUpload": { + "eventName": "CompleteMultipartUpload", + "readOnly": false + }, + "CopyObject": { + "eventName": "CopyObject", + "readOnly": false + }, + "CreateMultipartUpload": { + "eventName": "CreateMultipartUpload", + "readOnly": false + }, + "DeleteObject": { + "eventName": "DeleteObject", + "readOnly": false + }, + "DeleteObjectAnnotation": { + "eventName": "DeleteObjectAnnotation", + "readOnly": false + }, + "DeleteObjectTagging": { + "eventName": "DeleteObjectTagging", + "readOnly": false + }, + "DeleteObjects": { + "eventName": "DeleteObjects", + "readOnly": false + }, + "GetObject": { + "eventName": "GetObject", + "readOnly": true + }, + "GetObjectAcl": { + "eventName": "GetObjectAcl", + "readOnly": true + }, + "GetObjectAnnotation": { + "eventName": "GetObjectAnnotation", + "readOnly": true + }, + "GetObjectAttributes": { + "eventName": "GetObjectAttributes", + "readOnly": true + }, + "GetObjectLegalHold": { + "eventName": "GetObjectLegalHold", + "readOnly": true + }, + "GetObjectRetention": { + "eventName": "GetObjectRetention", + "readOnly": true + }, + "GetObjectTagging": { + "eventName": "GetObjectTagging", + "readOnly": true + }, + "GetObjectTorrent": { + "eventName": "GetObjectTorrent", + "readOnly": true + }, + "HeadBucket": { + "eventName": "HeadBucket", + "readOnly": true + }, + "HeadObject": { + "eventName": "HeadObject", + "readOnly": true + }, + "ListObjectAnnotations": { + "eventName": "ListObjectAnnotations", + "readOnly": true + }, + "ListObjectVersions": { + "eventName": "ListObjectVersions", + "readOnly": true + }, + "ListObjects": { + "eventName": "ListObjects", + "readOnly": true + }, + "ListObjectsV2": { + "eventName": "ListObjects", + "readOnly": true + }, + "ListParts": { + "eventName": "ListParts", + "readOnly": true + }, + "PutObject": { + "eventName": "PutObject", + "readOnly": false + }, + "PutObjectAcl": { + "eventName": "PutObjectAcl", + "readOnly": false + }, + "PutObjectAnnotation": { + "eventName": "PutObjectAnnotation", + "readOnly": false + }, + "PutObjectLegalHold": { + "eventName": "PutObjectLegalHold", + "readOnly": false + }, + "PutObjectRetention": { + "eventName": "PutObjectLockRetention", + "readOnly": false + }, + "PutObjectTagging": { + "eventName": "PutObjectTagging", + "readOnly": false + }, + "RestoreObject": { + "eventName": "RestoreObject", + "readOnly": false + }, + "SelectObjectContent": { + "eventName": "SelectObjectContent", + "readOnly": true + }, + "UpdateObjectEncryption": { + "eventName": "UpdateObjectEncryption", + "readOnly": false + }, + "UploadPart": { + "eventName": "UploadPart", + "readOnly": false + }, + "UploadPartCopy": { + "eventName": "UploadPartCopy", + "readOnly": false + } + }, + "unmodeled": [] +} diff --git a/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java index dc58206815..e57c1a9aaf 100644 --- a/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java @@ -47,6 +47,7 @@ import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -55,6 +56,7 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; @@ -2467,35 +2469,55 @@ class IamEnforcementFilterTest { void aDeniedExtraActionNamesThePermissionAndRecordsTheOperation() { // A PutObject placing a legal hold also needs s3:PutObjectLegalHold. The denial names that // permission, while CloudTrail records PutObject, the operation that was refused. - assertEquals("PutObject", deniedExtraActionEvent("PUT", new MultivaluedHashMap<>(), + assertEquals("PutObject", deniedExtraActionEvent("s3:PutObject", "PUT", new MultivaluedHashMap<>(), "x-amz-object-lock-legal-hold", "ON", "s3:PutObject", "s3:PutObjectLegalHold")); - // A retention change asking for the bypass is recorded as the retention change. + // A retention change asking for the bypass is recorded as the retention change, under the name the + // S3 user guide gives it, PutObjectLockRetention. MultivaluedHashMap retention = new MultivaluedHashMap<>(); retention.putSingle("retention", ""); - assertEquals("PutObjectRetention", deniedExtraActionEvent("PUT", retention, + assertEquals("PutObjectLockRetention", deniedExtraActionEvent("s3:PutObjectRetention", "PUT", retention, "x-amz-bypass-governance-retention", "true", "s3:PutObjectRetention", "s3:BypassGovernanceRetention")); // GetObjectAttributes is checked as the read and as its own action; denied the second, it is // recorded as GetObjectAttributes, not as the read. MultivaluedHashMap attributes = new MultivaluedHashMap<>(); attributes.putSingle("attributes", ""); - assertEquals("GetObjectAttributes", deniedExtraActionEvent("GET", attributes, + assertEquals("GetObjectAttributes", deniedExtraActionEvent("s3:GetObjectAttributes", "GET", attributes, "x-amz-object-attributes", "ETag", "s3:GetObject", "s3:GetObjectAttributes")); } @Test - void aDeniedPostIsRecordedAsTheOperationItsSubResourceSelects() { - // CreateMultipartUpload and CompleteMultipartUpload are both checked as s3:PutObject, so the - // event is named from the request's sub-resource. An upload placing a legal hold also needs + void aDeniedRequestIsRecordedAsTheOperationItMatched() { + // CreateMultipartUpload and CompleteMultipartUpload are both checked as s3:PutObject, and are + // recorded as the operation each request matched. An upload placing a legal hold also needs // s3:PutObjectLegalHold, and a conditional complete needs s3:GetObject. MultivaluedHashMap create = new MultivaluedHashMap<>(); create.putSingle("uploads", ""); - assertEquals("CreateMultipartUpload", deniedExtraActionEvent("POST", create, + assertEquals("CreateMultipartUpload", deniedExtraActionEvent("s3:CreateMultipartUpload", "POST", create, "x-amz-object-lock-legal-hold", "ON", "s3:PutObject", "s3:PutObjectLegalHold")); MultivaluedHashMap complete = new MultivaluedHashMap<>(); complete.putSingle("uploadId", "u1"); - assertEquals("CompleteMultipartUpload", deniedExtraActionEvent("POST", complete, - "If-Match", "\"etag\"", "s3:PutObject", "s3:GetObject")); + assertEquals("CompleteMultipartUpload", deniedExtraActionEvent("s3:CompleteMultipartUpload", "POST", + complete, "If-Match", "\"etag\"", "s3:PutObject", "s3:GetObject")); + // HeadBucket is checked as s3:ListBucket, as ListObjects is, and is recorded as itself; CopyObject is + // checked as s3:PutObject and is recorded as itself; ListObjectsV2 is recorded as ListObjects. + assertEquals("HeadBucket", deniedExtraActionEvent("s3:HeadBucket", "HEAD", new MultivaluedHashMap<>(), + "x-amz-expected-bucket-owner", "222233334444", "s3:ListBucket", "s3:ListBucket")); + assertEquals("CopyObject", deniedExtraActionEvent("s3:CopyObject", "PUT", new MultivaluedHashMap<>(), + "x-amz-copy-source", "/source/key", "s3:PutObject", "s3:PutObject")); + assertEquals("ListObjects", deniedExtraActionEvent("s3:ListObjectsV2", "GET", new MultivaluedHashMap<>(), + "x-amz-expected-bucket-owner", "222233334444", "s3:ListBucket", "s3:ListBucket")); + } + + @Test + void aDeniedRequestWhoseOperationIsNoDataEventIsNotRecordedAsOne() { + // ListBuckets and GetBucketPolicy are management events, not data events. + assertNull(deniedExtraActionEvent("s3:ListBuckets", "GET", new MultivaluedHashMap<>(), + "x-amz-expected-bucket-owner", "222233334444", "s3:ListAllMyBuckets", "s3:ListAllMyBuckets")); + MultivaluedHashMap policy = new MultivaluedHashMap<>(); + policy.putSingle("policy", ""); + assertNull(deniedExtraActionEvent("s3:GetBucketPolicy", "GET", policy, + "x-amz-expected-bucket-owner", "222233334444", "s3:GetBucketPolicy", "s3:GetBucketPolicy")); } @Test @@ -2539,12 +2561,15 @@ class IamEnforcementFilterTest { } /** - * Runs an S3 request whose own action is allowed and whose extra action is denied, asserts the - * denial names the extra action, and returns the event name CloudTrail recorded for it. + * Runs an S3 request matched to {@code operation} whose own action is allowed and whose extra action is + * denied, asserts the denial names the extra action, and returns the event name CloudTrail recorded for + * it, or null when it recorded none. The same action given twice is the request's own action, denied. */ - private String deniedExtraActionEvent(String method, MultivaluedHashMap query, String header, - String headerValue, String allowedAction, String deniedAction) { + private String deniedExtraActionEvent(String operation, String method, MultivaluedHashMap query, + String header, String headerValue, String allowedAction, + String deniedAction) { ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + when(containerRequest.getProperty(IamEnforcementFilter.RESOLVED_OPERATION_PROPERTY)).thenReturn(operation); UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getPath()).thenReturn("/bucket/object"); when(uriInfo.getQueryParameters()).thenReturn(query); @@ -2576,8 +2601,8 @@ class IamEnforcementFilterTest { assertEquals(403, denied.getValue().getStatus()); assertTrue(entityString(denied.getValue()).contains(deniedAction)); ArgumentCaptor event = ArgumentCaptor.captor(); - verify(cloudTrail).emitS3DataEvent(event.capture()); - return event.getValue().eventName(); + verify(cloudTrail, atMost(1)).emitS3DataEvent(event.capture()); + return event.getAllValues().isEmpty() ? null : event.getValue().eventName(); } @Test diff --git a/src/test/java/io/floci/aws/core/common/IamEnforcementFilterUnitTest.java b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterUnitTest.java index ff03dd376f..114d94e4ea 100644 --- a/src/test/java/io/floci/aws/core/common/IamEnforcementFilterUnitTest.java +++ b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterUnitTest.java @@ -2,143 +2,16 @@ package io.floci.aws.core.common; import org.junit.jupiter.api.Test; -import java.util.Set; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; /** - * Unit tests for the static helpers that drive CloudTrail emission on the - * IAM-deny path. Full HTTP-level coverage (filter → emit → log file) lives in + * Unit tests for the static helper that reads the bucket and key of a denied S3 request's resource + * for its CloudTrail event. Full HTTP-level coverage (filter → emit → log file) lives in * the SDK compatibility suite where SigV4 signing is available. */ class IamEnforcementFilterUnitTest { - // --- mapS3ActionToEventName --- - - @Test - void getObject_overGet_emitsAsGetObject() { - assertEquals("GetObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObject", "GET", Set.of())); - } - - @Test - void getObject_overHead_emitsAsHeadObject() { - assertEquals("HeadObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObject", "HEAD", Set.of())); - } - - @Test - void putObject_emitsAsPutObject() { - assertEquals("PutObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObject", "PUT", Set.of())); - } - - @Test - void deleteObject_emitsAsDeleteObject() { - assertEquals("DeleteObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObject", "DELETE", Set.of())); - } - - @Test - void listBucket_emitsAsListObjects() { - assertEquals("ListObjects", - IamEnforcementFilter.mapS3ActionToEventName("s3:ListBucket", "GET", Set.of())); - } - - @Test - void listAllMyBuckets_emitsAsListBuckets() { - assertEquals("ListBuckets", - IamEnforcementFilter.mapS3ActionToEventName("s3:ListAllMyBuckets", "GET", Set.of())); - } - - @Test - void getObjectAcl_emitsAsGetObjectAcl() { - assertEquals("GetObjectAcl", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectAcl", "GET", Set.of())); - } - - @Test - void putObjectAcl_emitsAsPutObjectAcl() { - assertEquals("PutObjectAcl", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectAcl", "PUT", Set.of())); - } - - @Test - void objectTagging_emitsCorrectEventNames() { - assertEquals("GetObjectTagging", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectTagging", "GET", Set.of())); - assertEquals("PutObjectTagging", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectTagging", "PUT", Set.of())); - assertEquals("DeleteObjectTagging", - IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectTagging", "DELETE", Set.of())); - } - - @Test - void versionActions_emitAsTheOperationTheyCheck() { - assertEquals("GetObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersion", "GET", Set.of())); - assertEquals("HeadObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersion", "HEAD", Set.of())); - assertEquals("DeleteObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectVersion", "DELETE", Set.of())); - assertEquals("GetObjectAcl", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersionAcl", "GET", Set.of())); - assertEquals("PutObjectAcl", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectVersionAcl", "PUT", Set.of())); - assertEquals("GetObjectTagging", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersionTagging", "GET", Set.of())); - assertEquals("PutObjectTagging", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectVersionTagging", "PUT", Set.of())); - assertEquals("DeleteObjectTagging", - IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectVersionTagging", "DELETE", Set.of())); - } - - @Test - void extraActionChecks_emitAsTheOperationTheyRefuse() { - assertEquals("PutObjectRetention", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectRetention", "PUT", Set.of())); - assertEquals("GetObjectAttributes", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectAttributes", "GET", Set.of())); - assertEquals("GetObjectAttributes", - IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersionAttributes", "GET", Set.of())); - } - - @Test - void postOperations_areNamedByTheSubResourceThatChoseTheirAction() { - // CreateMultipartUpload and CompleteMultipartUpload are both checked as s3:PutObject, and - // SelectObjectContent as s3:GetObject, so the sub-resource tells which operation ran. - assertEquals("CreateMultipartUpload", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObject", "POST", Set.of("uploads"))); - assertEquals("CompleteMultipartUpload", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObject", "POST", Set.of("uploadId"))); - // S3Controller runs ?uploads ahead of an uploadId, so a request naming both creates an upload. - assertEquals("CreateMultipartUpload", - IamEnforcementFilter.mapS3ActionToEventName("s3:PutObject", "POST", Set.of("uploads", "uploadId"))); - assertEquals("RestoreObject", - IamEnforcementFilter.mapS3ActionToEventName("s3:RestoreObject", "POST", Set.of("restore"))); - assertEquals("SelectObjectContent", IamEnforcementFilter.mapS3ActionToEventName("s3:GetObject", "POST", - Set.of("select", "select-type"))); - assertEquals("SelectObjectContent", IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersion", - "POST", Set.of("select", "select-type", "versionId"))); - } - - @Test - void postOperations_withoutTheirSubResource_returnNullRatherThanTheWrongName() { - assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:PutObject", "POST", Set.of())); - assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:GetObject", "POST", Set.of())); - assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:RestoreObject", "POST", Set.of())); - assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObject", "POST", Set.of("delete"))); - } - - @Test - void unknownAction_returnsNull() { - assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:GetBucketAcl", "GET", Set.of())); - assertNull(IamEnforcementFilter.mapS3ActionToEventName("dynamodb:Query", "POST", Set.of())); - assertNull(IamEnforcementFilter.mapS3ActionToEventName(null, "GET", Set.of())); - } - // --- parseS3Resource --- @Test diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailSelectorMatchingTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailSelectorMatchingTest.java index 4847493956..e840a2715f 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailSelectorMatchingTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailSelectorMatchingTest.java @@ -160,12 +160,14 @@ class CloudTrailSelectorMatchingTest { assertTrue(CloudTrailService.isReadOnlyEvent("GetObject")); assertTrue(CloudTrailService.isReadOnlyEvent("HeadObject")); assertTrue(CloudTrailService.isReadOnlyEvent("ListObjects")); - assertTrue(CloudTrailService.isReadOnlyEvent("ListObjectsV2")); assertTrue(CloudTrailService.isReadOnlyEvent("GetObjectAcl")); assertTrue(CloudTrailService.isReadOnlyEvent("GetObjectTagging")); - assertTrue(CloudTrailService.isReadOnlyEvent("ListMultipartUploads")); assertTrue(CloudTrailService.isReadOnlyEvent("GetObjectAttributes")); assertTrue(CloudTrailService.isReadOnlyEvent("SelectObjectContent")); + assertTrue(CloudTrailService.isReadOnlyEvent("HeadBucket")); + assertTrue(CloudTrailService.isReadOnlyEvent("ListObjectVersions")); + assertTrue(CloudTrailService.isReadOnlyEvent("ListParts")); + assertTrue(CloudTrailService.isReadOnlyEvent("GetObjectLegalHold")); } @Test @@ -173,7 +175,9 @@ class CloudTrailSelectorMatchingTest { assertFalse(CloudTrailService.isReadOnlyEvent("PutObject")); assertFalse(CloudTrailService.isReadOnlyEvent("DeleteObject")); assertFalse(CloudTrailService.isReadOnlyEvent("PutObjectAcl")); - assertFalse(CloudTrailService.isReadOnlyEvent("PutObjectRetention")); + assertFalse(CloudTrailService.isReadOnlyEvent("PutObjectLockRetention")); + assertFalse(CloudTrailService.isReadOnlyEvent("CopyObject")); + assertFalse(CloudTrailService.isReadOnlyEvent("DeleteObjects")); assertFalse(CloudTrailService.isReadOnlyEvent("CreateMultipartUpload")); assertFalse(CloudTrailService.isReadOnlyEvent("CompleteMultipartUpload")); assertFalse(CloudTrailService.isReadOnlyEvent("RestoreObject")); diff --git a/src/test/java/io/floci/aws/services/cloudtrail/S3DataEventsTest.java b/src/test/java/io/floci/aws/services/cloudtrail/S3DataEventsTest.java new file mode 100644 index 0000000000..71ec68b68a --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudtrail/S3DataEventsTest.java @@ -0,0 +1,58 @@ +package io.floci.aws.services.cloudtrail; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The S3 data events CloudTrail records, as the vendored table generated from botocore, the S3 user guide and the S3 + * service reference gives them. + */ +class S3DataEventsTest { + + @Test + void anOperationIsRecordedUnderItsOwnNameOrTheOneTheGuideGivesIt() { + assertEquals(Optional.of(new S3DataEvents.Event("HeadBucket", true)), S3DataEvents.forOperation("HeadBucket")); + assertEquals(Optional.of(new S3DataEvents.Event("CopyObject", false)), S3DataEvents.forOperation("CopyObject")); + assertEquals(Optional.of(new S3DataEvents.Event("UploadPart", false)), S3DataEvents.forOperation("UploadPart")); + assertEquals(Optional.of(new S3DataEvents.Event("ListObjects", true)), + S3DataEvents.forOperation("ListObjectsV2")); + assertEquals(Optional.of(new S3DataEvents.Event("PutObjectLockRetention", false)), + S3DataEvents.forOperation("PutObjectRetention")); + } + + @Test + void anOperationCloudTrailRecordsNoDataEventForHasNone() { + assertEquals(Optional.empty(), S3DataEvents.forOperation("ListBuckets")); + assertEquals(Optional.empty(), S3DataEvents.forOperation("GetBucketPolicy")); + assertEquals(Optional.empty(), S3DataEvents.forOperation(null)); + } + + @Test + void anEventIsReadOnlyWhenItsOperationChangesNothing() { + assertTrue(S3DataEvents.isReadOnly("GetObject")); + assertTrue(S3DataEvents.isReadOnly("ListParts")); + assertTrue(S3DataEvents.isReadOnly("SelectObjectContent")); + assertFalse(S3DataEvents.isReadOnly("PutObject")); + assertFalse(S3DataEvents.isReadOnly("DeleteObjects")); + assertFalse(S3DataEvents.isReadOnly("SomeFutureOperation")); + } + + @Test + void aFileWithoutAnEventsNameOrFlagIsRefused() { + ObjectMapper mapper = new ObjectMapper(); + assertThrows(IllegalStateException.class, () -> new S3DataEvents(mapper.createObjectNode())); + assertThrows(IllegalStateException.class, () -> new S3DataEvents(mapper.readTree( + "{\"dataEvents\":{\"GetObject\":{\"eventName\":\"GetObject\"}}}"))); + // One record carries one flag for its name, so the operations recorded under it must agree. + assertThrows(IllegalStateException.class, () -> new S3DataEvents(mapper.readTree( + "{\"dataEvents\":{\"ListObjects\":{\"eventName\":\"ListObjects\",\"readOnly\":true}," + + "\"ListObjectsV2\":{\"eventName\":\"ListObjects\",\"readOnly\":false}}}"))); + } +} diff --git a/tools/aws/fetch_cloudtrail_s3_data_events.py b/tools/aws/fetch_cloudtrail_s3_data_events.py new file mode 100644 index 0000000000..ab91e5a4eb --- /dev/null +++ b/tools/aws/fetch_cloudtrail_s3_data_events.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Vendor the names CloudTrail records Amazon S3 data events under, as the S3 user guide gives them, into +tools/aws/sources/cloudtrail-s3-data-events.json, a source of regen_cloudtrail_s3_data_events.py. + +Botocore models S3's operations but not which of them CloudTrail records as data events, nor the name a record +carries. The S3 user guide's "Amazon S3 CloudTrail events" page says both: its data events table lists, for each +resource type, the APIs CloudTrail logs, and a sentence gives the name of a call recorded under another one: + + S3 AWS::S3::Object AbortMultipartUpload CompleteMultipartUpload CopyObject ... + + When you call PutObjectRetention, the CloudTrail data event is recorded with the eventName + PutObjectLockRetention, ... + + https://docs.aws.amazon.com/AmazonS3/latest/userguide/cloudtrail-logging-s3-info.html + +This script copies each row of that table, its API cells as they stand, and each such sentence with the call and +the name it gives. Nothing in the output is written by hand; the generator reads it against botocore's operations. + +Run from anywhere in the repo: + python3 tools/aws/fetch_cloudtrail_s3_data_events.py # rewrite the vendored file from the page + python3 tools/aws/fetch_cloudtrail_s3_data_events.py --verify # online: the file still says what the page does +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +PAGE = "https://docs.aws.amazon.com/AmazonS3/latest/userguide/cloudtrail-logging-s3-info.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/cloudtrail-s3-data-events.json" + +TYPE_HEADING = "resources.type value" +APIS_HEADING = "Data APIs logged to CloudTrail" +TABLE_RE = re.compile(r"]*>(.*?)", re.S) +ROW_RE = re.compile(r"(.*?)", re.S) +CELL_RE = re.compile(r"]*>(.*?)", re.S) +ITEM_RE = re.compile(r"]*>(.*?)", re.S) +PARAGRAPH_RE = re.compile(r"

(.*?)

", re.S) +RECORDED_AS_RE = re.compile(r"^When you call (\w+), the CloudTrail data event is recorded with the eventName (\w+)\b") + + +def text(fragment: str) -> str: + """A fragment of the page as text, spaces collapsed and no space left before a comma or a period.""" + collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + return re.sub(r" ([,.])", r"\1", collapsed) + + +def read_data_events(page: str) -> dict[str, list[str]]: + """Each resource type of the page's data events table with the API cells it lists, as they stand.""" + for table in TABLE_RE.finditer(page): + rows = ROW_RE.findall(table.group(1)) + headings = [text(cell) for cell in CELL_RE.findall(rows[0])] if rows else [] + if TYPE_HEADING not in headings or APIS_HEADING not in headings: + continue + kind, apis = headings.index(TYPE_HEADING), headings.index(APIS_HEADING) + events: dict[str, list[str]] = {} + for row in rows[1:]: + cells = CELL_RE.findall(row) + if len(cells) > max(kind, apis): + events[text(cells[kind])] = [text(item) for item in ITEM_RE.findall(cells[apis])] + if not events: + raise ValueError(f"{PAGE}'s data events table lists no resource type: its layout changed") + return events + raise ValueError(f"{PAGE} gives no table headed '{TYPE_HEADING}' and '{APIS_HEADING}': its layout changed") + + +def read_recorded_as(page: str) -> list[dict[str, str]]: + """Each sentence of the page giving the name a call's data event is recorded with, as it stands.""" + found = [] + for paragraph in PARAGRAPH_RE.findall(page): + sentence = text(paragraph) + match = RECORDED_AS_RE.match(sentence) + if match: + found.append({"call": match.group(1), "eventName": match.group(2), "sentence": sentence}) + return found + + +def build(page: str) -> dict: + return { + "_source": { + "page": PAGE, + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "Each row of the page's data events table with its API cells, and each sentence giving the " + "name a call's data event is recorded with, copied as they stand.", + }, + "dataEvents": read_data_events(page), + "recordedAs": read_recorded_as(page), + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def stale(vendored: dict, page: str) -> bool: + """Whether the page now gives something other than the vendored file, its date aside.""" + built = build(page) + return any(vendored.get(key) != built[key] for key in built if key != "_source") + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the page") + args = parser.parse_args(argv) + try: + page = fetch(PAGE) + except OSError as e: + print(f"error: could not read the S3 user guide ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, page): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what {PAGE} does: run " + f"tools/aws/fetch_cloudtrail_s3_data_events.py and then make cloudtrail-s3-data-events-sync", + file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches {PAGE}") + return 0 + built = build(page) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['dataEvents'])} resource types, " + f"{len(built['recordedAs'])} renamed calls)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_cloudtrail_s3_data_events.py b/tools/aws/regen_cloudtrail_s3_data_events.py new file mode 100644 index 0000000000..02c2655631 --- /dev/null +++ b/tools/aws/regen_cloudtrail_s3_data_events.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Regenerate src/main/resources/aws/cloudtrail-s3-data-events.json, the name CloudTrail records each S3 operation's +data event under and whether it records it read-only, from botocore's S3 model, +tools/aws/sources/cloudtrail-s3-data-events.json and AWS's S3 service reference. + +CloudTrail records an S3 call on an object of a general purpose bucket as a data event when the S3 user guide's data +events table lists its API for `AWS::S3::Object`, the resource type of every object Floci serves. The vendored source +copies that table and the guide's sentences naming the event a call is recorded with +(fetch_cloudtrail_s3_data_events.py); this file reads them against botocore's operations: + +- An operation the row lists is recorded under its own name, or under the name a sentence gives its call + (`PutObjectRetention` as `PutObjectLockRetention`). +- An operation the row does not list, whose name ends in a version (`ListObjectsV2`), is recorded under the + version-less name when the row lists that one: the guide lists the versioned name beside it for the resource types + that record it apart (`AWS::S3::Access Point` lists both `ListObjects` and `ListObjectsV2`), and only the + version-less one for `AWS::S3::Object`. +- Any other operation is not a data event, and is absent. + +Each event carries `readOnly`, as CloudTrail records it: CloudTrail "considers an action read-only if it does not have +any mutating effect on a resource" (https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html), so +an operation is read-only when none of the actions the service reference authorizes it with has a mutating access +level, the reading regen_iam_action_resources.py vendors IAM's `readOnlyActions` by. An operation the reference lists +no S3 action for is authorized by the action of its own name, as regen_iam_authorized_actions.py takes it. + +The service reference is live rather than a pinned dependency, so `--check` is offline and reads the operations and +their event names against botocore and the vendored page, and `--verify` reads `readOnly` against the reference. + +The model is botocore's `s3/2006-03-01/` (Apache-2.0, https://github.com/boto/botocore), located, in order, at +`--botocore-data`, the `local/aws/botocore` checkout, then the installed `botocore` package, which `requirements.txt` +pins so CI regenerates the same bytes. + +Run from anywhere in the repo: + python3 tools/aws/regen_cloudtrail_s3_data_events.py # rewrite the vendored file (online) + python3 tools/aws/regen_cloudtrail_s3_data_events.py --check # offline: the event names are botocore's and the page's + python3 tools/aws/regen_cloudtrail_s3_data_events.py --verify # online: readOnly is still what the reference gives +""" +from __future__ import annotations + +import argparse +import json +import re +import sys +import urllib.request +from pathlib import Path + +from regen_iam_action_resources import read_only_actions_from +from regen_partitions import resolve_botocore_data +from request_shapes import REPO_ROOT, generator_name, load_model, render + +OUTPUT = REPO_ROOT / "src/main/resources/aws/cloudtrail-s3-data-events.json" +SOURCE = REPO_ROOT / "tools/aws/sources/cloudtrail-s3-data-events.json" +MODEL = Path("s3/2006-03-01") +REFERENCE_URL = "https://servicereference.us-east-1.amazonaws.com/v1/s3/s3.json" +FETCH_TIMEOUT_SECONDS = 30 +# The resource type of an object in a general purpose bucket, the only kind of bucket Floci serves. +RESOURCE_TYPE = "AWS::S3::Object" + +API_RE = re.compile(r"\w+") +VERSIONED_RE = re.compile(r"^(\w+?)V\d+$") + + +def api_name(cell: str) -> str: + """The API a cell of the data events table names, without the note some carry ("(same-region copies only)").""" + match = API_RE.match(cell) + if match is None: + raise ValueError(f"the data events table lists {cell!r}, which names no API") + return match.group(0) + + +def data_events(source: dict, operations: list[str]) -> dict[str, str]: + """Each operation CloudTrail records as a data event on a general purpose bucket's object, with the event name + it is recorded under.""" + rows = source["dataEvents"] + if RESOURCE_TYPE not in rows: + raise ValueError(f"the vendored data events table has no {RESOURCE_TYPE} row") + listed = {api_name(cell) for cell in rows[RESOURCE_TYPE]} + renamed = {sentence["call"]: sentence["eventName"] for sentence in source["recordedAs"]} + events = {} + for operation in sorted(operations): + if operation in listed: + events[operation] = renamed.get(operation, operation) + continue + versioned = VERSIONED_RE.match(operation) + if versioned and versioned.group(1) in listed: + events[operation] = renamed.get(versioned.group(1), versioned.group(1)) + return events + + +def read_only(reference: dict, operations: list[str]) -> dict[str, bool]: + """Whether CloudTrail records each operation read-only: none of the S3 actions the reference authorizes it with, + or else the action of its own name, has a mutating access level.""" + readable = set(read_only_actions_from(reference)) + actions = {action["Name"] for action in reference.get("Actions", [])} + authorized = {operation["Name"]: [action["Name"] for action in operation.get("AuthorizedActions", []) + if action.get("Service") == "s3"] + for operation in reference.get("Operations", [])} + found = {} + for operation in operations: + checked = authorized.get(operation) or ([operation] if operation in actions else []) + if not checked: + raise ValueError(f"the S3 service reference authorizes {operation} with no action") + found[operation] = all(action in readable for action in checked) + return found + + +def disagreeing(events: dict[str, dict]) -> list[str]: + """The event names whose operations are not all read-only or all not: a record carries one flag for its name, so + the operations recorded under it must agree.""" + names = {event.get("eventName") for event in events.values()} + return sorted(name for name in names if name is not None + and len({event.get("readOnly") for event in events.values() if event.get("eventName") == name}) > 1) + + +def build(model: dict, source: dict, reference: dict, provenance: str, generator: str) -> dict: + names = data_events(source, list(model["operations"])) + flags = read_only(reference, list(names)) + events = {operation: {"eventName": name, "readOnly": flags[operation]} for operation, name in names.items()} + conflicting = disagreeing(events) + if conflicting: + raise ValueError(f"the operations recorded as {conflicting} are not all read-only or all not") + unmodeled = sorted({api_name(cell) for cell in source["dataEvents"][RESOURCE_TYPE]} - set(names) + - set(names.values())) + return { + "_source": { + "botocore": provenance, + "page": source["_source"]["page"], + "reference": REFERENCE_URL, + "generator": generator, + "note": f"Each S3 operation CloudTrail records as a data event on an {RESOURCE_TYPE}, with the event " + "name it is recorded under and whether it is recorded read-only. `unmodeled` lists the APIs the " + "guide names that botocore models no operation for.", + }, + "dataEvents": events, + "unmodeled": unmodeled, + } + + +def fetch_reference(source: Path | None) -> dict: + """AWS's S3 service reference, from `source` when given.""" + if source is not None: + return json.loads(source.read_text(encoding="utf-8")) + request = urllib.request.Request(REFERENCE_URL, headers={"Accept": "application/json"}) + with urllib.request.urlopen(request, timeout=FETCH_TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8")) + + +def check(vendored: dict, model: dict, source: dict) -> list[str]: + """Offline: the vendored operations and event names are the ones botocore and the page give, each with a + `readOnly` flag the operations sharing its event name agree on.""" + events = vendored.get("dataEvents") + if not isinstance(events, dict): + return ["the file carries no dataEvents object"] + problems = [] + names = data_events(source, list(model["operations"])) + if {operation: event.get("eventName") for operation, event in events.items()} != names: + problems.append("the operations or their event names differ from botocore's and the vendored page's") + for operation, event in sorted(events.items()): + if not isinstance(event.get("readOnly"), bool): + problems.append(f"{operation} carries no readOnly flag") + conflicting = disagreeing(events) + if conflicting: + problems.append(f"the operations recorded as {conflicting} are not all read-only or all not") + return problems + + +def verify(vendored: dict, reference: dict) -> list[str]: + """Online: each operation's `readOnly` is still what the service reference gives.""" + events = vendored["dataEvents"] + upstream = read_only(reference, list(events)) + return [f"{operation} is vendored readOnly {event['readOnly']}, the service reference gives {upstream[operation]}" + for operation, event in sorted(events.items()) if event["readOnly"] != upstream[operation]] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--check", action="store_true", help="offline: the event names are botocore's and the page's") + parser.add_argument("--verify", action="store_true", help="online: readOnly is still what the reference gives") + parser.add_argument("--botocore-data", type=Path, help="botocore data directory") + parser.add_argument("--reference", type=Path, help="read the S3 service reference from this file") + parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + + data, provenance = resolve_botocore_data(args.botocore_data) + try: + model = load_model(data, MODEL) + source = json.loads(SOURCE.read_text(encoding="utf-8")) + if args.check or args.verify: + vendored = json.loads(args.output.read_text(encoding="utf-8")) + problems = check(vendored, model, source) if args.check else verify(vendored, fetch_reference(args.reference)) + else: + fresh = render(build(model, source, fetch_reference(args.reference), provenance, generator_name(__file__))) + except OSError as e: + print(f"error: could not read a source ({e})", file=sys.stderr) + return 2 + except (ValueError, KeyError) as e: + print(f"error: {e}", file=sys.stderr) + return 1 + if args.check or args.verify: + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + if problems: + print(f"error: {args.output} no longer matches; run make cloudtrail-s3-data-events-sync", file=sys.stderr) + return 1 + print(f"{args.output.name}: {len(vendored['dataEvents'])} operations " + f"{'match botocore and the vendored page' if args.check else 'match the S3 service reference'}") + return 0 + args.output.write_text(fresh, encoding="utf-8") + shown = args.output.relative_to(REPO_ROOT) if args.output.is_relative_to(REPO_ROOT) else args.output + print(f"wrote {shown} ({len(json.loads(fresh)['dataEvents'])} operations) from {provenance} and {REFERENCE_URL}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/sources/cloudtrail-s3-data-events.json b/tools/aws/sources/cloudtrail-s3-data-events.json new file mode 100644 index 0000000000..7cdb43da58 --- /dev/null +++ b/tools/aws/sources/cloudtrail-s3-data-events.json @@ -0,0 +1,142 @@ +{ + "_source": { + "page": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/cloudtrail-logging-s3-info.html", + "fetcher": "tools/aws/fetch_cloudtrail_s3_data_events.py", + "retrieved": "2026-11-25", + "note": "Each row of the page's data events table with its API cells, and each sentence giving the name a call's data event is recorded with, copied as they stand." + }, + "dataEvents": { + "AWS::S3::Object": [ + "AbortMultipartUpload", + "CompleteMultipartUpload", + "CopyObject", + "CreateMultipartUpload", + "DeleteObject", + "DeleteObjectTagging", + "DeleteObjects", + "GetObject", + "GetObjectAcl", + "GetObjectAttributes", + "GetObjectLegalHold", + "GetObjectRetention", + "GetObjectTagging", + "GetObjectTorrent", + "HeadObject", + "HeadBucket", + "ListObjectVersions", + "ListObjects", + "ListParts", + "PutObject", + "PutObjectAcl", + "PutObjectLegalHold", + "PutObjectRetention", + "PutObjectTagging", + "PutObjectAnnotation", + "GetObjectAnnotation", + "ListObjectAnnotations", + "DeleteObjectAnnotation", + "RestoreObject", + "SelectObjectContent", + "UpdateObjectEncryption", + "UploadPart", + "UploadPartCopy" + ], + "AWS::S3Express::Object": [ + "AbortMultipartUpload", + "CompleteMultipartUpload", + "CreateSession", + "CopyObject", + "CreateMultipartUpload", + "DeleteObject", + "DeleteObjects", + "GetObject", + "GetObjectAttributes", + "HeadBucket", + "HeadObject", + "ListObjectsV2", + "ListParts", + "PutObject", + "UploadPart", + "UploadPartCopy" + ], + "AWS::S3::Access Point": [ + "AbortMultipartUpload", + "CompleteMultipartUpload", + "CopyObject (same-region copies only)", + "CreateMultipartUpload", + "DeleteObject", + "DeleteObjectTagging", + "GetObject", + "GetObjectAcl", + "GetObjectAttributes", + "GetObjectLegalHold", + "GetObjectRetention", + "GetObjectTagging", + "HeadBucket", + "HeadObject", + "ListObjects", + "ListObjectsV2", + "ListObjectVersions", + "ListParts", + "Presign", + "PutObject", + "PutObjectLegalHold", + "PutObjectRetention", + "PutObjectAcl", + "PutObjectTagging", + "RestoreObject", + "UploadPart", + "UploadPartCopy (same-region copies only)" + ], + "AWS::S3ObjectLambda::AccessPoint": [ + "AbortMultipartUpload", + "CompleteMultipartUpload", + "CopyObject (same-region copies only)", + "CreateMultipartUpload", + "DeleteObject", + "DeleteObjectTagging", + "GetObject", + "GetObjectAcl", + "GetObjectLegalHold", + "GetObjectRetention", + "GetObjectTagging", + "HeadObject", + "ListObjects", + "ListObjectVersions", + "ListParts", + "PutObject", + "PutObjectLegalHold", + "PutObjectRetention", + "PutObjectAcl", + "PutObjectTagging", + "RestoreObject", + "UploadPart", + "WriteGetObjectResponse" + ], + "AWS::S3Outposts::Object": [ + "AbortMultipartUpload", + "CompleteMultipartUpload", + "CopyObject (same-region copies only)", + "CreateMultipartUpload", + "DeleteObject", + "DeleteObjectTagging", + "GetObject", + "GetObjectTagging", + "HeadObject", + "ListObjects", + "ListObjectsV2", + "ListParts", + "PutObject", + "PutObjectTagging", + "UploadPart", + "UploadPartCopy" + ] + }, + "recordedAs": [ + { + "call": "PutObjectRetention", + "eventName": "PutObjectLockRetention", + "sentence": "When you call PutObjectRetention, the CloudTrail data event is recorded with the eventName PutObjectLockRetention, and includes objectRetentionInfo in additionalEventData. This field contains the resulting retention mode, retain-until-date, event hold status, and event hold duration." + } + ] +} diff --git a/tools/aws/test_fetch_cloudtrail_s3_data_events.py b/tools/aws/test_fetch_cloudtrail_s3_data_events.py new file mode 100644 index 0000000000..a21c5af13a --- /dev/null +++ b/tools/aws/test_fetch_cloudtrail_s3_data_events.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Tests for fetch_cloudtrail_s3_data_events.py, on a page in the S3 user guide's markup.""" +from __future__ import annotations + +import pytest + +import fetch_cloudtrail_s3_data_events as f + + +def row(console: str, kind: str, apis: list[str]) -> str: + """A row of the data events table, its APIs an itemized list as the guide lays them out.""" + items = "".join(f'
  • {api.split(" (")[0]}{api[len(api.split(" (")[0]):]}

  • ' for api in apis) + return (f'{console}{kind}' + f'
      {items}
    ') + + +RECORDED_AS = ('

    When you call PutObjectRetention, the CloudTrail data event is\n' + ' recorded with the eventName\n PutObjectLockRetention' + ', and includes\n objectRetentionInfo in\n' + ' additionalEventData.

    ') +PAGE = ('

    Amazon S3 logs all control plane operations as management events.

    ' + '' + '' + + row("S3", "AWS::S3::Object", ["GetObject", "ListObjects", "PutObjectRetention"]) + + row("S3 Access Point", "AWS::S3::Access Point", + ["CopyObject (same-region copies only)", "ListObjects", "ListObjectsV2"]) + + "
    Data event type (console)resources.type valueData APIs logged to CloudTrail
    " + RECORDED_AS + "") + + +def test_each_resource_type_keeps_its_api_cells_as_they_stand(): + assert f.read_data_events(PAGE) == { + "AWS::S3::Object": ["GetObject", "ListObjects", "PutObjectRetention"], + "AWS::S3::Access Point": ["CopyObject (same-region copies only)", "ListObjects", "ListObjectsV2"]} + + +def test_a_sentence_naming_the_event_a_call_is_recorded_with_is_kept_as_it_stands(): + assert f.read_recorded_as(PAGE) == [{ + "call": "PutObjectRetention", "eventName": "PutObjectLockRetention", + "sentence": "When you call PutObjectRetention, the CloudTrail data event is recorded with the eventName " + "PutObjectLockRetention, and includes objectRetentionInfo in additionalEventData."}] + assert f.read_recorded_as("

    Amazon S3 logs all control plane operations as management events.

    ") == [] + + +def test_a_page_whose_layout_changed_is_refused(): + with pytest.raises(ValueError, match="no table headed"): + f.read_data_events(PAGE.replace("resources.type value", "Resource type")) + with pytest.raises(ValueError, match="lists no resource type"): + f.read_data_events(PAGE.split("Data event type (console)' + "resources.type valueData APIs logged to CloudTrail") + + +def test_the_file_is_stale_when_the_page_says_something_else(): + vendored = f.build(PAGE) + assert vendored["_source"]["page"] == f.PAGE + assert not f.stale(vendored, PAGE) + assert f.stale(vendored, PAGE.replace(">ListObjectsV2<", ">ListObjectVersions<")) + assert f.stale(vendored, PAGE.replace("PutObjectLockRetention", "PutObjectRetention")) diff --git a/tools/aws/test_iam_data_verify.py b/tools/aws/test_iam_data_verify.py index c81431da31..9c92591254 100644 --- a/tools/aws/test_iam_data_verify.py +++ b/tools/aws/test_iam_data_verify.py @@ -50,12 +50,17 @@ class IamDataVerifyTest(unittest.TestCase): def test_empty_diff_keeps_full_verification(self): result, calls = self.run_gate(self.changed_file("")) self.assertEqual(0, result.returncode, result.stderr) - self.assertEqual(12, len(calls)) + self.assertEqual(13, len(calls)) def test_weekly_run_checks_every_file(self): result, calls = self.run_gate() self.assertEqual(0, result.returncode, result.stderr) - self.assertEqual(12, len(calls)) + self.assertEqual(13, len(calls)) + + def test_the_cloudtrail_s3_data_events_check_covers_its_fetcher(self): + result, calls = self.run_gate(self.changed_file("tools/aws/fetch_cloudtrail_s3_data_events.py\n")) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual(["cloudtrail-s3-data-events-verify"], calls) def test_legacy_changed_argument_still_selects(self): result, calls = self.run_gate("CHANGED= tools/aws/regen_service_namespaces.py ") diff --git a/tools/aws/test_regen_cloudtrail_s3_data_events.py b/tools/aws/test_regen_cloudtrail_s3_data_events.py new file mode 100644 index 0000000000..0c1da449bf --- /dev/null +++ b/tools/aws/test_regen_cloudtrail_s3_data_events.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Tests for regen_cloudtrail_s3_data_events.py, on a vendored source in fetch_cloudtrail_s3_data_events.py's shape.""" +from __future__ import annotations + +import pytest + +import regen_cloudtrail_s3_data_events as r + + +def source(general: list[str], recorded_as: list[tuple[str, str]] = ()) -> dict: + return { + "_source": {"page": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/cloudtrail-logging-s3-info.html"}, + "dataEvents": {"AWS::S3::Object": general, + "AWS::S3::Access Point": ["CopyObject (same-region copies only)", "ListObjects", "ListObjectsV2"]}, + "recordedAs": [{"call": call, "eventName": name, "sentence": f"When you call {call}, ..."} + for call, name in recorded_as], + } + + +def test_an_operation_the_row_lists_is_recorded_under_its_name(): + events = r.data_events(source(["GetObject", "CopyObject (same-region copies only)"]), + ["GetObject", "CopyObject", "GetBucketPolicy"]) + assert events == {"CopyObject": "CopyObject", "GetObject": "GetObject"} + + +def test_a_sentence_naming_the_event_a_call_is_recorded_with_renames_it(): + events = r.data_events(source(["PutObjectRetention"], [("PutObjectRetention", "PutObjectLockRetention")]), + ["PutObjectRetention"]) + assert events == {"PutObjectRetention": "PutObjectLockRetention"} + + +def test_a_versioned_operation_the_row_does_not_list_takes_the_listed_version_less_name(): + assert r.data_events(source(["ListObjects"]), ["ListObjects", "ListObjectsV2"]) == { + "ListObjects": "ListObjects", "ListObjectsV2": "ListObjects"} + # A row listing the versioned name too records it apart, and one listing neither records neither. + assert r.data_events(source(["ListObjects", "ListObjectsV2"]), ["ListObjectsV2"]) == { + "ListObjectsV2": "ListObjectsV2"} + assert r.data_events(source(["GetObject"]), ["ListObjectsV2"]) == {} + + +def test_a_source_without_the_general_purpose_row_is_refused(): + broken = source(["GetObject"]) + del broken["dataEvents"]["AWS::S3::Object"] + with pytest.raises(ValueError, match="no AWS::S3::Object row"): + r.data_events(broken, ["GetObject"]) + + +def reference(operations: dict[str, list[str]], writes: set[str]) -> dict: + """An S3 service reference authorizing each operation with the actions given, those in `writes` mutating.""" + actions = sorted({action for listed in operations.values() for action in listed} | writes | {"GetObjectAnnotation"}) + return { + "Actions": [{"Name": action, "Annotations": {"Properties": { + "IsWrite": action in writes, "IsList": False, "IsPermissionManagement": False, "IsTaggingOnly": False}}} + for action in actions], + "Operations": [{"Name": operation, "AuthorizedActions": [{"Name": action, "Service": "s3"} for action in listed] + + [{"Name": "ListBucket", "Service": "s3-object-lambda"}]} + for operation, listed in operations.items()], + } + + +def test_an_operation_is_read_only_when_none_of_its_actions_mutates(): + ref = reference({"GetObject": ["GetObject"], "CopyObject": ["GetObject", "PutObject"], "HeadBucket": ["ListBucket"]}, + {"PutObject"}) + # An operation the reference lists no S3 action for is authorized by the action of its own name. + assert r.read_only(ref, ["GetObject", "CopyObject", "HeadBucket", "GetObjectAnnotation"]) == { + "GetObject": True, "CopyObject": False, "HeadBucket": True, "GetObjectAnnotation": True} + with pytest.raises(ValueError, match="authorizes PutObjectAnnotation with no action"): + r.read_only(ref, ["PutObjectAnnotation"]) + + +def test_the_built_file_carries_each_event_s_name_and_read_only_flag(): + ref = reference({"GetObject": ["GetObject"], "ListObjects": ["ListBucket"], "ListObjectsV2": ["ListBucket"]}, set()) + built = r.build({"operations": {"GetObject": {}, "ListObjects": {}, "ListObjectsV2": {}}}, + source(["GetObject", "ListObjects", "PutObjectAnnotation"]), ref, "botocore test", "tools/aws/x.py") + assert built["dataEvents"] == {"GetObject": {"eventName": "GetObject", "readOnly": True}, + "ListObjects": {"eventName": "ListObjects", "readOnly": True}, + "ListObjectsV2": {"eventName": "ListObjects", "readOnly": True}} + assert built["unmodeled"] == ["PutObjectAnnotation"] + + +def test_operations_recorded_under_one_name_must_agree_on_read_only(): + ref = reference({"ListObjects": ["ListBucket"], "ListObjectsV2": ["PutObject"]}, {"PutObject"}) + with pytest.raises(ValueError, match="not all read-only or all not"): + r.build({"operations": {"ListObjects": {}, "ListObjectsV2": {}}}, source(["ListObjects"]), ref, "b", "g") + + +def test_check_and_verify_read_the_vendored_file_against_botocore_the_page_and_the_reference(): + model = {"operations": {"GetObject": {}, "PutObject": {}}} + ref = reference({"GetObject": ["GetObject"], "PutObject": ["PutObject"]}, {"PutObject"}) + vendored = r.build(model, source(["GetObject", "PutObject"]), ref, "b", "g") + assert r.check(vendored, model, source(["GetObject", "PutObject"])) == [] + assert r.verify(vendored, ref) == [] + assert r.check(vendored, model, source(["GetObject"])) == [ + "the operations or their event names differ from botocore's and the vendored page's"] + assert r.verify(vendored, reference({"GetObject": ["GetObject"], "PutObject": ["PutObject"]}, set())) == [ + "PutObject is vendored readOnly False, the service reference gives True"] + + +def test_check_refuses_operations_recorded_under_one_name_that_disagree_on_read_only(): + model = {"operations": {"ListObjects": {}, "ListObjectsV2": {}}} + ref = reference({"ListObjects": ["ListBucket"], "ListObjectsV2": ["ListBucket"]}, set()) + vendored = r.build(model, source(["ListObjects"]), ref, "b", "g") + assert r.check(vendored, model, source(["ListObjects"])) == [] + vendored["dataEvents"]["ListObjectsV2"]["readOnly"] = False + assert r.check(vendored, model, source(["ListObjects"])) == [ + "the operations recorded as ['ListObjects'] are not all read-only or all not"]