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
+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("/");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user