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 }