package http import ( "context" "encoding/json" "io" "net" "net/http" "net/http/cookiejar" "strings" "sync" "testing" "time" "github.com/andrew/superbrain/internal/notify" ) // fakeSignalBridge mimics a signal-cli REST bridge: POST /v2/send?account=... // with {"message":..., "recipients":[...]}. type fakeSignalBridge struct { ln net.Listener srv *http.Server mu sync.Mutex got []map[string]string // account, recipient, message } func newFakeSignalBridge(t *testing.T) *fakeSignalBridge { t.Helper() ln, e := net.Listen("tcp", "127.0.0.1:0") if e != nil { t.Fatal(e) } f := &fakeSignalBridge{ln: ln} mux := http.NewServeMux() mux.HandleFunc("/v2/send", func(w http.ResponseWriter, r *http.Request) { raw, _ := io.ReadAll(r.Body) var body struct { Message string `json:"message"` Recipients []string `json:"recipients"` } _ = json.Unmarshal(raw, &body) f.mu.Lock() f.got = append(f.got, map[string]string{ "account": r.URL.Query().Get("account"), "recipient": strings.Join(body.Recipients, ","), "message": body.Message, }) f.mu.Unlock() w.WriteHeader(201) }) f.srv = &http.Server{Handler: mux} go f.srv.Serve(ln) t.Cleanup(func() { f.srv.Close() }) return f } func (f *fakeSignalBridge) url() string { return "http://" + f.ln.Addr().String() } func (f *fakeSignalBridge) sends() []map[string]string { f.mu.Lock() defer f.mu.Unlock() return append([]map[string]string(nil), f.got...) } func (f *fakeSMTP) lastMessage(t *testing.T) string { t.Helper() f.mu.Lock() defer f.mu.Unlock() if len(f.msgs) == 0 { t.Fatal("no mail received") } return f.msgs[len(f.msgs)-1][1] } // listGET fetches a JSON array endpoint (apiClient.request only parses objects). func listGET(c apiClient, path string) []any { c.t.Helper() res, e := c.c.Get(c.base + path) if e != nil { c.t.Fatal(e) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) if res.StatusCode != 200 { c.t.Fatalf("GET %s: wanted 200, got %d: %s", path, res.StatusCode, raw) } var v []any if e := json.Unmarshal(raw, &v); e != nil { c.t.Fatal(e) } return v } func phase2Client(t *testing.T, srvURL, email string) (apiClient, string) { t.Helper() jar, _ := cookiejar.New(nil) c := apiClient{t, &http.Client{Jar: jar}, srvURL} c.request("POST", "/api/signup", map[string]any{"email": email, "password": "a-long-test-password"}, 201) c.request("POST", "/api/auth/login", map[string]any{"email": email, "password": "a-long-test-password"}, 200) return c, meID(c) } // Phase 2 (Gitea #10): share triggers, targeted recipients delivered through // the target's OWN channel, the Signal channel kind, and the plan-gated // managed-by footer. func TestNotifySharesTargetsSignalFooter(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") hookA := newFakeWebhook(t) hookB := newFakeWebhook(t) bridge := newFakeSignalBridge(t) alice, _ := phase2Client(t, srv.URL, "alice@superbrain.test") bob, bu := phase2Client(t, srv.URL, "bob@superbrain.test") slackA := alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "slack", "name": "A", "config": map[string]any{"webhookUrl": hookA.url()}, }, 201)["id"].(string) slackB := bob.request("POST", "/api/notifications/channels", map[string]any{ "kind": "slack", "name": "B", "config": map[string]any{"webhookUrl": hookB.url()}, }, 201)["id"].(string) bob.request("POST", "/api/notifications/channels", map[string]any{ "kind": "email", "name": "B mail", "config": map[string]any{"address": "bob@superbrain.test"}, }, 201) // --- share_received: bob is notified through HIS channel when alice shares bob.request("POST", "/api/notifications/rules", map[string]any{ "name": "shares to me", "trigger": "share_received", "channelId": slackB, }, 201) bm := alice.request("POST", "/api/bookmarks", map[string]any{ "url": "https://127.0.0.1/shared-thing", "title": "Shared thing", }, 201)["id"].(string) alice.request("POST", "/api/bookmarks/"+bm+"/share", map[string]any{"userIds": []string{bu}}, 200) if e := notify.RunOnce(context.Background(), d); e != nil { t.Fatal(e) } bodies := hookB.received() if len(bodies) != 1 || !strings.Contains(bodies[0], "shared a bookmark with you") || !strings.Contains(bodies[0], "Shared thing") { t.Fatalf("share trigger did not deliver: %v", bodies) } hist := listGET(bob, "/api/notifications") if len(hist) != 1 || hist[0].(map[string]any)["status"] != "sent" { t.Fatalf("bob history wrong: %v", hist) } // Dedupe: a second pass sends nothing new. if e := notify.RunOnce(context.Background(), d); e != nil { t.Fatal(e) } if len(hookB.received()) != 1 { t.Fatal("share notification redelivered") } // --- targeted recipients: alice's due rule also notifies bob via bob's channel yesterday := time.Now().UTC().Add(-24 * time.Hour).Format("2006-01-02") alice.request("POST", "/api/notifications/rules", map[string]any{ "name": "due + bob", "trigger": "bookmark_due", "channelId": slackA, "config": map[string]any{"leadHours": 1, "targetUserIds": []string{bu}}, }, 201) alice.request("POST", "/api/bookmarks", map[string]any{ "url": "https://127.0.0.1/due-thing", "title": "Due thing", "dueDate": yesterday, }, 201) if e := notify.RunOnce(context.Background(), d); e != nil { t.Fatal(e) } if len(hookA.received()) != 1 || !strings.Contains(hookA.received()[0], "Due thing") { t.Fatalf("owner delivery missing: %v", hookA.received()) } if len(hookB.received()) != 2 || !strings.Contains(hookB.received()[1], "Due thing") { t.Fatalf("targeted delivery missing: %v", hookB.received()) } hist = listGET(bob, "/api/notifications") if len(hist) != 2 { t.Fatalf("bob should see the targeted row too: %v", hist) } // --- cross-tenant targeting refused at write time carol, cu := phase2Client(t, srv.URL, "carol@superbrain.test") _ = carol if _, e := d.Exec(`UPDATE "User" SET "tenantId"=NULL WHERE id=$1`, cu); e != nil { t.Fatal(e) } alice.request("POST", "/api/notifications/rules", map[string]any{ "name": "cross", "trigger": "bookmark_due", "channelId": slackA, "config": map[string]any{"targetUserIds": []string{cu}}, }, 400) // --- footer: free plan carries it, core plan does not (plan is data). // Free only allows the email kind, so this leg uses bob's email channel. var emailChannelID string for _, ch := range listGET(bob, "/api/notifications/channels") { if m, _ := ch.(map[string]any); m["kind"] == "email" { emailChannelID, _ = m["id"].(string) } } if emailChannelID == "" { t.Fatal("bob has no email channel") } bob.request("POST", "/api/notifications/rules", map[string]any{ "name": "shares by mail", "trigger": "share_received", "channelId": emailChannelID, }, 201) if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, "tenant-default"); e != nil { t.Fatal(e) } bm2 := alice.request("POST", "/api/bookmarks", map[string]any{ "url": "https://127.0.0.1/footer-thing", "title": "Footer thing", }, 201)["id"].(string) alice.request("POST", "/api/bookmarks/"+bm2+"/share", map[string]any{"userIds": []string{bu}}, 200) if e := notify.RunOnce(context.Background(), d); e != nil { t.Fatal(e) } mail := smtp.lastMessage(t) if !strings.Contains(mail, "Managed by David's Superbrain.") { t.Fatalf("free-plan delivery lacks the managed-by footer: %q", mail) } if _, e := d.Exec(`UPDATE "Tenant" SET plan='core' WHERE id=$1`, "tenant-default"); e != nil { t.Fatal(e) } // Zero cooldowns directly: the two footer passes run seconds apart and // the API's minimum cooldown is one minute. if _, e := d.Exec(`UPDATE "NotificationRule" SET "cooldownMinutes"=0`); e != nil { t.Fatal(e) } bm3 := alice.request("POST", "/api/bookmarks", map[string]any{ "url": "https://127.0.0.1/footer-thing-2", "title": "Footer thing 2", }, 201)["id"].(string) alice.request("POST", "/api/bookmarks/"+bm3+"/share", map[string]any{"userIds": []string{bu}}, 200) if e := notify.RunOnce(context.Background(), d); e != nil { t.Fatal(e) } if mail2 := smtp.lastMessage(t); strings.Contains(mail2, "Managed by David's Superbrain.") { t.Fatalf("core-plan delivery must not carry the footer: %q", mail2) } // --- signal channel: config validation, masked account, live send alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "signal", "name": "no account", "config": map[string]any{"restUrl": bridge.url(), "recipient": "+15550002222"}, }, 400) sig := alice.request("POST", "/api/notifications/channels", map[string]any{ "kind": "signal", "name": "signal", "config": map[string]any{ "restUrl": bridge.url(), "account": "+15550001111", "recipient": "+15550002222", }, }, 201) if sig["config"].(map[string]any)["account"] != "••••••••" { t.Fatalf("signal account not masked: %v", sig["config"]) } alice.request("POST", "/api/notifications/channels/"+sig["id"].(string)+"/test", map[string]any{}, 200) sends := bridge.sends() if len(sends) != 1 || sends[0]["account"] != "+15550001111" || sends[0]["recipient"] != "+15550002222" || sends[0]["message"] == "" { t.Fatalf("signal bridge got: %v", sends) } }