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
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user