From 0d783112f7a212e03e29b91177a158f13fd4ec9c Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Wed, 25 Nov 2026 22:25:30 -0800 Subject: [PATCH 1/3] feat(notify): sign notifications with Standard Webhooks A receiver that records deploy events, such as a monitoring service that verifies each production deploy, needs to know a notification came from this project's Onebox and not from anyone who learned the webhook URL. The notification field signingSecretEnv names a local environment variable holding a Standard Webhooks secret (whsec_ + base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature: v1,, computed over the exact bytes sent. The JSON payload shape does not change. A signed notification must declare format: JSON. The default text body is a sentence for a chat channel; signing it authenticates nothing a verifier reads. The loader and the published schema both refuse the combination, and the variable name uses the same grammar as registries.passwordEnv. A signed send is retried, because a verifying receiver is one that records the event: at most three attempts within 15 seconds, retrying only a network error, a 429, or a 5xx, with the same webhook-id and a fresh timestamp and signature each time. A 4xx is the receiver refusing the request and is not repeated. Fail-open holds: a missing or malformed secret, or exhausted retries, is the same stderr warning as any webhook problem, and the error names the variable, never its value. An unsigned send is one attempt, exactly as before. Scheduled jobs sign too. The host has no Onebox at 2am, so ob deploy resolves the key from the operator's environment and writes it into the root-only notifier beside the webhook URL, and the notifier signs each attempt with openssl over the body curl posts. The webhook-id is the systemd invocation id plus the notification's position, so retries repeat it. The unit's TimeoutStopSec grows by ten seconds for the retry budget. When the secret is unavailable at deploy, the deploy warns and the notifier logs that it did not send: an unsigned request to a receiver that verifies signatures is one it must reject. Co-Authored-By: Claude Opus 5.5 --- .../v1alpha2/application.schema.json | 23 ++ cmd/ob/commands.go | 3 +- internal/app/jsonschema.go | 9 + internal/app/load_test.go | 35 +++ internal/app/testdata/contract-verdicts.json | 20 ++ internal/app/types.go | 3 + internal/app/validate.go | 11 + internal/engine/schedule.go | 97 ++++++- internal/engine/schedule_signing_test.go | 188 +++++++++++++ internal/engine/schedule_test.go | 4 +- internal/notify/notify.go | 144 +++++++++- internal/notify/sign_test.go | 246 ++++++++++++++++++ .../v1alpha2/application.schema.json | 23 ++ .../content/docs/docs/guides/cron-jobs.mdx | 22 ++ .../docs/reference/fields/notifications.mdx | 3 +- 15 files changed, 817 insertions(+), 14 deletions(-) create mode 100644 internal/engine/schedule_signing_test.go create mode 100644 internal/notify/sign_test.go diff --git a/api/application/v1alpha2/application.schema.json b/api/application/v1alpha2/application.schema.json index 5cebd30d..93e8f999 100644 --- a/api/application/v1alpha2/application.schema.json +++ b/api/application/v1alpha2/application.schema.json @@ -800,6 +800,11 @@ "notifications": { "additionalProperties": { "additionalProperties": false, + "if": { + "required": [ + "signingSecretEnv" + ] + }, "properties": { "format": { "default": "Text", @@ -825,6 +830,14 @@ }, "type": "array" }, + "signingSecretEnv": { + "description": "Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "examples": [ + "ONEBOX_WEBHOOK_SECRET" + ], + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "type": "string" + }, "webhook": { "description": "HTTP endpoint that receives outcome notifications.", "examples": [ @@ -833,6 +846,16 @@ "type": "string" } }, + "then": { + "properties": { + "format": { + "const": "JSON" + } + }, + "required": [ + "format" + ] + }, "type": "object" }, "description": "Named webhooks that receive selected operation and scheduled-job outcomes.", diff --git a/cmd/ob/commands.go b/cmd/ob/commands.go index a56ed444..4c12a933 100644 --- a/cmd/ob/commands.go +++ b/cmd/ob/commands.go @@ -294,7 +294,8 @@ func notifyOperationOutcome(ctx context.Context, cfg *app.Resolved, g *globalFla evidenceID = result.ReleaseID } // The operation context is cancelled by Ctrl-C and SIGTERM. Its outcome is - // still worth sending; notify.Send has its own bounded HTTP timeout. + // still worth sending; notify.Send bounds itself: one 5s attempt, or for a + // signed notification at most three attempts within notify.SignedBudget. notifyOutcome(context.WithoutCancel(ctx), cfg, g, verb, evidenceID, err) } diff --git a/internal/app/jsonschema.go b/internal/app/jsonschema.go index 40351446..fce4ab66 100644 --- a/internal/app/jsonschema.go +++ b/internal/app/jsonschema.go @@ -606,6 +606,15 @@ var schemaConstraints = []struct { {[]string{"registries", "*", "username"}, pattern(gRegistryUser)}, {[]string{"registries", "*", "password_env"}, pattern(gEnvName)}, {[]string{"notifications", "*", "format"}, enum(eNotifyFormat)}, + {[]string{"notifications", "*", "signing_secret_env"}, pattern(gEnvName)}, + // Format defaults to text, so a signed notification has to say JSON. + {[]string{"notifications", "*"}, map[string]any{ + "if": map[string]any{"required": []any{"signing_secret_env"}}, + "then": map[string]any{ + "required": []any{"format"}, + "properties": map[string]any{"format": map[string]any{"const": "json"}}, + }, + }}, {[]string{"runtime", "env_files", "items", "file"}, pattern(gRepoPath)}, {[]string{"runtime", "env_files", "items", "provider"}, enum(eSecretProvider)}, {[]string{"runtime", "env_files", "items"}, map[string]any{"required": []any{"file"}}}, diff --git a/internal/app/load_test.go b/internal/app/load_test.go index 7903d98c..002cf2f5 100644 --- a/internal/app/load_test.go +++ b/internal/app/load_test.go @@ -316,6 +316,12 @@ spec: // event is a webhook that reads as configured and never calls. {"notification on an unknown event", min + "notifications: {ops: {webhook: \"https://h.example.com/x\", on: [deployed]}}\n", false}, {"notification with no events", min + "notifications: {ops: {webhook: \"https://h.example.com/x\"}}\n", true}, + // A signed notification authenticates the JSON body a verifier reads; + // the secret itself is never in the file, only the variable naming it. + {"signed JSON notification", min + "notifications: {ops: {webhook: \"https://h.example.com/x\", format: json, signing_secret_env: OPS_WEBHOOK_SECRET}}\n", true}, + {"signed notification with the default text format", min + "notifications: {ops: {webhook: \"https://h.example.com/x\", signing_secret_env: OPS_WEBHOOK_SECRET}}\n", false}, + {"signed text notification", min + "notifications: {ops: {webhook: \"https://h.example.com/x\", format: text, signing_secret_env: OPS_WEBHOOK_SECRET}}\n", false}, + {"signing secret env that is not a variable name", min + "notifications: {ops: {webhook: \"https://h.example.com/x\", format: json, signing_secret_env: \"whsec_abc=\"}}\n", false}, // logging lands verbatim in the generated runtime, so an unchecked value // fails at container create on the server, after validate/preview/plan // all reported the project fine. @@ -1065,3 +1071,32 @@ spec: }) } } + +// The published key is signingSecretEnv, and a signed notification must say +// format: JSON because the default text body is not what a verifier reads. +func TestSignedNotificationProjectFile(t *testing.T) { + project := func(notification string) []byte { + return []byte(`apiVersion: onebox.run/v1alpha2 +kind: Application +metadata: + name: shop +spec: + environments: {production: {server: root@203.0.113.10}} + workloads: + web: {image: nginx} + notifications: + facet: ` + notification + ` +`) + } + spec, err := loadFixtureBytes(project(`{webhook: "https://facet.example.com/hooks/onebox", format: JSON, signingSecretEnv: FACET_WEBHOOK_SECRET}`), "ob.yml") + if err != nil { + t.Fatal(err) + } + if got := spec.Notifications["facet"].SigningSecretEnv; got != "FACET_WEBHOOK_SECRET" { + t.Fatalf("signingSecretEnv = %q", got) + } + _, err = loadFixtureBytes(project(`{webhook: "https://facet.example.com/hooks/onebox", signingSecretEnv: FACET_WEBHOOK_SECRET}`), "ob.yml") + if err == nil || !strings.Contains(err.Error(), "notifications.facet.format") || !strings.Contains(err.Error(), "format: JSON") { + t.Fatalf("error = %v, want a refusal at notifications.facet.format", err) + } +} diff --git a/internal/app/testdata/contract-verdicts.json b/internal/app/testdata/contract-verdicts.json index ed952515..839dddfd 100644 --- a/internal/app/testdata/contract-verdicts.json +++ b/internal/app/testdata/contract-verdicts.json @@ -429,6 +429,26 @@ "loads": false, "code": "unknown_field" }, + { + "case": "conformance/signed JSON notification", + "loads": true, + "digest": "4722d2d66d41aa91e17ee4e3d9e56074ff6edbae82a46d6202abad3282521801" + }, + { + "case": "conformance/signed notification with the default text format", + "loads": false, + "code": "project_invalid" + }, + { + "case": "conformance/signed text notification", + "loads": false, + "code": "project_invalid" + }, + { + "case": "conformance/signing secret env that is not a variable name", + "loads": false, + "code": "project_invalid" + }, { "case": "conformance/status code 600", "loads": false, diff --git a/internal/app/types.go b/internal/app/types.go index 01ce2dab..3582adf2 100644 --- a/internal/app/types.go +++ b/internal/app/types.go @@ -518,6 +518,9 @@ type Notification struct { Webhook string `json:"webhook" description:"HTTP endpoint that receives outcome notifications." example:"https://hooks.example.com/onebox"` On []string `json:"on,omitempty" description:"Operation outcomes that trigger this notification." default:"success, failure"` Format string `json:"format" description:"Notification payload format." default:"text"` + // SigningSecretEnv names a variable in the operator's environment, never + // the secret itself, so the project file stays safe to commit. + SigningSecretEnv string `json:"signing_secret_env,omitempty" description:"Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked." example:"ONEBOX_WEBHOOK_SECRET"` } type Registry struct { diff --git a/internal/app/validate.go b/internal/app/validate.go index d15b3ead..dc941a6b 100644 --- a/internal/app/validate.go +++ b/internal/app/validate.go @@ -160,6 +160,17 @@ func validateTopLevel(p *Spec) error { return err } } + if err := gEnvName.checkOptional("notifications."+name+".signing_secret_env", p.Notifications[name].SigningSecretEnv); err != nil { + return err + } + // The signature covers the exact body bytes, and a receiver that + // verifies one reads the structured fields. A text body is a sentence + // for a chat channel, so signing it would authenticate nothing a + // verifier can use. + if p.Notifications[name].SigningSecretEnv != "" && p.Notifications[name].Format != "json" { + return errf("project_invalid", "notifications."+name+".format", "", + "a signed notification sends the JSON payload; set format: JSON beside signingSecretEnv") + } } for _, name := range sortedKeys(p.Hooks) { // A hook key is either a lifecycle seam the engine invokes, or the name diff --git a/internal/engine/schedule.go b/internal/engine/schedule.go index 4d167ef4..6afcf4b2 100644 --- a/internal/engine/schedule.go +++ b/internal/engine/schedule.go @@ -2,6 +2,7 @@ package engine import ( "context" + "encoding/hex" "errors" "fmt" "math" @@ -95,7 +96,7 @@ func (e *Engine) SyncSchedules(ctx context.Context) error { if err != nil { return fmt.Errorf("job %s: cannot render its failure notifier: %w", job.Name, err) } - service := scheduleServiceUnit(e.Spec.Name, job, runnerPath, notifyPath) + service := scheduleServiceUnit(e.Spec.Name, job, runnerPath, notifyPath, e.scheduleSigns(job)) timer := scheduleTimerUnit(e.Spec.Name, job) if err := e.writeServiceFile(ctx, runnerPath, []byte(runner)); err != nil { return fmt.Errorf("job %s: cannot install its runner: %w", job.Name, err) @@ -575,7 +576,16 @@ func scheduleRuntimeEnvArgs(projectDir string, entries []app.EnvFile) string { return args } -func scheduleServiceUnit(application string, job app.ScheduledJob, runnerPath, notifyPath string) string { +// signedStopAllowance is what a signed notification's retries can add to +// ExecStopPost beyond the single bounded send the stop timeout already +// allows for. +const signedStopAllowance = notify.SignedBudget - 5*time.Second + +func scheduleServiceUnit(application string, job app.ScheduledJob, runnerPath, notifyPath string, signed bool) string { + stop := job.ShutdownGrace + 10*time.Second + if signed { + stop += signedStopAllowance + } return strings.Join([]string{ "[Unit]", "Description=Onebox scheduled job " + job.Name + " for " + application, @@ -591,7 +601,7 @@ func scheduleServiceUnit(application string, job app.ScheduledJob, runnerPath, n // runner's state and SERVICE_RESULT, then notifies per the job's policy. "ExecStopPost=/bin/sh " + notifyPath, "TimeoutStartSec=" + job.Timeout, - "TimeoutStopSec=" + (job.ShutdownGrace + 10*time.Second).String(), + "TimeoutStopSec=" + stop.String(), "", }, "\n") } @@ -718,12 +728,13 @@ func (e *Engine) scheduleNotifier(job app.ScheduledJob) (string, error) { wants["fail"] = true } } + keys := e.scheduleSigningKeys(job) sends := map[string][]string{} for _, class := range []string{"ok", "skipped", "fail"} { if !wants[class] { continue } - rendered, err := e.scheduleNotificationSends(job.Name, environment, class) + rendered, err := e.scheduleNotificationSends(job.Name, environment, class, keys) if err != nil { return "", err } @@ -751,14 +762,55 @@ func orNoop(lines []string) []string { return lines } +// scheduleSigns reports whether any notification this job can send is signed, +// which is when its stop timeout must allow for retries. +func (e *Engine) scheduleSigns(job app.ScheduledJob) bool { + if len(job.Notify) == 0 { + return false + } + for _, cfg := range e.Spec.Notifications { + if cfg.SigningSecretEnv != "" { + return true + } + } + return false +} + +// scheduleSigningKeys resolves, from the deploying operator's environment, +// the signing key of each signed notification this job can send. The host has +// no Onebox to sign at 2am, so the key travels in the root-only notifier +// beside the webhook URL, and the host computes the signature at send time +// over the body it actually sends. A notification whose secret is unavailable +// maps to nil: the host is told not to send it, because an unsigned request +// to a receiver that verifies signatures is one it must reject. That is a +// warning, never a failed deploy. +func (e *Engine) scheduleSigningKeys(job app.ScheduledJob) map[string][]byte { + if !e.scheduleSigns(job) { + return nil + } + keys := map[string][]byte{} + for _, name := range sortedNames(e.Spec.Notifications) { + cfg := e.Spec.Notifications[name] + if cfg.SigningSecretEnv == "" { + continue + } + key, err := notify.SigningKey(cfg) + if err != nil { + e.warnf("job %s: notification %s will not be sent from the host: %v", job.Name, name, err) + } + keys[name] = key + } + return keys +} + // scheduleNotificationSends renders one backgrounded curl per notification // that selects the given class: ok, skipped, or fail. A skip routes with the // failures, because that is the channel an operator watches, and says what it // is rather than claiming the job failed. A failed send is logged and never // replaces the job's own result. -func (e *Engine) scheduleNotificationSends(job, environment, class string) ([]string, error) { +func (e *Engine) scheduleNotificationSends(job, environment, class string, keys map[string][]byte) ([]string, error) { var sends []string - for _, name := range sortedNames(e.Spec.Notifications) { + for i, name := range sortedNames(e.Spec.Notifications) { cfg := e.Spec.Notifications[name] status := "fail" if class == "ok" { @@ -780,6 +832,15 @@ func (e *Engine) scheduleNotificationSends(job, environment, class string) ([]st if prepared == nil { continue } + if cfg.SigningSecretEnv != "" { + key := keys[name] + if key == nil { + sends = append(sends, " echo "+q("onebox: notification "+name+" not sent: its signing secret was unavailable when this job was deployed")+" >&2") + continue + } + sends = append(sends, signedScheduleSend(name, i, cfg.Webhook, prepared, key)) + continue + } curl := "curl --fail --silent --show-error --max-time 5 --request POST" + " --header " + q("Content-Type: "+prepared.ContentType) + " --header " + q("X-Title: "+prepared.Title) + @@ -790,6 +851,30 @@ func (e *Engine) scheduleNotificationSends(job, environment, class string) ([]st return sends, nil } +// signedScheduleSend renders a Standard Webhooks send for the host: the same +// body as an unsigned send, signed with openssl over the bytes curl posts. +// The webhook-id is the systemd invocation plus the notification's position, +// fixed before the first attempt, so every retry repeats it. Each attempt +// takes a fresh timestamp and signature. At most notify.SignedAttempts +// attempts of four seconds with a one-second pause between them fit in +// notify.SignedBudget; only a network error (000), a 429 or a 5xx is retried. +// Without openssl the send is not attempted, and the failure is logged. +func signedScheduleSend(name string, index int, webhook string, prepared *notify.Request, key []byte) string { + attempts := strconv.Itoa(notify.SignedAttempts) + sign := `sig=$(printf '%s.%s.%s' "$id" "$wts" "$body" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$key" -binary | openssl base64 -A) || break; [ -n "$sig" ] || break; ` + curl := "code=$(curl --silent --show-error --max-time 4 --output /dev/null --write-out '%{http_code}' --request POST" + + " --header " + q("Content-Type: "+prepared.ContentType) + + " --header " + q("X-Title: "+prepared.Title) + + ` --header "webhook-id: $id" --header "webhook-timestamp: $wts" --header "webhook-signature: v1,$sig"` + + ` --data-binary "$body" ` + q(webhook) + "); " + return " (body=" + shellBody(string(prepared.Body)) + "; key=" + q(hex.EncodeToString(key)) + + `; id="msg_${INVOCATION_ID:-$(date -u '+%s')$$}_` + strconv.Itoa(index) + `"; attempt=0; sent=''; ` + + `while [ "$attempt" -lt ` + attempts + ` ]; do attempt=$((attempt + 1)); wts=$(date -u '+%s'); ` + + sign + curl + + `case "$code" in 2??) sent=1; break ;; 000|429|5??) [ "$attempt" -lt ` + attempts + ` ] && sleep 1 ;; *) break ;; esac; done; ` + + `if [ -z "$sent" ]; then echo ` + q("onebox: notification "+name+" failed") + " >&2; fi) &" +} + // shellBody quotes a prepared body for the shell, leaving the two runtime // placeholders as expansions of variables the notifier sets before sending. func shellBody(body string) string { diff --git a/internal/engine/schedule_signing_test.go b/internal/engine/schedule_signing_test.go new file mode 100644 index 00000000..1c1ec1ba --- /dev/null +++ b/internal/engine/schedule_signing_test.go @@ -0,0 +1,188 @@ +package engine + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/transport" +) + +var scheduleSigningKey = []byte("schedule-signing-key-for-tests-0001") + +// signedAttempt is one curl invocation by the host notifier. +type signedAttempt struct { + headers map[string]string + body string +} + +// runSignedNotifier executes the generated notifier for a failed run with a +// curl stub that answers each attempt with the next of codes, and real +// openssl, which is what signs on the host. +func runSignedNotifier(t *testing.T, codes []string, secret string) (string, []signedAttempt, string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("POSIX shell required") + } + if _, err := exec.LookPath("openssl"); err != nil { + t.Skip("openssl is what signs on the host, and it is not installed here") + } + t.Setenv("TEST_SCHEDULE_WEBHOOK_SECRET", secret) + base := t.TempDir() + cfg := testConfig() + cfg.BasePath = base + cfg.Notifications = map[string]app.Notification{ + "facet": {Webhook: "https://facet.example.invalid/hooks/onebox", On: []string{"failure"}, Format: "json", SigningSecretEnv: "TEST_SCHEDULE_WEBHOOK_SECRET"}, + } + out := &bytes.Buffer{} + e := New(cfg, testProject(t), &transport.Fake{TargetName: "root@example.internal"}, Options{Environment: "production", Out: out, Sleep: noSleep}) + script, err := e.scheduleNotifier(app.ScheduledJob{Name: "nightly", Notify: []string{"failure"}}) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(base, "app", "schedule"), 0o700); err != nil { + t.Fatal(err) + } + bin := t.TempDir() + if err := os.WriteFile(filepath.Join(bin, "logger"), []byte("#!/bin/sh\ncat >/dev/null\n"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(bin, "codes"), []byte(strings.Join(codes, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + curl := "#!/bin/sh\n" + + "n=$(cat " + bin + "/count 2>/dev/null || echo 0); n=$((n + 1)); echo \"$n\" >" + bin + "/count\n" + + "printf '%s\\n' \"$@\" >" + bin + "/args.$n\n" + + "code=$(sed -n \"${n}p\" " + bin + "/codes); [ -n \"$code\" ] || code=200\n" + + "printf '%s' \"$code\"\n" + if err := os.WriteFile(filepath.Join(bin, "curl"), []byte(curl), 0o755); err != nil { + t.Fatal(err) + } + command := exec.CommandContext(context.Background(), "sh", "-s") + command.Stdin = strings.NewReader(script) + command.Env = []string{ + "PATH=" + bin + ":" + os.Getenv("PATH"), "HOME=" + base, + "SERVICE_RESULT=exit-code", "EXIT_STATUS=1", "INVOCATION_ID=0123456789abcdef0123456789abcdef", + } + stderr, err := command.CombinedOutput() + if err != nil { + t.Fatalf("notifier exited non-zero: %v\n%s", err, stderr) + } + var attempts []signedAttempt + for n := 1; ; n++ { + raw, err := os.ReadFile(filepath.Join(bin, "args."+strconv.Itoa(n))) + if err != nil { + break + } + args := strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n") + a := signedAttempt{headers: map[string]string{}} + for i := 0; i+1 < len(args); i++ { + switch args[i] { + case "--header": + k, v, _ := strings.Cut(args[i+1], ": ") + a.headers[strings.ToLower(k)] = v + case "--data-binary": + a.body = args[i+1] + } + } + attempts = append(attempts, a) + } + return script, attempts, string(stderr) + out.String() +} + +func verifyScheduleSignature(t *testing.T, a signedAttempt) { + t.Helper() + id, ts := a.headers["webhook-id"], a.headers["webhook-timestamp"] + seconds, err := strconv.ParseInt(ts, 10, 64) + if err != nil || time.Since(time.Unix(seconds, 0)) > time.Minute { + t.Fatalf("webhook-timestamp %q is not the current unix time", ts) + } + mac := hmac.New(sha256.New, scheduleSigningKey) + mac.Write([]byte(id + "." + ts + "." + a.body)) + want := "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil)) + if a.headers["webhook-signature"] != want { + t.Fatalf("webhook-signature = %q, want %q over %q", a.headers["webhook-signature"], want, a.body) + } +} + +func TestScheduledJobSignsItsNotificationOnTheHost(t *testing.T) { + secret := "whsec_" + base64.StdEncoding.EncodeToString(scheduleSigningKey) + _, attempts, _ := runSignedNotifier(t, []string{"200"}, secret) + if len(attempts) != 1 { + t.Fatalf("got %d attempts, want 1", len(attempts)) + } + a := attempts[0] + if a.headers["webhook-id"] != "msg_0123456789abcdef0123456789abcdef_0" { + t.Fatalf("webhook-id = %q, want the run's invocation id", a.headers["webhook-id"]) + } + verifyScheduleSignature(t, a) + var payload map[string]any + if err := json.Unmarshal([]byte(a.body), &payload); err != nil { + t.Fatalf("signed body is not JSON: %v\n%s", err, a.body) + } + if payload["deploy_id"] != "0123456789abcdef0123456789abcdef" || payload["status"] != "fail" { + t.Fatalf("host-filled fields are wrong: %v", payload) + } +} + +func TestScheduledJobRetriesASignedSendWithTheSameID(t *testing.T) { + secret := "whsec_" + base64.StdEncoding.EncodeToString(scheduleSigningKey) + _, attempts, _ := runSignedNotifier(t, []string{"503", "000", "204"}, secret) + if len(attempts) != 3 { + t.Fatalf("got %d attempts, want 3", len(attempts)) + } + for _, a := range attempts { + if a.headers["webhook-id"] != attempts[0].headers["webhook-id"] { + t.Fatalf("webhook-id changed across retries") + } + verifyScheduleSignature(t, a) + } +} + +func TestScheduledJobDoesNotRetryARefusedSignedSend(t *testing.T) { + secret := "whsec_" + base64.StdEncoding.EncodeToString(scheduleSigningKey) + _, attempts, log := runSignedNotifier(t, []string{"401", "200"}, secret) + if len(attempts) != 1 { + t.Fatalf("got %d attempts; a 401 is not retried", len(attempts)) + } + if !strings.Contains(log, "onebox: notification facet failed") { + t.Fatalf("a refused send must be logged:\n%s", log) + } +} + +func TestScheduledJobWithoutASigningSecretSendsNothingUnsigned(t *testing.T) { + script, attempts, log := runSignedNotifier(t, nil, "") + if len(attempts) != 0 { + t.Fatalf("sent %d unsigned request(s) to a receiver that verifies signatures", len(attempts)) + } + if !strings.Contains(log, "TEST_SCHEDULE_WEBHOOK_SECRET") || !strings.Contains(log, "will not be sent from the host") { + t.Fatalf("the deploy must warn that the notification is off:\n%s", log) + } + if !strings.Contains(log, "signing secret was unavailable") { + t.Fatalf("the host must log why it sent nothing:\n%s", log) + } + if strings.Contains(script, "openssl") { + t.Fatalf("a notifier with no key must not try to sign:\n%s", script) + } +} + +func TestSignedScheduleExtendsTheStopTimeout(t *testing.T) { + job := app.ScheduledJob{Name: "nightly", Timeout: "45m", ShutdownGrace: 30 * time.Second} + plain := scheduleServiceUnit("sample", job, "/r", "/n", false) + signed := scheduleServiceUnit("sample", job, "/r", "/n", true) + if !strings.Contains(plain, "TimeoutStopSec=40s") || !strings.Contains(signed, "TimeoutStopSec=50s") { + t.Fatalf("stop timeouts:\n%s\n%s", plain, signed) + } +} diff --git a/internal/engine/schedule_test.go b/internal/engine/schedule_test.go index 176bae2a..0bab1573 100644 --- a/internal/engine/schedule_test.go +++ b/internal/engine/schedule_test.go @@ -187,7 +187,7 @@ func TestScheduledJobUnitContract(t *testing.T) { runner := scheduleRunnerScript("sample", job, names, "/var/lib/onebox/app/lock", nil, 10*time.Minute, true) service := scheduleServiceUnit("sample", job, "/etc/systemd/system/onebox-job-nightly.run", - "/etc/systemd/system/onebox-job-nightly.notify") + "/etc/systemd/system/onebox-job-nightly.notify", false) timer := scheduleTimerUnit("sample", job) for _, want := range []string{ @@ -1155,7 +1155,7 @@ func TestScheduledJobRunnersRecordRunStateForTheNotifier(t *testing.T) { }) } service := scheduleServiceUnit("sample", app.ScheduledJob{Name: "nightly", Timeout: "45m"}, - "/etc/systemd/system/onebox-job-nightly.run", "/etc/systemd/system/onebox-job-nightly.notify") + "/etc/systemd/system/onebox-job-nightly.run", "/etc/systemd/system/onebox-job-nightly.notify", false) if strings.Contains(service, "SuccessExitStatus") { t.Errorf("a skip is recorded by the runner and exits 0; the unit needs no exit-status remap:\n%s", service) } diff --git a/internal/notify/notify.go b/internal/notify/notify.go index 86157fae..19db12f8 100644 --- a/internal/notify/notify.go +++ b/internal/notify/notify.go @@ -7,14 +7,29 @@ // to WARN on, and must never block, fail, or slow an operation beyond the // send timeout. Error strings are the same redaction-safe strings printed to // the terminal — secret content never travels, only hashes. +// +// A notification that names signing_secret_env is signed with Standard +// Webhooks (https://www.standardwebhooks.com): webhook-id, webhook-timestamp +// and webhook-signature headers over the exact body bytes. A signed send is +// retried, because a receiver that verifies signatures is usually one that +// records the event rather than a chat channel, within a total bound that +// keeps the fail-open contract. An unsigned send is one attempt, as before. package notify import ( "bytes" "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" "encoding/json" + "errors" "fmt" "net/http" + "os" + "strconv" "strings" "time" @@ -23,6 +38,21 @@ import ( const timeout = 5 * time.Second +// A signed send makes at most SignedAttempts attempts, each bounded by the +// per-request timeout, and all of them within SignedBudget. The budget is the +// whole cost a signed notification can add to an operation. +const ( + SignedAttempts = 3 + SignedBudget = 15 * time.Second +) + +// signedBackoff is the pause before each retry. A variable so tests do not +// wait for it. +var signedBackoff = []time.Duration{500 * time.Millisecond, time.Second} + +// secretPrefix is the Standard Webhooks marker on a symmetric secret. +const secretPrefix = "whsec_" + // Payload is the notification: what ran, where, and how it ended. type Payload struct { App string `json:"app"` @@ -127,6 +157,60 @@ func Prepare(cfg app.Notification, p Payload) (*Request, error) { }, nil } +// SigningKey resolves cfg's signing secret from the local environment. It +// returns nil for an unsigned notification. Errors name the variable and never +// carry its value. +func SigningKey(cfg app.Notification) ([]byte, error) { + if cfg.SigningSecretEnv == "" { + return nil, nil + } + value := os.Getenv(cfg.SigningSecretEnv) + if value == "" { + return nil, fmt.Errorf("signing secret env var %s is empty; export the Standard Webhooks secret (whsec_...) to sign this notification", cfg.SigningSecretEnv) + } + key, err := ParseSigningSecret(value) + if err != nil { + return nil, fmt.Errorf("signing secret env var %s: %w", cfg.SigningSecretEnv, err) + } + return key, nil +} + +// ParseSigningSecret decodes a Standard Webhooks secret, whsec_ followed by +// standard base64, into the HMAC key. Errors describe the shape only. +func ParseSigningSecret(secret string) ([]byte, error) { + encoded, ok := strings.CutPrefix(secret, secretPrefix) + if !ok { + return nil, errors.New("not a Standard Webhooks secret: it must start with whsec_") + } + key, err := base64.StdEncoding.DecodeString(encoded) + if err != nil || len(key) == 0 { + return nil, errors.New("not a Standard Webhooks secret: the part after whsec_ must be non-empty base64") + } + return key, nil +} + +// Signature is the webhook-signature header value for one attempt: version 1, +// an HMAC-SHA256 over "id.timestamp.body". +func Signature(key []byte, id string, timestamp int64, body []byte) string { + mac := hmac.New(sha256.New, key) + mac.Write([]byte(id)) + mac.Write([]byte(".")) + mac.Write([]byte(strconv.FormatInt(timestamp, 10))) + mac.Write([]byte(".")) + mac.Write(body) + return "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil)) +} + +// newMessageID is the webhook-id for one logical notification: random, made +// once, and reused by every retry so a receiver can drop the duplicates. +func newMessageID() (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + return "msg_" + hex.EncodeToString(b[:]), nil +} + // Send fires the webhook if the payload's outcome is selected by cfg.On. An // unset webhook and a filtered outcome are silent no-ops. Callers treat a // returned error as a warning — never as the operation's result. @@ -135,20 +219,72 @@ func Send(ctx context.Context, cfg app.Notification, p Payload) error { if err != nil || prepared == nil { return err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.Webhook, bytes.NewReader(prepared.Body)) + if cfg.SigningSecretEnv == "" { + _, err := post(ctx, cfg.Webhook, prepared, nil) + return err + } + key, err := SigningKey(cfg) + if err != nil { + return err + } + id, err := newMessageID() if err != nil { return err } + ctx, cancel := context.WithTimeout(ctx, SignedBudget) + defer cancel() + var lastErr error + for attempt := 1; attempt <= SignedAttempts; attempt++ { + now := time.Now().Unix() + headers := map[string]string{ + "webhook-id": id, + "webhook-timestamp": strconv.FormatInt(now, 10), + "webhook-signature": Signature(key, id, now, prepared.Body), + } + retry, err := post(ctx, cfg.Webhook, prepared, headers) + if err == nil { + return nil + } + lastErr = err + if !retry || attempt == SignedAttempts || ctx.Err() != nil { + break + } + select { + case <-ctx.Done(): + case <-time.After(signedBackoff[attempt-1]): + } + if ctx.Err() != nil { + break + } + } + if errors.Is(lastErr, context.DeadlineExceeded) && ctx.Err() != nil { + return fmt.Errorf("webhook not delivered within %s: %w", SignedBudget, lastErr) + } + return lastErr +} + +// post makes one attempt. retry reports whether the failure is one a retry +// could fix: a network error, a 429, or a 5xx. A 4xx is the receiver refusing +// this request, and the same request will be refused again. +func post(ctx context.Context, webhook string, prepared *Request, headers map[string]string) (retry bool, err error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhook, bytes.NewReader(prepared.Body)) + if err != nil { + return false, err + } req.Header.Set("Content-Type", prepared.ContentType) req.Header.Set("X-Title", prepared.Title) + for k, v := range headers { + req.Header.Set(k, v) + } client := &http.Client{Timeout: timeout} res, err := client.Do(req) if err != nil { - return err + return true, err } defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode > 299 { - return fmt.Errorf("webhook returned %d", res.StatusCode) + return res.StatusCode == http.StatusTooManyRequests || res.StatusCode >= 500, + fmt.Errorf("webhook returned %d", res.StatusCode) } - return nil + return false, nil } diff --git a/internal/notify/sign_test.go b/internal/notify/sign_test.go new file mode 100644 index 00000000..97ab2957 --- /dev/null +++ b/internal/notify/sign_test.go @@ -0,0 +1,246 @@ +package notify + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/labstack/onebox/internal/app" +) + +// testSecret is a Standard Webhooks secret whose key bytes the test knows. +var ( + testKey = []byte("facet-test-signing-key-0123456789") + testSecret = "whsec_" + base64.StdEncoding.EncodeToString(testKey) +) + +// received is one request as the receiver saw it. +type received struct { + id, timestamp, signature string + body []byte +} + +// verify is an independent Standard Webhooks verifier: it shares no code with +// the sender, so a signature that passes here is one a receiver accepts. +func verify(t *testing.T, key []byte, r received) { + t.Helper() + ts, err := strconv.ParseInt(r.timestamp, 10, 64) + if err != nil { + t.Fatalf("webhook-timestamp %q is not unix seconds: %v", r.timestamp, err) + } + if d := time.Since(time.Unix(ts, 0)); d < -5*time.Second || d > 5*time.Minute { + t.Fatalf("webhook-timestamp %d is not now", ts) + } + mac := hmac.New(sha256.New, key) + mac.Write([]byte(r.id + "." + r.timestamp + "." + string(r.body))) + want := "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil)) + if !hmac.Equal([]byte(r.signature), []byte(want)) { + t.Fatalf("webhook-signature = %q, want %q", r.signature, want) + } +} + +// receiver answers with the given status codes in turn and records requests. +func receiver(t *testing.T, statuses ...int) (*httptest.Server, func() []received) { + t.Helper() + var mu sync.Mutex + var got []received + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + mu.Lock() + got = append(got, received{ + id: r.Header.Get("webhook-id"), timestamp: r.Header.Get("webhook-timestamp"), + signature: r.Header.Get("webhook-signature"), body: body, + }) + n := len(got) + mu.Unlock() + if n <= len(statuses) { + w.WriteHeader(statuses[n-1]) + } + })) + t.Cleanup(srv.Close) + return srv, func() []received { + mu.Lock() + defer mu.Unlock() + return append([]received(nil), got...) + } +} + +func fastBackoff(t *testing.T) { + t.Helper() + old := signedBackoff + signedBackoff = []time.Duration{time.Millisecond, time.Millisecond} + t.Cleanup(func() { signedBackoff = old }) +} + +func signedConfig(url string) app.Notification { + return app.Notification{Webhook: url, On: []string{"success", "failure"}, Format: "json", SigningSecretEnv: "TEST_ONEBOX_WEBHOOK_SECRET"} +} + +func TestSignedSendVerifiesWithAnIndependentImplementation(t *testing.T) { + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", testSecret) + srv, got := receiver(t) + p := Payload{App: "sample", Env: "production", Host: "root@h", Verb: "deploy", DeployID: "R1", Status: "ok", Operator: "v"} + if err := Send(t.Context(), signedConfig(srv.URL), p); err != nil { + t.Fatal(err) + } + reqs := got() + if len(reqs) != 1 { + t.Fatalf("got %d requests, want 1", len(reqs)) + } + r := reqs[0] + if !strings.HasPrefix(r.id, "msg_") || r.timestamp == "" || !strings.HasPrefix(r.signature, "v1,") { + t.Fatalf("Standard Webhooks headers missing: %+v", r) + } + verify(t, testKey, r) + // The payload shape a receiver parses is unchanged by signing. + var decoded map[string]any + if err := json.Unmarshal(r.body, &decoded); err != nil { + t.Fatalf("signed body is not the JSON payload: %v", err) + } + for _, field := range []string{"app", "env", "host", "verb", "deploy_id", "status", "operator", "ts", "text"} { + if _, ok := decoded[field]; !ok { + t.Errorf("payload lost %q: %s", field, r.body) + } + } +} + +func TestUnsignedSendCarriesNoSignatureHeaders(t *testing.T) { + srv, got := receiver(t, http.StatusServiceUnavailable) + n := app.Notification{Webhook: srv.URL, On: []string{"failure"}, Format: "json"} + if err := Send(t.Context(), n, Payload{Status: "fail"}); err == nil { + t.Fatal("503 must be reported") + } + reqs := got() + if len(reqs) != 1 { + t.Fatalf("an unsigned send is one attempt, got %d", len(reqs)) + } + if reqs[0].id != "" || reqs[0].timestamp != "" || reqs[0].signature != "" { + t.Fatalf("unsigned send carried signing headers: %+v", reqs[0]) + } +} + +func TestSignedSendRetriesWithAStableID(t *testing.T) { + fastBackoff(t) + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", testSecret) + for _, tc := range []struct { + name string + statuses []int + }{ + {"5xx", []int{http.StatusBadGateway, http.StatusServiceUnavailable}}, + {"429", []int{http.StatusTooManyRequests, http.StatusTooManyRequests}}, + } { + t.Run(tc.name, func(t *testing.T) { + srv, got := receiver(t, tc.statuses...) + if err := Send(t.Context(), signedConfig(srv.URL), Payload{App: "sample", Verb: "deploy", Status: "fail", Error: "x"}); err != nil { + t.Fatalf("third attempt succeeded, yet Send = %v", err) + } + reqs := got() + if len(reqs) != 3 { + t.Fatalf("got %d attempts, want 3", len(reqs)) + } + for _, r := range reqs { + if r.id != reqs[0].id { + t.Fatalf("webhook-id changed across retries: %q then %q", reqs[0].id, r.id) + } + // Each attempt is signed afresh over its own timestamp. + verify(t, testKey, r) + } + }) + } +} + +func TestSignedSendGivesUpAfterThreeAttempts(t *testing.T) { + fastBackoff(t) + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", testSecret) + srv, got := receiver(t, 500, 500, 500, 500) + err := Send(t.Context(), signedConfig(srv.URL), Payload{Status: "fail"}) + if err == nil || !strings.Contains(err.Error(), "500") { + t.Fatalf("Send = %v, want the last 500", err) + } + if n := len(got()); n != SignedAttempts { + t.Fatalf("got %d attempts, want %d", n, SignedAttempts) + } +} + +func TestSignedSendDoesNotRetryAClientError(t *testing.T) { + fastBackoff(t) + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", testSecret) + for _, status := range []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusNotFound} { + srv, got := receiver(t, status, status, status) + err := Send(t.Context(), signedConfig(srv.URL), Payload{Status: "fail"}) + if err == nil || !strings.Contains(err.Error(), strconv.Itoa(status)) { + t.Fatalf("Send = %v, want %d reported", err, status) + } + if n := len(got()); n != 1 { + t.Fatalf("%d: got %d attempts; a refused request is not retried", status, n) + } + } +} + +func TestSignedSendRetriesANetworkErrorWithinTheBudget(t *testing.T) { + fastBackoff(t) + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", testSecret) + start := time.Now() + err := Send(t.Context(), signedConfig("http://127.0.0.1:1"), Payload{Status: "fail"}) + if err == nil { + t.Fatal("a dead webhook must surface an error for the warn log") + } + if elapsed := time.Since(start); elapsed > SignedBudget+time.Second { + t.Fatalf("signed send took %s, beyond its %s budget", elapsed, SignedBudget) + } + if strings.Contains(err.Error(), testSecret) || strings.Contains(err.Error(), base64.StdEncoding.EncodeToString(testKey)) { + t.Fatalf("error carries the secret: %v", err) + } +} + +func TestSignedSendWithoutAUsableSecretIsAWarningAndSendsNothing(t *testing.T) { + for name, value := range map[string]string{ + "unset": "", + "no prefix": "c2VjcmV0LWNhbmFyeS12YWx1ZQ==", + "not b64": "whsec_secret-canary-value!!", + "empty key": "whsec_", + } { + t.Run(name, func(t *testing.T) { + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", value) + srv, got := receiver(t) + err := Send(t.Context(), signedConfig(srv.URL), Payload{Status: "fail"}) + if err == nil { + t.Fatal("a missing or malformed secret must be reported") + } + if !strings.Contains(err.Error(), "TEST_ONEBOX_WEBHOOK_SECRET") { + t.Fatalf("error must name the variable: %v", err) + } + if value != "" && value != "whsec_" && strings.Contains(err.Error(), strings.TrimPrefix(value, "whsec_")) { + t.Fatalf("error carries the secret value: %v", err) + } + if strings.Contains(err.Error(), "canary") { + t.Fatalf("error carries the secret value: %v", err) + } + if n := len(got()); n != 0 { + t.Fatalf("sent %d unsigned request(s) to a receiver that expects signatures", n) + } + }) + } +} + +func TestSignatureMatchesTheStandardWebhooksExample(t *testing.T) { + // The worked example from the Standard Webhooks specification's reference + // implementations. + key, err := ParseSigningSecret("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw") + if err != nil { + t.Fatal(err) + } + got := Signature(key, "msg_p5jXN8AQM9LWM0D4loKWxJek", 1614265330, []byte(`{"test": 2432232314}`)) + if want := "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE="; got != want { + t.Fatalf("Signature = %q, want %q", got, want) + } +} diff --git a/site/public/schemas/application/v1alpha2/application.schema.json b/site/public/schemas/application/v1alpha2/application.schema.json index 5cebd30d..93e8f999 100644 --- a/site/public/schemas/application/v1alpha2/application.schema.json +++ b/site/public/schemas/application/v1alpha2/application.schema.json @@ -800,6 +800,11 @@ "notifications": { "additionalProperties": { "additionalProperties": false, + "if": { + "required": [ + "signingSecretEnv" + ] + }, "properties": { "format": { "default": "Text", @@ -825,6 +830,14 @@ }, "type": "array" }, + "signingSecretEnv": { + "description": "Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "examples": [ + "ONEBOX_WEBHOOK_SECRET" + ], + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "type": "string" + }, "webhook": { "description": "HTTP endpoint that receives outcome notifications.", "examples": [ @@ -833,6 +846,16 @@ "type": "string" } }, + "then": { + "properties": { + "format": { + "const": "JSON" + } + }, + "required": [ + "format" + ] + }, "type": "object" }, "description": "Named webhooks that receive selected operation and scheduled-job outcomes.", diff --git a/site/src/content/docs/docs/guides/cron-jobs.mdx b/site/src/content/docs/docs/guides/cron-jobs.mdx index 94b49a00..53f05334 100644 --- a/site/src/content/docs/docs/guides/cron-jobs.mdx +++ b/site/src/content/docs/docs/guides/cron-jobs.mdx @@ -214,6 +214,28 @@ journal and never replaces the job's own result. The webhook must be reachable from the target host; timer delivery uses its network path, not the operator workstation's. +A notification with `signingSecretEnv` is signed on the host as well. `ob +deploy` reads the Standard Webhooks secret from the operator's environment and +writes the key into the same root-only handler as the webhook URL, and the +handler signs each attempt with `openssl` over the body it sends. The +`webhook-id` is `msg__`, the same on every retry. A signed send +makes at most three attempts of four seconds each, one second apart, and +retries only a network error, a 429, or a 5xx; the unit's `TimeoutStopSec` grows +by ten seconds to allow for them. While a signature is computed, the key is +visible in the host's process list, as the webhook URL already is in curl's. +If the secret is unset or malformed when you deploy, `ob deploy` warns and the +handler logs that the notification was not sent; it never sends that receiver +an unsigned request. A host without `openssl` logs the send as failed. Rotate +the secret by exporting the new one and deploying again. + +```yaml +notifications: + facet: + webhook: https://facet.example.com/hooks/onebox + format: JSON + signingSecretEnv: FACET_WEBHOOK_SECRET +``` + ## Cron is translated exactly, or refused ``` diff --git a/site/src/content/docs/docs/reference/fields/notifications.mdx b/site/src/content/docs/docs/reference/fields/notifications.mdx index b6d85971..512c9e5a 100644 --- a/site/src/content/docs/docs/reference/fields/notifications.mdx +++ b/site/src/content/docs/docs/reference/fields/notifications.mdx @@ -17,7 +17,7 @@ cannot drift from what `ob validate` accepts. ## Fields on this page -`format` · `on` · `webhook` +`format` · `on` · `signingSecretEnv` · `webhook` ## Reference @@ -25,4 +25,5 @@ cannot drift from what `ob validate` accepts. | --- | --- | --- | --- | | `.format` | `Text` · `JSON` | `Text` | Notification payload format. | | `.on` | list of `Success` · `Failure` | `success, failure` | Operation outcomes that trigger this notification. | +| `.signingSecretEnv` | string | — | Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked. Expects a variable name of letters, digits and underscores, not starting with a digit. | | `.webhook` | string | — | HTTP endpoint that receives outcome notifications. | From f7eb6dfb429dfd8bf78124844a760b4fede54e45 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Wed, 25 Nov 2026 22:29:04 -0800 Subject: [PATCH 2/3] fix(schedule): keep the signing key out of host command arguments The host notifier signed with openssl dgst -mac HMAC -macopt hexkey:..., which puts the key in the argument list of a running process, where ps and /proc//cmdline show it to every user on the host. openssl's HMAC options, dgst -hmac and mac -macopt alike, only take the key that way, and the host has no Onebox to sign for it. ob deploy now precomputes HMAC-SHA256's two keyed blocks (RFC 2104) and writes them as root-only files beside the notifier, which finds them through $0. The host computes the HMAC as two plain openssl dgst -sha256 runs over those files and the body, so no command takes the key or anything derived from it as an argument, and the notifier text no longer contains it. Each deploy clears the pad files before writing the current ones, and unit removal deletes them. A notifier whose pads are missing logs that it did not send. Tests run the notifier as systemd does, record the argv of every openssl and curl it starts, and assert that neither those nor the rendered script contain the key, its encodings, or the pads; the pads are checked against crypto/hmac, and schedule apply is checked to write them over stdin. Co-Authored-By: Claude Opus 5.5 --- internal/engine/schedule.go | 89 ++++++++-- internal/engine/schedule_signing_test.go | 157 +++++++++++++++++- .../content/docs/docs/guides/cron-jobs.mdx | 24 +-- 3 files changed, 241 insertions(+), 29 deletions(-) diff --git a/internal/engine/schedule.go b/internal/engine/schedule.go index 6afcf4b2..16657d67 100644 --- a/internal/engine/schedule.go +++ b/internal/engine/schedule.go @@ -2,7 +2,7 @@ package engine import ( "context" - "encoding/hex" + "crypto/sha256" "errors" "fmt" "math" @@ -92,7 +92,7 @@ func (e *Engine) SyncSchedules(ctx context.Context) error { runtimeEnvFiles = e.Spec.Runtime.EnvFiles } runner := scheduleRunnerScript(e.Spec.Name, job, n, e.lockPath(), runtimeEnvFiles, e.lockTTL(), e.hasTriggerUnit(ctx)) - notifier, err := e.scheduleNotifier(job) + notifier, pads, err := e.scheduleNotifierFiles(job) if err != nil { return fmt.Errorf("job %s: cannot render its failure notifier: %w", job.Name, err) } @@ -104,6 +104,18 @@ func (e *Engine) SyncSchedules(ctx context.Context) error { if err := e.writeServiceFile(ctx, notifyPath, []byte(notifier)); err != nil { return fmt.Errorf("job %s: cannot install its failure notifier: %w", job.Name, err) } + // Pads from a signing secret this deploy no longer uses must not stay + // on the host; the ones it does use are written fresh below. + if res, err := e.mutate(ctx, "rm -f "+q(notifyPath)+".*.ipad "+q(notifyPath)+".*.opad"); err != nil { + return fmt.Errorf("job %s: cannot clear its signing pads: %w", job.Name, err) + } else if res.ExitCode != 0 { + return fmt.Errorf("job %s: cannot clear its signing pads: %s", job.Name, strings.TrimSpace(res.Stderr)) + } + for _, suffix := range sortedNames(pads) { + if err := e.writeServiceFile(ctx, notifyPath+suffix, pads[suffix]); err != nil { + return fmt.Errorf("job %s: cannot install its notification signing pad: %w", job.Name, err) + } + } if err := e.writeServiceFile(ctx, "/etc/systemd/system/"+unit+".service", []byte(service)); err != nil { return fmt.Errorf("job %s: cannot install its unit: %w", job.Name, err) } @@ -701,6 +713,13 @@ const scheduleNotificationRun = "__ONEBOX_SCHEDULE_RUN__" // contract lives in the notify package and the host has no Onebox to ask at // 2am. Only the timestamp and the run id are filled in on the host. func (e *Engine) scheduleNotifier(job app.ScheduledJob) (string, error) { + script, _, err := e.scheduleNotifierFiles(job) + return script, err +} + +// scheduleNotifierFiles renders the notifier and the signing pads its signed +// sends read, keyed by the suffix each takes after the notifier's own path. +func (e *Engine) scheduleNotifierFiles(job app.ScheduledJob) (string, map[string][]byte, error) { cleanup := scheduleContainerRemove(e.names().Container(job.Name, 1)) environment := e.Opts.Environment lines := []string{ @@ -736,7 +755,7 @@ func (e *Engine) scheduleNotifier(job app.ScheduledJob) (string, error) { } rendered, err := e.scheduleNotificationSends(job.Name, environment, class, keys) if err != nil { - return "", err + return "", nil, err } sends[class] = rendered } @@ -751,7 +770,47 @@ func (e *Engine) scheduleNotifier(job app.ScheduledJob) (string, error) { lines = append(lines, "fi", "wait || true") } lines = append(lines, "exit 0", "") - return strings.Join(lines, "\n"), nil + var pads map[string][]byte + for i, name := range sortedNames(e.Spec.Notifications) { + if key := keys[name]; key != nil { + if pads == nil { + pads = map[string][]byte{} + } + inner, outer := hmacPads(key) + pads[signingPadSuffix(i)+".ipad"] = inner + pads[signingPadSuffix(i)+".opad"] = outer + } + } + return strings.Join(lines, "\n"), pads, nil +} + +// signingPadSuffix names a signed notification's pads after the notifier's +// path. The notifier finds them through $0, which systemd sets to that path +// because ExecStopPost runs it as `/bin/sh `. +func signingPadSuffix(index int) string { + return "." + strconv.Itoa(index) +} + +// hmacPads precomputes HMAC-SHA256's keyed blocks (RFC 2104): the key, hashed +// first when longer than the 64-byte block, zero-padded and XORed with 0x36 +// and 0x5c. With them the host computes the HMAC as two plain SHA-256 runs +// over files and pipes, so no command it runs takes the key, or anything +// derived from it, as an argument where ps or /proc//cmdline would show +// it. openssl's own HMAC options only take the key on the command line. +func hmacPads(key []byte) (inner, outer []byte) { + const block = 64 + if len(key) > block { + sum := sha256.Sum256(key) + key = sum[:] + } + inner, outer = make([]byte, block), make([]byte, block) + copy(inner, key) + copy(outer, key) + for i := range block { + inner[i] ^= 0x36 + outer[i] ^= 0x5c + } + return inner, outer } // orNoop keeps a shell branch syntactically present when it has nothing to do. @@ -778,9 +837,9 @@ func (e *Engine) scheduleSigns(job app.ScheduledJob) bool { // scheduleSigningKeys resolves, from the deploying operator's environment, // the signing key of each signed notification this job can send. The host has -// no Onebox to sign at 2am, so the key travels in the root-only notifier -// beside the webhook URL, and the host computes the signature at send time -// over the body it actually sends. A notification whose secret is unavailable +// no Onebox to sign at 2am, so the key travels as root-only HMAC pad files +// beside the notifier, never in it, and the host computes the signature at +// send time over the body it actually sends. A notification whose secret is unavailable // maps to nil: the host is told not to send it, because an unsigned request // to a receiver that verifies signatures is one it must reject. That is a // warning, never a failed deploy. @@ -838,7 +897,7 @@ func (e *Engine) scheduleNotificationSends(job, environment, class string, keys sends = append(sends, " echo "+q("onebox: notification "+name+" not sent: its signing secret was unavailable when this job was deployed")+" >&2") continue } - sends = append(sends, signedScheduleSend(name, i, cfg.Webhook, prepared, key)) + sends = append(sends, signedScheduleSend(name, i, cfg.Webhook, prepared)) continue } curl := "curl --fail --silent --show-error --max-time 5 --request POST" + @@ -852,22 +911,26 @@ func (e *Engine) scheduleNotificationSends(job, environment, class string, keys } // signedScheduleSend renders a Standard Webhooks send for the host: the same -// body as an unsigned send, signed with openssl over the bytes curl posts. +// body as an unsigned send, signed over the bytes curl posts. The HMAC is +// SHA-256 over the inner pad and the message, then over the outer pad and +// that digest; openssl only hashes, reading the pads from their root-only +// files, so the key is in no argument list. // The webhook-id is the systemd invocation plus the notification's position, // fixed before the first attempt, so every retry repeats it. Each attempt // takes a fresh timestamp and signature. At most notify.SignedAttempts // attempts of four seconds with a one-second pause between them fit in // notify.SignedBudget; only a network error (000), a 429 or a 5xx is retried. // Without openssl the send is not attempted, and the failure is logged. -func signedScheduleSend(name string, index int, webhook string, prepared *notify.Request, key []byte) string { +func signedScheduleSend(name string, index int, webhook string, prepared *notify.Request) string { attempts := strconv.Itoa(notify.SignedAttempts) - sign := `sig=$(printf '%s.%s.%s' "$id" "$wts" "$body" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$key" -binary | openssl base64 -A) || break; [ -n "$sig" ] || break; ` + sign := `sig=$({ cat "$pad.opad" && { cat "$pad.ipad" && printf '%s.%s.%s' "$id" "$wts" "$body"; } | openssl dgst -sha256 -binary; } | openssl dgst -sha256 -binary | openssl base64 -A) || break; [ ${#sig} -eq 44 ] || break; ` curl := "code=$(curl --silent --show-error --max-time 4 --output /dev/null --write-out '%{http_code}' --request POST" + " --header " + q("Content-Type: "+prepared.ContentType) + " --header " + q("X-Title: "+prepared.Title) + ` --header "webhook-id: $id" --header "webhook-timestamp: $wts" --header "webhook-signature: v1,$sig"` + ` --data-binary "$body" ` + q(webhook) + "); " - return " (body=" + shellBody(string(prepared.Body)) + "; key=" + q(hex.EncodeToString(key)) + + return " (body=" + shellBody(string(prepared.Body)) + `; pad="$0` + signingPadSuffix(index) + `"; ` + + `if [ ! -r "$pad.ipad" ] || [ ! -r "$pad.opad" ]; then echo ` + q("onebox: notification "+name+" not sent: its signing pads are missing; deploy again") + ` >&2; exit 0; fi` + `; id="msg_${INVOCATION_ID:-$(date -u '+%s')$$}_` + strconv.Itoa(index) + `"; attempt=0; sent=''; ` + `while [ "$attempt" -lt ` + attempts + ` ]; do attempt=$((attempt + 1)); wts=$(date -u '+%s'); ` + sign + curl + @@ -999,7 +1062,7 @@ func (e *Engine) RemoveSchedules(ctx context.Context) error { func (e *Engine) removeScheduleUnit(ctx context.Context, unit string) error { disable, disableErr := e.mutate(ctx, "systemctl disable --now "+unit+".timer >/dev/null") remove, removeErr := e.mutate(ctx, fmt.Sprintf( - "rm -f /etc/systemd/system/%s.timer /etc/systemd/system/%s.service /etc/systemd/system/%s.run /etc/systemd/system/%s.notify", unit, unit, unit, unit)) + "rm -f /etc/systemd/system/%s.timer /etc/systemd/system/%s.service /etc/systemd/system/%s.run /etc/systemd/system/%s.notify /etc/systemd/system/%s.notify.*.ipad /etc/systemd/system/%s.notify.*.opad", unit, unit, unit, unit, unit, unit)) var errs []error if disableErr != nil { errs = append(errs, fmt.Errorf("disable schedule %s: %w", unit, disableErr)) diff --git a/internal/engine/schedule_signing_test.go b/internal/engine/schedule_signing_test.go index 1c1ec1ba..5dcbaf75 100644 --- a/internal/engine/schedule_signing_test.go +++ b/internal/engine/schedule_signing_test.go @@ -6,6 +6,7 @@ import ( "crypto/hmac" "crypto/sha256" "encoding/base64" + "encoding/hex" "encoding/json" "os" "os/exec" @@ -32,11 +33,26 @@ type signedAttempt struct { // curl stub that answers each attempt with the next of codes, and real // openssl, which is what signs on the host. func runSignedNotifier(t *testing.T, codes []string, secret string) (string, []signedAttempt, string) { + t.Helper() + return runSignedNotifierWith(t, codes, secret, true) +} + +// signedRun is everything one notifier execution exposed: the rendered +// script, each curl attempt, the combined log, and every argument list the +// host's openssl and curl were started with — what ps and /proc//cmdline +// would show. +func runSignedNotifierWith(t *testing.T, codes []string, secret string, writePads bool) (string, []signedAttempt, string) { + script, attempts, log, _ := runSignedNotifierArgv(t, codes, secret, writePads) + return script, attempts, log +} + +func runSignedNotifierArgv(t *testing.T, codes []string, secret string, writePads bool) (string, []signedAttempt, string, string) { t.Helper() if runtime.GOOS == "windows" { t.Skip("POSIX shell required") } - if _, err := exec.LookPath("openssl"); err != nil { + realOpenSSL, err := exec.LookPath("openssl") + if err != nil { t.Skip("openssl is what signs on the host, and it is not installed here") } t.Setenv("TEST_SCHEDULE_WEBHOOK_SECRET", secret) @@ -48,10 +64,22 @@ func runSignedNotifier(t *testing.T, codes []string, secret string) (string, []s } out := &bytes.Buffer{} e := New(cfg, testProject(t), &transport.Fake{TargetName: "root@example.internal"}, Options{Environment: "production", Out: out, Sleep: noSleep}) - script, err := e.scheduleNotifier(app.ScheduledJob{Name: "nightly", Notify: []string{"failure"}}) + script, pads, err := e.scheduleNotifierFiles(app.ScheduledJob{Name: "nightly", Notify: []string{"failure"}}) if err != nil { t.Fatal(err) } + // Run it the way systemd does, `/bin/sh `, so $0 finds the pads. + notifyPath := filepath.Join(base, "onebox-job-nightly.notify") + if err := os.WriteFile(notifyPath, []byte(script), 0o600); err != nil { + t.Fatal(err) + } + if writePads { + for suffix, pad := range pads { + if err := os.WriteFile(notifyPath+suffix, pad, 0o600); err != nil { + t.Fatal(err) + } + } + } if err := os.MkdirAll(filepath.Join(base, "app", "schedule"), 0o700); err != nil { t.Fatal(err) } @@ -62,7 +90,13 @@ func runSignedNotifier(t *testing.T, codes []string, secret string) (string, []s if err := os.WriteFile(filepath.Join(bin, "codes"), []byte(strings.Join(codes, "\n")+"\n"), 0o600); err != nil { t.Fatal(err) } + argv := filepath.Join(bin, "argv") + openssl := "#!/bin/sh\nprintf 'openssl %s\\n' \"$*\" >>" + argv + "\nexec " + realOpenSSL + " \"$@\"\n" + if err := os.WriteFile(filepath.Join(bin, "openssl"), []byte(openssl), 0o755); err != nil { + t.Fatal(err) + } curl := "#!/bin/sh\n" + + "printf 'curl %s\\n' \"$*\" >>" + argv + "\n" + "n=$(cat " + bin + "/count 2>/dev/null || echo 0); n=$((n + 1)); echo \"$n\" >" + bin + "/count\n" + "printf '%s\\n' \"$@\" >" + bin + "/args.$n\n" + "code=$(sed -n \"${n}p\" " + bin + "/codes); [ -n \"$code\" ] || code=200\n" + @@ -70,8 +104,7 @@ func runSignedNotifier(t *testing.T, codes []string, secret string) (string, []s if err := os.WriteFile(filepath.Join(bin, "curl"), []byte(curl), 0o755); err != nil { t.Fatal(err) } - command := exec.CommandContext(context.Background(), "sh", "-s") - command.Stdin = strings.NewReader(script) + command := exec.CommandContext(context.Background(), "sh", notifyPath) command.Env = []string{ "PATH=" + bin + ":" + os.Getenv("PATH"), "HOME=" + base, "SERVICE_RESULT=exit-code", "EXIT_STATUS=1", "INVOCATION_ID=0123456789abcdef0123456789abcdef", @@ -99,7 +132,8 @@ func runSignedNotifier(t *testing.T, codes []string, secret string) (string, []s } attempts = append(attempts, a) } - return script, attempts, string(stderr) + out.String() + argvLog, _ := os.ReadFile(argv) + return script, attempts, string(stderr) + out.String(), string(argvLog) } func verifyScheduleSignature(t *testing.T, a signedAttempt) { @@ -186,3 +220,116 @@ func TestSignedScheduleExtendsTheStopTimeout(t *testing.T) { t.Fatalf("stop timeouts:\n%s\n%s", plain, signed) } } + +// The key, and the pads derived from it, are never a command argument: not in +// the rendered notifier, where every string becomes some process's argv, and +// not in the argument lists the host actually started openssl and curl with. +func TestScheduledJobSigningKeyIsNeverACommandArgument(t *testing.T) { + secret := "whsec_" + base64.StdEncoding.EncodeToString(scheduleSigningKey) + script, attempts, _, argv := runSignedNotifierArgv(t, []string{"200"}, secret, true) + if len(attempts) != 1 { + t.Fatalf("got %d attempts, want 1", len(attempts)) + } + verifyScheduleSignature(t, attempts[0]) + inner, outer := hmacPads(scheduleSigningKey) + forbidden := map[string]string{ + "secret": secret, + "base64 key": base64.StdEncoding.EncodeToString(scheduleSigningKey), + "hex key": hex.EncodeToString(scheduleSigningKey), + "raw key": string(scheduleSigningKey), + "hex inner pad": hex.EncodeToString(inner), + "hex outer pad": hex.EncodeToString(outer), + "base64 inner pad": base64.StdEncoding.EncodeToString(inner), + "openssl key flag": "hexkey", + "openssl macopt": "macopt", + "openssl hmac flag": "-hmac", + } + for what, value := range forbidden { + if strings.Contains(script, value) { + t.Errorf("the rendered notifier contains the %s:\n%s", what, script) + } + if strings.Contains(argv, value) { + t.Errorf("a host command was started with the %s in its arguments:\n%s", what, argv) + } + } + if !strings.Contains(argv, "openssl dgst -sha256 -binary") { + t.Fatalf("the argv log did not capture the signing commands:\n%s", argv) + } +} + +func TestHMACPadsMatchHMAC(t *testing.T) { + for _, key := range [][]byte{scheduleSigningKey, bytes.Repeat([]byte{7}, 64), bytes.Repeat([]byte{9}, 100)} { + inner, outer := hmacPads(key) + message := []byte("msg_1.1614265330.{}") + h := sha256.Sum256(append(append([]byte{}, inner...), message...)) + got := sha256.Sum256(append(append([]byte{}, outer...), h[:]...)) + mac := hmac.New(sha256.New, key) + mac.Write(message) + if !hmac.Equal(got[:], mac.Sum(nil)) { + t.Fatalf("pads for a %d-byte key do not reproduce HMAC-SHA256", len(key)) + } + } +} + +func TestScheduledJobWithMissingPadsSendsNothing(t *testing.T) { + secret := "whsec_" + base64.StdEncoding.EncodeToString(scheduleSigningKey) + _, attempts, log := runSignedNotifierWith(t, []string{"200"}, secret, false) + if len(attempts) != 0 { + t.Fatalf("sent %d request(s) without the pads to sign them", len(attempts)) + } + if !strings.Contains(log, "signing pads are missing") { + t.Fatalf("the host must log why it sent nothing:\n%s", log) + } +} + +func TestScheduleApplyWritesPadsBesideTheNotifierAndClearsStaleOnes(t *testing.T) { + t.Setenv("TEST_SCHEDULE_WEBHOOK_SECRET", "whsec_"+base64.StdEncoding.EncodeToString(scheduleSigningKey)) + cfg := testConfig() + cfg.Workloads["nightly"] = app.Workload{ + Role: app.RoleJob, DeploymentPhase: "none", DataEffect: "none", + Schedule: &app.JobSchedule{Cron: "0 2 * * *", Timezone: "UTC", Timeout: "45m", Notify: []string{"failure"}}, + } + cfg.Notifications = map[string]app.Notification{ + "facet": {Webhook: "https://facet.example.invalid/hooks/onebox", On: []string{"failure"}, Format: "json", SigningSecretEnv: "TEST_SCHEDULE_WEBHOOK_SECRET"}, + } + f := happyFake() + base := f.Dynamic + f.Dynamic = func(cmd string) (transport.Result, bool) { + switch { + case strings.Contains(cmd, "current/compose.yaml"), strings.Contains(cmd, "systemd-analyze calendar"), strings.Contains(cmd, "command -v flock"): + return transport.Result{Stdout: "ok\n"}, true + case strings.Contains(cmd, "list-unit-files"): + return transport.Result{}, true + } + return base(cmd) + } + e := New(cfg, testProject(t), f, Options{Out: &bytes.Buffer{}, Sleep: noSleep, Environment: "production"}) + if err := e.ScheduleApply(context.Background(), "R9-schedule-apply"); err != nil { + t.Fatalf("schedule apply: %v\n%s", err, strings.Join(f.Commands, "\n")) + } + seq := strings.Join(f.Commands, "\n") + notify := "/etc/systemd/system/onebox-job-nightly.notify" + for _, want := range []string{ + "rm -f '" + notify + "'.*.ipad '" + notify + "'.*.opad", + "cat > '" + notify + ".0.ipad.onebox-tmp'", + "cat > '" + notify + ".0.opad.onebox-tmp'", + } { + if !strings.Contains(seq, want) { + t.Errorf("schedule apply is missing %q:\n%s", want, seq) + } + } + inner, outer := hmacPads(scheduleSigningKey) + var sawInner, sawOuter bool + for _, in := range f.Inputs { + sawInner = sawInner || in == string(inner) + sawOuter = sawOuter || in == string(outer) + } + if !sawInner || !sawOuter { + t.Fatal("the pads were not written to the host") + } + for _, cmd := range f.Commands { + if strings.Contains(cmd, string(inner)) || strings.Contains(cmd, hex.EncodeToString(inner)) || strings.Contains(cmd, hex.EncodeToString(scheduleSigningKey)) { + t.Fatalf("a host command carries key material: %q", cmd) + } + } +} diff --git a/site/src/content/docs/docs/guides/cron-jobs.mdx b/site/src/content/docs/docs/guides/cron-jobs.mdx index 53f05334..97c4cb9e 100644 --- a/site/src/content/docs/docs/guides/cron-jobs.mdx +++ b/site/src/content/docs/docs/guides/cron-jobs.mdx @@ -216,17 +216,19 @@ workstation's. A notification with `signingSecretEnv` is signed on the host as well. `ob deploy` reads the Standard Webhooks secret from the operator's environment and -writes the key into the same root-only handler as the webhook URL, and the -handler signs each attempt with `openssl` over the body it sends. The -`webhook-id` is `msg__`, the same on every retry. A signed send -makes at most three attempts of four seconds each, one second apart, and -retries only a network error, a 429, or a 5xx; the unit's `TimeoutStopSec` grows -by ten seconds to allow for them. While a signature is computed, the key is -visible in the host's process list, as the webhook URL already is in curl's. -If the secret is unset or malformed when you deploy, `ob deploy` warns and the -handler logs that the notification was not sent; it never sends that receiver -an unsigned request. A host without `openssl` logs the send as failed. Rotate -the secret by exporting the new one and deploying again. +writes the HMAC's two keyed blocks, not the secret and not inside the handler, +as root-only files beside the handler. For each attempt the handler computes +the HMAC as two `openssl dgst -sha256` runs that read those files and the body +it sends, so the key never appears in any command's arguments, `ps`, or +`/proc//cmdline`. The `webhook-id` is `msg__`, the same on +every retry. A signed send makes at most three attempts of four seconds each, +one second apart, and retries only a network error, a 429, or a 5xx; the unit's +`TimeoutStopSec` grows by ten seconds to allow for them. If the secret is unset +or malformed when you deploy, `ob deploy` warns and the handler logs that the +notification was not sent; it never sends that receiver an unsigned request. A +host without `openssl` logs the send as failed. Rotate the secret by exporting +the new one and deploying again; each deploy rewrites the key files and removes +any a removed notification left behind. ```yaml notifications: From 25fcd03e74c73d6855d2e750df0cfc6fe645c50a Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Wed, 25 Nov 2026 23:15:53 -0800 Subject: [PATCH 3/3] fix(notify): bound signed sends together and keep host pads safe Four review findings on signed notifications. The retry budget was untested: the dead-endpoint test dialed a port that refuses at once. The per-attempt timeout and the signed budget are now package variables, and a test whose receiver hangs past the attempt timeout checks that the send ends at the budget with "not delivered within" in its error. Several signed notifications to dead receivers added their budgets together, because ob sent them one after another. notify.SendAll sends every notification at once and returns failures in name order, so a verb's notification tail stays about one budget however many webhooks are configured. writeServiceFile stages each pad as .onebox-tmp, which the cleanup globs did not match, so a half-written key-equivalent file could stay on the host. Both cleanups now match every *pad* file beside the notifier. A deploy run without the secret exported deleted working pads and left the job unable to sign. It now keeps a notification's existing pads and warns "signing secret unavailable; kept existing pads"; pads are deleted only when signing is removed from the configuration or the job is removed. Pad files are named from a hash of the notification name rather than its position, so a kept pad can never sign a different notification after the set changes. The engine signing tests fail instead of skipping when openssl is missing and CI is set, so CI cannot pass with host signing unverified. Co-Authored-By: Claude Opus 5.5 --- .../v1alpha2/application.schema.json | 2 +- cmd/ob/commands.go | 23 +-- internal/app/types.go | 2 +- internal/engine/schedule.go | 87 ++++++---- internal/engine/schedule_signing_test.go | 152 +++++++++++++++--- internal/notify/notify.go | 55 ++++++- internal/notify/sign_test.go | 78 +++++++++ .../v1alpha2/application.schema.json | 2 +- .../content/docs/docs/guides/cron-jobs.mdx | 12 +- .../docs/reference/fields/notifications.mdx | 2 +- 10 files changed, 338 insertions(+), 77 deletions(-) diff --git a/api/application/v1alpha2/application.schema.json b/api/application/v1alpha2/application.schema.json index 93e8f999..8666f300 100644 --- a/api/application/v1alpha2/application.schema.json +++ b/api/application/v1alpha2/application.schema.json @@ -831,7 +831,7 @@ "type": "array" }, "signingSecretEnv": { - "description": "Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "description": "Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning, never a blocked operation: the command does not send that notification, and a scheduled job keeps signing with the keys its last deploy wrote. Notifications are sent concurrently, so several dead receivers still cost one 15-second bound. Expects a variable name of letters, digits and underscores, not starting with a digit.", "examples": [ "ONEBOX_WEBHOOK_SECRET" ], diff --git a/cmd/ob/commands.go b/cmd/ob/commands.go index 4c12a933..e356caee 100644 --- a/cmd/ob/commands.go +++ b/cmd/ob/commands.go @@ -275,10 +275,10 @@ func notifyOutcome(ctx context.Context, cfg *app.Resolved, g *globalFlags, verb, // stable, redaction-safe outcome. p.Status, p.Error = "fail", "operation failed; inspect trusted local diagnostics and journal evidence" } - for _, name := range sortedNames(cfg.Notifications) { - if nerr := notify.Send(ctx, cfg.Notifications[name], p); nerr != nil { - fmt.Fprintf(os.Stderr, "warn: notify webhook %s: %v\n", name, nerr) - } + // Sent concurrently, so a verb waits for at most one send's bound however + // many webhooks are configured. + for _, failure := range notify.SendAll(ctx, cfg.Notifications, p) { + fmt.Fprintf(os.Stderr, "warn: notify webhook %s: %v\n", failure.Name, failure.Err) } } @@ -294,8 +294,9 @@ func notifyOperationOutcome(ctx context.Context, cfg *app.Resolved, g *globalFla evidenceID = result.ReleaseID } // The operation context is cancelled by Ctrl-C and SIGTERM. Its outcome is - // still worth sending; notify.Send bounds itself: one 5s attempt, or for a - // signed notification at most three attempts within notify.SignedBudget. + // still worth sending; notify.SendAll bounds itself: one 5s attempt, or for + // a signed notification at most three attempts within notify.SignedBudget, + // with every webhook sent at once. notifyOutcome(context.WithoutCancel(ctx), cfg, g, verb, evidenceID, err) } @@ -572,16 +573,6 @@ func notificationConfig(g *globalFlags) (*app.Resolved, error) { return spec.Resolve(g.Env) } -// sortedNames orders map keys so repeated runs report in the same sequence. -func sortedNames[V any](m map[string]V) []string { - out := make([]string, 0, len(m)) - for k := range m { - out = append(out, k) - } - sort.Strings(out) - return out -} - func renderDeployNoOp(u *ui.UI, currentRelease string) { u.Successf("nothing to deploy — %s is current (`--redeploy` forces a fresh roll)", currentRelease) } diff --git a/internal/app/types.go b/internal/app/types.go index 3582adf2..d18d7f67 100644 --- a/internal/app/types.go +++ b/internal/app/types.go @@ -520,7 +520,7 @@ type Notification struct { Format string `json:"format" description:"Notification payload format." default:"text"` // SigningSecretEnv names a variable in the operator's environment, never // the secret itself, so the project file stays safe to commit. - SigningSecretEnv string `json:"signing_secret_env,omitempty" description:"Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked." example:"ONEBOX_WEBHOOK_SECRET"` + SigningSecretEnv string `json:"signing_secret_env,omitempty" description:"Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning, never a blocked operation: the command does not send that notification, and a scheduled job keeps signing with the keys its last deploy wrote. Notifications are sent concurrently, so several dead receivers still cost one 15-second bound." example:"ONEBOX_WEBHOOK_SECRET"` } type Registry struct { diff --git a/internal/engine/schedule.go b/internal/engine/schedule.go index 16657d67..fdd8958e 100644 --- a/internal/engine/schedule.go +++ b/internal/engine/schedule.go @@ -3,6 +3,7 @@ package engine import ( "context" "crypto/sha256" + "encoding/hex" "errors" "fmt" "math" @@ -104,14 +105,19 @@ func (e *Engine) SyncSchedules(ctx context.Context) error { if err := e.writeServiceFile(ctx, notifyPath, []byte(notifier)); err != nil { return fmt.Errorf("job %s: cannot install its failure notifier: %w", job.Name, err) } - // Pads from a signing secret this deploy no longer uses must not stay - // on the host; the ones it does use are written fresh below. - if res, err := e.mutate(ctx, "rm -f "+q(notifyPath)+".*.ipad "+q(notifyPath)+".*.opad"); err != nil { + // Pads, and any half-written staging copy, of a notification that is + // no longer signed must not stay on the host. A signed notification + // whose secret this deploy could not read keeps the pads it has, and + // the ones this deploy can derive are written fresh below. + if res, err := e.mutate(ctx, signingPadCleanup(notifyPath, keptPads(pads))); err != nil { return fmt.Errorf("job %s: cannot clear its signing pads: %w", job.Name, err) } else if res.ExitCode != 0 { return fmt.Errorf("job %s: cannot clear its signing pads: %s", job.Name, strings.TrimSpace(res.Stderr)) } for _, suffix := range sortedNames(pads) { + if pads[suffix] == nil { + continue + } if err := e.writeServiceFile(ctx, notifyPath+suffix, pads[suffix]); err != nil { return fmt.Errorf("job %s: cannot install its notification signing pad: %w", job.Name, err) } @@ -718,7 +724,9 @@ func (e *Engine) scheduleNotifier(job app.ScheduledJob) (string, error) { } // scheduleNotifierFiles renders the notifier and the signing pads its signed -// sends read, keyed by the suffix each takes after the notifier's own path. +// sends read, keyed by the suffix each takes after the notifier's own path. A +// nil pad is one to keep as the host has it: the secret was unavailable to +// this deploy, which is no reason to stop signing with the last good one. func (e *Engine) scheduleNotifierFiles(job app.ScheduledJob) (string, map[string][]byte, error) { cleanup := scheduleContainerRemove(e.names().Container(job.Name, 1)) environment := e.Opts.Environment @@ -771,24 +779,54 @@ func (e *Engine) scheduleNotifierFiles(job app.ScheduledJob) (string, map[string } lines = append(lines, "exit 0", "") var pads map[string][]byte - for i, name := range sortedNames(e.Spec.Notifications) { - if key := keys[name]; key != nil { - if pads == nil { - pads = map[string][]byte{} - } - inner, outer := hmacPads(key) - pads[signingPadSuffix(i)+".ipad"] = inner - pads[signingPadSuffix(i)+".opad"] = outer + for _, name := range sortedNames(keys) { + if pads == nil { + pads = map[string][]byte{} } + suffix := signingPadSuffix(name) + key := keys[name] + if key == nil { + pads[suffix+".ipad"], pads[suffix+".opad"] = nil, nil + continue + } + inner, outer := hmacPads(key) + pads[suffix+".ipad"], pads[suffix+".opad"] = inner, outer } return strings.Join(lines, "\n"), pads, nil } // signingPadSuffix names a signed notification's pads after the notifier's // path. The notifier finds them through $0, which systemd sets to that path -// because ExecStopPost runs it as `/bin/sh `. -func signingPadSuffix(index int) string { - return "." + strconv.Itoa(index) +// because ExecStopPost runs it as `/bin/sh `. The suffix is derived from +// the notification's name, not its position, so a kept pad can never be read +// for a different notification after one is added or removed, and any name is +// safe in a file name. +func signingPadSuffix(name string) string { + sum := sha256.Sum256([]byte(name)) + return "." + hex.EncodeToString(sum[:8]) +} + +// keptPads lists the pad files a deploy leaves as the host has them. +func keptPads(pads map[string][]byte) []string { + var keep []string + for _, suffix := range sortedNames(pads) { + if pads[suffix] == nil { + keep = append(keep, suffix) + } + } + return keep +} + +// signingPadCleanup removes every pad file beside the notifier, staging +// copies included, except the ones listed to keep. +func signingPadCleanup(notifyPath string, keep []string) string { + var cmd strings.Builder + cmd.WriteString("for f in " + q(notifyPath) + ".*pad*; do case \"$f\" in ") + for _, suffix := range keep { + cmd.WriteString(q(notifyPath+suffix) + ") ;; ") + } + cmd.WriteString("*) rm -f \"$f\" ;; esac; done") + return cmd.String() } // hmacPads precomputes HMAC-SHA256's keyed blocks (RFC 2104): the key, hashed @@ -839,10 +877,10 @@ func (e *Engine) scheduleSigns(job app.ScheduledJob) bool { // the signing key of each signed notification this job can send. The host has // no Onebox to sign at 2am, so the key travels as root-only HMAC pad files // beside the notifier, never in it, and the host computes the signature at -// send time over the body it actually sends. A notification whose secret is unavailable -// maps to nil: the host is told not to send it, because an unsigned request -// to a receiver that verifies signatures is one it must reject. That is a -// warning, never a failed deploy. +// send time over the body it actually sends. A notification whose secret is +// unavailable maps to nil: its pads on the host are kept, and a host without +// them sends nothing, because an unsigned request to a receiver that verifies +// signatures is one it must reject. That is a warning, never a failed deploy. func (e *Engine) scheduleSigningKeys(job app.ScheduledJob) map[string][]byte { if !e.scheduleSigns(job) { return nil @@ -855,7 +893,7 @@ func (e *Engine) scheduleSigningKeys(job app.ScheduledJob) map[string][]byte { } key, err := notify.SigningKey(cfg) if err != nil { - e.warnf("job %s: notification %s will not be sent from the host: %v", job.Name, name, err) + e.warnf("job %s: notification %s: signing secret unavailable; kept existing pads, which sign until it is exported and deployed again: %v", job.Name, name, err) } keys[name] = key } @@ -892,11 +930,6 @@ func (e *Engine) scheduleNotificationSends(job, environment, class string, keys continue } if cfg.SigningSecretEnv != "" { - key := keys[name] - if key == nil { - sends = append(sends, " echo "+q("onebox: notification "+name+" not sent: its signing secret was unavailable when this job was deployed")+" >&2") - continue - } sends = append(sends, signedScheduleSend(name, i, cfg.Webhook, prepared)) continue } @@ -929,7 +962,7 @@ func signedScheduleSend(name string, index int, webhook string, prepared *notify " --header " + q("X-Title: "+prepared.Title) + ` --header "webhook-id: $id" --header "webhook-timestamp: $wts" --header "webhook-signature: v1,$sig"` + ` --data-binary "$body" ` + q(webhook) + "); " - return " (body=" + shellBody(string(prepared.Body)) + `; pad="$0` + signingPadSuffix(index) + `"; ` + + return " (body=" + shellBody(string(prepared.Body)) + `; pad="$0` + signingPadSuffix(name) + `"; ` + `if [ ! -r "$pad.ipad" ] || [ ! -r "$pad.opad" ]; then echo ` + q("onebox: notification "+name+" not sent: its signing pads are missing; deploy again") + ` >&2; exit 0; fi` + `; id="msg_${INVOCATION_ID:-$(date -u '+%s')$$}_` + strconv.Itoa(index) + `"; attempt=0; sent=''; ` + `while [ "$attempt" -lt ` + attempts + ` ]; do attempt=$((attempt + 1)); wts=$(date -u '+%s'); ` + @@ -1062,7 +1095,7 @@ func (e *Engine) RemoveSchedules(ctx context.Context) error { func (e *Engine) removeScheduleUnit(ctx context.Context, unit string) error { disable, disableErr := e.mutate(ctx, "systemctl disable --now "+unit+".timer >/dev/null") remove, removeErr := e.mutate(ctx, fmt.Sprintf( - "rm -f /etc/systemd/system/%s.timer /etc/systemd/system/%s.service /etc/systemd/system/%s.run /etc/systemd/system/%s.notify /etc/systemd/system/%s.notify.*.ipad /etc/systemd/system/%s.notify.*.opad", unit, unit, unit, unit, unit, unit)) + "rm -f /etc/systemd/system/%s.timer /etc/systemd/system/%s.service /etc/systemd/system/%s.run /etc/systemd/system/%s.notify /etc/systemd/system/%s.notify.*pad*", unit, unit, unit, unit, unit)) var errs []error if disableErr != nil { errs = append(errs, fmt.Errorf("disable schedule %s: %w", unit, disableErr)) diff --git a/internal/engine/schedule_signing_test.go b/internal/engine/schedule_signing_test.go index 5dcbaf75..2c8434a2 100644 --- a/internal/engine/schedule_signing_test.go +++ b/internal/engine/schedule_signing_test.go @@ -42,19 +42,17 @@ func runSignedNotifier(t *testing.T, codes []string, secret string) (string, []s // host's openssl and curl were started with — what ps and /proc//cmdline // would show. func runSignedNotifierWith(t *testing.T, codes []string, secret string, writePads bool) (string, []signedAttempt, string) { - script, attempts, log, _ := runSignedNotifierArgv(t, codes, secret, writePads) + script, attempts, log, _ := runSignedNotifierArgv(t, codes, secret, writePads, nil) return script, attempts, log } -func runSignedNotifierArgv(t *testing.T, codes []string, secret string, writePads bool) (string, []signedAttempt, string, string) { +// priorKey, when set, stands for the pads an earlier deploy left on the host. +func runSignedNotifierArgv(t *testing.T, codes []string, secret string, writePads bool, priorKey []byte) (string, []signedAttempt, string, string) { t.Helper() if runtime.GOOS == "windows" { t.Skip("POSIX shell required") } - realOpenSSL, err := exec.LookPath("openssl") - if err != nil { - t.Skip("openssl is what signs on the host, and it is not installed here") - } + realOpenSSL := requireOpenSSL(t) t.Setenv("TEST_SCHEDULE_WEBHOOK_SECRET", secret) base := t.TempDir() cfg := testConfig() @@ -73,8 +71,22 @@ func runSignedNotifierArgv(t *testing.T, codes []string, secret string, writePad if err := os.WriteFile(notifyPath, []byte(script), 0o600); err != nil { t.Fatal(err) } + if priorKey != nil { + inner, outer := hmacPads(priorKey) + suffix := signingPadSuffix("facet") + if err := os.WriteFile(notifyPath+suffix+".ipad", inner, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(notifyPath+suffix+".opad", outer, 0o600); err != nil { + t.Fatal(err) + } + } if writePads { + // What schedule apply writes: a nil pad is one it leaves alone. for suffix, pad := range pads { + if pad == nil { + continue + } if err := os.WriteFile(notifyPath+suffix, pad, 0o600); err != nil { t.Fatal(err) } @@ -196,19 +208,29 @@ func TestScheduledJobDoesNotRetryARefusedSignedSend(t *testing.T) { } } -func TestScheduledJobWithoutASigningSecretSendsNothingUnsigned(t *testing.T) { - script, attempts, log := runSignedNotifier(t, nil, "") +func TestScheduledJobWithoutASigningSecretOrPadsSendsNothing(t *testing.T) { + _, attempts, log := runSignedNotifier(t, nil, "") if len(attempts) != 0 { - t.Fatalf("sent %d unsigned request(s) to a receiver that verifies signatures", len(attempts)) + t.Fatalf("sent %d request(s) with nothing to sign them", len(attempts)) } - if !strings.Contains(log, "TEST_SCHEDULE_WEBHOOK_SECRET") || !strings.Contains(log, "will not be sent from the host") { - t.Fatalf("the deploy must warn that the notification is off:\n%s", log) + if !strings.Contains(log, "TEST_SCHEDULE_WEBHOOK_SECRET") || !strings.Contains(log, "signing secret unavailable; kept existing pads") { + t.Fatalf("the deploy must warn that the secret was unavailable:\n%s", log) } - if !strings.Contains(log, "signing secret was unavailable") { + if !strings.Contains(log, "signing pads are missing") { t.Fatalf("the host must log why it sent nothing:\n%s", log) } - if strings.Contains(script, "openssl") { - t.Fatalf("a notifier with no key must not try to sign:\n%s", script) +} + +// A deploy run without the secret exported keeps the pads the last deploy +// wrote, so the job goes on signing with the last good key. +func TestScheduledJobWithoutASigningSecretSignsWithKeptPads(t *testing.T) { + _, attempts, log, _ := runSignedNotifierArgv(t, []string{"200"}, "", true, scheduleSigningKey) + if len(attempts) != 1 { + t.Fatalf("got %d attempts, want 1 signed with the kept pads", len(attempts)) + } + verifyScheduleSignature(t, attempts[0]) + if !strings.Contains(log, "signing secret unavailable; kept existing pads") { + t.Fatalf("the deploy must warn that it kept the pads:\n%s", log) } } @@ -226,7 +248,7 @@ func TestSignedScheduleExtendsTheStopTimeout(t *testing.T) { // not in the argument lists the host actually started openssl and curl with. func TestScheduledJobSigningKeyIsNeverACommandArgument(t *testing.T) { secret := "whsec_" + base64.StdEncoding.EncodeToString(scheduleSigningKey) - script, attempts, _, argv := runSignedNotifierArgv(t, []string{"200"}, secret, true) + script, attempts, _, argv := runSignedNotifierArgv(t, []string{"200"}, secret, true, nil) if len(attempts) != 1 { t.Fatalf("got %d attempts, want 1", len(attempts)) } @@ -310,9 +332,9 @@ func TestScheduleApplyWritesPadsBesideTheNotifierAndClearsStaleOnes(t *testing.T seq := strings.Join(f.Commands, "\n") notify := "/etc/systemd/system/onebox-job-nightly.notify" for _, want := range []string{ - "rm -f '" + notify + "'.*.ipad '" + notify + "'.*.opad", - "cat > '" + notify + ".0.ipad.onebox-tmp'", - "cat > '" + notify + ".0.opad.onebox-tmp'", + "for f in '" + notify + "'.*pad*; do case \"$f\" in *) rm -f \"$f\" ;; esac; done", + "cat > '" + notify + signingPadSuffix("facet") + ".ipad.onebox-tmp'", + "cat > '" + notify + signingPadSuffix("facet") + ".opad.onebox-tmp'", } { if !strings.Contains(seq, want) { t.Errorf("schedule apply is missing %q:\n%s", want, seq) @@ -333,3 +355,97 @@ func TestScheduleApplyWritesPadsBesideTheNotifierAndClearsStaleOnes(t *testing.T } } } + +// requireOpenSSL finds the openssl the host signs with. Without it the host +// signing tests cannot run; under CI that is a failure, not a skip, so a green +// build always means host signing was verified. +func requireOpenSSL(t *testing.T) string { + t.Helper() + path, err := exec.LookPath("openssl") + if err != nil { + if os.Getenv("CI") != "" { + t.Fatal("openssl is what signs on the host and CI must verify it; install openssl on the runner") + } + t.Skip("openssl is what signs on the host, and it is not installed here") + } + return path +} + +// The cleanup a deploy runs, executed against real files: every pad and +// staging copy goes, except the pads of a notification whose secret the deploy +// could not read. +func TestSigningPadCleanupKeepsOnlyThePadsItWasTold(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX shell required") + } + dir := t.TempDir() + notify := filepath.Join(dir, "onebox-job-nightly.notify") + kept, gone := signingPadSuffix("facet"), signingPadSuffix("removed") + files := map[string]bool{ + notify: true, + notify + kept + ".ipad": true, + notify + kept + ".opad": true, + notify + kept + ".ipad.onebox-tmp": false, + notify + gone + ".ipad": false, + notify + gone + ".opad": false, + notify + gone + ".opad.onebox-tmp": false, + notify + ".onebox-tmp": true, // the notifier's own staging file is not a pad + filepath.Join(dir, "onebox-job-x.notify"): true, + } + for path := range files { + if err := os.WriteFile(path, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + keep := keptPads(map[string][]byte{kept + ".ipad": nil, kept + ".opad": nil, ".other.ipad": {1}}) + if out, err := exec.CommandContext(context.Background(), "sh", "-c", signingPadCleanup(notify, keep)).CombinedOutput(); err != nil { + t.Fatalf("cleanup failed: %v\n%s", err, out) + } + for path, stays := range files { + _, err := os.Stat(path) + if stays != (err == nil) { + t.Errorf("%s: present=%t, want %t", filepath.Base(path), err == nil, stays) + } + } +} + +// With no signed notification left, every pad goes. +func TestScheduleApplyWithoutSecretKeepsPadsAndWarns(t *testing.T) { + cfg := testConfig() + cfg.Workloads["nightly"] = app.Workload{ + Role: app.RoleJob, DeploymentPhase: "none", DataEffect: "none", + Schedule: &app.JobSchedule{Cron: "0 2 * * *", Timezone: "UTC", Timeout: "45m", Notify: []string{"failure"}}, + } + cfg.Notifications = map[string]app.Notification{ + "facet": {Webhook: "https://facet.example.invalid/hooks/onebox", On: []string{"failure"}, Format: "json", SigningSecretEnv: "TEST_SCHEDULE_WEBHOOK_SECRET"}, + } + t.Setenv("TEST_SCHEDULE_WEBHOOK_SECRET", "") + f := happyFake() + base := f.Dynamic + f.Dynamic = func(cmd string) (transport.Result, bool) { + switch { + case strings.Contains(cmd, "current/compose.yaml"), strings.Contains(cmd, "systemd-analyze calendar"), strings.Contains(cmd, "command -v flock"): + return transport.Result{Stdout: "ok\n"}, true + case strings.Contains(cmd, "list-unit-files"): + return transport.Result{}, true + } + return base(cmd) + } + out := &bytes.Buffer{} + e := New(cfg, testProject(t), f, Options{Out: out, Sleep: noSleep, Environment: "production"}) + if err := e.ScheduleApply(context.Background(), "R9-schedule-apply"); err != nil { + t.Fatalf("a missing signing secret must not fail the deploy: %v", err) + } + seq := strings.Join(f.Commands, "\n") + notify := "/etc/systemd/system/onebox-job-nightly.notify" + suffix := signingPadSuffix("facet") + if want := "case \"$f\" in '" + notify + suffix + ".ipad') ;; '" + notify + suffix + ".opad') ;; *) rm -f"; !strings.Contains(seq, want) { + t.Fatalf("the cleanup must keep the existing pads; want %q in:\n%s", want, seq) + } + if strings.Contains(seq, suffix+".ipad.onebox-tmp") { + t.Fatal("pads were written without a key to derive them from") + } + if !strings.Contains(out.String(), "signing secret unavailable; kept existing pads") { + t.Fatalf("the deploy must warn:\n%s", out.String()) + } +} diff --git a/internal/notify/notify.go b/internal/notify/notify.go index 19db12f8..25132d62 100644 --- a/internal/notify/notify.go +++ b/internal/notify/notify.go @@ -29,8 +29,10 @@ import ( "fmt" "net/http" "os" + "slices" "strconv" "strings" + "sync" "time" "github.com/labstack/onebox/internal/app" @@ -46,9 +48,15 @@ const ( SignedBudget = 15 * time.Second ) -// signedBackoff is the pause before each retry. A variable so tests do not -// wait for it. -var signedBackoff = []time.Duration{500 * time.Millisecond, time.Second} +// The values Send uses. Variables so tests can exercise the bounds without +// waiting for them: attemptTimeout bounds one request, signedBudget every +// attempt of one signed send, and signedBackoff is the pause before each +// retry. +var ( + attemptTimeout = timeout + signedBudget = SignedBudget + signedBackoff = []time.Duration{500 * time.Millisecond, time.Second} +) // secretPrefix is the Standard Webhooks marker on a symmetric secret. const secretPrefix = "whsec_" @@ -231,7 +239,8 @@ func Send(ctx context.Context, cfg app.Notification, p Payload) error { if err != nil { return err } - ctx, cancel := context.WithTimeout(ctx, SignedBudget) + parent := ctx + ctx, cancel := context.WithTimeout(ctx, signedBudget) defer cancel() var lastErr error for attempt := 1; attempt <= SignedAttempts; attempt++ { @@ -257,12 +266,44 @@ func Send(ctx context.Context, cfg app.Notification, p Payload) error { break } } - if errors.Is(lastErr, context.DeadlineExceeded) && ctx.Err() != nil { - return fmt.Errorf("webhook not delivered within %s: %w", SignedBudget, lastErr) + if errors.Is(ctx.Err(), context.DeadlineExceeded) && parent.Err() == nil { + return fmt.Errorf("webhook not delivered within %s: %w", signedBudget, lastErr) } return lastErr } +// Failure is one notification that could not be delivered, for the caller to +// warn on. +type Failure struct { + Name string + Err error +} + +// SendAll sends p to every named notification at once and returns the +// failures in name order. Concurrency is what keeps the fail-open bound: one +// dead receiver costs at most one budget however many are configured, where +// sending in turn would add their budgets together. +func SendAll(ctx context.Context, notifications map[string]app.Notification, p Payload) []Failure { + names := make([]string, 0, len(notifications)) + for name := range notifications { + names = append(names, name) + } + slices.Sort(names) + errs := make([]error, len(names)) + var wg sync.WaitGroup + for i, name := range names { + wg.Go(func() { errs[i] = Send(ctx, notifications[name], p) }) + } + wg.Wait() + var failures []Failure + for i, err := range errs { + if err != nil { + failures = append(failures, Failure{Name: names[i], Err: err}) + } + } + return failures +} + // post makes one attempt. retry reports whether the failure is one a retry // could fix: a network error, a 429, or a 5xx. A 4xx is the receiver refusing // this request, and the same request will be refused again. @@ -276,7 +317,7 @@ func post(ctx context.Context, webhook string, prepared *Request, headers map[st for k, v := range headers { req.Header.Set(k, v) } - client := &http.Client{Timeout: timeout} + client := &http.Client{Timeout: attemptTimeout} res, err := client.Do(req) if err != nil { return true, err diff --git a/internal/notify/sign_test.go b/internal/notify/sign_test.go index 97ab2957..46bb612a 100644 --- a/internal/notify/sign_test.go +++ b/internal/notify/sign_test.go @@ -244,3 +244,81 @@ func TestSignatureMatchesTheStandardWebhooksExample(t *testing.T) { t.Fatalf("Signature = %q, want %q", got, want) } } + +// shortBounds shrinks the per-attempt timeout and the signed budget so a +// receiver that never answers exercises both without a 15-second test. +func shortBounds(t *testing.T, attempt, budget time.Duration) { + t.Helper() + oldAttempt, oldBudget, oldBackoff := attemptTimeout, signedBudget, signedBackoff + attemptTimeout, signedBudget = attempt, budget + signedBackoff = []time.Duration{10 * time.Millisecond, 10 * time.Millisecond} + t.Cleanup(func() { attemptTimeout, signedBudget, signedBackoff = oldAttempt, oldBudget, oldBackoff }) +} + +// hangingReceiver accepts each request and never answers until the test ends. +func hangingReceiver(t *testing.T) (*httptest.Server, func() int) { + t.Helper() + var mu sync.Mutex + hits := 0 + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + mu.Lock() + hits++ + mu.Unlock() + select { + case <-release: + case <-r.Context().Done(): + } + })) + t.Cleanup(func() { close(release); srv.Close() }) + return srv, func() int { mu.Lock(); defer mu.Unlock(); return hits } +} + +func TestSignedSendStopsAtItsBudget(t *testing.T) { + shortBounds(t, 200*time.Millisecond, 450*time.Millisecond) + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", testSecret) + srv, hits := hangingReceiver(t) + start := time.Now() + err := Send(t.Context(), signedConfig(srv.URL), Payload{Status: "fail"}) + elapsed := time.Since(start) + if err == nil || !strings.Contains(err.Error(), "not delivered within 450ms") { + t.Fatalf("Send = %v, want the budget named", err) + } + if elapsed > 450*time.Millisecond+150*time.Millisecond { + t.Fatalf("signed send took %s, beyond its 450ms budget", elapsed) + } + // A hung attempt is timed out and retried, and the budget, not the + // attempt count, ends the send. + if n := hits(); n < 2 || n > SignedAttempts { + t.Fatalf("got %d attempts within the budget, want 2 to %d", n, SignedAttempts) + } + if strings.Contains(err.Error(), testSecret) { + t.Fatalf("error carries the secret: %v", err) + } +} + +func TestSendAllBoundsManyDeadReceiversByOneBudget(t *testing.T) { + shortBounds(t, 200*time.Millisecond, 400*time.Millisecond) + t.Setenv("TEST_ONEBOX_WEBHOOK_SECRET", testSecret) + notifications := map[string]app.Notification{} + for _, name := range []string{"a", "b", "c", "d"} { + srv, _ := hangingReceiver(t) + notifications[name] = signedConfig(srv.URL) + } + ok, _ := receiver(t) + notifications["live"] = signedConfig(ok.URL) + start := time.Now() + failures := SendAll(t.Context(), notifications, Payload{Status: "fail"}) + elapsed := time.Since(start) + // Sent in turn, four dead receivers would take four budgets. + if elapsed > 400*time.Millisecond+200*time.Millisecond { + t.Fatalf("SendAll took %s; several dead receivers must cost about one budget", elapsed) + } + var names []string + for _, f := range failures { + names = append(names, f.Name) + } + if strings.Join(names, ",") != "a,b,c,d" { + t.Fatalf("failures = %v, want the four dead receivers in name order", names) + } +} diff --git a/site/public/schemas/application/v1alpha2/application.schema.json b/site/public/schemas/application/v1alpha2/application.schema.json index 93e8f999..8666f300 100644 --- a/site/public/schemas/application/v1alpha2/application.schema.json +++ b/site/public/schemas/application/v1alpha2/application.schema.json @@ -831,7 +831,7 @@ "type": "array" }, "signingSecretEnv": { - "description": "Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "description": "Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning, never a blocked operation: the command does not send that notification, and a scheduled job keeps signing with the keys its last deploy wrote. Notifications are sent concurrently, so several dead receivers still cost one 15-second bound. Expects a variable name of letters, digits and underscores, not starting with a digit.", "examples": [ "ONEBOX_WEBHOOK_SECRET" ], diff --git a/site/src/content/docs/docs/guides/cron-jobs.mdx b/site/src/content/docs/docs/guides/cron-jobs.mdx index 97c4cb9e..0fa600be 100644 --- a/site/src/content/docs/docs/guides/cron-jobs.mdx +++ b/site/src/content/docs/docs/guides/cron-jobs.mdx @@ -224,11 +224,13 @@ it sends, so the key never appears in any command's arguments, `ps`, or every retry. A signed send makes at most three attempts of four seconds each, one second apart, and retries only a network error, a 429, or a 5xx; the unit's `TimeoutStopSec` grows by ten seconds to allow for them. If the secret is unset -or malformed when you deploy, `ob deploy` warns and the handler logs that the -notification was not sent; it never sends that receiver an unsigned request. A -host without `openssl` logs the send as failed. Rotate the secret by exporting -the new one and deploying again; each deploy rewrites the key files and removes -any a removed notification left behind. +or malformed when you deploy, `ob deploy` warns and keeps the key files already +on the host, so the job goes on signing with the last good key; a host with no +key files logs that the notification was not sent, and never sends that +receiver an unsigned request. A host without `openssl` logs the send as failed. +Rotate the secret by exporting the new one and deploying again. The key files +are deleted, staging copies included, only when the notification stops being +signed or the job is removed. ```yaml notifications: diff --git a/site/src/content/docs/docs/reference/fields/notifications.mdx b/site/src/content/docs/docs/reference/fields/notifications.mdx index 512c9e5a..2e7ce9fb 100644 --- a/site/src/content/docs/docs/reference/fields/notifications.mdx +++ b/site/src/content/docs/docs/reference/fields/notifications.mdx @@ -25,5 +25,5 @@ cannot drift from what `ob validate` accepts. | --- | --- | --- | --- | | `.format` | `Text` · `JSON` | `Text` | Notification payload format. | | `.on` | list of `Success` · `Failure` | `success, failure` | Operation outcomes that trigger this notification. | -| `.signingSecretEnv` | string | — | Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning and the notification is not sent; the operation is never blocked. Expects a variable name of letters, digits and underscores, not starting with a digit. | +| `.signingSecretEnv` | string | — | Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning, never a blocked operation: the command does not send that notification, and a scheduled job keeps signing with the keys its last deploy wrote. Notifications are sent concurrently, so several dead receivers still cost one 15-second bound. Expects a variable name of letters, digits and underscores, not starting with a digit. | | `.webhook` | string | — | HTTP endpoint that receives outcome notifications. |