Add notification engine phase 1: channels, rules, plan-gated delivery
release gate / check (push) Failing after 6m54s

When something happens in the brain, tell the user (PLAN_PRICING_TIERS
step 3). The engine is a SCANNER, not a hook system: producers are never
instrumented; exactly-once comes solely from UNIQUE(ruleId,dedupeKey) +
ON CONFLICT DO NOTHING, so rescans are free and restarts are safe.

Schema (migration 013 + schema.sql, converge-verified):
NotificationChannel (secrets encrypted at rest via internal/crypto, the
IMAP-password format), NotificationRule (one channel per rule in phase 1,
cooldown, version column), Notification (dedupe ledger + delivery state:
pending/sent/failed/suppressed, attempts, backoff timestamp).

internal/notify: two triggers — signal_created (fires only for signals
newer than the rule, never retro-notifying history) and bookmark_due
(lead-hours window, dedupe key carries the UTC due date so moving a
dueDate re-notifies and same-day rescans do not). Delivery claims rows in
one short transaction (FOR UPDATE SKIP LOCKED, batch 10) so multiple app
instances never double-send; exponential backoff to 5 attempts; per-rule
cooldown; per-owner pending cap. Channels: email (internal/mailer,
falls back to the account email), Slack webhook, Matrix room, Telegram
bot — webhooks dial through netguard inside outbound.Reserve budgets.
The plan gate re-checks at delivery: a downgraded tenant's rows become
'suppressed' instead of sending. Signal-app delivery deliberately absent
(needs a daemon; see plan doc hard truths).

API: channel/rule CRUD with the house version contract (409 on stale
base), write-only secrets (masked in every response; a PATCH echoing the
mask keeps the stored value), test-send endpoint with its own budget,
owner-scoped delivery history. Channel kinds gate on the ENTITLEMENT
CATALOG (403 'Not available on your plan') — never on TIER, per the
tenancy invariant.

Web: Settings -> Notifications tab (channels with per-kind forms and
Test button, rule builder, recent-delivery strip). Data loading uses the
house promise-chain shape; setState only in async callbacks (SSR lint).

Fixes along the way: mailer send budget raised 5->20/min (shared by
resets and notifications; 5/min would throttle a hosted instance) and
outbound gains ResetBudget() wired into the test harness — the global
'smtp' window made password-reset and notification tests collide when
the package ran as a whole.

Tests: full channel/rule/engine integration pass (masking + encryption
round-trip, masked-PATCH preservation, version contract, plan gating via
a forced 'free' tenant, dedupe across rescans, cooldown, real SMTP and
webhook delivery via loopback fakes, backoff recording, downgrade
suppression, history). Full suite green with -race; web lint/SSR-eslint/
build clean. Docs: API.md endpoint table, RUNNING.md, AGENTS.md
invariants, DESIGN_NOTIFICATIONS.md (local).
This commit is contained in:
Andrew S Erwin
2026-10-26 14:43:15 -05:00
parent 1f38c4d56c
commit 451312c3cf
15 changed files with 2034 additions and 7 deletions
+5 -1
View File
@@ -6,6 +6,7 @@ import (
"github.com/andrew/superbrain/internal/auth"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/outbound"
"io"
"net/http"
"net/http/cookiejar"
@@ -29,9 +30,12 @@ func testServerDB(t *testing.T) (*httptest.Server, *db.DB) {
t.Skip("set TEST_DATABASE_URL to run PostgreSQL integration tests")
}
// The limiter stores are process-global and login has no loopback
// exemption (review SEC-1); give every test a clean slate.
// exemption (review SEC-1); give every test a clean slate. Same for the
// outbound budgets (mailer/notify/preview share one process-wide store).
auth.ResetRateLimits()
outbound.ResetBudget()
t.Cleanup(auth.ResetRateLimits)
t.Cleanup(outbound.ResetBudget)
t.Setenv("AUTH_SECRET", "integration-test-secret")
t.Setenv("NEXTAUTH_SECRET", "integration-test-secret")
t.Setenv("ADMIN_EMAILS", "")
+287
View File
@@ -0,0 +1,287 @@
package http
import (
"context"
"io"
"net"
"net/http"
"net/http/cookiejar"
"strings"
"sync"
"testing"
"time"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/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
}
+12
View File
@@ -115,6 +115,18 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
mux.HandleFunc("PATCH /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesUpdate))
mux.HandleFunc("DELETE /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesDelete))
// 4.7b Notifications (DESIGN_NOTIFICATIONS.md): channels, rules, history.
mux.HandleFunc("GET /api/notifications/channels", authed(handlers.HandleNotificationChannelsList))
mux.HandleFunc("POST /api/notifications/channels", authed(handlers.HandleNotificationChannelsCreate))
mux.HandleFunc("PATCH /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsUpdate))
mux.HandleFunc("DELETE /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsDelete))
mux.HandleFunc("POST /api/notifications/channels/{id}/test", authed(handlers.HandleNotificationChannelsTest))
mux.HandleFunc("GET /api/notifications/rules", authed(handlers.HandleNotificationRulesList))
mux.HandleFunc("POST /api/notifications/rules", authed(handlers.HandleNotificationRulesCreate))
mux.HandleFunc("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate))
mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete))
mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList))
// 4.8 Alerts, contacts, email, dates, users
mux.HandleFunc("GET /api/alerts/check", authed(handlers.HandleAlertsCheck))
mux.HandleFunc("DELETE /api/alerts/{bookmarkId}", authed(handlers.HandleAlertsDismiss))