mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudtrail): implement AddTags, RemoveTags and ListTags (#2934)
* feat(cloudtrail): implement AddTags, RemoveTags and ListTags CloudTrailJsonHandler dispatched none of the three tag actions, so any trail lookup went through the unsupported-action path — including the Terraform AWS provider's transparent-tagging ListTags call on every read of aws_cloudtrail, which broke refresh/plan/destroy for any state containing a trail regardless of whether it was tagged. Tags are tracked per-trail in CloudTrailEntry (not the wire-serialized Trail record, which AWS never includes tags on) and are resolved by ARN only, matching AWS's actual request shape for these three actions. An ARN that isn't a well-formed CloudTrail trail ARN raises CloudTrailARNInvalidException; a well-formed ARN with no matching trail raises ResourceNotFoundException, so a stale Terraform state entry surfaces as a real error instead of an empty tag list. Fixes floci-io/floci#2297 * fix(cloudtrail): omit Value from ListTags response for valueless tags AddTags only requires Key, so a tag can legitimately have no Value. listTags() was serializing that as an explicit "Value":null, but AWS omits absent optionals from the response entirely.
This commit is contained in:
1 parent
65e1d506cc
commit
671628b525
5 files changed
+245
-6
No files matched your search
@@ -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 |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
Selector matching honors `ReadWriteType` (`All`, `ReadOnly`, `WriteOnly`)
|
||||
|
||||
@@ -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<EventSelector> selectors,
|
||||
boolean logging,
|
||||
Long startLoggingTime,
|
||||
Long stopLoggingTime) {
|
||||
Long stopLoggingTime,
|
||||
Map<String, String> 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<EventSelector> 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<String, String> updated) {
|
||||
return new CloudTrailEntry(trail, selectors, logging, startLoggingTime, stopLoggingTime, updated);
|
||||
}
|
||||
|
||||
/** Returns a mutable copy suitable for merging in new tags. */
|
||||
public Map<String, String> mutableTags() {
|
||||
return new LinkedHashMap<>(tags);
|
||||
}
|
||||
}
|
||||
+48
@@ -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<String> keys = new ArrayList<>(parseTagsList(req.path("TagsList")).keySet());
|
||||
service.removeTags(resourceId, keys);
|
||||
return Response.ok(mapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response listTags(JsonNode req) {
|
||||
List<String> resourceIdList = extractStringList(req, "ResourceIdList");
|
||||
ObjectNode resp = mapper.createObjectNode();
|
||||
ArrayNode resourceTagList = resp.putArray("ResourceTagList");
|
||||
for (String resourceId : resourceIdList) {
|
||||
Map<String, String> 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<String, String> parseTagsList(JsonNode tagsNode) {
|
||||
Map<String, String> 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<EventSelector> parseEventSelectors(JsonNode selectorsNode) {
|
||||
List<EventSelector> result = new ArrayList<>();
|
||||
if (selectorsNode == null || !selectorsNode.isArray()) return result;
|
||||
|
||||
+54
-1
@@ -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<String, String> tagsToAdd) {
|
||||
CloudTrailEntry entry = findEntryByArnOrThrow(resourceId);
|
||||
Map<String, String> 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<String> tagKeys) {
|
||||
CloudTrailEntry entry = findEntryByArnOrThrow(resourceId);
|
||||
Map<String, String> remaining = entry.mutableTags();
|
||||
tagKeys.forEach(remaining::remove);
|
||||
store.put(regionKey(entry.trail().homeRegion(), entry.trail().name()), entry.withTags(remaining));
|
||||
}
|
||||
|
||||
public Map<String, String> 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) {
|
||||
|
||||
+116
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user