package main import ( "errors" "fmt" "maps" "net/url" "regexp" "slices" "strings" "gopkg.in/yaml.v3" ) // targetName is what a target's name may be: it names Redis keys and // labels series, so it takes no separators and no spaces. var targetName = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) // validate reports every problem in the configuration, so that a file // with one makes LoadConfiguration fail and a reload keeps the // configuration that last loaded. It fills in the defaults of each // target. func (c *Configuration) validate() error { var problems []error paths := slices.Sorted(maps.Keys(c.Paths)) seen := map[string]bool{} for _, path := range paths { pc := c.Paths[path] if err := pc.validateVerification(); err != nil { problems = append(problems, fmt.Errorf("path %q: %w", path, err)) } for i := range pc.Deliver { target := &pc.Deliver[i] target.applyDefaults() if err := c.validateTarget(path, *target, seen); err != nil { problems = append(problems, fmt.Errorf("path %q: deliver %q: %w", path, target.Name, err)) } seen[target.Name] = true } } problems = append(problems, c.validateDeadLetterLoops()...) return errors.Join(problems...) } // validateVerification refuses a verification without the secret or // keys it checks with. os.ExpandEnv turns an unset variable into "", and // an empty HMAC key or bearer token is one that anyone can sign or send. func (pc PathConfiguration) validateVerification() error { switch pc.Verify { case "hmac-sha256", "hmac-sha1", "bearer": if pc.Secret == "" { return fmt.Errorf("verify %s needs a secret", pc.Verify) } case "rfc9421": if pc.KeysURL == "" { return errors.New("verify rfc9421 needs a keys_url") } case "": default: _, err := NewVerifier(pc.Verify, nil) return err } return nil } // refuseEmptySubscribeSecrets refuses a subscribe_secret that is set but // empty. os.ExpandEnv turns an unset variable into "", which reads the // same as no subscribe_secret at all, so the path would admit every // subscriber. The key's presence is only in the YAML, which is read // again here with a pointer that tells "" from absent. func refuseEmptySubscribeSecrets(data []byte) error { var declared struct { Paths map[string]struct { SubscribeSecret *string `yaml:"subscribe_secret"` } `yaml:"paths"` } // LoadConfiguration has already read these bytes into a // Configuration, whose subscribe_secret has the same type, so they // parse here too. _ = yaml.Unmarshal(data, &declared) var problems []error for _, path := range slices.Sorted(maps.Keys(declared.Paths)) { if secret := declared.Paths[path].SubscribeSecret; secret != nil && *secret == "" { problems = append(problems, fmt.Errorf("path %q: subscribe_secret is empty", path)) } } return errors.Join(problems...) } func (c *Configuration) validateTarget(path string, target Target, seen map[string]bool) error { var problems []error problem := func(format string, args ...any) { problems = append(problems, fmt.Errorf(format, args...)) } if path == "" { problem("the root path cannot deliver, because every path's events would reach it") } if c.LookupVerification(path) == nil { problem("a path that delivers must verify its POSTs, or anyone could send through it") } if !targetName.MatchString(target.Name) { problem("name must be letters, digits, '.', '_', or '-'") } if seen[target.Name] { problem("another target has the name") } if u, err := url.Parse(target.URL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { // The URL can hold a secret, so the message does not repeat it. problem("url must be an http or https URL") } for _, raw := range target.Filter { if _, ok := parseFilter(raw); !ok { problem("filter %q is not path:value", raw) } } if target.Sign != nil && (target.Sign.Header == "" || target.Sign.Secret == "") { problem("sign needs a header and a secret") } if target.MaxBackoff < 0 || target.GiveUpAfter < 0 || target.MaxPending < 0 || target.MaxPendingBytes < 0 || target.Concurrency < 0 { problem("max_backoff, give_up_after, max_pending, max_pending_bytes, and concurrency cannot be negative") } if target.MaxBackoff > target.GiveUpAfter { // A delivery that waits longer than it may be retried for // would be given up at the first retry anyway. problem("max_backoff cannot be longer than give_up_after") } if target.DeadLetter != "" { if err := c.validateDeadLetter(path, target.DeadLetter); err != nil { problems = append(problems, err) } } return errors.Join(problems...) } // validateDeadLetter refuses a dead-letter path that a publisher could // forge, or whose subscribers are not exactly the subscribers of the // events that reach it. func (c *Configuration) validateDeadLetter(path, deadLetter string) error { if !strings.HasPrefix(deadLetter, reservedPath+"/") { return fmt.Errorf("dead_letter %q must be under %s/, where no POST can forge one", deadLetter, reservedPath) } if !sameProtection(c.LookupSubscription(path), c.LookupSubscription(deadLetter)) { return fmt.Errorf("dead_letter %q must have the subscribe protection of %q, or its subscribers would differ from the events'", deadLetter, path) } return nil } func sameProtection(a, b *PathConfiguration) bool { if a == nil || b == nil { return a == b } return a.SubscribeSecret == b.SubscribeSecret && slices.Equal(slices.Sorted(slices.Values(a.SubscribeServiceAccounts)), slices.Sorted(slices.Values(b.SubscribeServiceAccounts))) } // validateDeadLetterLoops refuses a target that would receive a dead // letter, which could give it up into another dead letter without end. func (c *Configuration) validateDeadLetterLoops() []error { routes := c.routes() var problems []error for _, name := range slices.Sorted(maps.Keys(routes)) { for _, other := range slices.Sorted(maps.Keys(routes)) { deadLetter := routes[other].target.DeadLetter if deadLetter != "" && pathMatches(routes[name].path, deadLetter) { problems = append(problems, fmt.Errorf("deliver %q on %q would receive the dead letters of %q at %q", name, routes[name].path, other, deadLetter)) } } } return problems }