fix(s3): validate notification destinations before storing configuration (#4747)

* fix(s3): validate notification destinations before storing configuration

* test(s3): consume validation events before POST notifications

* fix(s3): preserve bucket lifecycle during notification validation

* fix(s3): enforce SQS queue policies for notifications

* fix(s3): align notification validation with IAM enforcement

* fix(test): stub IAM config for S3 failure delivery

* fix(s3): validate cross-account SNS without test publish

* fix(sns): recognize legacy topics during destination validation

* docs(s3): describe cross-account notification validation

* fix(s3): skip cross-account SNS notification test publishes
This commit is contained in:
XuJian authored and GitHub committed 2026-10-01 11:35:16 -04:00
1 parent bc2592e300
commit b2dd5665db
14 files changed
+1051 -23

No files matched your search

@@ -289,7 +289,8 @@ public class S3Controller {
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
if (hasQueryParam(uriInfo, "notification")) {
s3Service.authorizeBucketWrite(bucket, "s3:PutBucketNotification", authorization);
return handlePutBucketNotification(bucket, body);
return handlePutBucketNotification(bucket, body,
Boolean.parseBoolean(httpHeaders.getHeaderString("x-amz-skip-destination-validation")));
}
if (hasQueryParam(uriInfo, "versioning")) {
s3Service.authorizeBucketWrite(bucket, "s3:PutBucketVersioning", authorization);
@@ -1916,31 +1917,31 @@ public class S3Controller {
}
}
private Response handlePutBucketNotification(String bucket, byte[] body) {
private Response handlePutBucketNotification(String bucket, byte[] body, boolean skipDestinationValidation) {
try {
String xml = new String(body, StandardCharsets.UTF_8);
NotificationConfiguration config = new NotificationConfiguration();
for (var parsed : parseNotificationGroups(xml, "QueueConfiguration", "Queue")) {
for (ParsedNotificationGroup parsed : parseNotificationGroups(xml, "QueueConfiguration", "Queue")) {
config.getQueueConfigurations().add(
new QueueNotification(parsed.id, parsed.arn, parsed.events, parsed.filterRules));
}
for (var parsed : parseNotificationGroups(xml, "TopicConfiguration", "Topic")) {
for (ParsedNotificationGroup parsed : parseNotificationGroups(xml, "TopicConfiguration", "Topic")) {
config.getTopicConfigurations().add(
new TopicNotification(parsed.id, parsed.arn, parsed.events, parsed.filterRules));
}
for (var parsed : parseNotificationGroups(xml, "LambdaFunctionConfiguration", "LambdaFunctionArn")) {
for (ParsedNotificationGroup parsed : parseNotificationGroups(xml, "LambdaFunctionConfiguration", "LambdaFunctionArn")) {
config.getLambdaFunctionConfigurations().add(
new LambdaNotification(parsed.id, parsed.arn, parsed.events, parsed.filterRules));
}
for (var parsed : parseNotificationGroups(xml, "CloudFunctionConfiguration", "CloudFunction")) {
for (ParsedNotificationGroup parsed : parseNotificationGroups(xml, "CloudFunctionConfiguration", "CloudFunction")) {
config.getLambdaFunctionConfigurations().add(
new LambdaNotification(parsed.id, parsed.arn, parsed.events, parsed.filterRules));
}
config.setEventBridgeEnabled(parseEventBridgeConfiguration(xml));
s3Service.putBucketNotificationConfiguration(bucket, config);
s3Service.putBucketNotificationConfiguration(bucket, config, skipDestinationValidation);
return Response.ok().build();
} catch (AwsException e) {
return xmlErrorResponse(e, bucket);
@@ -3285,6 +3286,19 @@ public class S3Controller {
if (argumentValue != null) {
xmlBuilder.elem("ArgumentValue", argumentValue.toString());
}
for (int index = 1; ; index++) {
Object numberedName = e.getExtendedData().get("ArgumentName" + index);
Object numberedValue = e.getExtendedData().get("ArgumentValue" + index);
if (numberedName == null && numberedValue == null) {
break;
}
if (numberedName != null) {
xmlBuilder.elem("ArgumentName" + index, numberedName.toString());
}
if (numberedValue != null) {
xmlBuilder.elem("ArgumentValue" + index, numberedValue.toString());
}
}
}
String xml = xmlBuilder
.elem("RequestId", java.util.UUID.randomUUID().toString())
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicy
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.s3.model.*;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.sns.SnsService;
@@ -163,6 +164,7 @@ public class S3Service implements Resettable, ResourceProvider {
private final String baseUrl;
private final ObjectMapper objectMapper;
private final boolean enforceAuth;
private final boolean enforceIam;
private final IamService iamService;
private final boolean globalBucketNamespace;
private final IamPolicyEvaluator policyEvaluator;
@@ -195,7 +197,7 @@ public class S3Service implements Resettable, ResourceProvider {
eventBridgeService, s3UpdatedEvent,
regionResolver,
config.effectiveBaseUrl(), objectMapper,
config.services().s3().enforceAuth(), iamService,
config.services().s3().enforceAuth(), config.services().iam().enforcementEnabled(), iamService,
config.services().s3().globalBucketNamespace()
);
}
@@ -208,7 +210,7 @@ public class S3Service implements Resettable, ResourceProvider {
Path dataRoot, boolean inMemory) {
this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, null, false);
null, "http://localhost:4566", new ObjectMapper(), false, false, null, false);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -217,7 +219,7 @@ public class S3Service implements Resettable, ResourceProvider {
boolean enforceAuth, IamService iamService) {
this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), enforceAuth, iamService, false);
null, "http://localhost:4566", new ObjectMapper(), enforceAuth, false, iamService, false);
}
/** Package-private constructor for testing account-level Block Public Access persistence. */
@@ -227,7 +229,7 @@ public class S3Service implements Resettable, ResourceProvider {
Path dataRoot, boolean inMemory) {
this(bucketStore, objectStore, defaultAnnotationStore(), accountPublicAccessBlockStore,
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, null, false);
null, "http://localhost:4566", new ObjectMapper(), false, false, null, false);
}
/** Package-private constructor for testing the global-bucket-namespace resolution flag. */
@@ -236,7 +238,7 @@ public class S3Service implements Resettable, ResourceProvider {
Path dataRoot, boolean inMemory, boolean globalBucketNamespace) {
this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, null, globalBucketNamespace);
null, "http://localhost:4566", new ObjectMapper(), false, false, null, globalBucketNamespace);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -246,7 +248,7 @@ public class S3Service implements Resettable, ResourceProvider {
RegionResolver regionResolver) {
this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, lambdaService, null, null, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null, false);
regionResolver, "http://localhost:4566", new ObjectMapper(), false, false, null, false);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
@@ -256,7 +258,7 @@ public class S3Service implements Resettable, ResourceProvider {
RegionResolver regionResolver) {
this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, lambdaInvoker, null, null,
regionResolver, "http://localhost:4566", new ObjectMapper(), false, null, false);
regionResolver, "http://localhost:4566", new ObjectMapper(), false, false, null, false);
}
/** In-memory account-level Block Public Access store for the package-private test constructors. */
@@ -280,7 +282,8 @@ public class S3Service implements Resettable, ResourceProvider {
EventBridgeService eventBridgeService,
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,
boolean enforceAuth, IamService iamService, boolean globalBucketNamespace) {
boolean enforceAuth, boolean enforceIam, IamService iamService,
boolean globalBucketNamespace) {
this.bucketStore = bucketStore;
this.objectStore = objectStore;
this.annotationStore = annotationStore;
@@ -298,6 +301,7 @@ public class S3Service implements Resettable, ResourceProvider {
this.baseUrl = baseUrl;
this.objectMapper = objectMapper;
this.enforceAuth = enforceAuth;
this.enforceIam = enforceIam;
this.iamService = iamService;
this.globalBucketNamespace = globalBucketNamespace;
this.policyEvaluator = new IamPolicyEvaluator(objectMapper);
@@ -3631,14 +3635,174 @@ public class S3Service implements Resettable, ResourceProvider {
// --- Notification Configuration ---
public void putBucketNotificationConfiguration(String bucketName, NotificationConfiguration config) {
putBucketNotificationConfiguration(bucketName, config, false);
}
public void putBucketNotificationConfiguration(String bucketName, NotificationConfiguration config,
boolean skipDestinationValidation) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
bucket.setNotificationConfiguration(config);
bucketStore.put(bucketName, bucket);
List<NotificationDestination> destinations = notificationDestinations(config);
if (!skipDestinationValidation) {
List<DestinationFailure> failures = new ArrayList<>();
for (NotificationDestination destination : destinations) {
if (!notificationDestinationExists(destination)) {
failures.add(missingDestination(destination));
}
}
if (!failures.isEmpty()) {
throw invalidNotificationDestinations(failures);
}
String testEvent = s3TestEvent(bucketName);
for (NotificationDestination destination : destinations) {
try {
if (!destination.accountId().equals(ownerId())
&& ("sns".equals(destination.service())
|| enforceIam && "sqs".equals(destination.service()))) {
// SNS publish still resolves topics in the caller's account.
continue;
}
if ("sqs".equals(destination.service())) {
sqsService.sendMessage(sqsUrlFromArn(destination.arn()), testEvent, 0,
destination.region());
} else if ("sns".equals(destination.service())) {
snsService.publish(destination.arn(), null, testEvent, "Amazon S3 Notification",
destination.region());
}
} catch (AwsException e) {
failures.add(new DestinationFailure(destination, e.getMessage()));
}
}
if (!failures.isEmpty()) {
throw invalidNotificationDestinations(failures);
}
}
synchronized (bucket) {
requireSameRecord(bucketName, bucket);
bucket.setNotificationConfiguration(config);
bucketStore.put(bucketName, bucket);
}
LOG.infov("Set notification configuration for bucket: {0}", bucketName);
}
private record NotificationDestination(String arn, String service, String region, String accountId) {}
private record DestinationFailure(NotificationDestination destination, String reason) {}
private static List<NotificationDestination> notificationDestinations(NotificationConfiguration config) {
List<NotificationDestination> destinations = new ArrayList<>();
for (QueueNotification queue : config.getQueueConfigurations()) {
destinations.add(notificationDestination(queue.queueArn(), "Queue", "sqs"));
}
for (TopicNotification topic : config.getTopicConfigurations()) {
destinations.add(notificationDestination(topic.topicArn(), "Topic", "sns"));
}
for (LambdaNotification lambda : config.getLambdaFunctionConfigurations()) {
destinations.add(notificationDestination(lambda.functionArn(), "CloudFunction", "lambda"));
}
return destinations;
}
private static NotificationDestination notificationDestination(String arn, String argumentName,
String service) {
AwsArnUtils.Arn parsed;
try {
parsed = AwsArnUtils.parse(arn);
} catch (IllegalArgumentException e) {
throw invalidNotificationArn(arn, argumentName);
}
boolean validResource = switch (service) {
case "sqs" -> parsed.resource().matches("[A-Za-z0-9_-]{1,80}")
|| parsed.resource().matches("[A-Za-z0-9_-]{1,75}\\.fifo");
case "sns" -> parsed.resource().matches("[A-Za-z0-9_-]{1,256}")
|| parsed.resource().matches("[A-Za-z0-9_-]{1,251}\\.fifo");
case "lambda" -> parsed.resource().matches(
"function:[A-Za-z0-9_-]{1,64}(?::[A-Za-z0-9_$-]{1,128})?");
default -> false;
};
if (!parsed.partition().matches(AwsArnUtils.PARTITION_REGEX)
|| !parsed.service().equals(service)
|| !parsed.region().matches("[a-z0-9-]+")
|| !parsed.accountId().matches("[0-9]{12}")
|| !validResource
|| AwsRegions.isRegionId(parsed.region())
&& !parsed.partition().equals(AwsRegions.partitionFor(parsed.region()))) {
throw invalidNotificationArn(arn, argumentName);
}
return new NotificationDestination(arn, service, parsed.region(), parsed.accountId());
}
private static AwsException invalidNotificationArn(String arn, String argumentName) {
Map<String, Object> details = new LinkedHashMap<>();
details.put("ArgumentName", argumentName);
details.put("ArgumentValue", arn);
return new AwsException("InvalidArgument", "The ARN could not be parsed", 400, details);
}
private boolean notificationDestinationExists(NotificationDestination destination) {
return switch (destination.service()) {
case "sqs" -> sqsService != null
&& sqsService.queueExists(sqsUrlFromArn(destination.arn()), destination.region());
case "sns" -> snsService != null && snsService.topicExists(destination.arn(), destination.region());
case "lambda" -> lambdaNotificationDestinationExists(destination);
default -> false;
};
}
private boolean lambdaNotificationDestinationExists(NotificationDestination destination) {
LambdaService service = resolveLambdaService();
if (service == null) {
return false;
}
try {
LambdaFunction function = service.getFunction(destination.region(), destination.arn(), null);
return destination.accountId().equals(AwsArnUtils.accountOrDefault(function.getFunctionArn(), null));
} catch (AwsException e) {
LOG.debugv("Lambda notification destination {0} is unavailable: {1} ({2})",
destination.arn(), e.getErrorCode(), e.getMessage());
return false;
}
}
private static DestinationFailure missingDestination(NotificationDestination destination) {
String reason = switch (destination.service()) {
case "sqs" -> "The destination queue does not exist";
case "sns" -> "The destination topic does not exist";
case "lambda" -> "Not authorized to invoke function [" + destination.arn() + "]";
default -> "The destination does not exist";
};
return new DestinationFailure(destination, reason);
}
private static AwsException invalidNotificationDestinations(List<DestinationFailure> failures) {
Map<String, Object> details = new LinkedHashMap<>();
for (int index = 0; index < failures.size(); index++) {
DestinationFailure failure = failures.get(index);
NotificationDestination destination = failure.destination();
String argument = "lambda".equals(destination.service())
? destination.arn() + ", null" : destination.arn();
details.put("ArgumentName" + (index + 1), argument);
details.put("ArgumentValue" + (index + 1), failure.reason());
}
return new AwsException("InvalidArgument",
"Unable to validate the following destination configurations", 400, details);
}
private String s3TestEvent(String bucketName) {
ObjectNode event = objectMapper.createObjectNode();
event.put("Service", "Amazon S3");
event.put("Event", "s3:TestEvent");
event.put("Time", Instant.now().toString());
event.put("Bucket", bucketName);
event.put("RequestId", UUID.randomUUID().toString());
event.put("HostId", UUID.randomUUID().toString());
return event.toString();
}
public NotificationConfiguration getBucketNotificationConfiguration(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
@@ -4529,7 +4693,8 @@ public class S3Service implements Resettable, ResourceProvider {
for (QueueNotification qn : config.getQueueConfigurations()) {
if (qn.events().stream().anyMatch(p -> matchesEvent(p, eventName)) && qn.matchesKey(key)) {
try {
sqsService.sendMessage(sqsUrlFromArn(qn.queueArn()), eventJson, 0, extractRegionFromArn(qn.queueArn()));
sqsService.sendMessage(sqsUrlFromArn(qn.queueArn()), eventJson, 0,
extractRegionFromArn(qn.queueArn()));
LOG.debugv("Fired S3 event {0} to SQS {1}", eventName, qn.queueArn());
} catch (Exception e) {
LOG.warnv("Failed to deliver S3 event to SQS {0}: {1}", qn.queueArn(), e.getMessage());
@@ -4540,7 +4705,8 @@ public class S3Service implements Resettable, ResourceProvider {
for (TopicNotification tn : config.getTopicConfigurations()) {
if (tn.events().stream().anyMatch(p -> matchesEvent(p, eventName)) && tn.matchesKey(key)) {
try {
snsService.publish(tn.topicArn(), null, eventJson, "Amazon S3 Notification", region);
snsService.publish(tn.topicArn(), null, eventJson, "Amazon S3 Notification",
extractRegionFromArn(tn.topicArn()));
LOG.debugv("Fired S3 event {0} to SNS {1}", eventName, tn.topicArn());
} catch (Exception e) {
LOG.warnv("Failed to deliver S3 event to SNS {0}: {1}", tn.topicArn(), e.getMessage());
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.SsrfProtection;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
@@ -383,6 +384,11 @@ public class SnsService implements Resettable, ResourceProvider {
}
public boolean topicExists(String topicArn, String region) {
if (topicStore instanceof AccountAwareStorageBackend<Topic> aware) {
String accountId = AwsArnUtils.accountOrDefault(topicArn, regionResolver.getAccountId());
return aware.getForAccountMigratingLegacy(accountId, topicKey(region, topicArn),
topic -> topicArn.equals(topic.getTopicArn())).isPresent();
}
return topicStore.get(topicKey(region, topicArn)).isPresent();
}
@@ -702,6 +702,10 @@ public class SqsService implements Resettable, ResourceProvider {
return queueUrl;
}
public boolean queueExists(String queueUrl, String region) {
return getQueueByUrl(regionKey(region, queueUrl), queueUrl).isPresent();
}
public Map<String, String> getQueueAttributes(String queueUrl, List<String> attributeNames, String region) {
String storageKey = regionKey(region, queueUrl);
Queue queue = queueStore.get(storageKey)