diff --git a/docs/services/s3.md b/docs/services/s3.md index 1f80e347e7..41d76047a7 100644 --- a/docs/services/s3.md +++ b/docs/services/s3.md @@ -763,3 +763,18 @@ Current limitations: - cross-account canned ACL variants collapse to the emulator's single synthetic owner where Floci does not model a distinct second principal - `aws-exec-read` is accepted for compatibility, but Floci does not yet model a distinct EC2 bundle-reader grantee in `GetObjectAcl` - `log-delivery-write` grants the well-known S3 log-delivery group (`http://acs.amazonaws.com/groups/s3/LogDelivery`) `WRITE` and `READ_ACP`, matching AWS on the bucket path. Floci's shared canned-ACL helper also accepts it on `PutObjectAcl`, where AWS does not: the canned ACL is documented as bucket-only and the SDK's `ObjectCannedACL` enum omits it. That object path is a Floci leniency, not parity. It is the mirror image of `aws-exec-read` above, which botocore's `BucketCannedACL` enum omits, though AWS's canned-ACL reference documents it as valid for both bucket and object; there the narrower party is the SDK model, not AWS + +## Notification event compatibility + +Native queue, topic and Lambda notification records include both response identifiers and the +legacy bucket owner identity expected by existing AWS event consumers. Each destination receives +its configured rule ID, or `emulator` if the ID is null, empty or blank. Copies of the same operation +retain a common event time, response IDs, object details and sequencer, including version details +captured before delivery. Response IDs are synthetic emulator identifiers and do not correlate +with the initiating HTTP response headers. + +The legacy `ownerIdentity.principalId` is the owning account's synthetic customer ID, separate +from the canonical user ID used by ACL APIs. Notification object keys use form URL encoding: +spaces become `+`, literal plus signs become `%2B`, and `/` is preserved. Consumers must ignore +additional fields as described in the +[AWS event message structure](https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html). diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index 91f6f922e8..fc8395fbfb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -6886,12 +6886,15 @@ public class S3Service implements Resettable, ResourceProvider { } String region = bucket.getRegion(); - String eventJson = buildS3EventJson(bucketName, key, eventName, obj, region, bucket.isVersioningEnabled(), - sequencer); + String eventTime = DateTimeFormatter.ISO_INSTANT.format(Instant.now()); + String requestId = UUID.randomUUID().toString(); + ObjectNode event = buildS3Event(bucketName, key, eventName, obj, region, + bucket.isVersioningEnabled(), sequencer, eventTime, requestId); for (QueueNotification qn : config.getQueueConfigurations()) { if (qn.events().stream().anyMatch(p -> matchesEvent(p, eventName)) && qn.matchesKey(key)) { try { + String eventJson = notificationEventJson(event, qn.id()); sqsService.sendMessage(sqsUrlFromArn(qn.queueArn()), eventJson, 0, extractRegionFromArn(qn.queueArn())); LOG.debugv("Fired S3 event {0} to SQS {1}", eventName, qn.queueArn()); @@ -6904,6 +6907,7 @@ public class S3Service implements Resettable, ResourceProvider { for (TopicNotification tn : config.getTopicConfigurations()) { if (tn.events().stream().anyMatch(p -> matchesEvent(p, eventName)) && tn.matchesKey(key)) { try { + String eventJson = notificationEventJson(event, tn.id()); snsService.publish(tn.topicArn(), null, eventJson, "Amazon S3 Notification", extractRegionFromArn(tn.topicArn())); LOG.debugv("Fired S3 event {0} to SNS {1}", eventName, tn.topicArn()); @@ -6923,6 +6927,7 @@ public class S3Service implements Resettable, ResourceProvider { throw new AwsException("InvalidParameterValueException", "Invalid Lambda function ARN: " + ln.functionArn(), 400); } + String eventJson = notificationEventJson(event, ln.id()); invokeLambda(lambdaRegion, ln.functionArn(), eventJson.getBytes(StandardCharsets.UTF_8)); LOG.debugv("Fired S3 event {0} to Lambda {1}", eventName, ln.functionArn()); } catch (Exception e) { @@ -7054,16 +7059,17 @@ public class S3Service implements Resettable, ResourceProvider { } } - private String buildS3EventJson(String bucketName, String key, String eventName, - S3Object obj, String region, boolean isVersionEnabled, String sequencer) { + private ObjectNode buildS3Event(String bucketName, String key, String eventName, + S3Object obj, String region, boolean isVersionEnabled, String sequencer, + String eventTime, String requestId) { try { - String eventTime = DateTimeFormatter.ISO_INSTANT.format(Instant.now()); long size = obj != null ? obj.getSize() : 0; String eTag = obj != null && obj.getETag() != null ? obj.getETag().replace("\"", "") : ""; - String requestId = UUID.randomUUID().toString(); - ObjectNode bucketNode = objectMapper.createObjectNode(); bucketNode.put("name", bucketName); + String bucketOwner = resolveBucketEntry(bucketName) + .map(AccountAwareStorageBackend.OwnedEntry::account).orElseGet(this::ownerId); + bucketNode.putObject("ownerIdentity").put("principalId", bucketOwner); bucketNode.put("arn", AwsArnUtils.Arn.global(bucketPartition(bucketName), "s3", "", bucketName).toString()); ObjectNode objectNode = objectMapper.createObjectNode(); @@ -7092,17 +7098,31 @@ public class S3Service implements Resettable, ResourceProvider { record.putObject("userIdentity").put("principalId", lifecycle ? ServicePrincipals.of("s3") : "AWS:EMULATOR"); record.putObject("requestParameters") .put("sourceIPAddress", lifecycle ? ServicePrincipals.of("s3") : "127.0.0.1"); - record.putObject("responseElements").put("x-amz-request-id", requestId); + record.putObject("responseElements") + .put("x-amz-request-id", requestId) + .put("x-amz-id-2", requestId); record.set("s3", s3Node); ObjectNode root = objectMapper.createObjectNode(); root.putArray("Records").add(record); - return objectMapper.writeValueAsString(root); + return root; } catch (Exception e) { - return "{\"Records\":[]}"; + LOG.warnv("Failed to build S3 event for {0}: {1}", bucketName, e.getMessage()); + ObjectNode empty = objectMapper.createObjectNode(); + empty.putArray("Records"); + return empty; } } + private String notificationEventJson(ObjectNode event, String configurationId) throws JsonProcessingException { + ObjectNode copy = event.deepCopy(); + if (copy.path("Records").path(0).path("s3") instanceof ObjectNode s3) { + s3.put("configurationId", + configurationId == null || configurationId.isBlank() ? "emulator" : configurationId); + } + return objectMapper.writeValueAsString(copy); + } + /** * The key as S3 writes it into an event record: form URL-encoded (a space is {@code +}, a * {@code +} is {@code %2B}) with {@code /} left as is, so consumers decode it the documented diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3NotificationDestinationValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3NotificationDestinationValidationIntegrationTest.java index a7b6e17d65..92cfbcded1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3NotificationDestinationValidationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3NotificationDestinationValidationIntegrationTest.java @@ -13,6 +13,8 @@ import jakarta.inject.Inject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.time.Instant; import java.util.ArrayList; @@ -175,6 +177,62 @@ class S3NotificationDestinationValidationIntegrationTest { assertTestEvent(receiveQueueMessage(queueUrls.get(1)).getFirst().getBody()); } + @Test + void queueAndTopicCopiesKeepOperationMetadataAndTheirOwnRuleIds() throws Exception { + String directQueueArn = createQueue("event-direct", Map.of()); + String subscribedQueueArn = createQueue("event-subscribed", Map.of()); + String topicArn = createTopic("event-topic"); + snsService.subscribe(topicArn, "sqs", subscribedQueueArn, REGION, + Map.of("RawMessageDelivery", "true")); + putNotification(notificationConfiguration( + queueConfiguration(directQueueArn, "queue-rule") + + topicConfiguration(topicArn, "topic-rule")), true) + .statusCode(200); + try { + given().body("payload").put("/" + bucket + "/a%20b%2Bc.txt").then().statusCode(200); + + JsonNode queueEvent = objectMapper.readTree(receiveQueueMessage(queueUrls.get(0)) + .getFirst().getBody()).path("Records").get(0); + JsonNode topicEvent = objectMapper.readTree(receiveQueueMessage(queueUrls.get(1)) + .getFirst().getBody()).path("Records").get(0); + assertEquals("queue-rule", queueEvent.path("s3").path("configurationId").asText()); + assertEquals("topic-rule", topicEvent.path("s3").path("configurationId").asText()); + assertFalse(queueEvent.path("responseElements").path("x-amz-id-2").asText().isBlank()); + assertEquals("000000000000", queueEvent.path("s3").path("bucket") + .path("ownerIdentity").path("principalId").asText()); + assertEquals(queueEvent.path("eventTime"), topicEvent.path("eventTime")); + assertEquals(queueEvent.path("responseElements"), topicEvent.path("responseElements")); + assertEquals(queueEvent.path("s3").path("object"), topicEvent.path("s3").path("object")); + } finally { + given().delete("/" + bucket + "/a%20b%2Bc.txt").then().statusCode(204); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", "", " \t "}) + void missingQueueAndTopicRuleIdsUseEmulator(String idXml) throws Exception { + String directQueueArn = createQueue("fallback-direct", Map.of()); + String subscribedQueueArn = createQueue("fallback-subscribed", Map.of()); + String topicArn = createTopic("fallback-topic"); + snsService.subscribe(topicArn, "sqs", subscribedQueueArn, REGION, + Map.of("RawMessageDelivery", "true")); + putNotification(notificationConfiguration( + queueConfiguration(directQueueArn, idXml) + + topicConfiguration(topicArn, idXml)), true) + .statusCode(200); + try { + given().body("payload").put("/" + bucket + "/fallback.txt").then().statusCode(200); + + for (String queueUrl : queueUrls) { + JsonNode event = objectMapper.readTree(receiveQueueMessage(queueUrl) + .getFirst().getBody()).path("Records").get(0); + assertEquals("emulator", event.path("s3").path("configurationId").asText()); + } + } finally { + given().delete("/" + bucket + "/fallback.txt").then().statusCode(204); + } + } + @Test void crossRegionTopicReceivesTestEventAndLaterObjectEvent() throws Exception { String topicRegion = "ap-southeast-2"; @@ -335,12 +393,20 @@ class S3NotificationDestinationValidationIntegrationTest { } private static String queueConfiguration(String arn) { - return "" + arn + return queueConfiguration(arn, ""); + } + + private static String queueConfiguration(String arn, String idXml) { + return "" + idXml + "" + arn + "s3:ObjectCreated:*"; } private static String topicConfiguration(String arn) { - return "" + arn + return topicConfiguration(arn, ""); + } + + private static String topicConfiguration(String arn, String idXml) { + return "" + idXml + "" + arn + "s3:ObjectCreated:*"; } diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java index da64c282bf..a36a1aa993 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java @@ -28,6 +28,7 @@ import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import java.io.ByteArrayInputStream; @@ -972,6 +973,68 @@ class S3ServiceTest { assertTrue(deleted.compareTo(put) > 0, put + " then " + deleted); } + @Test + void notificationCarriesDocumentedEventFieldsAndConfiguredId() throws IOException { + RecordingLambdaInvoker invoker = new RecordingLambdaInvoker(); + S3Service service = bucketNotifyingOnCreation(invoker, "notification-consumer-fields"); + service.putObject("test-bucket", "original/a b+c.txt", + "payload".getBytes(StandardCharsets.UTF_8), "text/plain", null); + + JsonNode event = onlyRecordedS3Event(invoker); + assertFalse(event.path("responseElements").path("x-amz-id-2").asText().isBlank()); + assertFalse(event.path("responseElements").path("x-amz-request-id").asText().isBlank()); + assertEquals("000000000000", event.path("s3").path("bucket") + .path("ownerIdentity").path("principalId").asText()); + assertEquals("lambda-notif", event.path("s3").path("configurationId").asText()); + assertEquals("original/a+b%2Bc.txt", event.path("s3").path("object").path("key").asText()); + assertEquals(7, event.path("s3").path("object").path("size").asInt()); + } + + @Test + void eachMatchingNotificationCarriesItsOwnConfigurationId() throws IOException { + RecordingLambdaInvoker invoker = new RecordingLambdaInvoker(); + S3Service service = bucketNotifyingOnCreation(invoker, "notification-rule-identity"); + NotificationConfiguration config = service.getBucketNotificationConfiguration("test-bucket"); + config.getLambdaFunctionConfigurations().add(new LambdaNotification( + "second-rule", "arn:aws:lambda:us-east-1:000000000000:function:second", + List.of("s3:ObjectCreated:*"), List.of())); + service.putBucketNotificationConfiguration("test-bucket", config, true); + service.putBucketVersioning("test-bucket", "Enabled"); + invoker.afterDelivery = () -> service.putBucketVersioning("test-bucket", "Suspended"); + S3Object stored = service.putObject("test-bucket", "original.txt", new byte[]{1}, "text/plain", null); + + assertEquals(2, invoker.payloads.size()); + ObjectMapper mapper = new ObjectMapper(); + assertEquals("lambda-notif", mapper.readTree(invoker.payloads.get(0)) + .path("Records").get(0).path("s3").path("configurationId").asText()); + assertEquals("second-rule", mapper.readTree(invoker.payloads.get(1)) + .path("Records").get(0).path("s3").path("configurationId").asText()); + JsonNode first = mapper.readTree(invoker.payloads.get(0)).path("Records").get(0); + JsonNode second = mapper.readTree(invoker.payloads.get(1)).path("Records").get(0); + assertFalse(first.path("s3").path("object").path("versionId").asText().isBlank()); + assertEquals(stored.getVersionId(), first.path("s3").path("object").path("versionId").asText()); + assertEquals(first.path("eventTime"), second.path("eventTime")); + assertEquals(first.path("responseElements"), second.path("responseElements")); + assertEquals(first.path("s3").path("object"), second.path("s3").path("object")); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" \t "}) + void missingLambdaNotificationRuleIdUsesEmulator(String id) throws IOException { + RecordingLambdaInvoker invoker = new RecordingLambdaInvoker(); + S3Service service = bucketNotifyingOnCreation(invoker, "notification-missing-rule-id"); + NotificationConfiguration config = new NotificationConfiguration(); + config.getLambdaFunctionConfigurations().add(new LambdaNotification( + id, "arn:aws:lambda:us-east-1:000000000000:function:s3-notif-test", + List.of("s3:ObjectCreated:*"), List.of())); + service.putBucketNotificationConfiguration("test-bucket", config, true); + + service.putObject("test-bucket", "original.txt", new byte[]{1}, "text/plain", null); + + assertEquals("emulator", onlyRecordedS3Event(invoker).path("s3").path("configurationId").asText()); + } + private S3Service bucketNotifyingOnCreation(RecordingLambdaInvoker lambdaInvoker, String dataDir) { return bucketNotifyingOn(lambdaInvoker, dataDir, "s3:ObjectCreated:*"); } @@ -1029,6 +1092,8 @@ class S3ServiceTest { private String region; private String functionName; private byte[] payload; + private final List payloads = new ArrayList<>(); + private Runnable afterDelivery; private InvocationType type; @Override @@ -1036,7 +1101,11 @@ class S3ServiceTest { this.region = region; this.functionName = functionName; this.payload = payload; + this.payloads.add(payload); this.type = type; + if (afterDelivery != null) { + afterDelivery.run(); + } } }