package server import ( "context" "fmt" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" "os" "path/filepath" "strings" "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 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 attached artifact // or the run link and says why on the receipt. func TestStageHookLinkClick(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() store := newOperatorStore(t) 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 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: "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: "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: "credentials", link: "standup-link.txt", files: map[string]string{"standup-link.txt": "https://user:pw@example.com/doc"}, 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) { workspace := t.TempDir() 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} if err := store.FinishStep(ctx, id, step); err != nil { t.Fatal(err) } r.notifyStep(id, d.Name, workspace, policy, step) // The app opens the link, else the attached artifact, else the run. runClick := fmt.Sprintf("pipelines://run/%d", id) 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 } 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) != 1 || receipts[0].Status != "sent" || receipts[0].Destination != "app" { t.Fatalf("receipts = %+v", receipts) } if got := receipts[0].Diagnostic; (test.diagnostic == "") != (got == "") || !strings.Contains(got, test.diagnostic) { t.Fatalf("receipt diagnostic = %q, want %q", got, test.diagnostic) } }) } } // A terminal stage hook whose notification is not recorded 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) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() store := newOperatorStore(t) 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() notes, recorder := newNoteCapture(t, store) r := &runner{ctx: ctx, store: store, notes: notes, artifactsRoot: artifacts} for _, test := range []struct { name string files map[string]string retry string // the retry's tap target; "" 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) } recorder.mu.Lock() recorder.fail, recorder.got = true, nil recorder.mu.Unlock() 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) } recorder.mu.Lock() recorder.fail = false recorder.mu.Unlock() r.deliverRunNotifications(time.Now().Add(time.Minute)) want := test.retry if want == "" { want = runAttentionClick(id) } got := recorder.recorded() if len(got) != 1 || got[0].Click != want || got[0].ID != fmt.Sprintf("run:%d:1:succeeded", id) { t.Fatalf("retried notification = %+v, want click %q", 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() }