package http import ( "context" "io" "net" "net/http" "net/http/cookiejar" "strings" "sync" "testing" "time" "gitea.federated.computer/Federated_Computer/brain/internal/db" "gitea.federated.computer/Federated_Computer/brain/internal/notify" ) // fakeWebhook captures one Slack-style POST for the delivery tests. type fakeWebhook struct { t *testing.T srv *http.Server ln net.Listener mu sync.Mutex bodies []string } func newFakeWebhook(t *testing.T) *fakeWebhook { t.Helper() ln, e := net.Listen("tcp", "127.0.0.1:0") if e != nil { t.Fatal(e) } f := &fakeWebhook{t: t, ln: ln} mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { raw, _ := io.ReadAll(r.Body) f.mu.Lock() f.bodies = append(f.bodies, string(raw)) f.mu.Unlock() w.WriteHeader(200) }) f.srv = &http.Server{Handler: mux} go f.srv.Serve(ln) t.Cleanup(func() { f.srv.Close() }) return f } func (f *fakeWebhook) url() string { return "http://" + f.ln.Addr().String() + "/hook" } func (f *fakeWebhook) received() []string { f.mu.Lock() defer f.mu.Unlock() return append([]string(nil), f.bodies...) } // The full phase-1 surface: channel CRUD with write-only secrets, plan // gating via the entitlement catalog, the version contract on rules, and // engine behavior (dedupe, cooldown, delivery, backoff, suppression). func TestNotificationsChannelsAndRules(t *testing.T) { srv, d := testServerDB(t) smtp := newFakeSMTP(t) host, port, _ := net.SplitHostPort(smtp.ln.Addr().String()) t.Setenv("SMTP_HOST", host) t.Setenv("SMTP_PORT", port) t.Setenv("SMTP_FROM", "superbrain@superbrain.test") t.Setenv("NEXTAUTH_URL", "https://superbrain.test") jar, _ := cookiejar.New(nil) alice := apiClient{t, &http.Client{Jar: jar}, srv.URL} alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201) alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200) // --- channel create: secrets are masked in every response --- created := alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "email", "name": "My inbox", "config": map[string]any{"address": ""}, }, 201) emailChID := created["id"].(string) version := int(created["version"].(float64)) hook := newFakeWebhook(t) slack := alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "slack", "name": "team", "config": map[string]any{"webhookUrl": hook.url()}, }, 201) slackID := slack["id"].(string) if cfg := slack["config"].(map[string]any); cfg["webhookUrl"] != notify.MaskValue { t.Fatalf("secret leaked in create response: %v", cfg) } // The stored secret decrypts to the original (encryption round-trip). var storedCfg string if e := d.QueryRow(`SELECT config::text FROM "NotificationChannel" WHERE id=$1`, slackID).Scan(&storedCfg); e != nil { t.Fatal(e) } if strings.Contains(storedCfg, hook.url()) { t.Fatal("webhook URL stored in plaintext") } dec, e := notify.DecryptConfig("slack", []byte(storedCfg), "integration-test-secret") if e != nil || dec["webhookUrl"] != hook.url() { t.Fatalf("decrypt round-trip failed: %v %v", dec, e) } // --- PATCH contract: version required, stale rejected, mask keeps secret --- alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{"name": "renamed"}, 400) alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{"name": "renamed", "version": version + 5}, 409) slackVersion := int(slack["version"].(float64)) patched := alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{ "name": "renamed", "version": slackVersion, "config": map[string]any{"webhookUrl": notify.MaskValue}, }, 200) if patched["name"] != "renamed" { t.Fatal("rename not applied") } dec2, e := notify.DecryptConfig("slack", []byte(mustConfigJSON(t, d, slackID)), "integration-test-secret") if e != nil || dec2["webhookUrl"] != hook.url() { t.Fatalf("masked PATCH clobbered the stored secret: %v %v", dec2, e) } // Bad config shape is rejected. alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "matrix", "name": "bad", "config": map[string]any{"homeserver": "notaurl", "roomId": "!x:y", "accessToken": "t"}, }, 400) // --- plan gating via the entitlement catalog (never TIER directly) --- // Default tenant is 'selfhosted' (everything allowed); force the free // plan and telegram must be refused while email stays allowed. if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil { t.Fatal(e) } alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "telegram", "name": "tg", "config": map[string]any{"botToken": "123:abc", "chatId": "42"}, }, 403) alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "email", "name": "second inbox", }, 201) if _, e := d.Exec(`UPDATE "Tenant" SET plan='selfhosted' WHERE id=$1`, db.DefaultTenantID); e != nil { t.Fatal(e) } // --- rules: create, version contract, list projection --- due := time.Now().UTC().Add(6 * time.Hour).Format(time.RFC3339) bm := alice.request("POST", "/api/bookmarks", map[string]any{ "url": "https://example.org/due-soon", "title": "Due soon", "dueDate": due, }, 201) _ = bm rule := alice.request("POST", "/api/notifications/rules", map[string]any{ "name": "Due reminders", "trigger": "bookmark_due", "channelId": emailChID, "config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60, }, 201) ruleID := rule["id"].(string) if rule["channelKind"] != "email" { t.Fatalf("rule projection missing channel join: %v", rule) } alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{"cooldownMinutes": float64(99999)}, 400) alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{"enabled": false}, 400) upd := alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{ "enabled": true, "version": int(rule["version"].(float64)), }, 200) _ = upd // --- engine: scan fires exactly once, delivers through mailer --- ctx := context.Background() if e := notify.RunOnce(ctx, d); e != nil { t.Fatal(e) } msg := smtp.waitForMessage(t, 1) if msg[0] != "alice@superbrain.test" || !strings.Contains(msg[1], "Bookmark due: Due soon") { t.Fatalf("unexpected notification mail: %v", msg) } var status string if e := d.QueryRow(`SELECT status FROM "Notification" WHERE "ruleId"=$1`, ruleID).Scan(&status); e != nil || status != "sent" { t.Fatalf("notification status = %s (%v), want sent", status, e) } // Rescan: the dedupe key makes the second pass a no-op. if e := notify.RunOnce(ctx, d); e != nil { t.Fatal(e) } if n := smtp.messages(); len(n) != 1 { t.Fatalf("dedupe failed: %d mails", len(n)) } // Cooldown: a NEW due bookmark does not fire while the rule cools. alice.request("POST", "/api/bookmarks", map[string]any{ "url": "https://example.org/due-too", "title": "Due too", "dueDate": time.Now().UTC().Add(2 * time.Hour).Format(time.RFC3339), }, 201) if e := notify.RunOnce(ctx, d); e != nil { t.Fatal(e) } if n := smtp.messages(); len(n) != 1 { t.Fatalf("cooldown ignored: %d mails", len(n)) } if _, e := d.Exec(`UPDATE "NotificationRule" SET "lastFiredAt"=now()-interval '2 hours' WHERE id=$1`, ruleID); e != nil { t.Fatal(e) } if e := notify.RunOnce(ctx, d); e != nil { t.Fatal(e) } if n := smtp.messages(); len(n) != 2 { t.Fatalf("after cooldown expiry: %d mails, want 2", len(n)) } // --- webhook delivery through the netguarded client --- slackRule := alice.request("POST", "/api/notifications/rules", map[string]any{ "name": "Signals to slack", "trigger": "signal_created", "channelId": slackID, }, 201) _ = slackRule if _, e := d.Exec(` INSERT INTO "Signal"(id,"sourceType",title,summary,"bookmarkId","ownerId") SELECT 'sig-1','email','Invoice arrived','from billing', b.id, u.id FROM "Bookmark" b, "User" u WHERE b.url='https://example.org/due-soon' AND u.email='alice@superbrain.test' LIMIT 1`); e != nil { t.Fatal(e) } if e := notify.RunOnce(ctx, d); e != nil { t.Fatal(e) } got := hook.received() if len(got) != 1 || !strings.Contains(got[0], "Invoice arrived") { t.Fatalf("webhook delivery missing: %v", got) } // --- failure path: attempts bump, backoff pushes the row out --- deadLn, e := net.Listen("tcp", "127.0.0.1:0") if e != nil { t.Fatal(e) } deadAddr := deadLn.Addr().String() deadLn.Close() dead := alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "slack", "name": "dead", "config": map[string]any{"webhookUrl": "http://" + deadAddr + "/hook"}, }, 201) deadRule := alice.request("POST", "/api/notifications/rules", map[string]any{ "name": "dead hook", "trigger": "signal_created", "channelId": dead["id"].(string), }, 201) if _, e := d.Exec(`INSERT INTO "Signal"(id,"sourceType",title,"bookmarkId","ownerId") SELECT 'sig-2','email','Second', b.id, u.id FROM "Bookmark" b, "User" u WHERE b.url='https://example.org/due-soon' AND u.email='alice@superbrain.test' LIMIT 1`); e != nil { t.Fatal(e) } if e := notify.RunOnce(ctx, d); e != nil { t.Fatal(e) } var attempts int var nextAt time.Time var lastErr *string if e := d.QueryRow(`SELECT attempts, "nextAttemptAt", "lastError" FROM "Notification" WHERE "ruleId"=$1`, deadRule["id"].(string)). Scan(&attempts, &nextAt, &lastErr); e != nil { t.Fatal(e) } if attempts != 1 || lastErr == nil || !nextAt.After(time.Now()) { t.Fatalf("failure not recorded: attempts=%d nextAt=%v err=%v", attempts, nextAt, lastErr) } // --- suppression: a downgraded plan stops delivery (no send attempted) --- if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil { t.Fatal(e) } if _, e := d.Exec(`UPDATE "Notification" SET status='pending', attempts=0, "nextAttemptAt"=now() WHERE "ruleId"=$1`, deadRule["id"].(string)); e != nil { t.Fatal(e) } if e := notify.RunOnce(ctx, d); e != nil { t.Fatal(e) } var suppressed string if e := d.QueryRow(`SELECT status FROM "Notification" WHERE "ruleId"=$1`, deadRule["id"].(string)).Scan(&suppressed); e != nil || suppressed != "suppressed" { t.Fatalf("downgraded plan must suppress delivery, got %q (%v)", suppressed, e) } // --- history endpoint (array response: fetch raw with the session jar) --- req, _ := http.NewRequest("GET", srv.URL+"/api/notifications", nil) res, e := (&http.Client{Jar: jar}).Do(req) if e != nil { t.Fatal(e) } defer res.Body.Close() rawBody, _ := io.ReadAll(res.Body) if res.StatusCode != 200 || !strings.Contains(string(rawBody), `"status":"sent"`) { t.Fatalf("history missing delivered rows: %d %s", res.StatusCode, rawBody) } } func mustConfigJSON(t *testing.T, d *db.DB, channelID string) string { t.Helper() var raw string if e := d.QueryRow(`SELECT config::text FROM "NotificationChannel" WHERE id=$1`, channelID).Scan(&raw); e != nil { t.Fatal(e) } return raw }