Files
seaweedfs/weed/s3api/s3notification/config.go
T
Chris LuandClaude Opus 5.5 6b2e22950a s3: bucket notification configuration API and target registry (#13236)
* s3: add the bucket notification target registry

Notification destinations are defined by the operator in
/etc/s3/notification/targets.json and referred to by name from bucket
configurations, so a bucket owner cannot make the server connect anywhere
new. The registry parses and validates that file: unique names that fit in
an ARN segment and an MQ topic name, known types (topic and webhook now,
kafka, aws_sqs, google_pub_sub and pubsub accepted for later), the fields
each type needs, and no unknown keys. A target serves only the buckets its
allowed_buckets globs match, and none when the list is empty. Parse errors
never carry credential values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: hot-reload the notification target registry

Every gateway reads /etc/s3/notification/targets.json at startup and
reloads it from the /etc metadata subscription it already runs for the IAM
and circuit breaker files. A write reloads it, a delete or rename away
empties it, and a file that does not parse leaves the previous registry in
place so a bad edit does not cut every bucket off its destinations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: parse and validate bucket notification configurations

The full PutBucketNotificationConfiguration document is parsed: topic,
queue and cloud function configurations with their Id, destination ARN,
events and key filter. Event names are checked against the AWS list,
wildcards and names for things that never happen here included, plus the
multipart and retention events this server emits. A filter takes at most
one prefix and one suffix rule, a document at most 100 configurations, and
overlapping rules are allowed. EventBridge stays NotImplemented.

A destination resolves by the last segment of its ARN to a target, which
must exist, be enabled and allow the bucket; the error does not say which
of those failed. A rule without an Id gets one derived from its content, so
every gateway reports the same configurationId for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: match an event against a bucket's notification rules

Configuration.Match takes an event name such as s3:ObjectCreated:Put and
an object key and returns each rule that covers them, with its
configurationId and target, in configuration order. Category wildcards
cover every event in the category, prefix and suffix are case-sensitive and
checked independently, and an event that several rules cover matches each
of them, as AWS delivers one record per rule. Publishing calls this; it is
a pure function of the stored configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: store bucket notification configurations

PutBucketNotificationConfiguration used to accept only an empty document
and answer NotImplemented for any destination. It now parses the full
document, checks every destination against the target registry for this
bucket, and stores the XML exactly as sent in one Extended key on the
bucket entry through updateBucketConfig, which patches that key alone on
the bucket's owner filer. An empty document removes the key. GET returns
the stored bytes unchanged, so tools comparing ARNs see no diff, and the
bucket config cache carries the parsed rules for publishing to match.

x-amz-skip-destination-validation is parsed and must be true or false. It
only skips the test event, which publishing will send; the registry check
always runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3notification: reject content after the configuration's root element

The stored document is served back unchanged by GET, so anything after the
root other than whitespace, comments or processing instructions is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3notification: reject unknown elements inside rules and filters

A misspelled Filter, S3Key, FilterRule or Value was dropped by decoding and
left an unfiltered rule; it is now MalformedXML like an unknown root child.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3notification: URL-decode prefix and suffix filter values

AWS has special characters in filter values percent-encoded and a space
written as +, so reports+2026/ selects reports 2026/a. A value that is not
valid encoding is still matched as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: refuse a notification targets file stored in chunks

Only inline content is read, so a targets.json kept in chunks (written by a
mount, for one) read as an empty registry and dropped every target. It is
now refused with a warning and the loaded registry stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3notification: refuse overlapping rules as AWS does

AWS answers InvalidArgument ("Configuration is ambiguously defined") when two
rules share an event type and both their prefixes and suffixes overlap, so an
event for a key matches at most one rule. Such configurations were accepted
and matched every rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:45:21 -08:00

315 lines
9.3 KiB
Go

package s3notification
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"net/url"
"strings"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
const (
MaxConfigurations = 100
// MaxConfigurationSize bounds the stored document; 100 rules with long
// filters and every event name fit well within it.
MaxConfigurationSize = 256 * 1024
maxFilterValueLength = 1024
)
// NotificationConfiguration is the PutBucketNotificationConfiguration document.
type NotificationConfiguration struct {
XMLName xml.Name `xml:"NotificationConfiguration"`
TopicConfigurations []TopicConfiguration `xml:"TopicConfiguration"`
QueueConfigurations []QueueConfiguration `xml:"QueueConfiguration"`
CloudFunctionConfigurations []CloudFunctionConfiguration `xml:"CloudFunctionConfiguration"`
EventBridgeConfiguration []struct{} `xml:"EventBridgeConfiguration"`
Unknown []struct{} `xml:",any"`
}
type commonConfiguration struct {
ID string `xml:"Id"`
Events []string `xml:"Event"`
Filter *Filter `xml:"Filter"`
Unknown []struct{} `xml:",any"`
}
type TopicConfiguration struct {
commonConfiguration
Topic string `xml:"Topic"`
}
type QueueConfiguration struct {
commonConfiguration
Queue string `xml:"Queue"`
}
type CloudFunctionConfiguration struct {
commonConfiguration
CloudFunction string `xml:"CloudFunction"`
InvocationRole string `xml:"InvocationRole"`
}
type Filter struct {
S3Key *S3KeyFilter `xml:"S3Key"`
Unknown []struct{} `xml:",any"`
}
type S3KeyFilter struct {
FilterRules []FilterRule `xml:"FilterRule"`
Unknown []struct{} `xml:",any"`
}
type FilterRule struct {
Name string `xml:"Name"`
Value string `xml:"Value"`
Unknown []struct{} `xml:",any"`
}
// Rule is one topic, queue or cloud function configuration, resolved to the
// target named by the last segment of its destination ARN.
type Rule struct {
ID string
Destination string
Target string
Events []string
Prefix string
Suffix string
}
// Configuration is a bucket's validated notification configuration.
type Configuration struct {
Rules []Rule
}
// ConfigError carries the S3 error a rejected configuration is answered with.
type ConfigError struct {
Code s3err.ErrorCode
Message string
}
func (e *ConfigError) Error() string {
if e.Message != "" {
return e.Message
}
return s3err.GetAPIError(e.Code).Description
}
func invalidArgument(format string, args ...any) *ConfigError {
return &ConfigError{Code: s3err.ErrInvalidArgument, Message: fmt.Sprintf(format, args...)}
}
var errMalformed = &ConfigError{Code: s3err.ErrMalformedXML}
// ParseConfiguration decodes and validates a notification configuration
// document. Destinations are checked against the target registry separately,
// by ValidateDestinations, since a stored configuration stays readable when a
// target is later removed. Errors are *ConfigError.
func ParseConfiguration(data []byte) (*Configuration, error) {
var doc NotificationConfiguration
dec := xml.NewDecoder(bytes.NewReader(data))
dec.CharsetReader = func(_ string, input io.Reader) (io.Reader, error) { return input, nil }
if err := dec.Decode(&doc); err != nil || len(doc.Unknown) > 0 || !onlyMiscAfterRoot(dec) {
return nil, errMalformed
}
if len(doc.EventBridgeConfiguration) > 0 {
return nil, &ConfigError{Code: s3err.ErrNotImplemented, Message: "EventBridge configurations are not supported"}
}
type rawRule struct {
common commonConfiguration
destination string
}
var raw []rawRule
for _, c := range doc.TopicConfigurations {
raw = append(raw, rawRule{c.commonConfiguration, c.Topic})
}
for _, c := range doc.QueueConfigurations {
raw = append(raw, rawRule{c.commonConfiguration, c.Queue})
}
for _, c := range doc.CloudFunctionConfigurations {
raw = append(raw, rawRule{c.commonConfiguration, c.CloudFunction})
}
if len(raw) > MaxConfigurations {
return nil, invalidArgument("A notification configuration can have at most %d topic, queue and cloud function configurations", MaxConfigurations)
}
config := &Configuration{Rules: make([]Rule, 0, len(raw))}
ids := make(map[string]bool, len(raw))
for _, r := range raw {
rule, err := parseRule(r.common, r.destination)
if err != nil {
return nil, err
}
if rule.ID != "" {
if ids[rule.ID] {
return nil, invalidArgument("Configuration Id %q is used more than once", rule.ID)
}
ids[rule.ID] = true
}
config.Rules = append(config.Rules, rule)
}
for i := range config.Rules {
for j := i + 1; j < len(config.Rules); j++ {
if config.Rules[i].overlaps(&config.Rules[j]) {
return nil, invalidArgument("Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.")
}
}
}
for i := range config.Rules {
if config.Rules[i].ID == "" {
config.Rules[i].ID = generatedID(&config.Rules[i], ids)
}
}
return config, nil
}
// onlyMiscAfterRoot reports whether the rest of the input holds nothing but
// whitespace, comments and processing instructions, since the stored document
// is served back unchanged.
func onlyMiscAfterRoot(dec *xml.Decoder) bool {
for {
tok, err := dec.Token()
if err == io.EOF {
return true
}
if err != nil {
return false
}
switch t := tok.(type) {
case xml.Comment, xml.ProcInst:
case xml.CharData:
if len(bytes.TrimSpace(t)) > 0 {
return false
}
default:
return false
}
}
}
func parseRule(c commonConfiguration, destination string) (Rule, error) {
rule := Rule{ID: strings.TrimSpace(c.ID), Destination: strings.TrimSpace(destination)}
if rule.Destination == "" || len(c.Events) == 0 || hasUnknownElements(c) {
return Rule{}, errMalformed
}
target, ok := targetFromARN(rule.Destination)
if !ok {
return Rule{}, invalidArgument("Invalid ARN %q", rule.Destination)
}
rule.Target = target
for _, event := range c.Events {
event = strings.TrimSpace(event)
if !IsSupportedEvent(event) {
return Rule{}, invalidArgument("The event %q is not supported for notifications", event)
}
rule.Events = append(rule.Events, event)
}
if c.Filter != nil && c.Filter.S3Key != nil {
var hasPrefix, hasSuffix bool
for _, fr := range c.Filter.S3Key.FilterRules {
if len(fr.Value) > maxFilterValueLength {
return Rule{}, invalidArgument("FilterRule value cannot be longer than %d characters", maxFilterValueLength)
}
switch strings.ToLower(strings.TrimSpace(fr.Name)) {
case "prefix":
if hasPrefix {
return Rule{}, invalidArgument("Cannot specify more than one prefix rule in a filter.")
}
hasPrefix, rule.Prefix = true, decodeFilterValue(fr.Value)
case "suffix":
if hasSuffix {
return Rule{}, invalidArgument("Cannot specify more than one suffix rule in a filter.")
}
hasSuffix, rule.Suffix = true, decodeFilterValue(fr.Value)
default:
return Rule{}, invalidArgument("filter rule name must be either prefix or suffix")
}
}
}
return rule, nil
}
// decodeFilterValue turns a filter value into the key text it matches: AWS has
// special characters in prefix and suffix values URL-encoded, with + for a
// space. A value that is not valid encoding is matched as written.
func decodeFilterValue(v string) string {
if decoded, err := url.QueryUnescape(v); err == nil {
return decoded
}
return v
}
// hasUnknownElements reports a misspelled or misplaced element anywhere in a
// rule, which decoding would otherwise drop, widening the rule.
func hasUnknownElements(c commonConfiguration) bool {
if len(c.Unknown) > 0 {
return true
}
if c.Filter == nil {
return false
}
if len(c.Filter.Unknown) > 0 {
return true
}
if c.Filter.S3Key == nil {
return false
}
if len(c.Filter.S3Key.Unknown) > 0 {
return true
}
for _, fr := range c.Filter.S3Key.FilterRules {
if len(fr.Unknown) > 0 {
return true
}
}
return false
}
// targetFromARN returns the last segment of arn:partition:service:region:account:resource;
// everything before it is ignored.
func targetFromARN(arn string) (string, bool) {
parts := strings.Split(arn, ":")
if len(parts) < 6 || parts[0] != "arn" {
return "", false
}
name := parts[len(parts)-1]
return name, name != ""
}
// generatedID stands in for the Id AWS assigns to a rule that has none. It is
// derived from the rule so every gateway, and every PUT of the same rule, agrees.
func generatedID(rule *Rule, taken map[string]bool) string {
h := sha256.New()
fmt.Fprintf(h, "%s\x00%s\x00%s\x00%s", rule.Destination, strings.Join(rule.Events, ","), rule.Prefix, rule.Suffix)
base := base64.RawURLEncoding.EncodeToString(h.Sum(nil)[:18])
id := base
for n := 2; taken[id]; n++ {
id = fmt.Sprintf("%s-%d", base, n)
}
taken[id] = true
return id
}
// ValidateDestinations checks that every rule's target exists, is enabled and
// allows bucket. One message covers all of them and does not say which check
// failed, so a bucket owner cannot probe the registry.
func (c *Configuration) ValidateDestinations(reg *Registry, bucket string) error {
var unresolved []string
for _, rule := range c.Rules {
if _, ok := reg.Resolve(rule.Target, bucket); !ok {
unresolved = append(unresolved, rule.Destination)
}
}
if len(unresolved) > 0 {
return invalidArgument("Unable to validate the following destination configurations: %s", strings.Join(unresolved, ", "))
}
return nil
}