mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iam): record IAM API calls in CloudTrail (#9263)
CloudTrail logs every authenticated IAM API request, but Floci recorded none, so a trail showed no user, key or policy change. Each IAM call now reaches the logging trails that select it as a management event: the calls IAM runs, the ones it answers with an error, and the ones IAM enforcement refuses. requestParameters carries the request's members as the IAM model types them, responseElements the result of a call that is not read-only, without sensitive members, and the record carries the caller's address, read through RequestSourceAddress, and user agent. An error IAM models is recorded under its error shape's name (NoSuchEntityException). A refusal, on IAM's policies or because a GetSessionToken session without MFA cannot make the call, is recorded as AccessDenied with "requestParameters": null and the message and request ID of the response the caller receives. The caller is read before the call runs, so a key that deletes itself is recorded as its user's, and every call reaches the account's event history whether or not a trail records it. Basic selectors' ReadWriteType now matches a management event's readOnly. IAM is a global service, so only a trail with IncludeGlobalServiceEvents records its calls, as botocore's CloudTrail model says of the setting. Which calls are read-only is generated from the Service Reference into iam-action-resources.json (readOnlyActions). How members are named, typed and redacted, and each error's shape name, are generated from botocore's IAM model into iam-cloudtrail-shapes.json through request_shapes, the walk every vendored shape file shares, which now keeps an operation's result and its wrapper, the sensitive flag and the modeled errors when a generator asks for them. Both files are checked by make aws-data-check. The integration test reads the trail's log files through CloudTrailLogFiles, calls CloudTrail through CloudTrailRequests, both now in io.floci.aws.testing with an Authorization a test under IAM enforcement signs with, and calls IAM through QueryRequests. Closes #9013 Co-authored-by: Jeremy Chapeau <jeremy.chapeau@gmail.com>
This commit is contained in:
1 parent
946d1392a5
commit
64f74c6bc4
28 files changed
+5614
-67
No files matched your search
@@ -62,6 +62,9 @@
|
||||
# check fails until the actions of no resource type list the model's scope.
|
||||
# src/main/resources/aws/iam-paginators.json, what each paged IAM list pages by, is generated
|
||||
# from botocore's IAM model and paginators by tools/aws/regen_iam_paginators.py.
|
||||
# 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.
|
||||
|
||||
PYTHON ?= python3
|
||||
|
||||
@@ -322,6 +325,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s
|
||||
$(PYTHON) tools/aws/regen_query_services.py
|
||||
$(PYTHON) tools/aws/regen_rest_routes.py
|
||||
$(PYTHON) tools/aws/regen_iam_paginators.py
|
||||
$(PYTHON) tools/aws/regen_iam_cloudtrail_shapes.py
|
||||
|
||||
aws-data-check: aws-data-check-botocore ## CI gate: the vendored AWS data must match a fresh generation
|
||||
@$(PYTHON) tools/aws/regen_partitions.py --check || { \
|
||||
@@ -522,6 +526,12 @@ 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; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_iam_cloudtrail_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/iam-cloudtrail-shapes.json is out of date."; \
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(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
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
**Protocol:** JSON 1.1 (`X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.*`)
|
||||
**Endpoint:** `POST http://localhost:4566/`
|
||||
|
||||
Floci emulates a CloudTrail trail's full life cycle and emits S3 data events
|
||||
Floci emulates a CloudTrail trail's full life cycle and emits S3 data events, IAM API calls
|
||||
and selected Secrets Manager management writes to the trail's destination bucket as gzipped JSON log files at the
|
||||
AWS-shaped key path:
|
||||
|
||||
@@ -90,15 +90,51 @@ refused for a permission it needs besides its own, such as
|
||||
operation. A browser `POST` upload, whose credential is in its form fields, is
|
||||
recorded as `PostObject` when IAM refuses it.
|
||||
|
||||
## IAM Coverage
|
||||
|
||||
Every IAM API call is recorded as a management event, as CloudTrail
|
||||
["logs all authenticated API requests to IAM"](https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html):
|
||||
one IAM ran, one IAM answered with an error, and, with `floci.services.iam.enforcement-enabled`, one IAM enforcement
|
||||
refused.
|
||||
|
||||
- `eventSource` is `iam.amazonaws.com` and `awsRegion` the Region IAM signs for in the request's partition
|
||||
(`us-east-1` in `aws`). IAM is a global service, so only a trail with `IncludeGlobalServiceEvents` (the default)
|
||||
records its calls, and only a multi-Region trail or one whose home Region is that Region.
|
||||
- `readOnly` is `true` for the actions AWS's service reference
|
||||
([`iam.json`](https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json)) gives the Read or List access
|
||||
level, vendored as `readOnlyActions` in `iam-action-resources.json` by `make iam-action-resources-sync`.
|
||||
- `requestParameters` holds the request's members, named with a lower first letter (`userName`, `policyArn`,
|
||||
`tags: [{"key": ..., "value": ...}]`), numbers and booleans typed as botocore's IAM model types them. A member the
|
||||
model marks sensitive (a password, a private key) is left out, and a request whose only members are sensitive
|
||||
(`ChangePassword`) has `"requestParameters": null`.
|
||||
- `responseElements` is `null` for a failed call and for a read-only one, as CloudTrail
|
||||
"redacts the responseElements information" of a read-only event. Otherwise it holds the call's result
|
||||
(`{"accessKey": {...}}` for `CreateAccessKey`), numbers, booleans and timestamps typed as the model types them,
|
||||
timestamps written as CloudTrail writes them (`Oct 29, 2024 2:43:20 PM`), and without the members the model marks
|
||||
sensitive (`secretAccessKey`, a service-specific credential's password or secret, a virtual MFA device's seed).
|
||||
- An error IAM models is recorded under its error shape's name: `NoSuchEntity` as `NoSuchEntityException`,
|
||||
`DeleteConflict` as `DeleteConflictException`, with IAM's message. A call IAM enforcement refuses, on its
|
||||
policies or because a `GetSessionToken` session without MFA cannot make it, is recorded as
|
||||
`errorCode: "AccessDenied"` and `"requestParameters": null`, with the message and the request ID the refusal
|
||||
answered with.
|
||||
- `sourceIPAddress` is the address the request came from and `userAgent` its `User-Agent`; `requestID` is the one
|
||||
IAM answered with. `userIdentity` is the caller as it was before the call ran, so a key that deletes itself is
|
||||
still recorded as its user's.
|
||||
- Like every management event, an IAM call also reaches the account's event history, which `LookupEvents` reads,
|
||||
whether or not a trail records it.
|
||||
|
||||
How each member is typed, which members are sensitive and each error's shape name are read from
|
||||
`iam-cloudtrail-shapes.json`, which `make aws-data-sync` generates from the pinned botocore.
|
||||
|
||||
## Management Write Coverage
|
||||
|
||||
Successful Secrets Manager `PutSecretValue` and `UpdateSecret` API calls produce management
|
||||
records when a logging trail selects them. New trails include management events by default.
|
||||
Basic selectors honor `IncludeManagementEvents`, `ReadWriteType`, and source exclusions.
|
||||
Basic selectors honor `IncludeManagementEvents`, `ReadWriteType` (against each event's `readOnly`), and source exclusions.
|
||||
Advanced selectors evaluate `eventCategory`, `eventSource`, `eventName`, `readOnly`, `eventType`,
|
||||
and `userIdentity.arn`; unsupported fields do not match these records.
|
||||
|
||||
Records have `eventCategory: Management`, `managementEvent: true`, and `readOnly: false`.
|
||||
Records have `eventCategory: Management` and `managementEvent: true`; the Secrets Manager writes have `readOnly: false`.
|
||||
Sensitive secret values are omitted. Buffers and background S3 delivery retain the originating
|
||||
account, including when different accounts use the same trail name. Multi-region trails cover
|
||||
regions within their own partition.
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsController;
|
||||
import io.floci.aws.services.iam.AccessDeniedMessages;
|
||||
import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType;
|
||||
import io.floci.aws.services.iam.IamActionRegistry;
|
||||
import io.floci.aws.services.iam.IamCloudTrailEvents;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
|
||||
@@ -35,6 +36,7 @@ import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.ResourceInfo;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
@@ -481,7 +483,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
Optional<String> sessionTokenRefusal = iamService.sessionTokenRefusal(akid, action);
|
||||
if (sessionTokenRefusal.isPresent()) {
|
||||
LOG.debugv("Rejecting {0} signed with a session token that cannot reach it: {1}", action, akid);
|
||||
ctx.abortWith(queryXmlAccessDenied(sessionTokenRefusal.get()));
|
||||
abortIamAware(ctx, queryXmlAccessDenied(sessionTokenRefusal.get()), akid, action, credentialScope,
|
||||
region);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1276,7 +1279,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
+ " on resource: \"" + resource + "\""
|
||||
+ " " + PolicyType.IDENTITY_BASED_POLICY.noAllow(action);
|
||||
emitS3DenialIfApplicable(akid, operationAction, resource, ctx, region, denyMessage);
|
||||
ctx.abortWith(accessDeniedForRequest(action, credentialScope, ctx, resource));
|
||||
abortIamAware(ctx, accessDeniedForRequest(action, credentialScope, ctx, resource), akid, action,
|
||||
credentialScope, region);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1696,6 +1700,29 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses the request with {@code refusal}, recording an IAM API call as the CloudTrail management event
|
||||
* IAM records for the calls it runs, with the code, message and request ID the refusal answers with.
|
||||
*/
|
||||
private void abortIamAware(ContainerRequestContext ctx, Response refusal, String akid, String action,
|
||||
String credentialScope, String region) {
|
||||
if ("iam".equals(credentialScope)) {
|
||||
try {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
IamConditionContextResolver.formParameters(ctx).forEach(params::putSingle);
|
||||
CloudTrailService.ManagementEventInput event = IamCloudTrailEvents.denied(params, akid, region,
|
||||
currentVertxRequest.getCurrent(), refusal);
|
||||
if (event != null) {
|
||||
cloudTrailService.emitManagementEvent(event);
|
||||
}
|
||||
} 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}", action);
|
||||
}
|
||||
}
|
||||
ctx.abortWith(refusal);
|
||||
}
|
||||
|
||||
/** Records an S3 request IAM refused as a CloudTrail data event named {@code eventName}. */
|
||||
private void emitS3Denial(String akid, String eventName, String resource, String region, String denyMessage) {
|
||||
try {
|
||||
|
||||
@@ -33,6 +33,7 @@ import org.jboss.logging.Logger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -487,11 +488,34 @@ public class CloudTrailService implements StoredResourceArns, Resettable {
|
||||
|
||||
// --- Data plane: called by S3 (and other services) when an op happens ---
|
||||
|
||||
/**
|
||||
* One management API call. {@code requestParameters} and {@code responseElements} may be null,
|
||||
* which the record carries as a JSON null, as CloudTrail does for a call without parameters and
|
||||
* for a read-only call or a failed one. {@code sourceIp}, {@code userAgent} and
|
||||
* {@code requestId} are left out of the record, or generated for the request ID, when null.
|
||||
* {@code globalService} marks a call to a global service such as IAM, which a trail records only
|
||||
* when it includes global service events: "Setting this value to true only delivers global service
|
||||
* events to the trail if the trail is multi-Region or if the trail's home Region is the partition
|
||||
* leader Region" (botocore's CloudTrail model, {@code IncludeGlobalServiceEvents}).
|
||||
* {@code userIdentity} is the caller as {@link #userIdentity} read it before the call ran, for a call
|
||||
* that can remove the key it was signed with; when null it is read from {@code accessKeyId} here.
|
||||
*/
|
||||
public record ManagementEventInput(String eventSource, String eventName, String region, String accessKeyId,
|
||||
ObjectNode requestParameters, ObjectNode responseElements) {}
|
||||
ObjectNode requestParameters, ObjectNode responseElements,
|
||||
boolean readOnly, String sourceIp, String userAgent, String requestId,
|
||||
String errorCode, String errorMessage, boolean globalService,
|
||||
ObjectNode userIdentity) {
|
||||
|
||||
/** A successful write, from a caller whose address and agent are not known. */
|
||||
public ManagementEventInput(String eventSource, String eventName, String region, String accessKeyId,
|
||||
ObjectNode requestParameters, ObjectNode responseElements) {
|
||||
this(eventSource, eventName, region, accessKeyId, requestParameters, responseElements, false,
|
||||
null, null, null, null, null, false, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records one management write in the account's event history and returns the event only when
|
||||
* Records one management call in the account's event history and returns the event only when
|
||||
* a logging trail also selects it.
|
||||
*/
|
||||
public Optional<ObjectNode> emitManagementEvent(ManagementEventInput in) {
|
||||
@@ -500,7 +524,8 @@ public class CloudTrailService implements StoredResourceArns, Resettable {
|
||||
Instant eventTime = Instant.now();
|
||||
ObjectNode record = mapper.createObjectNode();
|
||||
record.put("eventVersion", EVENT_VERSION);
|
||||
record.put("eventTime", eventTime.toString());
|
||||
// ISO 8601 to the second, as every record CloudTrail's guide shows ("2014-07-16T15:49:27Z").
|
||||
record.put("eventTime", DateTimeFormatter.ISO_INSTANT.format(eventTime.truncatedTo(ChronoUnit.SECONDS)));
|
||||
record.put("eventSource", in.eventSource());
|
||||
record.put("eventName", in.eventName());
|
||||
record.put("awsRegion", region);
|
||||
@@ -508,14 +533,31 @@ public class CloudTrailService implements StoredResourceArns, Resettable {
|
||||
record.put("eventType", "AwsApiCall");
|
||||
record.put("eventCategory", "Management");
|
||||
record.put("managementEvent", true);
|
||||
record.put("readOnly", false);
|
||||
record.put("readOnly", in.readOnly());
|
||||
record.put("eventID", UUID.randomUUID().toString());
|
||||
record.put("requestID", UUID.randomUUID().toString());
|
||||
record.set("userIdentity", buildUserIdentity(in.accessKeyId()));
|
||||
record.set("requestParameters", in.requestParameters().deepCopy());
|
||||
record.set("responseElements", in.responseElements().deepCopy());
|
||||
record.put("requestID", in.requestId() != null ? in.requestId() : UUID.randomUUID().toString());
|
||||
record.set("userIdentity", in.userIdentity() != null
|
||||
? in.userIdentity().deepCopy() : buildUserIdentity(in.accessKeyId()));
|
||||
if (in.sourceIp() != null) {
|
||||
record.put("sourceIPAddress", in.sourceIp());
|
||||
}
|
||||
if (in.userAgent() != null) {
|
||||
record.put("userAgent", in.userAgent());
|
||||
}
|
||||
if (in.errorCode() != null) {
|
||||
record.put("errorCode", in.errorCode());
|
||||
if (in.errorMessage() != null) {
|
||||
record.put("errorMessage", in.errorMessage());
|
||||
}
|
||||
}
|
||||
record.set("requestParameters", in.requestParameters() == null
|
||||
? mapper.nullNode() : in.requestParameters().deepCopy());
|
||||
record.set("responseElements", in.responseElements() == null
|
||||
? mapper.nullNode() : in.responseElements().deepCopy());
|
||||
eventHistory.record(regionResolver.getAccountId(), region, eventTime, record);
|
||||
List<MatchedTrail> matched = trailsMatching(region, entry -> matchesManagementEvent(entry, record));
|
||||
List<MatchedTrail> matched = trailsMatching(region, entry ->
|
||||
(!in.globalService() || entry.trail().includeGlobalServiceEvents())
|
||||
&& matchesManagementEvent(entry, record));
|
||||
if (matched.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -871,9 +913,10 @@ public class CloudTrailService implements StoredResourceArns, Resettable {
|
||||
if (selectors == null || selectors.isEmpty()) {
|
||||
return !entry.trail().hasCustomEventSelectors();
|
||||
}
|
||||
String recordType = record.path("readOnly").asBoolean() ? "ReadOnly" : "WriteOnly";
|
||||
return selectors.stream().anyMatch(selector -> !Boolean.FALSE.equals(selector.includeManagementEvents())
|
||||
&& (selector.readWriteType() == null || "All".equalsIgnoreCase(selector.readWriteType())
|
||||
|| "WriteOnly".equalsIgnoreCase(selector.readWriteType()))
|
||||
|| recordType.equalsIgnoreCase(selector.readWriteType()))
|
||||
&& (selector.excludeManagementEventSources() == null
|
||||
|| !selector.excludeManagementEventSources().contains(record.path("eventSource").asText())));
|
||||
}
|
||||
@@ -1108,6 +1151,11 @@ public class CloudTrailService implements StoredResourceArns, Resettable {
|
||||
return record;
|
||||
}
|
||||
|
||||
/** The {@code userIdentity} a record names the caller signing with {@code accessKeyId} by, as IAM holds it now. */
|
||||
public ObjectNode userIdentity(String accessKeyId) {
|
||||
return buildUserIdentity(accessKeyId);
|
||||
}
|
||||
|
||||
private ObjectNode buildUserIdentity(String accessKeyId) {
|
||||
ObjectNode identity = mapper.createObjectNode();
|
||||
String accountId = regionResolver.getAccountId();
|
||||
|
||||
@@ -6,9 +6,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Which of IAM's own resources each IAM action is authorized against, read once from the vendored
|
||||
@@ -29,6 +31,10 @@ import java.util.Map;
|
||||
* drifts from what AWS publishes fails in CI rather than quietly authorizing against the wrong
|
||||
* resource. {@link SimulatedResourceTemplates} reads it for the templates a simulation names.
|
||||
*
|
||||
* <p>The file also lists the actions the reference gives neither the Write, the Permissions
|
||||
* management nor the Tagging access level: the Read and List ones, which CloudTrail records as
|
||||
* {@code readOnly}. {@link IamCloudTrailEvents} reads them through {@link #isReadOnly}.
|
||||
*
|
||||
* <p>An action absent from the file is one AWS does not publish, which is different from an action
|
||||
* published with no resource type: the first is a gap, the second is a wildcard on purpose. Both
|
||||
* read as {@link #typesOf} returning an empty list, and the caller treats both as {@code *}, but
|
||||
@@ -49,9 +55,13 @@ public final class IamActionResources {
|
||||
static final Catalog CATALOG = load();
|
||||
}
|
||||
|
||||
/** The two halves of the vendored file: what each action names, and how each type is spelled. */
|
||||
/**
|
||||
* The vendored file: what each action names, how each type is spelled, and which actions are
|
||||
* read-only.
|
||||
*/
|
||||
record Catalog(Map<String, List<String>> actionResources,
|
||||
Map<String, List<String>> resourceArnFormats) {
|
||||
Map<String, List<String>> resourceArnFormats,
|
||||
Set<String> readOnlyActions) {
|
||||
}
|
||||
|
||||
private IamActionResources() {
|
||||
@@ -73,6 +83,11 @@ public final class IamActionResources {
|
||||
return Holder.CATALOG.resourceArnFormats();
|
||||
}
|
||||
|
||||
/** Whether AWS gives {@code action} the Read or List access level; false for one it does not publish. */
|
||||
public static boolean isReadOnly(String action) {
|
||||
return action != null && Holder.CATALOG.readOnlyActions().contains(action);
|
||||
}
|
||||
|
||||
/** Every action the file carries, which is every action AWS publishes for IAM. */
|
||||
public static Map<String, List<String>> all() {
|
||||
return Holder.CATALOG.actionResources();
|
||||
@@ -106,7 +121,19 @@ public final class IamActionResources {
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Catalog(actions, formats);
|
||||
JsonNode readOnly = root.path("readOnlyActions");
|
||||
if (!readOnly.isArray() || readOnly.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no readOnlyActions");
|
||||
}
|
||||
Set<String> readOnlyActions = new HashSet<>();
|
||||
for (JsonNode action : readOnly) {
|
||||
if (!actions.containsKey(action.asText(""))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " lists " + action
|
||||
+ " as read-only, which is not one of its actions");
|
||||
}
|
||||
readOnlyActions.add(action.asText());
|
||||
}
|
||||
return new Catalog(actions, formats, Set.copyOf(readOnlyActions));
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> readLists(JsonNode node, String field) {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AccountResolver;
|
||||
import io.floci.aws.core.common.AwsPartition;
|
||||
import io.floci.aws.core.common.AwsPartitions;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.core.common.RequestSourceAddress;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.services.cloudtrail.CloudTrailService;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Records IAM API calls as CloudTrail management events, as the IAM User Guide says CloudTrail
|
||||
* does: "CloudTrail logs all authenticated API requests to IAM and AWS STS API operations"
|
||||
* (https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html). A call is recorded
|
||||
* whether it succeeds, fails, or is refused by IAM enforcement.
|
||||
*
|
||||
* <p>The record follows that page's and the CloudTrail log file examples' IAM events
|
||||
* (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-log-file-examples.html):
|
||||
* {@code eventSource} {@code iam.amazonaws.com}, {@code awsRegion} the partition's IAM signing Region
|
||||
* ({@code us-east-1} in {@code aws}), {@code requestParameters} the request's members, and
|
||||
* {@code responseElements} null for a read-only call, as "When logging a read-only event,
|
||||
* CloudTrail redacts the responseElements information", and the call's result otherwise. Which
|
||||
* call is read-only is AWS's Service Reference's access level ({@link IamActionResources#isReadOnly});
|
||||
* how each member is named and typed, which members are left out as sensitive, and the name each
|
||||
* error is recorded under are botocore's IAM model ({@link IamCloudTrailShapes}).
|
||||
*
|
||||
* <p>A call IAM enforcement refuses carries the code, the message and the request ID its refusal
|
||||
* answered with, so the record and the response match, and {@code "requestParameters": null}, as AWS
|
||||
* records an authorization refusal. Every call is recorded, a trail or not, since event history keeps
|
||||
* every management event.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IamCloudTrailEvents {
|
||||
|
||||
private static final String EVENT_SOURCE = ServicePrincipals.of("iam");
|
||||
|
||||
private final CloudTrailService cloudTrail;
|
||||
private final AccountResolver accounts;
|
||||
private final RequestContext requestContext;
|
||||
private final CurrentVertxRequest currentRequest;
|
||||
|
||||
@Inject
|
||||
public IamCloudTrailEvents(CloudTrailService cloudTrail, AccountResolver accounts,
|
||||
RequestContext requestContext, CurrentVertxRequest currentRequest) {
|
||||
this.cloudTrail = cloudTrail;
|
||||
this.accounts = accounts;
|
||||
this.requestContext = requestContext;
|
||||
this.currentRequest = currentRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller signing with {@code authorization}'s key, as a record names it, read before the call runs:
|
||||
* a call such as {@code DeleteAccessKey} can remove the very key it was signed with.
|
||||
*/
|
||||
public ObjectNode caller(String authorization) {
|
||||
return cloudTrail.userIdentity(accounts.extractAccessKeyId(authorization));
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the call {@code response} answered, made by {@code caller}, as {@link #caller} read it. It is
|
||||
* recorded whether or not a trail selects it, as event history keeps every management event.
|
||||
*/
|
||||
public void record(String action, MultivaluedMap<String, String> params, String authorization,
|
||||
ObjectNode caller, Response response) {
|
||||
if (response == null || !(response.getEntity() instanceof String xml)) {
|
||||
return;
|
||||
}
|
||||
Answer answer = Answer.of(xml, response.getStatus() >= 400);
|
||||
if ("UnsupportedOperation".equals(answer.errorCode())) {
|
||||
return;
|
||||
}
|
||||
// A read-only call's result is left out: "When logging a read-only event, CloudTrail redacts
|
||||
// the responseElements information".
|
||||
ObjectNode result = answer.errorCode() == null && !IamActionResources.isReadOnly(action)
|
||||
? IamCloudTrailShapes.get().result(action, xml) : null;
|
||||
cloudTrail.emitManagementEvent(event(action, params, accounts.extractAccessKeyId(authorization), caller,
|
||||
requestContext.getRegion(), request(currentRequest.getCurrent()), result, answer));
|
||||
}
|
||||
|
||||
/**
|
||||
* The record of a call IAM enforcement refused with {@code refusal} before IAM ran it, named after the
|
||||
* request's {@code Action} and carrying the code, message and request ID the refusal answered with; null
|
||||
* for a request that names none.
|
||||
*/
|
||||
public static CloudTrailService.ManagementEventInput denied(MultivaluedMap<String, String> params,
|
||||
String accessKeyId, String region,
|
||||
RoutingContext routingContext, Response refusal) {
|
||||
String action = params.getFirst("Action");
|
||||
if (action == null || action.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return event(action, null, accessKeyId, null, region, request(routingContext), null,
|
||||
Answer.of(refusal.getEntity() instanceof String xml ? xml : "", true));
|
||||
}
|
||||
|
||||
/** The request ID a Query response answered with, and for a failed one its error's code and message. */
|
||||
private record Answer(String requestId, String errorCode, String errorMessage) {
|
||||
|
||||
static Answer of(String xml, boolean failed) {
|
||||
String code = failed ? XmlParser.extractFirst(xml, "Code", null) : null;
|
||||
return new Answer(XmlParser.extractFirst(xml, "RequestId", null), code,
|
||||
code == null ? null : XmlParser.extractFirst(xml, "Message", null));
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpServerRequest request(RoutingContext routingContext) {
|
||||
return routingContext == null ? null : routingContext.request();
|
||||
}
|
||||
|
||||
private static CloudTrailService.ManagementEventInput event(String action, MultivaluedMap<String, String> params,
|
||||
String accessKeyId, ObjectNode caller, String region,
|
||||
HttpServerRequest request, ObjectNode result,
|
||||
Answer answer) {
|
||||
String sourceIp = request == null ? null : RequestSourceAddress.of(request);
|
||||
String userAgent = request == null ? null : request.getHeader("User-Agent");
|
||||
IamCloudTrailShapes shapes = IamCloudTrailShapes.get();
|
||||
// IAM's events are recorded in the Region IAM's global endpoint signs for in the request's
|
||||
// partition, and as a global service's, which only a trail including global service events records.
|
||||
Optional<AwsPartition.GlobalEndpoint> iam = AwsPartitions.forRegionOrCommercial(region).globalEndpoint("iam");
|
||||
return new CloudTrailService.ManagementEventInput(EVENT_SOURCE, action,
|
||||
iam.map(AwsPartition.GlobalEndpoint::signingRegion).orElse(region), accessKeyId,
|
||||
params == null ? null : shapes.requestParameters(action, params), result,
|
||||
IamActionResources.isReadOnly(action), sourceIp, userAgent, answer.requestId(),
|
||||
shapes.recordedErrorCode(answer.errorCode()), answer.errorMessage(), iam.isPresent(), caller);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsQueryLists;
|
||||
import io.floci.aws.core.common.VendoredResources;
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* IAM's request and result shapes as a CloudTrail record writes them, read once from the vendored
|
||||
* {@code aws/iam-cloudtrail-shapes.json}.
|
||||
*
|
||||
* <p>The file is generated by {@code tools/aws/regen_iam_cloudtrail_shapes.py} from botocore's IAM
|
||||
* model, through the shape walk every vendored shape file shares: every operation's input shape
|
||||
* ({@code operations}), its output shape and the element its result is wrapped in
|
||||
* ({@code results}), every shape they reach with its type and whether the model marks it
|
||||
* {@code sensitive}, and the code each modeled error answers with ({@code errors}). A
|
||||
* member is named with a lower first letter ({@code userName}, {@code tags: [{"key", "value"}]}),
|
||||
* a number, a boolean or a timestamp is written as one because its shape says so, and a sensitive
|
||||
* member is left out. {@code make aws-data-check} fails when it is stale against the pinned
|
||||
* botocore.
|
||||
*
|
||||
* <p>A missing or malformed resource is a build defect, not a runtime condition, so loading fails
|
||||
* with {@link IllegalStateException}.
|
||||
*/
|
||||
final class IamCloudTrailShapes {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/iam-cloudtrail-shapes.json";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Pattern INTEGER = Pattern.compile("[+-]?\\d+");
|
||||
|
||||
/**
|
||||
* A timestamp as CloudTrail writes one in an IAM record's {@code responseElements}, as the IAM
|
||||
* events of the CloudTrail log file examples do ({@code "createDate": "Jul 19, 2023 9:25:09 PM"},
|
||||
* https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-log-file-examples.html).
|
||||
*/
|
||||
private static final DateTimeFormatter RECORD_TIMESTAMP =
|
||||
DateTimeFormatter.ofPattern("MMM d, yyyy h:mm:ss a", Locale.US).withZone(ZoneOffset.UTC);
|
||||
|
||||
private static final class Holder {
|
||||
static final IamCloudTrailShapes SHAPES = VendoredResources.read(RESOURCE_NAME,
|
||||
"IAM CloudTrail shapes", in -> new IamCloudTrailShapes(MAPPER.readTree(in)));
|
||||
}
|
||||
|
||||
private final JsonNode operations;
|
||||
private final JsonNode results;
|
||||
private final JsonNode shapes;
|
||||
private final JsonNode errors;
|
||||
|
||||
private IamCloudTrailShapes(JsonNode model) {
|
||||
this.operations = model.path("operations");
|
||||
this.results = model.path("results");
|
||||
this.shapes = model.path("shapes");
|
||||
this.errors = model.path("errors");
|
||||
if (!operations.isObject() || operations.isEmpty() || !results.isObject() || results.isEmpty()
|
||||
|| !shapes.isObject() || shapes.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no operations, no results or no shapes");
|
||||
}
|
||||
}
|
||||
|
||||
static IamCloudTrailShapes get() {
|
||||
return Holder.SHAPES;
|
||||
}
|
||||
|
||||
/**
|
||||
* The members {@code params} carries for {@code operation}, without the sensitive ones; null for
|
||||
* an operation the model does not carry and for a request that carries none of its members.
|
||||
*/
|
||||
ObjectNode requestParameters(String operation, MultivaluedMap<String, String> params) {
|
||||
JsonNode input = shapes.path(operations.path(operation).asText(""));
|
||||
if (!input.has("members")) {
|
||||
return null;
|
||||
}
|
||||
ObjectNode read = readStructure(input, "", params);
|
||||
return read.isEmpty() ? null : read;
|
||||
}
|
||||
|
||||
/**
|
||||
* The result {@code xml} answers {@code operation} with, without the sensitive members; null
|
||||
* for an operation whose result the model does not wrap and for a result that carries nothing.
|
||||
*/
|
||||
ObjectNode result(String operation, String xml) {
|
||||
JsonNode entry = results.path(operation);
|
||||
String wrapper = entry.path("resultWrapper").asText("");
|
||||
if (wrapper.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
XmlParser.XmlElement result = XmlParser.extractElementTree(xml, wrapper);
|
||||
if (result == null) {
|
||||
return null;
|
||||
}
|
||||
JsonNode read = readElement(entry.path("shape").asText(), result);
|
||||
return read instanceof ObjectNode object && !object.isEmpty() ? object : null;
|
||||
}
|
||||
|
||||
/** The name of the error shape that answers {@code code}; a code IAM does not model is kept. */
|
||||
String recordedErrorCode(String code) {
|
||||
return code == null ? null : errors.path(code).asText(code);
|
||||
}
|
||||
|
||||
private ObjectNode readStructure(JsonNode structure, String prefix, MultivaluedMap<String, String> params) {
|
||||
ObjectNode read = MAPPER.createObjectNode();
|
||||
for (Map.Entry<String, JsonNode> member : structure.path("members").properties()) {
|
||||
JsonNode value = readParameter(member.getValue().asText(), prefix + member.getKey(), params);
|
||||
if (value != null) {
|
||||
read.set(lowerFirst(member.getKey()), value);
|
||||
}
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
private JsonNode readParameter(String shapeName, String param, MultivaluedMap<String, String> params) {
|
||||
JsonNode shape = shapes.path(shapeName);
|
||||
if (shape.path("sensitive").asBoolean()) {
|
||||
return null;
|
||||
}
|
||||
return switch (shape.path("type").asText()) {
|
||||
case "structure" -> {
|
||||
if (params.keySet().stream().noneMatch(key -> key.startsWith(param + "."))) {
|
||||
yield null;
|
||||
}
|
||||
ObjectNode read = readStructure(shape, param + ".", params);
|
||||
yield read.isEmpty() ? null : read;
|
||||
}
|
||||
case "list" -> {
|
||||
List<AwsQueryLists.IndexedMember> members = AwsQueryLists.members(params, param, null);
|
||||
if (members.isEmpty()) {
|
||||
yield null;
|
||||
}
|
||||
ArrayNode read = MAPPER.createArrayNode();
|
||||
for (AwsQueryLists.IndexedMember member : members) {
|
||||
JsonNode value = readParameter(shape.path("member").asText(), member.prefix(), params);
|
||||
if (value != null) {
|
||||
read.add(value);
|
||||
}
|
||||
}
|
||||
yield read;
|
||||
}
|
||||
case "map" -> {
|
||||
List<AwsQueryLists.IndexedMember> entries = AwsQueryLists.members(params, param, "entry");
|
||||
if (entries.isEmpty()) {
|
||||
yield null;
|
||||
}
|
||||
ObjectNode read = MAPPER.createObjectNode();
|
||||
for (AwsQueryLists.IndexedMember entry : entries) {
|
||||
String key = params.getFirst(entry.prefix() + ".key");
|
||||
if (key != null) {
|
||||
JsonNode value = readParameter(shape.path("value").asText(), entry.prefix() + ".value", params);
|
||||
read.set(key, value == null ? MAPPER.nullNode() : value);
|
||||
}
|
||||
}
|
||||
yield read;
|
||||
}
|
||||
default -> scalar(shape.path("type").asText(), params.getFirst(param), false);
|
||||
};
|
||||
}
|
||||
|
||||
private JsonNode readElement(String shapeName, XmlParser.XmlElement element) {
|
||||
JsonNode shape = shapes.path(shapeName);
|
||||
if (shape.path("sensitive").asBoolean()) {
|
||||
return null;
|
||||
}
|
||||
return switch (shape.path("type").asText()) {
|
||||
case "structure" -> {
|
||||
ObjectNode read = MAPPER.createObjectNode();
|
||||
JsonNode members = shape.path("members");
|
||||
for (XmlParser.XmlElement child : element.children()) {
|
||||
JsonNode member = members.path(child.name());
|
||||
JsonNode value = member.isTextual() ? readElement(member.asText(), child) : null;
|
||||
if (value != null) {
|
||||
read.set(lowerFirst(child.name()), value);
|
||||
}
|
||||
}
|
||||
yield read;
|
||||
}
|
||||
case "list" -> {
|
||||
ArrayNode read = MAPPER.createArrayNode();
|
||||
for (XmlParser.XmlElement child : element.children()) {
|
||||
JsonNode value = readElement(shape.path("member").asText(), child);
|
||||
if (value != null) {
|
||||
read.add(value);
|
||||
}
|
||||
}
|
||||
yield read;
|
||||
}
|
||||
case "map" -> {
|
||||
ObjectNode read = MAPPER.createObjectNode();
|
||||
for (XmlParser.XmlElement entry : element.children()) {
|
||||
XmlParser.XmlElement key = entry.child("key");
|
||||
XmlParser.XmlElement value = entry.child("value");
|
||||
if (key != null) {
|
||||
JsonNode entryValue = value == null ? null : readElement(shape.path("value").asText(), value);
|
||||
read.set(key.text(), entryValue == null ? MAPPER.nullNode() : entryValue);
|
||||
}
|
||||
}
|
||||
yield read;
|
||||
}
|
||||
default -> element.text().isEmpty() ? null : scalar(shape.path("type").asText(), element.rawText(), true);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A scalar as its shape types it; a value that does not read as its type is kept as the text
|
||||
* sent. A timestamp is rewritten only in a result, as CloudTrail writes one there.
|
||||
*/
|
||||
private static JsonNode scalar(String type, String value, boolean inResult) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
switch (type) {
|
||||
case "integer", "long" -> {
|
||||
if (INTEGER.matcher(trimmed).matches()) {
|
||||
return MAPPER.getNodeFactory().numberNode(new BigInteger(trimmed));
|
||||
}
|
||||
}
|
||||
case "double", "float" -> {
|
||||
try {
|
||||
return MAPPER.getNodeFactory().numberNode(new BigDecimal(trimmed));
|
||||
} catch (NumberFormatException expected) {
|
||||
// Not a number: kept as the text sent.
|
||||
}
|
||||
}
|
||||
case "boolean" -> {
|
||||
if ("true".equals(trimmed) || "false".equals(trimmed)) {
|
||||
return MAPPER.getNodeFactory().booleanNode(Boolean.parseBoolean(trimmed));
|
||||
}
|
||||
}
|
||||
case "timestamp" -> {
|
||||
if (inResult) {
|
||||
try {
|
||||
return MAPPER.getNodeFactory().textNode(RECORD_TIMESTAMP.format(Instant.parse(trimmed)));
|
||||
} catch (DateTimeParseException expected) {
|
||||
// Not an ISO 8601 instant: kept as the text sent.
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
// A string or a blob is written as sent.
|
||||
}
|
||||
}
|
||||
return MAPPER.getNodeFactory().textNode(value);
|
||||
}
|
||||
|
||||
private static String lowerFirst(String name) {
|
||||
return name.isEmpty() ? name : Character.toLowerCase(name.charAt(0)) + name.substring(1);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.*;
|
||||
import io.floci.aws.core.common.AwsQueryLists;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
@@ -106,6 +107,7 @@ public class IamQueryHandler {
|
||||
/** The caller this request signed as, which says whether a delegation bounds what it creates. */
|
||||
private final RequestContext requestContext;
|
||||
private final Instance<ServerCertificateReferenceProvider> serverCertificateReferenceProviders;
|
||||
private final IamCloudTrailEvents cloudTrailEvents;
|
||||
/** Signs each page's Marker, so only a marker this handler issued names an item. */
|
||||
private final SignedMarkers markers = new SignedMarkers(MARKER_MAX_LENGTH);
|
||||
|
||||
@@ -118,7 +120,8 @@ public class IamQueryHandler {
|
||||
CentralRootAccess centralRootAccess,
|
||||
RegionResolver regionResolver,
|
||||
RequestContext requestContext,
|
||||
Instance<ServerCertificateReferenceProvider> serverCertificateReferenceProviders) {
|
||||
Instance<ServerCertificateReferenceProvider> serverCertificateReferenceProviders,
|
||||
IamCloudTrailEvents cloudTrailEvents) {
|
||||
this.iamService = iamService;
|
||||
this.policyEvaluator = policyEvaluator;
|
||||
this.accountResolver = accountResolver;
|
||||
@@ -130,11 +133,19 @@ public class IamQueryHandler {
|
||||
this.centralRootAccess = centralRootAccess;
|
||||
this.regionResolver = regionResolver;
|
||||
this.serverCertificateReferenceProviders = serverCertificateReferenceProviders;
|
||||
this.cloudTrailEvents = cloudTrailEvents;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params, String authorization) {
|
||||
LOG.debugv("IAM action: {0}", action);
|
||||
// The caller is read before the call runs, which may delete the key it was signed with.
|
||||
ObjectNode caller = cloudTrailEvents.caller(authorization);
|
||||
Response response = dispatch(action, params, authorization);
|
||||
cloudTrailEvents.record(action, params, authorization, caller, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
private Response dispatch(String action, MultivaluedMap<String, String> params, String authorization) {
|
||||
try {
|
||||
IamArnShapes.checkPolicySourceArn(action, params);
|
||||
IamRequestShapes.check(action, params);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_iam_action_resources.py",
|
||||
"reference": "https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json",
|
||||
"retrieved": "2026-11-21",
|
||||
"retrieved": "2026-11-23",
|
||||
"note": "make iam-action-resources-verify checks every entry against AWS."
|
||||
},
|
||||
"actionResources": {
|
||||
@@ -544,5 +544,86 @@
|
||||
"user": [
|
||||
"arn:${Partition}:iam::${Account}:user/${UserNameWithPath}"
|
||||
]
|
||||
}
|
||||
},
|
||||
"readOnlyActions": [
|
||||
"GenerateCredentialReport",
|
||||
"GenerateOrganizationsAccessReport",
|
||||
"GenerateServiceLastAccessedDetails",
|
||||
"GetAccessKeyLastUsed",
|
||||
"GetAccountAuthorizationDetails",
|
||||
"GetAccountEmailAddress",
|
||||
"GetAccountName",
|
||||
"GetAccountPasswordPolicy",
|
||||
"GetAccountProperties",
|
||||
"GetAccountSummary",
|
||||
"GetCloudFrontPublicKey",
|
||||
"GetContextKeysForCustomPolicy",
|
||||
"GetContextKeysForPrincipalPolicy",
|
||||
"GetCredentialReport",
|
||||
"GetDelegationRequest",
|
||||
"GetGroup",
|
||||
"GetGroupPolicy",
|
||||
"GetHumanReadableSummary",
|
||||
"GetInstanceProfile",
|
||||
"GetLoginProfile",
|
||||
"GetMFADevice",
|
||||
"GetOpenIDConnectProvider",
|
||||
"GetOrganizationsAccessReport",
|
||||
"GetOutboundWebIdentityFederationInfo",
|
||||
"GetPolicy",
|
||||
"GetPolicyVersion",
|
||||
"GetRequestAuthorizationDetails",
|
||||
"GetRequestAuthorizationPolicy",
|
||||
"GetRole",
|
||||
"GetRolePolicy",
|
||||
"GetRoleTemplateVersion",
|
||||
"GetSAMLProvider",
|
||||
"GetSSHPublicKey",
|
||||
"GetServerCertificate",
|
||||
"GetServiceLastAccessedDetails",
|
||||
"GetServiceLastAccessedDetailsWithEntities",
|
||||
"GetServiceLinkedRoleDeletionStatus",
|
||||
"GetUser",
|
||||
"GetUserPolicy",
|
||||
"ListAccessKeys",
|
||||
"ListAccountAliases",
|
||||
"ListAttachedGroupPolicies",
|
||||
"ListAttachedRolePolicies",
|
||||
"ListAttachedUserPolicies",
|
||||
"ListCloudFrontPublicKeys",
|
||||
"ListDelegationRequests",
|
||||
"ListEntitiesForPolicy",
|
||||
"ListGroupPolicies",
|
||||
"ListGroups",
|
||||
"ListGroupsForUser",
|
||||
"ListInstanceProfileTags",
|
||||
"ListInstanceProfiles",
|
||||
"ListInstanceProfilesForRole",
|
||||
"ListMFADeviceTags",
|
||||
"ListMFADevices",
|
||||
"ListOpenIDConnectProviderTags",
|
||||
"ListOpenIDConnectProviders",
|
||||
"ListOrganizationsFeatures",
|
||||
"ListPolicies",
|
||||
"ListPoliciesGrantingServiceAccess",
|
||||
"ListPolicyTags",
|
||||
"ListPolicyVersions",
|
||||
"ListRolePolicies",
|
||||
"ListRoleTags",
|
||||
"ListRoles",
|
||||
"ListSAMLProviderTags",
|
||||
"ListSAMLProviders",
|
||||
"ListSSHPublicKeys",
|
||||
"ListSTSRegionalEndpointsStatus",
|
||||
"ListServerCertificateTags",
|
||||
"ListServerCertificates",
|
||||
"ListServiceSpecificCredentials",
|
||||
"ListSigningCertificates",
|
||||
"ListUserPolicies",
|
||||
"ListUserTags",
|
||||
"ListUsers",
|
||||
"ListVirtualMFADevices",
|
||||
"SimulateCustomPolicy",
|
||||
"SimulatePrincipalPolicy"
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -10,7 +10,7 @@ import java.io.ByteArrayInputStream;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.floci.aws.testing.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
@@ -13,7 +13,7 @@ import java.io.ByteArrayInputStream;
|
||||
import java.util.UUID;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.floci.aws.testing.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.floci.aws.testing.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.floci.aws.testing.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
@@ -110,6 +110,27 @@ class CloudTrailManagementEventTest {
|
||||
assertTrue(service.emitManagementEvent(event("cn-north-1")).isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* A global service's event, such as IAM's, reaches only a trail that includes global service events: "Setting
|
||||
* this value to true only delivers global service events to the trail" (botocore, IncludeGlobalServiceEvents).
|
||||
*/
|
||||
@Test
|
||||
void aGlobalServiceEventReachesOnlyTheTrailsThatIncludeGlobalServiceEvents() {
|
||||
trail(false);
|
||||
service.createTrail(REGION, "global-trail", "example-audit-logs", null, null, true, false, false, false);
|
||||
service.startLogging(REGION, "management-trail");
|
||||
service.startLogging(REGION, "global-trail");
|
||||
|
||||
service.emitManagementEvent(new CloudTrailService.ManagementEventInput("iam.amazonaws.com", "CreateUser",
|
||||
REGION, "test", MAPPER.createObjectNode().put("userName", "alice"), null, false, null, null, null,
|
||||
null, null, true, null)).orElseThrow();
|
||||
|
||||
assertEquals(0, service.pendingRecordCount(new CloudTrailService.TrailKey(REGION, "management-trail", REGION)));
|
||||
assertEquals(1, service.pendingRecordCount(new CloudTrailService.TrailKey(REGION, "global-trail", REGION)));
|
||||
service.emitManagementEvent(event(REGION)).orElseThrow();
|
||||
assertEquals(1, service.pendingRecordCount(new CloudTrailService.TrailKey(REGION, "management-trail", REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleTrailsRecordTheSameEventIdAndKeepIndependentCopies() {
|
||||
trail(false);
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package io.floci.aws.services.cloudtrail;
|
||||
|
||||
import io.restassured.response.Response;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** CloudTrail's JSON 1.1 calls, as the integration tests send them: the action in {@code X-Amz-Target}. */
|
||||
final class CloudTrailRequests {
|
||||
|
||||
private CloudTrailRequests() {
|
||||
}
|
||||
|
||||
static Response invokeCloudTrail(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "CloudTrail_20131101." + action)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body)
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.cloudtrail;
|
||||
|
||||
import io.floci.aws.testing.CloudTrailLogFiles;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -9,7 +10,7 @@ import org.junit.jupiter.api.Test;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.services.cloudtrail.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.floci.aws.testing.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@@ -87,6 +87,26 @@ class IamActionResourcesTest {
|
||||
"resourceArnFormats":{"role":["arn:${Partition}:iam::${Account}:role/${Name}"]}}"""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReadAndListActionsAreReadOnly() {
|
||||
assertTrue(IamActionResources.isReadOnly("GetUser"));
|
||||
assertTrue(IamActionResources.isReadOnly("ListAccessKeys"));
|
||||
assertTrue(IamActionResources.isReadOnly("GenerateCredentialReport"));
|
||||
assertTrue(IamActionResources.isReadOnly("SimulatePrincipalPolicy"));
|
||||
assertFalse(IamActionResources.isReadOnly("CreateUser"));
|
||||
assertFalse(IamActionResources.isReadOnly("PutRolePolicy"));
|
||||
assertFalse(IamActionResources.isReadOnly("TagUser"));
|
||||
assertFalse(IamActionResources.isReadOnly("NotAnAction"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReadOnlyActionTheFileDoesNotCarryIsABuildDefect() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
{"actionResources":{"GetUser":["user"]},
|
||||
"resourceArnFormats":{"user":["arn:${Partition}:iam::${Account}:user/${Name}"]},
|
||||
"readOnlyActions":["ListUsers"]}"""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankEntryIsABuildDefect() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("""
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.services.cloudtrail.CloudTrailLogWriter;
|
||||
import io.floci.aws.testing.CloudTrailLogFiles;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.QueryRequests;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.CloudTrailRequests.invokeCloudTrail;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.emptyOrNullString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* IAM API calls reach a trail's log files as CloudTrail management events, whether IAM ran them,
|
||||
* refused them, or IAM enforcement refused them first.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamCloudTrailIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "661100000231";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@Inject
|
||||
CloudTrailLogWriter writer;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamCallsAreRecordedAsManagementEvents() throws IOException {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String user = "ct-user-" + suffix;
|
||||
String logs = startTrail(suffix);
|
||||
|
||||
createUser(user, "Tags.member.1.Key", "team", "Tags.member.1.Value", "it");
|
||||
String accessKeyId = createAccessKey(user);
|
||||
iam(ACCOUNT, "GetUser", "UserName", user).statusCode(200);
|
||||
XmlPath refusal = iam(accessKeyId, "CreateUser", "UserName", user + "-other").statusCode(403)
|
||||
.extract().xmlPath();
|
||||
iam(ACCOUNT, "UpdateAccessKey", "UserName", user, "AccessKeyId", accessKeyId,
|
||||
"Status", "Inactive").statusCode(200);
|
||||
iam(ACCOUNT, "DeleteUser", "UserName", "ct-missing-" + suffix).statusCode(404);
|
||||
|
||||
List<JsonNode> records = iamRecords(logs, suffix);
|
||||
|
||||
JsonNode createUser = only(records, "CreateUser", ACCOUNT);
|
||||
assertThat(createUser.path("eventCategory").asText(), equalTo("Management"));
|
||||
assertThat(createUser.path("managementEvent").asBoolean(), equalTo(true));
|
||||
assertThat(createUser.path("readOnly").asBoolean(), equalTo(false));
|
||||
assertThat(createUser.path("awsRegion").asText(), equalTo("us-east-1"));
|
||||
assertThat(createUser.path("eventTime").asText(), matchesPattern("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z"));
|
||||
assertThat(createUser.path("recipientAccountId").asText(), equalTo(ACCOUNT));
|
||||
assertThat(createUser.path("sourceIPAddress").asText(), equalTo("127.0.0.1"));
|
||||
assertThat(createUser.path("userAgent").asText(), not(emptyOrNullString()));
|
||||
assertThat(createUser.path("requestParameters").path("userName").asText(), equalTo(user));
|
||||
assertThat(createUser.path("requestParameters").path("tags").get(0).path("key").asText(), equalTo("team"));
|
||||
assertThat(createUser.path("requestParameters").path("tags").get(0).path("value").asText(), equalTo("it"));
|
||||
assertThat(createUser.path("responseElements").path("user").path("userName").asText(), equalTo(user));
|
||||
assertThat(createUser.path("responseElements").path("user").path("createDate").asText(),
|
||||
matchesPattern("[A-Z][a-z]{2} \\d{1,2}, \\d{4} \\d{1,2}:\\d{2}:\\d{2} [AP]M"));
|
||||
|
||||
JsonNode createKey = only(records, "CreateAccessKey", ACCOUNT);
|
||||
JsonNode created = createKey.path("responseElements").path("accessKey");
|
||||
assertThat(created.path("accessKeyId").asText(), equalTo(accessKeyId));
|
||||
assertThat(created.path("secretAccessKey").isMissingNode(), equalTo(true));
|
||||
|
||||
JsonNode getUser = only(records, "GetUser", ACCOUNT);
|
||||
assertThat(getUser.path("readOnly").asBoolean(), equalTo(true));
|
||||
assertThat(getUser.path("responseElements").isNull(), equalTo(true));
|
||||
|
||||
JsonNode denied = only(records, "CreateUser", accessKeyId);
|
||||
assertThat(denied.path("errorCode").asText(), equalTo("AccessDenied"));
|
||||
// The record carries what the refusal answered, so the two can be matched by message and request ID.
|
||||
assertThat(denied.path("errorMessage").asText(), equalTo(refusal.getString("ErrorResponse.Error.Message")));
|
||||
assertThat(denied.path("requestID").asText(), equalTo(refusal.getString("ErrorResponse.RequestId")));
|
||||
assertThat(denied.path("userIdentity").path("userName").asText(), equalTo(user));
|
||||
assertThat(denied.path("requestParameters").isNull(), equalTo(true));
|
||||
assertThat(denied.path("responseElements").isNull(), equalTo(true));
|
||||
|
||||
JsonNode deactivated = only(records, "UpdateAccessKey", ACCOUNT);
|
||||
assertThat(deactivated.path("requestParameters").path("accessKeyId").asText(), equalTo(accessKeyId));
|
||||
assertThat(deactivated.path("requestParameters").path("status").asText(), equalTo("Inactive"));
|
||||
assertThat(deactivated.path("responseElements").isNull(), equalTo(true));
|
||||
|
||||
JsonNode missing = only(records, "DeleteUser", ACCOUNT);
|
||||
assertThat(missing.path("errorCode").asText(), equalTo("NoSuchEntityException"));
|
||||
assertThat(missing.path("requestParameters").path("userName").asText(), equalTo("ct-missing-" + suffix));
|
||||
assertThat(missing.path("errorMessage").asText(), not(emptyOrNullString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordsAreLeftOutOfTheRecord() throws IOException {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String user = "ct-login-" + suffix;
|
||||
String logs = startTrail(suffix);
|
||||
createUser(user);
|
||||
iam(ACCOUNT, "CreateLoginProfile", "UserName", user, "Password", "Sup3r-secret-" + suffix,
|
||||
"PasswordResetRequired", "true").statusCode(200);
|
||||
iam(ACCOUNT, "DeleteLoginProfile", "UserName", user).statusCode(200);
|
||||
|
||||
JsonNode login = only(iamRecords(logs, suffix), "CreateLoginProfile", ACCOUNT);
|
||||
assertThat(login.path("requestParameters").path("userName").asText(), equalTo(user));
|
||||
assertThat(login.path("requestParameters").path("passwordResetRequired").isBoolean(), equalTo(true));
|
||||
assertThat(login.path("requestParameters").has("password"), equalTo(false));
|
||||
assertThat(login.toString().contains("Sup3r-secret-"), equalTo(false));
|
||||
assertThat(login.path("responseElements").path("loginProfile").path("passwordResetRequired").isBoolean(),
|
||||
equalTo(true));
|
||||
}
|
||||
|
||||
/** Starts a trail named after {@code suffix}, including global service events, and returns its bucket. */
|
||||
private String startTrail(String suffix) {
|
||||
String bucket = "ct-iam-logs-" + suffix;
|
||||
startTrail("ct-iam-" + suffix, bucket, true);
|
||||
return bucket;
|
||||
}
|
||||
|
||||
/** Creates {@code user} with {@code params}, removing it after the test. */
|
||||
private void createUser(String user, String... params) {
|
||||
String[] request = new String[params.length + 2];
|
||||
request[0] = "UserName";
|
||||
request[1] = user;
|
||||
System.arraycopy(params, 0, request, 2, params.length);
|
||||
iam(ACCOUNT, "CreateUser", request).statusCode(200);
|
||||
cleanup.register(() -> EnforcementFixtures.removeUser(baseUri.getPort(), auth(ACCOUNT, "iam"), user));
|
||||
}
|
||||
|
||||
private String createAccessKey(String user) {
|
||||
return iam(ACCOUNT, "CreateAccessKey", "UserName", user).statusCode(200).extract().xmlPath()
|
||||
.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
private void startTrail(String trail, String bucket, boolean includeGlobalServiceEvents) {
|
||||
given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "s3"))
|
||||
.when().put("/" + bucket).then().statusCode(200);
|
||||
cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), auth(ACCOUNT, "s3"), bucket));
|
||||
cloudTrail("CreateTrail", "{\"Name\":\"" + trail + "\",\"S3BucketName\":\"" + bucket
|
||||
+ "\",\"IncludeGlobalServiceEvents\":" + includeGlobalServiceEvents + "}");
|
||||
cleanup.register(() -> cloudTrail("DeleteTrail", "{\"Name\":\"" + trail + "\"}"));
|
||||
cloudTrail("StartLogging", "{\"Name\":\"" + trail + "\"}");
|
||||
}
|
||||
|
||||
/** A key that deletes itself is recorded as its user's, as the caller was before the call removed the key. */
|
||||
@Test
|
||||
void aKeyDeletingItselfIsRecordedAsItsUser() throws IOException {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String user = "ct-rotate-" + suffix;
|
||||
String logs = startTrail(suffix);
|
||||
createUser(user);
|
||||
iam(ACCOUNT, "PutUserPolicy", "UserName", user, "PolicyName", "rotate", "PolicyDocument",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iam:DeleteAccessKey\","
|
||||
+ "\"Resource\":\"*\"}]}").statusCode(200);
|
||||
String accessKeyId = createAccessKey(user);
|
||||
|
||||
iam(accessKeyId, "DeleteAccessKey", "UserName", user, "AccessKeyId", accessKeyId).statusCode(200);
|
||||
|
||||
JsonNode deleted = only(iamRecords(logs, suffix), "DeleteAccessKey", accessKeyId);
|
||||
assertThat(deleted.path("userIdentity").path("userName").asText(), equalTo(user));
|
||||
assertThat(deleted.path("errorCode").isMissingNode(), equalTo(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* A call a session token without MFA cannot make is refused before IAM's policies are read, and recorded as
|
||||
* the refusal answered it.
|
||||
*/
|
||||
@Test
|
||||
void aSessionTokenRefusalIsRecorded() throws IOException {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String user = "ct-session-" + suffix;
|
||||
String logs = startTrail(suffix);
|
||||
createUser(user);
|
||||
String accessKeyId = createAccessKey(user);
|
||||
XmlPath session = QueryRequests.request(accessKeyId, "sts", "GetSessionToken").formParam("Version", "2011-06-15")
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
String credentials = "GetSessionTokenResponse.GetSessionTokenResult.Credentials.";
|
||||
String sessionKey = session.getString(credentials + "AccessKeyId");
|
||||
|
||||
XmlPath refusal = QueryRequests.request(sessionKey, "iam", "ListUsers")
|
||||
.header("X-Amz-Security-Token", session.getString(credentials + "SessionToken"))
|
||||
.formParam("Version", "2010-05-08").when().post("/").then().statusCode(403).extract().xmlPath();
|
||||
|
||||
JsonNode refused = only(iamRecords(logs, sessionKey), "ListUsers", sessionKey);
|
||||
assertThat(refused.path("errorCode").asText(), equalTo("AccessDenied"));
|
||||
assertThat(refused.path("errorMessage").asText(), equalTo(refusal.getString("ErrorResponse.Error.Message")));
|
||||
assertThat(refused.path("requestParameters").isNull(), equalTo(true));
|
||||
}
|
||||
|
||||
/** Event history keeps every management event, IAM's among them, whether or not a trail records it. */
|
||||
@Test
|
||||
void iamCallsReachEventHistoryWithoutATrail() {
|
||||
String user = "ct-history-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
createUser(user);
|
||||
|
||||
List<String> events = invokeCloudTrail(auth(ACCOUNT, "cloudtrail"), "LookupEvents",
|
||||
"{\"LookupAttributes\":[{\"AttributeKey\":\"EventName\",\"AttributeValue\":\"CreateUser\"}]}")
|
||||
.then().statusCode(200).extract().jsonPath().getList("Events.CloudTrailEvent", String.class);
|
||||
assertThat(events.stream().filter(event -> event.contains("\"eventName\":\"CreateUser\"")
|
||||
&& event.contains("\"userName\":\"" + user + "\"")).count(), equalTo(1L));
|
||||
}
|
||||
|
||||
/** IAM is a global service, so a trail that leaves out global service events records none of its calls. */
|
||||
@Test
|
||||
void onlyATrailIncludingGlobalServiceEventsRecordsIamCalls() throws IOException {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String user = "ct-global-" + suffix;
|
||||
String included = startTrail(suffix);
|
||||
String excluded = "ct-iam-regional-" + suffix;
|
||||
startTrail(excluded, excluded, false);
|
||||
|
||||
createUser(user);
|
||||
|
||||
only(iamRecords(included, suffix), "CreateUser", ACCOUNT);
|
||||
assertThat(iamRecords(excluded, suffix), hasSize(0));
|
||||
}
|
||||
|
||||
private void cloudTrail(String action, String body) {
|
||||
invokeCloudTrail(auth(ACCOUNT, "cloudtrail"), action, body).then().statusCode(200);
|
||||
}
|
||||
|
||||
private ValidatableResponse iam(String accessKeyId, String action, String... params) {
|
||||
return QueryRequests.request(accessKeyId, "iam", action, params).formParam("Version", "2010-05-08")
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
/**
|
||||
* The IAM records of this test's calls, read from the log files the writer delivers to {@code bucket}: those
|
||||
* whose parameters, caller or caller's key carry {@code marker}.
|
||||
*/
|
||||
private List<JsonNode> iamRecords(String bucket, String marker) throws IOException {
|
||||
writer.flushNow();
|
||||
return CloudTrailLogFiles.records(bucket, auth(ACCOUNT, "s3")).stream()
|
||||
.filter(record -> "iam.amazonaws.com".equals(record.path("eventSource").asText()))
|
||||
.filter(record -> record.path("requestParameters").toString().contains(marker)
|
||||
|| record.path("userIdentity").path("userName").asText().contains(marker)
|
||||
|| record.path("userIdentity").path("accessKeyId").asText().equals(marker))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static JsonNode only(List<JsonNode> records, String eventName, String accessKeyId) {
|
||||
List<JsonNode> found = records.stream()
|
||||
.filter(record -> eventName.equals(record.path("eventName").asText()))
|
||||
.filter(record -> accessKeyId.equals(record.path("userIdentity").path("accessKeyId").asText()))
|
||||
.toList();
|
||||
assertThat(eventName + " by " + accessKeyId + " in " + records, found, hasSize(1));
|
||||
return found.getFirst();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
class IamCloudTrailShapesTest {
|
||||
|
||||
private static final IamCloudTrailShapes SHAPES = IamCloudTrailShapes.get();
|
||||
|
||||
private static MultivaluedMap<String, String> params(String... pairs) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
for (int i = 0; i < pairs.length; i += 2) {
|
||||
params.putSingle(pairs[i], pairs[i + 1]);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestParametersAreTheMembersWithALowerFirstLetterAndTheirModelTypes() {
|
||||
ObjectNode read = SHAPES.requestParameters("CreateRole", params("Action", "CreateRole",
|
||||
"Version", "2010-05-08", "RoleName", "ops", "AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\"}",
|
||||
"MaxSessionDuration", "7200", "Tags.member.1.Key", "team", "Tags.member.1.Value", "it",
|
||||
"Tags.member.2.Key", "env", "Tags.member.2.Value", "prod"));
|
||||
assertThat(read.path("roleName").asText(), equalTo("ops"));
|
||||
assertThat(read.path("assumeRolePolicyDocument").asText(), equalTo("{\"Version\":\"2012-10-17\"}"));
|
||||
assertThat(read.path("maxSessionDuration").isNumber(), equalTo(true));
|
||||
assertThat(read.path("maxSessionDuration").asInt(), equalTo(7200));
|
||||
assertThat(read.path("tags").size(), equalTo(2));
|
||||
assertThat(read.path("tags").get(1).path("key").asText(), equalTo("env"));
|
||||
assertThat(read.path("tags").get(1).path("value").asText(), equalTo("prod"));
|
||||
assertThat(read.has("action"), equalTo(false));
|
||||
assertThat(read.has("version"), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aListOfStringsIsAnArrayOfThem() {
|
||||
ObjectNode read = SHAPES.requestParameters("UntagUser", params("Action", "UntagUser",
|
||||
"UserName", "alice", "TagKeys.member.1", "team", "TagKeys.member.2", "env"));
|
||||
assertThat(read.path("userName").asText(), equalTo("alice"));
|
||||
assertThat(read.path("tagKeys").size(), equalTo(2));
|
||||
assertThat(read.path("tagKeys").get(0).asText(), equalTo("team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallWhoseOnlyMembersAreSensitiveHasNoRequestParameters() {
|
||||
assertThat(SHAPES.requestParameters("ChangePassword",
|
||||
params("Action", "ChangePassword", "OldPassword", "old-one", "NewPassword", "new-one")), nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSensitiveMemberIsLeftOutOfTheRequestParameters() {
|
||||
ObjectNode read = SHAPES.requestParameters("CreateLoginProfile", params("Action", "CreateLoginProfile",
|
||||
"UserName", "alice", "Password", "s3cr3t-P@ss", "PasswordResetRequired", "true"));
|
||||
assertThat(read.has("password"), equalTo(false));
|
||||
assertThat(read.path("userName").asText(), equalTo("alice"));
|
||||
assertThat(read.path("passwordResetRequired").isBoolean(), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOperationTheModelDoesNotCarryHasNoRequestParameters() {
|
||||
assertThat(SHAPES.requestParameters("MadeUpOperation", params("UserName", "alice")), nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theResultLeavesSecretsOutAndWritesTimestampsAsCloudTrailDoes() {
|
||||
String xml = """
|
||||
<CreateAccessKeyResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
|
||||
<CreateAccessKeyResult><AccessKey>
|
||||
<UserName>alice</UserName><AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>
|
||||
<Status>Active</Status><SecretAccessKey>wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY</SecretAccessKey>
|
||||
<CreateDate>2023-07-19T21:25:09Z</CreateDate>
|
||||
</AccessKey></CreateAccessKeyResult>
|
||||
<ResponseMetadata><RequestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</RequestId></ResponseMetadata>
|
||||
</CreateAccessKeyResponse>""";
|
||||
ObjectNode result = SHAPES.result("CreateAccessKey", xml);
|
||||
assertThat(result.path("accessKey").path("accessKeyId").asText(), equalTo("AKIAIOSFODNN7EXAMPLE"));
|
||||
assertThat(result.path("accessKey").has("secretAccessKey"), equalTo(false));
|
||||
assertThat(result.path("accessKey").path("createDate").asText(), equalTo("Jul 19, 2023 9:25:09 PM"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceSpecificCredentialsPasswordIsLeftOutOfTheResult() {
|
||||
String xml = """
|
||||
<CreateServiceSpecificCredentialResponse><CreateServiceSpecificCredentialResult>
|
||||
<ServiceSpecificCredential>
|
||||
<UserName>alice</UserName><ServiceName>codecommit.amazonaws.com</ServiceName>
|
||||
<ServiceUserName>alice-at-123456789012</ServiceUserName><ServicePassword>p4ss</ServicePassword>
|
||||
<ServiceSpecificCredentialId>ACCAEXAMPLE123EXAMPLE</ServiceSpecificCredentialId>
|
||||
<Status>Active</Status><CreateDate>2024-10-29T14:43:20Z</CreateDate>
|
||||
</ServiceSpecificCredential>
|
||||
</CreateServiceSpecificCredentialResult></CreateServiceSpecificCredentialResponse>""";
|
||||
ObjectNode credential = (ObjectNode) SHAPES.result("CreateServiceSpecificCredential", xml)
|
||||
.path("serviceSpecificCredential");
|
||||
assertThat(credential.has("servicePassword"), equalTo(false));
|
||||
assertThat(credential.path("serviceUserName").asText(), equalTo("alice-at-123456789012"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"NoSuchEntity,NoSuchEntityException", "DeleteConflict,DeleteConflictException",
|
||||
"MalformedPolicyDocument,MalformedPolicyDocumentException", "ReportInProgress,CredentialReportNotReadyException",
|
||||
"NotSupportedService,ServiceNotSupportedException", "AccessDenied,AccessDenied",
|
||||
"ValidationError,ValidationError"})
|
||||
void modeledErrorsAreRecordedUnderTheirShapesName(String code, String recorded) {
|
||||
assertThat(SHAPES.recordedErrorCode(code), equalTo(recorded));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theResultTypesBooleansAndNumbersAsTheModelDoes() {
|
||||
String xml = """
|
||||
<CreatePolicyResponse><CreatePolicyResult><Policy>
|
||||
<PolicyName>Level3</PolicyName><DefaultVersionId>v1</DefaultVersionId>
|
||||
<AttachmentCount>0</AttachmentCount><PermissionsBoundaryUsageCount>0</PermissionsBoundaryUsageCount>
|
||||
<IsAttachable>true</IsAttachable><PolicyId>ANPAHI17SXDY4VPL1N1K8</PolicyId>
|
||||
<Description>true</Description>
|
||||
</Policy></CreatePolicyResult></CreatePolicyResponse>""";
|
||||
ObjectNode policy = (ObjectNode) SHAPES.result("CreatePolicy", xml).path("policy");
|
||||
assertThat(policy.path("attachmentCount").isNumber(), equalTo(true));
|
||||
assertThat(policy.path("permissionsBoundaryUsageCount").isNumber(), equalTo(true));
|
||||
assertThat(policy.path("isAttachable").isBoolean(), equalTo(true));
|
||||
assertThat(policy.path("defaultVersionId").asText(), equalTo("v1"));
|
||||
assertThat(policy.path("description").isTextual(), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aListInTheResultIsAnArrayAndAnEmptyResultIsNull() {
|
||||
String xml = """
|
||||
<AddUserToGroupResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
|
||||
<ResponseMetadata><RequestId>1</RequestId></ResponseMetadata>
|
||||
</AddUserToGroupResponse>""";
|
||||
assertThat(SHAPES.result("AddUserToGroup", xml), nullValue());
|
||||
String listed = """
|
||||
<CreateRoleResponse><CreateRoleResult><Role>
|
||||
<RoleName>ops</RoleName><MaxSessionDuration>3600</MaxSessionDuration>
|
||||
<Tags><member><Key>a</Key><Value>1</Value></member></Tags>
|
||||
</Role></CreateRoleResult></CreateRoleResponse>""";
|
||||
ObjectNode role = (ObjectNode) SHAPES.result("CreateRole", listed).path("role");
|
||||
assertThat(role.path("tags").get(0).path("key").asText(), equalTo("a"));
|
||||
assertThat(role.path("tags").get(0).path("value").asText(), equalTo("1"));
|
||||
assertThat(role.path("maxSessionDuration").isNumber(), equalTo(true));
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ class IamQueryHandlerTest {
|
||||
when(service.getServerCertificate(CERTIFICATE_NAME)).thenReturn(certificate);
|
||||
when(service.listServerCertificates(null)).thenReturn(List.of(certificate));
|
||||
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null,
|
||||
new RequestContext(), null);
|
||||
new RequestContext(), null, mock(IamCloudTrailEvents.class));
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ServerCertificateName", CERTIFICATE_NAME);
|
||||
@@ -94,7 +94,7 @@ class IamQueryHandlerTest {
|
||||
when(service.createRole(ROLE_NAME, "/", EMPTY_POLICY_DOCUMENT, null, 3600, Map.of(), null)).thenReturn(role);
|
||||
when(service.getValidatedRole(ROLE_NAME)).thenReturn(role);
|
||||
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null,
|
||||
new RequestContext(), null);
|
||||
new RequestContext(), null, mock(IamCloudTrailEvents.class));
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("RoleName", ROLE_NAME);
|
||||
|
||||
+24
-7
@@ -1,4 +1,4 @@
|
||||
package io.floci.aws.services.cloudtrail;
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -14,7 +14,7 @@ import java.util.zip.GZIPInputStream;
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** Reads the records a trail delivered to its S3 bucket, through the S3 API, as a client of the trail would. */
|
||||
final class CloudTrailLogFiles {
|
||||
public final class CloudTrailLogFiles {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@@ -22,10 +22,22 @@ final class CloudTrailLogFiles {
|
||||
}
|
||||
|
||||
/** Every record of every log file in {@code bucket}, in key order, across every page of the listing. */
|
||||
static List<JsonNode> records(String bucket) throws IOException {
|
||||
public static List<JsonNode> records(String bucket) throws IOException {
|
||||
return records(bucket, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #records(String)}, with each S3 request signed with {@code authorization} when it is not
|
||||
* null, as a test under IAM enforcement needs.
|
||||
*/
|
||||
public static List<JsonNode> records(String bucket, String authorization) throws IOException {
|
||||
List<JsonNode> records = new ArrayList<>();
|
||||
for (String key : keys(bucket)) {
|
||||
byte[] gz = given().when().get("/" + bucket + "/" + key).then().statusCode(200).extract().asByteArray();
|
||||
for (String key : keys(bucket, authorization)) {
|
||||
if (!key.endsWith(".json.gz")) {
|
||||
continue;
|
||||
}
|
||||
byte[] gz = request(authorization).when().get("/" + bucket + "/" + key)
|
||||
.then().statusCode(200).extract().asByteArray();
|
||||
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(gz))) {
|
||||
MAPPER.readTree(in).path("Records").forEach(records::add);
|
||||
}
|
||||
@@ -33,11 +45,11 @@ final class CloudTrailLogFiles {
|
||||
return records;
|
||||
}
|
||||
|
||||
private static List<String> keys(String bucket) {
|
||||
private static List<String> keys(String bucket, String authorization) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
String token = null;
|
||||
do {
|
||||
RequestSpecification listing = given().queryParam("list-type", "2");
|
||||
RequestSpecification listing = request(authorization).queryParam("list-type", "2");
|
||||
if (token != null) {
|
||||
listing = listing.queryParam("continuation-token", token);
|
||||
}
|
||||
@@ -48,4 +60,9 @@ final class CloudTrailLogFiles {
|
||||
} while (token != null);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static RequestSpecification request(String authorization) {
|
||||
RequestSpecification request = given();
|
||||
return authorization == null ? request : request.header("Authorization", authorization);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** CloudTrail's JSON 1.1 calls, as the integration tests send them: the action in {@code X-Amz-Target}. */
|
||||
public final class CloudTrailRequests {
|
||||
|
||||
private CloudTrailRequests() {
|
||||
}
|
||||
|
||||
public static Response invokeCloudTrail(String action, String body) {
|
||||
return invokeCloudTrail(null, action, body);
|
||||
}
|
||||
|
||||
/** As {@link #invokeCloudTrail(String, String)}, signed with {@code authorization} when it is not null. */
|
||||
public static Response invokeCloudTrail(String authorization, String action, String body) {
|
||||
RequestSpecification request = given()
|
||||
.header("X-Amz-Target", "CloudTrail_20131101." + action)
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body(body);
|
||||
if (authorization != null) {
|
||||
request = request.header("Authorization", authorization);
|
||||
}
|
||||
return request.when().post("/");
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,13 @@ the ARN formats AWS mints it in. Both halves are vendored: the types decide whic
|
||||
names, and the formats are what `ResourceArnBuilder` checks its own minting against, so a prefix
|
||||
that drifts from AWS fails at startup rather than producing an ARN no policy matches.
|
||||
|
||||
Each action also carries its access level, as the properties `IsWrite`, `IsPermissionManagement`
|
||||
and `IsTaggingOnly`. The actions that have none of them, the Read and List ones, are vendored as
|
||||
`readOnlyActions`: CloudTrail "considers an action read-only if it does not have any mutating
|
||||
effect on a resource" and records it with `readOnly: true` and no `responseElements`
|
||||
(https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html), which is what
|
||||
`IamCloudTrailEvents` reads them for.
|
||||
|
||||
That endpoint is live rather than a pinned dependency, so a fresh generation is not byte-identical:
|
||||
AWS adds actions whenever it ships them. Byte-equality is therefore the wrong gate. What must be
|
||||
guaranteed is that nothing here is invented, which is checkable directly:
|
||||
@@ -79,6 +86,21 @@ ANCHORS = {
|
||||
"ListUsers": [],
|
||||
}
|
||||
|
||||
# The access level properties that mark an action as one that changes something. An action with
|
||||
# none of them set is a Read or List one.
|
||||
MUTATING_PROPERTIES = ("IsWrite", "IsPermissionManagement", "IsTaggingOnly")
|
||||
|
||||
# Read-only or not, whichever way the reference says, for one action of each kind the file must
|
||||
# still carry: a read, a list, a simulation, and a write, a permissions change and a tagging one.
|
||||
READ_ONLY_ANCHORS = {
|
||||
"GetUser": True,
|
||||
"ListUsers": True,
|
||||
"SimulatePrincipalPolicy": True,
|
||||
"CreateUser": False,
|
||||
"PutUserPolicy": False,
|
||||
"TagUser": False,
|
||||
}
|
||||
|
||||
|
||||
def fetch_reference(source: Path | None) -> tuple[dict, str]:
|
||||
"""AWS's IAM service reference and a provenance label for where it came from."""
|
||||
@@ -115,6 +137,22 @@ def action_resources_from(reference: dict) -> dict[str, list[str]]:
|
||||
return dict(sorted(found.items()))
|
||||
|
||||
|
||||
def read_only_actions_from(reference: dict) -> list[str]:
|
||||
"""Every action the reference gives none of the mutating access level properties, sorted.
|
||||
|
||||
An action whose properties the reference leaves out is not counted as read-only: nothing then
|
||||
says it changes nothing.
|
||||
"""
|
||||
found: list[str] = []
|
||||
for action in reference.get("Actions", []):
|
||||
properties = action.get("Annotations", {}).get("Properties")
|
||||
if not isinstance(properties, dict):
|
||||
continue
|
||||
if not any(properties.get(name) for name in MUTATING_PROPERTIES):
|
||||
found.append(action["Name"])
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def arn_formats_from(reference: dict) -> dict[str, list[str]]:
|
||||
"""Every resource type the reference publishes, mapped to its ARN formats, sorted."""
|
||||
resources = reference.get("Resources")
|
||||
@@ -145,6 +183,7 @@ def build(reference: dict, provenance: str) -> dict:
|
||||
},
|
||||
"actionResources": action_resources_from(reference),
|
||||
"resourceArnFormats": arn_formats_from(reference),
|
||||
"readOnlyActions": read_only_actions_from(reference),
|
||||
}
|
||||
|
||||
|
||||
@@ -194,9 +233,35 @@ def validate(document: dict) -> list[str]:
|
||||
elif actions[action] != expected:
|
||||
problems.append(f"{action!r} should be authorized against {expected}, "
|
||||
f"not {actions[action]}")
|
||||
read_only = document.get("readOnlyActions")
|
||||
if not isinstance(read_only, list) or not read_only:
|
||||
problems.append("readOnlyActions is missing or empty")
|
||||
return problems
|
||||
if read_only != sorted(read_only):
|
||||
problems.append("readOnlyActions is not sorted")
|
||||
if len(read_only) != len(set(read_only)):
|
||||
problems.append("readOnlyActions lists an action twice")
|
||||
for action in read_only:
|
||||
if action not in actions:
|
||||
problems.append(f"readOnlyActions names {action!r}, which is not an action of the file")
|
||||
for action, expected in READ_ONLY_ANCHORS.items():
|
||||
if (action in read_only) != expected:
|
||||
problems.append(f"{action!r} should {'' if expected else 'not '}be read-only")
|
||||
return problems
|
||||
|
||||
|
||||
def verify_read_only_against(vendored: list[str], upstream: list[str]) -> tuple[list[str], list[str]]:
|
||||
"""What the vendored read-only list claims and AWS does not, and what AWS has since added.
|
||||
|
||||
An action listed here that AWS gives a mutating access level fails: its record would hide the
|
||||
result of a change. A read-only action AWS has added is only a file that is behind.
|
||||
"""
|
||||
untrue = [f"{action!r} is not a read-only action AWS publishes" for action in vendored
|
||||
if action not in upstream]
|
||||
added = [f"{action} (new read-only action)" for action in upstream if action not in vendored]
|
||||
return untrue, sorted(added)
|
||||
|
||||
|
||||
def verify_against(vendored: dict[str, list[str]],
|
||||
upstream: dict[str, list[str]]) -> tuple[list[str], list[str]]:
|
||||
"""What the vendored file claims and AWS does not, and what AWS has since added.
|
||||
@@ -287,10 +352,12 @@ def main(argv: list[str] | None = None) -> int:
|
||||
document = json.loads(args.output.read_text(encoding="utf-8"))
|
||||
vendored = document["actionResources"]
|
||||
vendored_formats = document.get("resourceArnFormats", {})
|
||||
vendored_read_only = document.get("readOnlyActions", [])
|
||||
try:
|
||||
reference, provenance = fetch_reference(args.source)
|
||||
upstream = action_resources_from(reference)
|
||||
upstream_formats = arn_formats_from(reference)
|
||||
upstream_read_only = read_only_actions_from(reference)
|
||||
except (OSError, ValueError) as e:
|
||||
# Distinct from a data problem: the gate could not run, rather than having found
|
||||
# something invented. Separate exit code so CI can tell the two apart. ValueError
|
||||
@@ -300,8 +367,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
return 2
|
||||
untrue, added = verify_against(vendored, upstream)
|
||||
format_untrue, format_added = verify_formats_against(vendored_formats, upstream_formats)
|
||||
untrue += format_untrue
|
||||
added += format_added
|
||||
read_only_untrue, read_only_added = verify_read_only_against(vendored_read_only, upstream_read_only)
|
||||
untrue += format_untrue + read_only_untrue
|
||||
added += format_added + read_only_added
|
||||
for claim in untrue:
|
||||
print(f"error: {claim}", file=sys.stderr)
|
||||
if untrue:
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate src/main/resources/aws/iam-cloudtrail-shapes.json from botocore's IAM model.
|
||||
|
||||
CloudTrail records every IAM API call, and `IamCloudTrailEvents` writes each record's
|
||||
`requestParameters` and `responseElements` from the call's request and result. What the record
|
||||
says of a member is what the model says of it, so it is read from here rather than guessed. The
|
||||
walk is `request_shapes.build`'s, as for every other vendored shape file:
|
||||
|
||||
- `operations`: each operation's input shape, and `results` each one's output shape and the element
|
||||
its result is wrapped in on the wire (`resultWrapper`, `CreateUserResult`).
|
||||
- `shapes`: every shape reachable from them, with its type and the shapes its members, list
|
||||
elements and map values have. A number, a boolean or a timestamp is typed as one in the record
|
||||
because its shape says so. A shape the model marks `sensitive` (a password, a secret access key,
|
||||
a private key, a virtual MFA device's seed) carries `"sensitive": true`, and the record leaves it
|
||||
out.
|
||||
- `errors`: every error IAM models, from the code it answers with to its shape's name.
|
||||
CloudTrail records an IAM error under the shape's name (`NoSuchEntity` as
|
||||
`NoSuchEntityException`).
|
||||
|
||||
The model is botocore's `iam/2010-05-08/` (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_iam_cloudtrail_shapes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_iam_cloudtrail_shapes.py --check # exit 1 when the vendored file is stale
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import request_shapes
|
||||
from request_shapes import REPO_ROOT
|
||||
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-cloudtrail-shapes.json"
|
||||
MODEL = Path("iam/2010-05-08")
|
||||
|
||||
# The shape types `IamCloudTrailShapes` reads, and the member traits it reads beside the shape a
|
||||
# member names. Any other is one it would pass over or misread, so the generation stops rather than
|
||||
# vendoring it.
|
||||
TYPES = {"structure", "list", "map", "string", "integer", "long", "boolean", "timestamp", "blob",
|
||||
"double", "float"}
|
||||
MEMBER_TRAITS = {"shape", "documentation"}
|
||||
|
||||
|
||||
def readable(name: str, shape: dict) -> None:
|
||||
"""Raises for a shape the record cannot read: a type it does not know, or a member trait, such as
|
||||
a `locationName`, that would rename the member on the wire."""
|
||||
if shape["type"] not in TYPES:
|
||||
raise ValueError(f"{name} is a {shape['type']}, which the record does not read")
|
||||
for member, spec in shape.get("members", {}).items():
|
||||
extra = set(spec) - MEMBER_TRAITS
|
||||
if extra:
|
||||
raise ValueError(f"{name}.{member} carries {sorted(extra)}, which the record does not read")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__,
|
||||
results=True, sensitive=True, errors=True, check=readable)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -8,6 +8,10 @@ shape of every operation, reduced to the members carried in the JSON body, and f
|
||||
reachable from one, its type and the shapes of its members, list elements or map values.
|
||||
`regen_emr_serverless_shapes.py` keeps every operation's output shape too, with `outputs=True`.
|
||||
`regen_dynamodb_shapes.py` keeps the members each structure requires too, with `required=True`.
|
||||
`regen_iam_cloudtrail_shapes.py` keeps what a CloudTrail record reads of every call: each operation's
|
||||
result shape and the element it is wrapped in with `results=True`, the shapes the model marks
|
||||
`sensitive` with `sensitive=True`, and the shape each modeled error code is answered by with
|
||||
`errors=True`, holding every shape it keeps to what the record can read through `check`.
|
||||
`regen_iam_shapes.py` and `regen_sts_shapes.py` name their operations instead, which switches
|
||||
`main()` to `build_constraints()`.
|
||||
|
||||
@@ -36,7 +40,30 @@ def load_model(data: Path, model: Path) -> dict:
|
||||
return load_json_model(source)
|
||||
|
||||
|
||||
def build(model: dict, provenance: str, generator: str, outputs: bool = False, required: bool = False) -> dict:
|
||||
def errors_from(model: dict) -> dict[str, str]:
|
||||
"""Every error the model declares, from the code the service answers it with to its shape's name."""
|
||||
found: dict[str, str] = {}
|
||||
for name, shape in model["shapes"].items():
|
||||
if not shape.get("exception"):
|
||||
continue
|
||||
code = shape.get("error", {}).get("code", name)
|
||||
if code in found:
|
||||
raise ValueError(f"{found[code]} and {name} both answer {code}")
|
||||
found[code] = name
|
||||
return dict(sorted(found.items()))
|
||||
|
||||
|
||||
def build(model: dict, provenance: str, generator: str, outputs: bool = False, required: bool = False,
|
||||
results: bool = False, sensitive: bool = False, errors: bool = False,
|
||||
check: Callable[[str, dict], None] | None = None) -> dict:
|
||||
"""The input shape of every operation and every shape reachable from one, reduced to its type and
|
||||
the shapes of its members, list elements or map values.
|
||||
|
||||
`outputs` keeps each operation's output shape too. `results` does as well, and names it with the
|
||||
element its result is wrapped in, under `results`. `required` keeps the members each structure
|
||||
requires, `sensitive` marks the shapes the model marks `sensitive`, and `errors` adds the shape
|
||||
each modeled error code is answered by. `check` sees every shape kept, by name and as the model
|
||||
declares it, and raises for one the file's reader cannot read."""
|
||||
shapes = model["shapes"]
|
||||
kept: dict[str, dict] = {}
|
||||
|
||||
@@ -44,8 +71,12 @@ def build(model: dict, provenance: str, generator: str, outputs: bool = False, r
|
||||
if name in kept:
|
||||
return
|
||||
shape = shapes[name]
|
||||
if check is not None:
|
||||
check(name, shape)
|
||||
kind = shape["type"]
|
||||
entry: dict = {"type": kind}
|
||||
if sensitive and shape.get("sensitive"):
|
||||
entry["sensitive"] = True
|
||||
kept[name] = entry
|
||||
if kind == "structure":
|
||||
members = {member: spec for member, spec in shape.get("members", {}).items()
|
||||
@@ -63,21 +94,30 @@ def build(model: dict, provenance: str, generator: str, outputs: bool = False, r
|
||||
keep(shape["value"]["shape"])
|
||||
|
||||
operations = {}
|
||||
wrapped = {}
|
||||
for name, operation in sorted(model["operations"].items()):
|
||||
if "input" in operation:
|
||||
operations[name] = operation["input"]["shape"]
|
||||
keep(operation["input"]["shape"], body_only=True)
|
||||
if outputs and "output" in operation:
|
||||
if (outputs or results) and "output" in operation:
|
||||
keep(operation["output"]["shape"], body_only=True)
|
||||
if results and "output" in operation:
|
||||
wrapped[name] = {"shape": operation["output"]["shape"],
|
||||
"resultWrapper": operation["output"].get("resultWrapper")}
|
||||
|
||||
return {
|
||||
document = {
|
||||
"_source": {
|
||||
"generator": generator,
|
||||
"botocore": provenance,
|
||||
},
|
||||
"operations": operations,
|
||||
"shapes": dict(sorted(kept.items())),
|
||||
}
|
||||
if results:
|
||||
document["results"] = wrapped
|
||||
document["shapes"] = dict(sorted(kept.items()))
|
||||
if errors:
|
||||
document["errors"] = errors_from(model)
|
||||
return document
|
||||
|
||||
|
||||
def build_constraints(model: dict, operations: tuple[str, ...], provenance: str, generator: str) -> dict:
|
||||
@@ -171,7 +211,9 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path,
|
||||
description: str | None = None,
|
||||
outputs: bool = False, required: bool = False, operations: tuple[str, ...] | None = None,
|
||||
constraints: bool = False,
|
||||
prepare: Callable[[dict], dict] | None = None) -> int:
|
||||
prepare: Callable[[dict], dict] | None = None,
|
||||
results: bool = False, sensitive: bool = False, errors: bool = False,
|
||||
check: Callable[[str, dict], None] | None = None) -> int:
|
||||
"""Drives one generator: parse the flags, read the model, write or check the vendored file.
|
||||
|
||||
`operations` picks the constraints flavour, keeping those operations' declared constraints
|
||||
@@ -185,7 +227,10 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path,
|
||||
|
||||
`prepare` is the one thing a generator may do to the model before any of that, for an operation
|
||||
it vendors in part: IAM reduces a paged request to its paging members, the rest of it keeping
|
||||
the reading it has today."""
|
||||
the reading it has today.
|
||||
|
||||
`results`, `sensitive`, `errors` and `check` are `build`'s, for a generator that keeps every
|
||||
operation's member types."""
|
||||
parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
|
||||
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
|
||||
@@ -200,7 +245,8 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path,
|
||||
operations = tuple(name for name, operation in sorted(loaded["operations"].items()) if "input" in operation)
|
||||
generator = generator_name(script)
|
||||
fresh = render(build_constraints(loaded, operations, provenance, generator) if operations is not None
|
||||
else build(loaded, provenance, generator, outputs, required))
|
||||
else build(loaded, provenance, generator, outputs, required,
|
||||
results=results, sensitive=sensitive, errors=errors, check=check))
|
||||
|
||||
if args.check:
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
|
||||
@@ -9,13 +9,22 @@ import pytest
|
||||
import regen_iam_action_resources as r
|
||||
|
||||
|
||||
def reference(actions: dict[str, list[str]], types: list[str] | None = None) -> dict:
|
||||
"""A reference payload shaped like AWS's, with an ARN format for every type mentioned."""
|
||||
READ_ONLY = ("GetUser", "ListUsers", "SimulatePrincipalPolicy")
|
||||
|
||||
|
||||
def reference(actions: dict[str, list[str]], types: list[str] | None = None,
|
||||
read_only: tuple[str, ...] = READ_ONLY) -> dict:
|
||||
"""A reference payload shaped like AWS's, with an ARN format for every type mentioned, and
|
||||
every action not in `read_only` given the Write access level."""
|
||||
if types is None:
|
||||
types = sorted({t for names in actions.values() for t in names})
|
||||
return {
|
||||
"Name": "iam",
|
||||
"Actions": [{"Name": name, "Resources": [{"Name": t} for t in resource_types]}
|
||||
"Actions": [{"Name": name,
|
||||
"Annotations": {"Properties": {"IsList": False, "IsPermissionManagement": False,
|
||||
"IsTaggingOnly": False,
|
||||
"IsWrite": name not in read_only}},
|
||||
"Resources": [{"Name": t} for t in resource_types]}
|
||||
for name, resource_types in actions.items()],
|
||||
"Resources": [{"Name": t,
|
||||
"ARNFormats": ["arn:${Partition}:iam::${Account}:" + t + "/${Name}"]}
|
||||
@@ -35,6 +44,10 @@ ANCHORED = {
|
||||
"DeactivateMFADevice": ["user"],
|
||||
"CreateUser": ["user"],
|
||||
"ListUsers": [],
|
||||
"GetUser": ["user"],
|
||||
"SimulatePrincipalPolicy": ["user"],
|
||||
"PutUserPolicy": ["user"],
|
||||
"TagUser": ["user"],
|
||||
}
|
||||
|
||||
|
||||
@@ -152,6 +165,40 @@ def test_a_resource_type_with_no_arn_format_is_rejected():
|
||||
assert any("no ARN format" in problem for problem in r.validate(doc))
|
||||
|
||||
|
||||
def test_read_only_actions_are_those_with_no_mutating_access_level():
|
||||
payload = reference({"GetUser": ["user"], "CreateUser": ["user"], "TagUser": ["user"],
|
||||
"PutUserPolicy": ["user"], "ListUsers": []}, read_only=("GetUser", "ListUsers"))
|
||||
tagging = next(action for action in payload["Actions"] if action["Name"] == "TagUser")
|
||||
tagging["Annotations"]["Properties"].update({"IsWrite": False, "IsTaggingOnly": True})
|
||||
permissions = next(action for action in payload["Actions"] if action["Name"] == "PutUserPolicy")
|
||||
permissions["Annotations"]["Properties"].update({"IsWrite": False, "IsPermissionManagement": True})
|
||||
assert r.read_only_actions_from(payload) == ["GetUser", "ListUsers"]
|
||||
|
||||
|
||||
def test_an_action_without_access_level_properties_is_not_read_only():
|
||||
payload = reference({"GetUser": ["user"]})
|
||||
del payload["Actions"][0]["Annotations"]
|
||||
assert r.read_only_actions_from(payload) == []
|
||||
|
||||
|
||||
def test_a_read_only_anchor_aws_calls_a_write_is_rejected():
|
||||
doc = document(ANCHORED)
|
||||
doc["readOnlyActions"] = sorted(doc["readOnlyActions"] + ["CreateUser"])
|
||||
assert "'CreateUser' should not be read-only" in r.validate(doc)
|
||||
|
||||
|
||||
def test_a_read_only_action_the_file_does_not_carry_is_rejected():
|
||||
doc = document(ANCHORED)
|
||||
doc["readOnlyActions"] = sorted(doc["readOnlyActions"] + ["GetMadeUp"])
|
||||
assert any("GetMadeUp" in problem for problem in r.validate(doc))
|
||||
|
||||
|
||||
def test_a_read_only_claim_aws_does_not_make_fails():
|
||||
untrue, added = r.verify_read_only_against(["GetUser", "UpdateUser"], ["GetUser", "ListUsers"])
|
||||
assert untrue == ["'UpdateUser' is not a read-only action AWS publishes"]
|
||||
assert added == ["ListUsers (new read-only action)"]
|
||||
|
||||
|
||||
def test_an_empty_map_is_rejected():
|
||||
assert r.validate({"actionResources": {}, "resourceArnFormats": {}}) == [
|
||||
"actionResources is missing or empty"]
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Tests for regen_iam_cloudtrail_shapes, and for what request_shapes.build keeps for it: each
|
||||
operation's result and its wrapper, the sensitive flag and the modeled errors.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make aws-data-test)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import regen_iam_cloudtrail_shapes as cloudtrail
|
||||
import request_shapes as r
|
||||
|
||||
GENERATOR = "tools/aws/regen_iam_cloudtrail_shapes.py"
|
||||
|
||||
SHAPES = {
|
||||
"CreateUserRequest": {"type": "structure", "members": {
|
||||
"UserName": {"shape": "userNameType", "documentation": "<p>The name.</p>"},
|
||||
"Tags": {"shape": "tagListType"}}},
|
||||
"CreateUserResponse": {"type": "structure", "members": {"User": {"shape": "User"}}},
|
||||
"User": {"type": "structure", "members": {
|
||||
"UserName": {"shape": "userNameType"}, "CreateDate": {"shape": "dateType"}}},
|
||||
"ChangePasswordRequest": {"type": "structure", "members": {
|
||||
"OldPassword": {"shape": "passwordType"}, "NewPassword": {"shape": "passwordType"}}},
|
||||
"tagListType": {"type": "list", "member": {"shape": "Tag"}},
|
||||
"Tag": {"type": "structure", "members": {"Key": {"shape": "tagKeyType"}, "Value": {"shape": "tagKeyType"}}},
|
||||
"userNameType": {"type": "string", "max": 64, "pattern": "[\\w+=,.@-]+"},
|
||||
"tagKeyType": {"type": "string"},
|
||||
"dateType": {"type": "timestamp"},
|
||||
"passwordType": {"type": "string", "sensitive": True},
|
||||
"NoSuchEntityException": {"type": "structure", "members": {}, "exception": True,
|
||||
"error": {"code": "NoSuchEntity", "httpStatusCode": 404}},
|
||||
"RoleModifiedException": {"type": "structure", "members": {}, "exception": True},
|
||||
"unreachable": {"type": "string"},
|
||||
}
|
||||
OPERATIONS = {
|
||||
"CreateUser": {"input": {"shape": "CreateUserRequest"},
|
||||
"output": {"shape": "CreateUserResponse", "resultWrapper": "CreateUserResult"}},
|
||||
"ChangePassword": {"input": {"shape": "ChangePasswordRequest"}},
|
||||
"GenerateCredentialReport": {},
|
||||
}
|
||||
|
||||
|
||||
def build(shapes: dict = SHAPES, operations: dict = OPERATIONS) -> dict:
|
||||
return r.build({"operations": operations, "shapes": shapes}, "botocore test", GENERATOR,
|
||||
results=True, sensitive=True, errors=True, check=cloudtrail.readable)
|
||||
|
||||
|
||||
def test_each_operation_names_its_input_and_each_result_its_shape_and_wrapper():
|
||||
document = build()
|
||||
assert document["operations"] == {"ChangePassword": "ChangePasswordRequest",
|
||||
"CreateUser": "CreateUserRequest"}
|
||||
assert document["results"] == {"CreateUser": {"shape": "CreateUserResponse",
|
||||
"resultWrapper": "CreateUserResult"}}
|
||||
|
||||
|
||||
def test_shapes_keep_their_types_and_members_without_constraints_or_documentation():
|
||||
shapes = build()["shapes"]
|
||||
assert shapes["CreateUserRequest"] == {"type": "structure",
|
||||
"members": {"UserName": "userNameType", "Tags": "tagListType"}}
|
||||
assert shapes["tagListType"] == {"type": "list", "member": "Tag"}
|
||||
assert shapes["userNameType"] == {"type": "string"}
|
||||
assert shapes["dateType"] == {"type": "timestamp"}
|
||||
assert shapes["User"] == {"type": "structure", "members": {"UserName": "userNameType",
|
||||
"CreateDate": "dateType"}}
|
||||
|
||||
|
||||
def test_a_sensitive_shape_says_so():
|
||||
assert build()["shapes"]["passwordType"] == {"type": "string", "sensitive": True}
|
||||
|
||||
|
||||
def test_the_sensitive_flag_is_kept_only_when_asked_for():
|
||||
document = r.build({"operations": OPERATIONS, "shapes": SHAPES}, "botocore test", GENERATOR)
|
||||
assert document["shapes"]["passwordType"] == {"type": "string"}
|
||||
assert list(document) == ["_source", "operations", "shapes"]
|
||||
|
||||
|
||||
def test_only_the_shapes_an_operation_reaches_are_kept():
|
||||
shapes = build()["shapes"]
|
||||
assert "unreachable" not in shapes
|
||||
assert "NoSuchEntityException" not in shapes
|
||||
|
||||
|
||||
def test_a_shape_type_the_record_does_not_read_stops_the_generation():
|
||||
with pytest.raises(ValueError, match="does not read"):
|
||||
build(dict(SHAPES, userNameType={"type": "document"}))
|
||||
|
||||
|
||||
def test_a_member_trait_the_record_does_not_read_stops_the_generation():
|
||||
shapes = dict(SHAPES, User={"type": "structure", "members": {
|
||||
"UserName": {"shape": "userNameType", "locationName": "name"}}})
|
||||
with pytest.raises(ValueError, match="locationName"):
|
||||
build(shapes)
|
||||
|
||||
|
||||
def test_errors_map_the_code_they_answer_with_to_their_shape():
|
||||
assert build()["errors"] == {
|
||||
"NoSuchEntity": "NoSuchEntityException",
|
||||
"RoleModifiedException": "RoleModifiedException",
|
||||
}
|
||||
|
||||
|
||||
def test_two_errors_answering_one_code_stop_the_generation():
|
||||
shapes = dict(SHAPES, EntityMissingException={"type": "structure", "members": {}, "exception": True,
|
||||
"error": {"code": "NoSuchEntity"}})
|
||||
with pytest.raises(ValueError, match="both answer NoSuchEntity"):
|
||||
build(shapes)
|
||||
|
||||
|
||||
def test_the_document_names_its_generator_and_source():
|
||||
document = build()
|
||||
assert document["_source"] == {"generator": GENERATOR, "botocore": "botocore test"}
|
||||
assert list(document) == ["_source", "operations", "results", "shapes", "errors"]
|
||||
Reference in new issue
Block a user