package server import ( "context" "encoding/json" "fmt" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync" "sync/atomic" "syscall" "testing" "time" ) const standupDoc = "https://claude.ai/public/artifacts/0f3c-standup" // writePublic writes files into run id's shared public/ directory. func writePublic(t *testing.T, artifacts string, id int64, files map[string]string) { t.Helper() public := filepath.Join(artifacts, fmt.Sprint(id), "public") if err := os.MkdirAll(public, 0700); err != nil { t.Fatal(err) } for name, content := range files { if err := os.WriteFile(filepath.Join(public, name), []byte(content), 0600); err != nil { t.Fatal(err) } } } // appNotification returns the app notification with id, or nil. func appNotification(t *testing.T, store *pipeline.Store, id string) *protocol.AppNotification { t.Helper() active, _, err := store.ActiveAppNotifications(context.Background(), "", time.Now()) if err != nil { t.Fatal(err) } for i := range active { if active[i].ID == id { return &active[i] } } return nil } // A stage hook's `link=` file decides the ntfy and app tap target when its // first non-empty line is an http(s) URL, keeping the run one action away and // never attaching the link file; anything else falls back to the run link and // says why on the first receipt. func TestStageHookLinkClick(t *testing.T) { captured := newNtfyCapture(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() store := newOperatorStore(t) if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil { t.Fatal(err) } if _, err := store.Submit(ctx, "standup", pipeline.Template([]string{"one"}, true)); err != nil { t.Fatal(err) } items, _ := store.List(ctx) d, _ := store.Get(ctx, items[0].ID, 0) artifacts := t.TempDir() r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts} const doc = standupDoc for _, test := range []struct { name, link, open string files map[string]string noWeb bool // no web origin: ntfy has no run view attach bool // markdown and a workspace file are also attached click bool // the doc URL is the app tap target artifact string // the attached artifact path diagnostic string }{ {name: "valid", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "\n " + doc + " \r\nnotes\n", "notes.txt": "n", "more.txt": "m"}, click: true}, {name: "valid-only-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, click: true}, {name: "valid-other-file", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"}, {name: "valid-no-web", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc}, noWeb: true, click: true, diagnostic: "notify link: ntfy keeps the run tap target"}, {name: "missing", link: "standup-link.txt", diagnostic: "notify link: no public file matches standup-link.txt"}, {name: "missing-other-file", link: "standup-link.txt", files: map[string]string{"report.md": "# Report"}, artifact: "report.md", diagnostic: "notify link: no public file matches standup-link.txt"}, {name: "missing-attachments", link: "standup-link.txt", attach: true, diagnostic: "notify link: no public file matches standup-link.txt"}, {name: "relative", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "standup.html\n" + doc}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt does not start with an absolute http(s) URL"}, {name: "scheme", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "javascript:alert(1)"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"}, {name: "fragment", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "#top"}, artifact: "standup-link.txt", diagnostic: "does not start with an absolute http(s) URL"}, {name: "empty", link: "standup-link.txt", files: map[string]string{"standup-link.txt": " \n\n"}, artifact: "standup-link.txt", diagnostic: "notify link: public/standup-link.txt is empty"}, {name: "large", link: "standup-link.txt", files: map[string]string{"standup-link.txt": doc + "\n" + strings.Repeat("x", 4<<10)}, artifact: "standup-link.txt", diagnostic: "at most 4 KiB"}, {name: "absent", files: map[string]string{"standup-link.txt": doc, "notes.txt": "n"}}, {name: "absent-only-file", files: map[string]string{"standup-link.txt": doc}, artifact: "standup-link.txt"}, {name: "with-open", link: "*-link.txt", open: "*", files: map[string]string{"standup-link.txt": doc, "standup.md": "# Standup"}, click: true, artifact: "standup.md"}, } { t.Run(test.name, func(t *testing.T) { web := "https://pipelines.example.com" if test.noWeb { web = "" } t.Setenv("PIPELINES_WEB_PUBLIC_URL", web) workspace := t.TempDir() if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("report"), 0600); err != nil { t.Fatal(err) } id, _, err := store.CreateRun(ctx, d, test.name, workspace, false, nil, map[string]any{"prompt": "task"}) if err != nil { t.Fatal(err) } writePublic(t, artifacts, id, test.files) if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil { t.Fatal(err) } step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: "two", Output: map[string]any{}} policy := &protocol.NotificationPolicy{On: []string{"success"}, Destination: "system", Link: test.link, Open: test.open} publications := 1 if test.attach { step.Output = map[string]any{"markdown": "# Standup", "artifacts": []any{"report.txt"}} policy.Artifacts = []string{"markdown", "files"} publications = 2 } if err := store.FinishStep(ctx, id, step); err != nil { t.Fatal(err) } before := len(captured()) r.notifyStep(id, d.Name, workspace, policy, step) // ntfy opens the link only beside a web run view; the app opens the // link (else the attached artifact, else the run). runClick := fmt.Sprintf("pipelines://run/%d", id) wantNtfy, wantActions := runClick, "" if !test.noWeb { wantActions = fmt.Sprintf("view, Open in browser, https://pipelines.example.com/runs/%d", id) if test.click { wantNtfy = doc } } wantClick, wantRunClick := runClick, "" if test.artifact != "" { wantClick, wantRunClick = fmt.Sprintf("pipelines://artifact/%d/1/%s", id, test.artifact), runClick } if test.click { wantClick, wantRunClick = doc, runClick } got := captured()[before:] if len(got) != publications { t.Fatalf("ntfy publications = %+v", got) } for _, publication := range got { if publication.Click != wantNtfy || publication.Actions != wantActions { t.Fatalf("ntfy click/actions = %q %q, want %q %q", publication.Click, publication.Actions, wantNtfy, wantActions) } } n := appNotification(t, store, fmt.Sprintf("run:%d:1:success", id)) if n == nil || n.Click != wantClick || n.RunClick != wantRunClick { t.Fatalf("app notification = %+v, want click %q run %q", n, wantClick, wantRunClick) } if (n.Artifact == nil) != (test.artifact == "") || (n.Artifact != nil && n.Artifact.Path != test.artifact) { t.Fatalf("app artifact = %+v, want %q", n.Artifact, test.artifact) } detail, err := store.GetRun(ctx, id) if err != nil { t.Fatal(err) } receipts := detail.Steps[0].Notifications if len(receipts) != publications { t.Fatalf("receipts = %+v", receipts) } // The reason is recorded once, on the first receipt. (The capture // acknowledges no attachment, so attachment receipts fail.) for i, receipt := range receipts { noted := strings.Contains(receipt.Diagnostic, "notify link") if i == 0 && test.diagnostic != "" { noted = !strings.Contains(receipt.Diagnostic, test.diagnostic) } if noted || (!test.attach && (receipt.Status != "sent" || (test.diagnostic == "") != (receipt.Diagnostic == ""))) { t.Fatalf("receipts = %+v, want diagnostic %q on the first only", receipts, test.diagnostic) } } }) } } // A terminal stage hook whose publication fails hands the run event back to // the durable outbox; the retry keeps the hook's link, and the run-level // failure reason never carries the link note. func TestStageHookLinkSurvivesOutboxRetry(t *testing.T) { t.Setenv("PIPELINES_WEB_PUBLIC_URL", "https://pipelines.example.com") var mu sync.Mutex var clicks []string var fail atomic.Bool srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() clicks = append(clicks, r.Header.Get("Click")) mu.Unlock() if fail.Swap(false) { http.Error(w, "transient", http.StatusServiceUnavailable) return } _ = json.NewEncoder(w).Encode(map[string]string{"id": "msg", "event": "message"}) })) defer srv.Close() t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines") t.Setenv("PIPELINES_NTFY_TOKEN", "") t.Setenv("PIPELINES_NTFY_TOKEN_FILE", "") ctx, cancel := context.WithCancel(context.Background()) defer cancel() store := newOperatorStore(t) if _, err := store.UpdateNotificationSettings(ctx, map[string]any{protocol.NotifyNtfyEnabled: true}); err != nil { t.Fatal(err) } source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\nlink=standup-link.txt\n```", 1) if _, err := store.Submit(ctx, "standup", source); err != nil { t.Fatal(err) } items, _ := store.List(ctx) d, _ := store.Get(ctx, items[0].ID, 0) policy := d.Graph.Stages[0].Notify if policy == nil || policy.Link != "standup-link.txt" { t.Fatalf("stage policy = %+v", policy) } artifacts := t.TempDir() r := &runner{ctx: ctx, store: store, notes: newAppNotifier(store), artifactsRoot: artifacts} for _, test := range []struct { name string files map[string]string retry string // the retry's ntfy click; "" means the run }{ {name: "valid", files: map[string]string{"standup-link.txt": standupDoc}, retry: standupDoc}, {name: "missing"}, } { t.Run(test.name, func(t *testing.T) { id, _, err := store.CreateRun(ctx, d, test.name, t.TempDir(), false, nil, map[string]any{"prompt": "task"}) if err != nil { t.Fatal(err) } writePublic(t, artifacts, id, test.files) if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil { t.Fatal(err) } step := protocol.RunStep{Sequence: 1, Stage: "one", Status: "completed", Outcome: "success", Target: protocol.SuccessEnd, Output: map[string]any{}} if err := store.FinishStep(ctx, id, step); err != nil { t.Fatal(err) } // The run's transactional success intent the hook arbitrates against. if err := store.EnqueueRunNotification(ctx, pipeline.RunNotification{RunID: id, Sequence: 1, Event: "succeeded", Channel: "system", Title: "Run succeeded", Body: "Run succeeded", Click: runAttentionClick(id)}); err != nil { t.Fatal(err) } mu.Lock() clicks = nil mu.Unlock() fail.Store(true) r.notifyStep(id, d.Name, t.TempDir(), policy, step) rows, err := store.RunNotifications(ctx, id) if err != nil || len(rows) != 1 || rows[0].Status != "pending" || rows[0].Diagnostic == "" || strings.Contains(rows[0].Diagnostic, "notify link") { t.Fatalf("released run notification = %+v %v", rows, err) } r.deliverRunNotifications(time.Now().Add(time.Minute)) want := test.retry if want == "" { want = runAttentionClick(id) } mu.Lock() got := append([]string(nil), clicks...) mu.Unlock() if len(got) != 2 || got[0] != want || got[1] != want { t.Fatalf("hook and retry clicks = %q, want %q twice", got, want) } if rows, err = store.RunNotifications(ctx, id); err != nil || len(rows) != 1 || rows[0].Status != "sent" { t.Fatalf("retried run notification = %+v %v", rows, err) } }) } } // Notification files in public/ are read without following a symlink (a swap // after selection) or blocking on a special file. func TestOpenPublicFileRefusesSymlinksAndSpecialFiles(t *testing.T) { root := t.TempDir() outside := filepath.Join(t.TempDir(), "secret.txt") if err := os.WriteFile(outside, []byte("secret"), 0600); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(root, "report.md"), []byte("# Report"), 0600); err != nil { t.Fatal(err) } if err := os.Symlink(outside, filepath.Join(root, "alias.md")); err != nil { t.Fatal(err) } if err := syscall.Mkfifo(filepath.Join(root, "pipe.md"), 0600); err != nil { t.Fatal(err) } for _, name := range []string{"alias.md", "pipe.md", "../secret.txt"} { if file, _, err := openPublicFile(root, name); err == nil { file.Close() t.Fatal("unsafe public file opened", name) } } file, _, err := openPublicFile(root, "report.md") if err != nil { t.Fatal(err) } file.Close() }