diff --git a/docs/services/cloudtrail.md b/docs/services/cloudtrail.md index d36a8d6129..bc75eec4d1 100644 --- a/docs/services/cloudtrail.md +++ b/docs/services/cloudtrail.md @@ -26,6 +26,9 @@ ${prefix}AWSLogs/${accountId}/CloudTrail/${region}/yyyy/MM/dd/${accountId}_Cloud | `StopLogging` | Stops logging for a trail | | `GetTrailStatus` | Returns the logging status of a trail | | `LookupEvents` | - | +| `AddTags` | Adds or overwrites tags on a trail, identified by ARN | +| `RemoveTags` | Removes the given tag keys from a trail, identified by ARN | +| `ListTags` | Returns the tags for one or more trails, identified by ARN | Selector matching honors `ReadWriteType` (`All`, `ReadOnly`, `WriteOnly`) diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.java index 20fd0d45ef..ebd8977e3b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.java @@ -6,7 +6,10 @@ import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector; import io.github.hectorvent.floci.services.cloudtrail.model.Trail; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; @RegisterForReflection @JsonInclude(JsonInclude.Include.NON_NULL) @@ -16,10 +19,17 @@ public record CloudTrailEntry( List selectors, boolean logging, Long startLoggingTime, - Long stopLoggingTime) { + Long stopLoggingTime, + Map tags) { + + // Not Map.copyOf: AWS allows a tag with a null value (AddTags omitting "Value"), + // and Map.copyOf/Map.of reject null values. + public CloudTrailEntry { + tags = tags == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(tags)); + } public CloudTrailEntry withTrail(Trail updated) { - return new CloudTrailEntry(updated, selectors, logging, startLoggingTime, stopLoggingTime); + return new CloudTrailEntry(updated, selectors, logging, startLoggingTime, stopLoggingTime, tags); } public CloudTrailEntry withSelectors(List updated, boolean hasCustomSelectors) { @@ -28,14 +38,23 @@ public record CloudTrailEntry( trail.snsTopicArn(), trail.includeGlobalServiceEvents(), trail.isMultiRegionTrail(), trail.homeRegion(), trail.logFileValidationEnabled(), hasCustomSelectors, trail.hasInsightSelectors(), trail.isOrganizationTrail()); - return new CloudTrailEntry(updatedTrail, updated, logging, startLoggingTime, stopLoggingTime); + return new CloudTrailEntry(updatedTrail, updated, logging, startLoggingTime, stopLoggingTime, tags); } public CloudTrailEntry startLogging(long time) { - return new CloudTrailEntry(trail, selectors, true, time, stopLoggingTime); + return new CloudTrailEntry(trail, selectors, true, time, stopLoggingTime, tags); } public CloudTrailEntry stopLogging(long time) { - return new CloudTrailEntry(trail, selectors, false, startLoggingTime, time); + return new CloudTrailEntry(trail, selectors, false, startLoggingTime, time, tags); + } + + public CloudTrailEntry withTags(Map updated) { + return new CloudTrailEntry(trail, selectors, logging, startLoggingTime, stopLoggingTime, updated); + } + + /** Returns a mutable copy suitable for merging in new tags. */ + public Map mutableTags() { + return new LinkedHashMap<>(tags); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java index 472c4770cb..a5d84690a6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudtrail; 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.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudtrail.model.DataResource; @@ -12,7 +13,9 @@ import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; @ApplicationScoped public class CloudTrailJsonHandler { @@ -38,6 +41,9 @@ public class CloudTrailJsonHandler { case "StopLogging" -> stopLogging(request, region); case "GetTrailStatus" -> getTrailStatus(request, region); case "LookupEvents" -> lookupEvents(request, region); + case "AddTags" -> addTags(request); + case "RemoveTags" -> removeTags(request); + case "ListTags" -> listTags(request); default -> throw new AwsException( "InvalidAction", "Could not find operation " + action, 400); }; @@ -182,8 +188,50 @@ public class CloudTrailJsonHandler { return Response.ok(resp).build(); } + private Response addTags(JsonNode req) { + String resourceId = req.path("ResourceId").asText(null); + service.addTags(resourceId, parseTagsList(req.path("TagsList"))); + return Response.ok(mapper.createObjectNode()).build(); + } + + private Response removeTags(JsonNode req) { + String resourceId = req.path("ResourceId").asText(null); + List keys = new ArrayList<>(parseTagsList(req.path("TagsList")).keySet()); + service.removeTags(resourceId, keys); + return Response.ok(mapper.createObjectNode()).build(); + } + + private Response listTags(JsonNode req) { + List resourceIdList = extractStringList(req, "ResourceIdList"); + ObjectNode resp = mapper.createObjectNode(); + ArrayNode resourceTagList = resp.putArray("ResourceTagList"); + for (String resourceId : resourceIdList) { + Map tags = service.listTags(resourceId); + ObjectNode entry = resourceTagList.addObject(); + entry.put("ResourceId", resourceId); + ArrayNode tagsList = entry.putArray("TagsList"); + tags.forEach((k, v) -> { + ObjectNode tag = tagsList.addObject().put("Key", k); + if (v != null) { + tag.put("Value", v); + } + }); + } + return Response.ok(resp).build(); + } + // --- Helpers --- + private Map parseTagsList(JsonNode tagsNode) { + Map tags = new LinkedHashMap<>(); + if (tagsNode != null && tagsNode.isArray()) { + tagsNode.forEach(t -> { + tags.put(t.path("Key").asText(), t.path("Value").asText(null)); + }); + } + return tags; + } + private List parseEventSelectors(JsonNode selectorsNode) { List result = new ArrayList<>(); if (selectorsNode == null || !selectorsNode.isArray()) return result; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java index fbd40f1856..01fb9af806 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java @@ -76,7 +76,7 @@ public class CloudTrailService { name, arn, s3BucketName, s3KeyPrefix, snsTopicArn, includeGlobalServiceEvents, isMultiRegionTrail, region, enableLogFileValidation, false, false, isOrganizationTrail); - store.put(key, new CloudTrailEntry(trail, List.of(), false, null, null)); + store.put(key, new CloudTrailEntry(trail, List.of(), false, null, null, Map.of())); return trail; } @@ -165,6 +165,59 @@ public class CloudTrailService { .orElse(new TrailStatus(false, null, null)); } + // --- Tagging --- + // + // AddTags/RemoveTags/ListTags identify the trail solely by ARN (ResourceId / + // ResourceIdList), unlike every other CloudTrail action here which also accepts a + // bare trail name — so these don't take a `region` parameter. + + private static final int MAX_TAGS_PER_RESOURCE = 50; + + public void addTags(String resourceId, Map tagsToAdd) { + CloudTrailEntry entry = findEntryByArnOrThrow(resourceId); + Map merged = entry.mutableTags(); + merged.putAll(tagsToAdd); + if (merged.size() > MAX_TAGS_PER_RESOURCE) { + throw new AwsException("TagsLimitExceededException", + "Tag limit exceeded for resource " + resourceId + + ". Maximum allowed: " + MAX_TAGS_PER_RESOURCE + ".", 400); + } + store.put(regionKey(entry.trail().homeRegion(), entry.trail().name()), entry.withTags(merged)); + } + + public void removeTags(String resourceId, List tagKeys) { + CloudTrailEntry entry = findEntryByArnOrThrow(resourceId); + Map remaining = entry.mutableTags(); + tagKeys.forEach(remaining::remove); + store.put(regionKey(entry.trail().homeRegion(), entry.trail().name()), entry.withTags(remaining)); + } + + public Map listTags(String resourceId) { + return findEntryByArnOrThrow(resourceId).tags(); + } + + private CloudTrailEntry findEntryByArnOrThrow(String resourceId) { + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(resourceId); + } catch (IllegalArgumentException e) { + throw new AwsException("CloudTrailARNInvalidException", + resourceId + " is not a valid ARN.", 400); + } + if (!"cloudtrail".equals(arn.service()) || !arn.resource().startsWith("trail/")) { + throw new AwsException("CloudTrailARNInvalidException", + resourceId + " is not a valid trail ARN.", 400); + } + for (String k : store.keys()) { + CloudTrailEntry entry = store.get(k).orElse(null); + if (entry != null && resourceId.equals(entry.trail().trailArn())) { + return entry; + } + } + throw new AwsException("ResourceNotFoundException", + "Resource not found: " + resourceId, 400); + } + // --- Data plane: called by S3 (and other services) when an op happens --- public void emitS3DataEvent(S3EventInput in) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailIntegrationTest.java index d9d5b2709f..667b8efd47 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailIntegrationTest.java @@ -14,7 +14,9 @@ import java.util.zip.GZIPInputStream; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -292,6 +294,120 @@ class CloudTrailIntegrationTest { .body(containsString(newBucket)); } + @Test + void tagLifecycleAddsListsAndRemovesTags() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String trailName = "tag-" + suffix; + String destBucket = "tag-logs-" + suffix; + + createBucket(destBucket); + String trailArn = invokeCloudTrail("CreateTrail", String.format(""" + {"Name":"%s","S3BucketName":"%s"} + """, trailName, destBucket)) + .then().statusCode(200) + .extract().path("TrailARN"); + + // A trail with no tags yet returns an entry with an empty TagsList, not an + // omitted entry. + invokeCloudTrail("ListTags", String.format(""" + {"ResourceIdList":["%s"]} + """, trailArn)) + .then().statusCode(200) + .body("ResourceTagList[0].ResourceId", equalTo(trailArn)) + .body("ResourceTagList[0].TagsList", hasSize(0)); + + invokeCloudTrail("AddTags", String.format(""" + {"ResourceId":"%s","TagsList":[{"Key":"env","Value":"prod"},{"Key":"team","Value":"sec"}]} + """, trailArn)) + .then().statusCode(200); + + invokeCloudTrail("ListTags", String.format(""" + {"ResourceIdList":["%s"]} + """, trailArn)) + .then().statusCode(200) + .body("ResourceTagList[0].TagsList", hasSize(2)); + + // AddTags overwrites an existing key's value rather than duplicating it. + invokeCloudTrail("AddTags", String.format(""" + {"ResourceId":"%s","TagsList":[{"Key":"env","Value":"staging"}]} + """, trailArn)) + .then().statusCode(200); + + invokeCloudTrail("ListTags", String.format(""" + {"ResourceIdList":["%s"]} + """, trailArn)) + .then().statusCode(200) + .body("ResourceTagList[0].TagsList", hasSize(2)) + .body("ResourceTagList[0].TagsList.find { it.Key == 'env' }.Value", equalTo("staging")); + + invokeCloudTrail("RemoveTags", String.format(""" + {"ResourceId":"%s","TagsList":[{"Key":"env"}]} + """, trailArn)) + .then().statusCode(200); + + invokeCloudTrail("ListTags", String.format(""" + {"ResourceIdList":["%s"]} + """, trailArn)) + .then().statusCode(200) + .body("ResourceTagList[0].TagsList", hasSize(1)) + .body("ResourceTagList[0].TagsList[0].Key", equalTo("team")); + } + + @Test + void listTagsOmitsValueForTagWithNoValue() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String trailName = "novalue-" + suffix; + String destBucket = "novalue-logs-" + suffix; + + createBucket(destBucket); + String trailArn = invokeCloudTrail("CreateTrail", String.format(""" + {"Name":"%s","S3BucketName":"%s"} + """, trailName, destBucket)) + .then().statusCode(200) + .extract().path("TrailARN"); + + invokeCloudTrail("AddTags", String.format(""" + {"ResourceId":"%s","TagsList":[{"Key":"novalue"}]} + """, trailArn)) + .then().statusCode(200); + + // AWS omits absent optionals: a valueless tag must come back as + // {"Key":"novalue"} with no "Value" member at all, not "Value":null. + invokeCloudTrail("ListTags", String.format(""" + {"ResourceIdList":["%s"]} + """, trailArn)) + .then().statusCode(200) + .body(containsString("{\"Key\":\"novalue\"}")) + .body(not(containsString("\"Value\":null"))); + } + + @Test + void listTagsForUnknownTrailArnReturnsResourceNotFound() { + invokeCloudTrail("ListTags", """ + {"ResourceIdList":["arn:aws:cloudtrail:us-east-1:000000000000:trail/does-not-exist"]} + """) + .then().statusCode(400) + .body(containsString("ResourceNotFoundException")); + } + + @Test + void addTagsWithMalformedArnReturnsCloudTrailArnInvalid() { + invokeCloudTrail("AddTags", """ + {"ResourceId":"not-an-arn","TagsList":[{"Key":"env","Value":"prod"}]} + """) + .then().statusCode(400) + .body(containsString("CloudTrailARNInvalidException")); + } + + @Test + void addTagsWithNonTrailArnReturnsCloudTrailArnInvalid() { + invokeCloudTrail("AddTags", """ + {"ResourceId":"arn:aws:s3:::some-bucket","TagsList":[{"Key":"env","Value":"prod"}]} + """) + .then().statusCode(400) + .body(containsString("CloudTrailARNInvalidException")); + } + // --- Helpers --- private static io.restassured.response.Response invokeCloudTrail(String action, String body) {