fix(cloudtrail): implement CreateTrail with tagging support and add integration tests (#3206)

Signed-off-by: Matheus André <matheusandr2@gmail.com>
This commit is contained in:
Matheus André authored and GitHub committed 2026-09-07 21:46:14 -04:00
1 parent 84a7ce67e4
commit 991470e7c4
8 files changed
+185 -3

No files matched your search

@@ -675,3 +675,24 @@ resource "aws_transfer_server" "compat" {
output "transfer_server_id" {
value = aws_transfer_server.compat.id
}
# -- CloudTrail Trail (issue #2800) --------------------------------------------
# The provider sends tags inside CreateTrail and reads them back with ListTags on
# every refresh, so this covers the post-create tag refresh path end to end.
resource "aws_s3_bucket" "trail_logs" {
bucket = "floci-compat-trail-logs"
force_destroy = true
}
resource "aws_cloudtrail" "compat" {
name = "floci-compat-trail"
s3_bucket_name = aws_s3_bucket.trail_logs.id
tags = {
Environment = "compat-test"
}
}
output "cloudtrail_arn" {
value = aws_cloudtrail.compat.arn
}
@@ -449,3 +449,35 @@ sha256_composite_by_sizes() {
assert_success
assert_output "ONLINE"
}
@test "OpenTofu: CloudTrail trail created, logging and tagged" {
run aws_cmd cloudtrail describe-trails --trail-name-list floci-compat-trail \
--query "trailList[0].S3BucketName" --output text
assert_success
assert_output "floci-compat-trail-logs"
run aws_cmd cloudtrail get-trail-status --name floci-compat-trail \
--query "IsLogging" --output text
assert_success
assert_output "True"
run aws_cmd cloudtrail describe-trails --trail-name-list floci-compat-trail \
--query "trailList[0].TrailARN" --output text
assert_success
TRAIL_ARN="$output"
run aws_cmd cloudtrail list-tags --resource-id-list "$TRAIL_ARN" \
--query "ResourceTagList[0].TagsList[?Key=='Environment'].Value" --output text
assert_success
assert_output "compat-test"
}
# The tag refresh path (issue #2800): a re-plan reads the trail back, including its
# tags via ListTags, and must not report drift.
@test "OpenTofu: re-planning CloudTrail reports no changes" {
cd "$TOFU_DIR"
run tofu plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode \
-target=aws_cloudtrail.compat
if [ "$status" -eq 2 ]; then
echo "# drift detected on re-plan:" >&3
echo "$output" >&3
fi
[ "$status" -eq 0 ]
}
@@ -852,3 +852,24 @@ resource "aws_transfer_server" "compat" {
output "transfer_server_id" {
value = aws_transfer_server.compat.id
}
# -- CloudTrail Trail (issue #2800) --------------------------------------------
# The provider sends tags inside CreateTrail and reads them back with ListTags on
# every refresh, so this covers the post-create tag refresh path end to end.
resource "aws_s3_bucket" "trail_logs" {
bucket = "floci-compat-trail-logs"
force_destroy = true
}
resource "aws_cloudtrail" "compat" {
name = "floci-compat-trail"
s3_bucket_name = aws_s3_bucket.trail_logs.id
tags = {
Environment = "compat-test"
}
}
output "cloudtrail_arn" {
value = aws_cloudtrail.compat.arn
}
@@ -614,3 +614,35 @@ sha256_composite_by_sizes() {
assert_success
assert_output "ONLINE"
}
@test "Terraform: CloudTrail trail created, logging and tagged" {
run aws_cmd cloudtrail describe-trails --trail-name-list floci-compat-trail \
--query "trailList[0].S3BucketName" --output text
assert_success
assert_output "floci-compat-trail-logs"
run aws_cmd cloudtrail get-trail-status --name floci-compat-trail \
--query "IsLogging" --output text
assert_success
assert_output "True"
run aws_cmd cloudtrail describe-trails --trail-name-list floci-compat-trail \
--query "trailList[0].TrailARN" --output text
assert_success
TRAIL_ARN="$output"
run aws_cmd cloudtrail list-tags --resource-id-list "$TRAIL_ARN" \
--query "ResourceTagList[0].TagsList[?Key=='Environment'].Value" --output text
assert_success
assert_output "compat-test"
}
# The tag refresh path (issue #2800): a re-plan reads the trail back, including its
# tags via ListTags, and must not report drift.
@test "Terraform: re-planning CloudTrail reports no changes" {
cd "$TF_DIR"
run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode \
-target=aws_cloudtrail.compat
if [ "$status" -eq 2 ]; then
echo "# drift detected on re-plan:" >&3
echo "$output" >&3
fi
[ "$status" -eq 0 ]
}
+1 -1
View File
@@ -16,7 +16,7 @@ ${prefix}AWSLogs/${accountId}/CloudTrail/${region}/yyyy/MM/dd/${accountId}_Cloud
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `CreateTrail` | Creates a trail and returns its ARN |
| `CreateTrail` | Creates a trail, optionally tagged via `TagsList`, and returns its ARN |
| `DescribeTrails` | Returns the settings for one or more trails |
| `DeleteTrail` | Deletes a trail |
| `UpdateTrail` | Updates the settings of an existing trail |
@@ -60,8 +60,10 @@ public class CloudTrailJsonHandler {
boolean enableLogFileValidation = req.path("EnableLogFileValidation").asBoolean(false);
boolean isOrganizationTrail = req.path("IsOrganizationTrail").asBoolean(false);
Map<String, String> tags = parseTagsList(req.path("TagsList"));
Trail trail = service.createTrail(region, name, s3BucketName, s3KeyPrefix, snsTopicArn,
includeGlobal, isMultiRegion, enableLogFileValidation, isOrganizationTrail);
includeGlobal, isMultiRegion, enableLogFileValidation, isOrganizationTrail, tags);
ObjectNode resp = mapper.createObjectNode();
resp.put("Name", trail.name());
@@ -71,10 +71,31 @@ public class CloudTrailService {
String snsTopicArn, boolean includeGlobalServiceEvents,
boolean isMultiRegionTrail, boolean enableLogFileValidation,
boolean isOrganizationTrail) {
return createTrail(region, name, s3BucketName, s3KeyPrefix, snsTopicArn,
includeGlobalServiceEvents, isMultiRegionTrail, enableLogFileValidation,
isOrganizationTrail, Map.of());
}
/**
* Creates a trail, optionally tagged from the outset. CreateTrail carries a {@code TagsList}
* on the wire, and the Terraform AWS provider always sends the resource's tags there rather
* than through a follow-up AddTags, then reads them back with ListTags on every refresh, so
* tags dropped here would surface as a perpetual diff on {@code aws_cloudtrail}.
*/
public Trail createTrail(String region, String name, String s3BucketName, String s3KeyPrefix,
String snsTopicArn, boolean includeGlobalServiceEvents,
boolean isMultiRegionTrail, boolean enableLogFileValidation,
boolean isOrganizationTrail, Map<String, String> tags) {
validateTrailName(name);
if (s3BucketName == null || s3BucketName.isEmpty()) {
throw new AwsException("S3BucketDoesNotExistException", "S3 bucket name is required.", 400);
}
Map<String, String> initialTags = tags == null ? Map.of() : tags;
if (initialTags.size() > MAX_TAGS_PER_RESOURCE) {
throw new AwsException("TagsLimitExceededException",
"Tag limit exceeded for trail " + name
+ ". Maximum allowed: " + MAX_TAGS_PER_RESOURCE + ".", 400);
}
String key = regionKey(region, name);
if (store.get(key).isPresent()) {
throw new AwsException("TrailAlreadyExistsException",
@@ -86,7 +107,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, Map.of()));
store.put(key, new CloudTrailEntry(trail, List.of(), false, null, null, initialTags));
return trail;
}
@@ -353,6 +353,59 @@ class CloudTrailIntegrationTest {
.body("ResourceTagList[0].TagsList[0].Key", equalTo("team"));
}
@Test
void createTrailWithTagsListIsVisibleThroughListTags() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String trailName = "created-tagged-" + suffix;
String destBucket = "created-tagged-logs-" + suffix;
createBucket(destBucket);
// The Terraform AWS provider never calls AddTags on create: it sends the resource's
// tags inside CreateTrail and then reads them back with ListTags on the post-create
// refresh, so tags dropped here would show up as a perpetual diff.
String trailArn = invokeCloudTrail("CreateTrail", String.format("""
{"Name":"%s","S3BucketName":"%s","TagsList":[{"Key":"Environment","Value":"compat-test"},{"Key":"Owner","Value":"floci"}]}
""", trailName, destBucket))
.then().statusCode(200)
.extract().path("TrailARN");
invokeCloudTrail("ListTags", String.format("""
{"ResourceIdList":["%s"]}
""", trailArn))
.then().statusCode(200)
.body("ResourceTagList[0].ResourceId", equalTo(trailArn))
.body("ResourceTagList[0].TagsList", hasSize(2))
.body("ResourceTagList[0].TagsList.find { it.Key == 'Environment' }.Value", equalTo("compat-test"))
.body("ResourceTagList[0].TagsList.find { it.Key == 'Owner' }.Value", equalTo("floci"));
}
@Test
void createTrailWithMoreThanFiftyTagsIsRejected() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String trailName = "too-many-tags-" + suffix;
String destBucket = "too-many-tags-logs-" + suffix;
createBucket(destBucket);
StringBuilder tagsList = new StringBuilder();
for (int i = 0; i < 51; i++) {
if (i > 0) {
tagsList.append(',');
}
tagsList.append("{\"Key\":\"k").append(i).append("\",\"Value\":\"v\"}");
}
invokeCloudTrail("CreateTrail", String.format("""
{"Name":"%s","S3BucketName":"%s","TagsList":[%s]}
""", trailName, destBucket, tagsList))
.then().statusCode(400)
.body(containsString("TagsLimitExceededException"));
// A rejected CreateTrail must not leave a half-created trail behind.
invokeCloudTrail("DescribeTrails",
String.format("{\"trailNameList\":[\"%s\"]}", trailName))
.then().statusCode(200)
.body("trailList", hasSize(0));
}
@Test
void listTagsOmitsValueForTagWithNoValue() {
String suffix = UUID.randomUUID().toString().substring(0, 8);