package s3notification import ( "bytes" "encoding/json" "fmt" "io" "net/url" "regexp" "github.com/seaweedfs/seaweedfs/weed/util/wildcard" ) const ( TargetsDirectory = "/etc/s3/notification" TargetsFile = "targets.json" // TopicNamespace keeps notification topics apart from the kafka namespace, // so Kafka clients cannot produce into them or collide with their names. TopicNamespace = "s3" topicPrefix = "notify-" ) const ( TargetTypeTopic = "topic" TargetTypeWebhook = "webhook" TargetTypeKafka = "kafka" TargetTypeAwsSqs = "aws_sqs" TargetTypeGooglePubSub = "google_pub_sub" TargetTypePubSub = "pubsub" ) // A target name is the last segment of a destination ARN and part of an MQ // topic name, so it stays within what both can carry. var targetNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`) // Target is an operator-defined destination. Bucket owners refer to it by name // and cannot make the server connect anywhere else. Credentials are only ever // read from the registry file, never returned or logged. type Target struct { Name string `json:"name"` Type string `json:"type"` Enabled bool `json:"enabled"` // AllowedBuckets are bucket name globs; a target with none is usable by no bucket. AllowedBuckets []string `json:"allowed_buckets,omitempty"` // webhook Endpoint string `json:"endpoint,omitempty"` BearerToken string `json:"bearer_token,omitempty"` // kafka; Topic is shared with google_pub_sub Hosts []string `json:"hosts,omitempty"` Topic string `json:"topic,omitempty"` SASLEnabled bool `json:"sasl_enabled,omitempty"` SASLMechanism string `json:"sasl_mechanism,omitempty"` SASLUsername string `json:"sasl_username,omitempty"` SASLPassword string `json:"sasl_password,omitempty"` TLSEnabled bool `json:"tls_enabled,omitempty"` TLSCACert string `json:"tls_ca_cert,omitempty"` TLSClientCert string `json:"tls_client_cert,omitempty"` TLSClientKey string `json:"tls_client_key,omitempty"` TLSInsecureSkipVerify bool `json:"tls_insecure_skip_verify,omitempty"` // aws_sqs Region string `json:"region,omitempty"` SqsQueueName string `json:"sqs_queue_name,omitempty"` AwsAccessKeyID string `json:"aws_access_key_id,omitempty"` AwsSecretAccessKey string `json:"aws_secret_access_key,omitempty"` // google_pub_sub ProjectID string `json:"project_id,omitempty"` GoogleApplicationCredentials string `json:"google_application_credentials,omitempty"` // pubsub TopicURL string `json:"topic_url,omitempty"` } // TopicName is the MQ topic, in TopicNamespace, that carries the target's events. func (t *Target) TopicName() string { return topicPrefix + t.Name } // AllowsBucket reports whether the target is enabled and bucket matches one of its globs. func (t *Target) AllowsBucket(bucket string) bool { if !t.Enabled { return false } for _, pattern := range t.AllowedBuckets { if wildcard.MatchesWildcard(pattern, bucket) { return true } } return false } func (t *Target) validate() error { if !targetNamePattern.MatchString(t.Name) { return fmt.Errorf("invalid target name %q", t.Name) } missing := func(field string) error { return fmt.Errorf("target %s: %s is required for type %s", t.Name, field, t.Type) } switch t.Type { case TargetTypeTopic: case TargetTypeWebhook: if t.Endpoint == "" { return missing("endpoint") } u, err := url.Parse(t.Endpoint) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { return fmt.Errorf("target %s: endpoint must be an http or https URL", t.Name) } case TargetTypeKafka: if len(t.Hosts) == 0 { return missing("hosts") } if t.Topic == "" { return missing("topic") } case TargetTypeAwsSqs: if t.Region == "" { return missing("region") } if t.SqsQueueName == "" { return missing("sqs_queue_name") } case TargetTypeGooglePubSub: if t.ProjectID == "" { return missing("project_id") } if t.Topic == "" { return missing("topic") } case TargetTypePubSub: if t.TopicURL == "" { return missing("topic_url") } default: return fmt.Errorf("target %s: unknown type %q", t.Name, t.Type) } return nil } // Registry is the parsed targets file. A nil Registry has no targets. type Registry struct { targets map[string]*Target names []string } type registryFile struct { Targets []*Target `json:"targets"` } // ParseTargets parses and validates the targets file. Unknown fields are // rejected so a misspelled key does not silently drop a setting. func ParseTargets(content []byte) (*Registry, error) { reg := &Registry{targets: map[string]*Target{}} if len(bytes.TrimSpace(content)) == 0 { return reg, nil } var file registryFile dec := json.NewDecoder(bytes.NewReader(content)) dec.DisallowUnknownFields() if err := dec.Decode(&file); err != nil { return nil, fmt.Errorf("parse %s: %w", TargetsFile, err) } if _, err := dec.Token(); err != io.EOF { return nil, fmt.Errorf("parse %s: trailing data after the document", TargetsFile) } for i, t := range file.Targets { if t == nil { return nil, fmt.Errorf("target %d is null", i) } if err := t.validate(); err != nil { return nil, err } if _, dup := reg.targets[t.Name]; dup { return nil, fmt.Errorf("duplicate target name %q", t.Name) } reg.targets[t.Name] = t reg.names = append(reg.names, t.Name) } return reg, nil } // Lookup returns the named target, enabled or not. func (r *Registry) Lookup(name string) (*Target, bool) { if r == nil { return nil, false } t, ok := r.targets[name] return t, ok } // Resolve returns the named target if bucket may send events to it. func (r *Registry) Resolve(name, bucket string) (*Target, bool) { t, ok := r.Lookup(name) if !ok || !t.AllowsBucket(bucket) { return nil, false } return t, true } // Names lists the targets in file order. func (r *Registry) Names() []string { if r == nil { return nil } return append([]string(nil), r.names...) }