package controlplanestore import ( "encoding/json" "fmt" "net/url" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/alert" "github.com/samcharles93/archie-core/internal/domain/storecontract" ) const TaskPolicyKind = "task-policy" type taskPolicy struct { NotifyWebhook string `json:"notify_webhook"` NotifyMinSeverity string `json:"notify_min_severity"` NotifySecret config.SecretRef `json:"notify_secret"` } func taskPolicyDefinition() Definition { return Definition{Kind: TaskPolicyKind, Title: "Task policy", ApplyMode: "live", Document: taskPolicy{}, Seed: func(cfg config.Config) any { return taskPolicyOf(cfg) }, Validate: func(input []byte) error { return validateAs(input, func(doc taskPolicy) error { if doc.NotifyWebhook != "" { parsed, err := url.Parse(doc.NotifyWebhook) if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") { return fmt.Errorf("notify_webhook must be an HTTP or HTTPS URL") } if parsed.User != nil { return fmt.Errorf("notify_webhook must not carry credentials in the URL") } if parsed.RawQuery != "" || parsed.ForceQuery { return fmt.Errorf("notify_webhook must not carry a query string") } } if !alert.Severity(doc.NotifyMinSeverity).Valid() && doc.NotifyMinSeverity != "" { return fmt.Errorf("notify_min_severity must be info, warning or action") } if (doc.NotifySecret.Engine == "") != (doc.NotifySecret.Key == "") { return fmt.Errorf("notify_secret needs both an engine and a key") } return nil }) }} } func taskPolicyOf(cfg config.Config) taskPolicy { return taskPolicy{ NotifyWebhook: cfg.Notify.Webhook, NotifyMinSeverity: cfg.Notify.MinSeverity, NotifySecret: cfg.Notify.Secret, } } // OrgNotify is the alert webhook a non-system org's task policy names. Its // signing secret is never read from the document (checkTaskPolicyWrite). func OrgNotify(stored []byte) (config.Notify, error) { var doc taskPolicy if err := json.Unmarshal(stored, &doc); err != nil { return config.Notify{}, fmt.Errorf("decode %s: %w", TaskPolicyKind, err) } return config.Notify{Webhook: doc.NotifyWebhook, MinSeverity: doc.NotifyMinSeverity}, nil } // checkTaskPolicyWrite keeps an org from naming a secret: the reference // resolves against the instance's engines, so it would let the org sign with // any secret the instance holds. The org's signing key is its credential // binding named notify. func checkTaskPolicyWrite(orgID string, value []byte) error { if orgID == storecontract.DefaultOrgID { return nil } var doc taskPolicy if err := json.Unmarshal(value, &doc); err != nil { return err } if doc.NotifySecret != (config.SecretRef{}) { return fmt.Errorf("%w: notify_secret is the instance's; an org signs with its credential binding named notify", ErrValidation) } return nil }