package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"go/parser"
"go/token"
"path/filepath"
"reflect"
"strings"
"testing"
"craftdesign.group/quarry/internal/artifact"
"craftdesign.group/quarry/internal/chat"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// A TAKEDOWN HOLD (RFC 0023) MUST REACH EVERY CROSS-REPOSITORY READ.
//
// The router's takedown gate sees a repository only where the path names
// one. An op that reads across repositories names none, so it asked
// CanRead and never Held, and a held public repository went on appearing
// in fleet search, the people list, a dashboard's feed and its rows.
// Every such op now says so (ops.Op.CrossRepo) and this guard walks them
// against one public, one private and two held repositories, as four
// callers, so an op added without hold handling fails here.
const (
fxPub = "pubrepo" // public
fxPriv = "privrepo" // private to its owner
fxHeld = "zz-held" // public, disabled: its admins and a site admin still reach it
fxLegal = "zz-legal" // public, legal hold: a site admin person alone
fxOwner = "owena"
fxStrang = "strangera"
fxCollab = "collaba" // a non-admin granted on the held repositories
fxAdmin = "sitea"
)
type fxAttention struct{ events []AttentionEvent }
func (f fxAttention) Attend(string, AttentionEvent) (uint64, error) { return 0, nil }
func (f fxAttention) TailAttention(_ string, from uint64) (<-chan AttentionEvent, func()) {
ch := make(chan AttentionEvent, len(f.events))
for _, e := range f.events {
if e.Seq > from {
ch <- e
}
}
close(ch)
return ch, func() {}
}
func (f fxAttention) AttentionTip(string) (uint64, error) { return uint64(len(f.events)), nil }
func (f fxAttention) AttentionPending(string, uint64) (int, error) { return len(f.events), nil }
func (f fxAttention) RecentAttention(string, int) ([]AttentionEvent, error) {
return f.events, nil
}
// fxSignOffs holds one request per repository for each of three owners.
type fxSignOffs struct {
SignOffStore
rows []SignOffRequest
}
func (f fxSignOffs) SignOffsFor(owner string, _ int) ([]SignOffRequest, error) {
var out []SignOffRequest
for _, r := range f.rows {
if r.Owner == owner {
out = append(out, r)
}
}
return out, nil
}
func (f fxSignOffs) DecideSignOff(id, _ string, _ bool) (SignOffRequest, error) {
r, _, _ := f.SignOffByID(id)
r.State = "denied"
return r, nil
}
func (f fxSignOffs) SignOffByID(id string) (SignOffRequest, bool, error) {
for _, r := range f.rows {
if r.ID == id {
return r, true, nil
}
}
return SignOffRequest{}, false, nil
}
type fxStamp struct{ StampStore }
func (fxStamp) StampedBy(string) ([]string, error) {
return []string{fxPub, fxPriv, fxHeld, fxLegal}, nil
}
// fxHeldFor is RFC 0023's table as the fixture states it.
func fxHeldFor(ctx context.Context, repo string) string {
who := ops.User(ctx)
switch repo {
case fxHeld:
if who == fxOwner || who == fxAdmin {
return ""
}
return "unavailable for legal reasons"
case fxLegal:
if who == fxAdmin {
return ""
}
return "unavailable for legal reasons"
}
return ""
}
func fxIndex(t *testing.T, name string, n int) *index.Index {
t.Helper()
ix, err := index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
h := func(c string) string { return strings.Repeat(c, 32) }
hex := "0123456789abcdef"
if err := ix.FoldNow([]index.Parsed{
{Hash: h(hex[n:n+1]) + h(hex[n+8 : n+9])[:32], Art: &artifact.Artifact{Type: artifact.Wiki,
WikiTitle: "Notes " + name, Date: "2026-08-15T10:00:00", User: "u" + name,
Mimetype: "text/x-markdown", Body: []byte("needle " + name + "\n")}},
{Hash: h(hex[n+4:n+5]) + h(hex[n : n+1])[:32], Art: &artifact.Artifact{Type: artifact.Manifest,
Date: "2026-08-15T11:00:00", User: "u" + name, Comment: "needle " + name}},
{Hash: "t" + name, Art: &artifact.Artifact{Type: artifact.Ticket,
TicketID: strings.Repeat(hex[n:n+1], 40), Date: "2026-08-15T12:00:00", User: "u" + name,
Fields: []artifact.Field{{Name: "status", Value: "Open"}, {Name: "title", Value: "needle " + name}}}},
}); err != nil {
t.Fatal(err)
}
return ix
}
func fxDeps(t *testing.T) Deps {
t.Helper()
db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
for _, a := range []struct {
name string
admin bool
}{{fxOwner, false}, {fxStrang, false}, {fxCollab, false}, {fxAdmin, true}} {
if err := db.AddAccount(a.name, "a-long-enough-password", a.admin); err != nil {
t.Fatal(err)
}
}
for _, r := range []string{fxPub, fxPriv, fxHeld, fxLegal} {
if err := db.SetCaps(fxOwner, r, "a"); err != nil {
t.Fatal(err)
}
}
for _, who := range []string{fxAdmin, fxCollab} {
for _, r := range []string{fxPub, fxHeld, fxLegal} {
if err := db.SetCaps(who, r, "i"); err != nil {
t.Fatal(err)
}
}
}
if err := db.NewAgent("bota", fxOwner, 5); err != nil {
t.Fatal(err)
}
for _, r := range []string{fxPub, fxPriv, fxHeld, fxLegal} {
if err := db.SetCaps("bota", r, "i"); err != nil {
t.Fatal(err)
}
}
if err := db.AddTeam("grove", "Grove", "", fxOwner); err != nil {
t.Fatal(err)
}
for _, r := range []string{fxPub, fxPriv, fxHeld, fxLegal} {
if err := db.SetTeamRepo("grove", r, fxOwner); err != nil {
t.Fatal(err)
}
}
for _, who := range []string{fxStrang, fxCollab} {
if err := db.SetTeamMember("grove", who, "", false, true); err != nil {
t.Fatal(err)
}
}
fc := &fakeChat{}
repos := map[string]*Repo{}
var evs []AttentionEvent
for i, r := range []string{fxPub, fxPriv, fxHeld, fxLegal} {
repos[r] = &Repo{Index: fxIndex(t, r, i), Code: "code-" + r}
if _, err := fc.Post("code-"+r, chat.Message{User: "someone", Text: "hello from " + r, Repo: r}); err != nil {
t.Fatal(err)
}
evs = append(evs, AttentionEvent{Seq: uint64(i + 1), Kind: "activity", Repo: r, Summary: "news from " + r})
}
var msgs []InboxMessage
for _, r := range []string{fxPub, fxPriv, fxHeld, fxLegal} {
msgs = append(msgs, InboxMessage{ID: "m-" + r, Workflow: "quarry-mention",
Subject: "mail from " + r, Link: "/r/" + r + "/forum/x"})
}
msgs = append(msgs,
// The same repository by its address, not its key.
InboxMessage{ID: "m-addr", Workflow: "quarry-mention", Subject: "by address", Link: "https://forge.example/r/acme/" + fxHeld + "/forum/y"},
// A repository workflow whose link names none cannot be shown safe.
InboxMessage{ID: "m-nolink", Workflow: "quarry-mention", Subject: "mentions zz-held"},
// One that names no repository at all is the person's own.
InboxMessage{ID: "m-news", Workflow: "quarry-changelog", Subject: "release notes", Link: "/changelog"})
var reqs []SignOffRequest
for _, owner := range []string{fxOwner, fxCollab, fxAdmin} {
for _, r := range []string{fxPub, fxPriv, fxHeld, fxLegal} {
reqs = append(reqs, SignOffRequest{ID: "so-" + r + "-" + owner, Agent: "bota", Owner: owner,
Op: "agent.grant", Repo: r, Summary: "grant on " + r, State: "pending"})
}
}
return Deps{
SignOffs: fxSignOffs{rows: reqs},
Inbox: &fixedPageInbox{msgs: msgs, pageSize: 100, honourLimit: true},
Address: func(key string) (string, string, bool) { return "acme", key, true },
Version: "v", Accounts: acctAdapter{db}, Teams: db, Repos: NewRepos(repos),
Chat: fc, Stamp: fxStamp{}, Attention: fxAttention{evs}, Forum: nil, Pending: func() []string { return []string{fxPub, fxPriv, fxHeld, fxLegal} },
CanRead: func(ctx context.Context, repo string) bool {
return repo != fxPriv || ops.User(ctx) == fxOwner
},
Held: fxHeldFor,
}
}
type fxCaller struct {
who string
seesHeld bool // fxHeld
seesHold bool // fxLegal
seesPriv bool
}
var fxCallers = []fxCaller{
{"", false, false, false},
{fxStrang, false, false, false},
{fxCollab, false, false, false},
{fxOwner, true, false, true},
{fxAdmin, true, true, false},
}
// fxProbes is the input each marked op is asked with.
var fxProbes = map[string]any{
"repo.list": repoListIn{},
"people.list": peopleListIn{Limit: 50},
"search.all": searchAllIn{Q: "needle", Limit: 50},
"stamp.list": stampListIn{},
"me.feed": meFeedIn{},
"me.repos": meReposIn{},
"ticket.across": ticketAcrossIn{},
"chat.unread": chatUnreadIn{},
"meta.version": versionIn{},
"team.list": teamListIn{},
"team.get": teamGetIn{Name: "grove"},
"team.chat": teamChatIn{Name: "grove", Limit: 50},
"team.tickets": teamBoardIn{Name: "grove", State: "all"},
"inbox.list": inboxListIn{},
"inbox.recent": inboxRecentIn{},
"inbox.count": inboxCountIn{},
"signoff.list": signOffListIn{},
"agent.list": agentListIn{},
}
// fxCountOnly answers with numbers and no names; a direct test reads them.
var fxCountOnly = map[string]bool{"team.list": true, "inbox.count": true}
// fxElsewhere are marked ops a shared fixture cannot drive, each with the
// test that does.
var fxElsewhere = map[string]string{
"events.stream": "TestTheEventStreamSkipsAHeldRepository",
"landing.queue": "TestLandingQueueSkipsAHeldRepository",
"me.attention": "TestMeAttentionSkipsAHeldRepository",
"signoff.get": "TestSignOffGetHidesAHeldRepository",
"signoff.decide": "TestSignOffGetHidesAHeldRepository",
"setup.start.look": "TestSetupChoicesSkipAHeldRepository",
"ticket.number": "TestATicketNumberSkipsAHeldRepository",
}
func TestEveryCrossRepositoryOpHonoursTheHold(t *testing.T) {
d := fxDeps(t)
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, ".", nil, 0)
if err != nil {
t.Fatal(err)
}
marked := 0
for _, desc := range r.All() {
if !desc.CrossRepo {
continue
}
marked++
if fn, ok := fxElsewhere[desc.Name]; ok {
found := false
for _, p := range pkgs {
for _, f := range p.Files {
if f.Scope.Lookup(fn) != nil {
found = true
}
}
}
if !found {
t.Errorf("FAIL: %s is covered by %s, which does not exist", desc.Name, fn)
}
continue
}
in, ok := fxProbes[desc.Name]
if !ok {
t.Errorf("FAIL: %s reads across repositories and has no hold probe: add it to fxProbes", desc.Name)
continue
}
seen := false
for _, c := range fxCallers {
ctx := context.Background()
if c.who != "" {
ctx = ops.WithUser(ctx, c.who)
}
out, err := r.Invoke(ctx, desc.Name, in)
if err != nil {
// Not signed in, or nothing there for them: no rows, so no leak.
continue
}
raw, _ := json.Marshal(out)
body := string(raw)
if got := strings.Contains(body, fxHeld); got {
if !c.seesHeld {
t.Errorf("FAIL: %s as %q shows a disabled repository\n%s", desc.Name, c.who, body)
}
seen = true
}
if got := strings.Contains(body, fxLegal); got && !c.seesHold {
t.Errorf("FAIL: %s as %q shows a repository on legal hold\n%s", desc.Name, c.who, body)
}
if got := strings.Contains(body, fxPriv); got && !c.seesPriv {
t.Errorf("FAIL: %s as %q shows a private repository\n%s", desc.Name, c.who, body)
}
}
if !seen && !fxCountOnly[desc.Name] {
// The probe must be able to see the thing it guards: for the
// repository's own admin the disabled repository is listed.
t.Errorf("FAIL: %s never showed the disabled repository to anyone allowed it, so the probe proves nothing", desc.Name)
}
}
if marked == 0 {
t.Error("FAIL: no op is marked CrossRepo")
}
if !t.Failed() {
t.Log("ok")
}
}
func fxInvoke(t *testing.T, r *ops.Registry, who, op string, in any) any {
t.Helper()
ctx := context.Background()
if who != "" {
ctx = ops.WithUser(ctx, who)
}
out, err := r.Invoke(ctx, op, in)
if err != nil {
t.Fatalf("%s as %q: %v", op, who, err)
}
return out
}
func fxRegistry(t *testing.T, d Deps) *ops.Registry {
t.Helper()
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
return r
}
// A held repository adds nothing a private one does not: not a hit, not
// a facet, not a count of repositories searched.
func TestSearchAllTakesNoHeldRepositoryIntoAnyCount(t *testing.T) {
r := fxRegistry(t, fxDeps(t))
for _, c := range fxCallers {
got := fxInvoke(t, r, c.who, "search.all", searchAllIn{Q: "needle", Limit: 50}).(searchAllOut)
want := 1 // the public one
for _, b := range []bool{c.seesPriv, c.seesHeld, c.seesHold} {
if b {
want++
}
}
if got.Searched != want {
t.Errorf("FAIL: as %q search.all consulted %d repositories, want %d", c.who, got.Searched, want)
}
if len(got.ByRepo) != want {
t.Errorf("FAIL: as %q search.all counts %d repositories in its facet, want %d", c.who, len(got.ByRepo), want)
}
for _, h := range got.Results {
if (h.Repo == fxHeld && !c.seesHeld) || (h.Repo == fxLegal && !c.seesHold) {
t.Errorf("FAIL: as %q search.all returned a hit from %s", c.who, h.Repo)
}
}
}
if !t.Failed() {
t.Log("ok")
}
}
// Naming a held repository is refused with its sentence, as every
// single-repository route refuses it; whoever the hold admits is served.
func TestSearchAllNamingAHeldRepository(t *testing.T) {
r := fxRegistry(t, fxDeps(t))
for _, c := range fxCallers {
ctx := context.Background()
if c.who != "" {
ctx = ops.WithUser(ctx, c.who)
}
_, err := r.Invoke(ctx, "search.all", searchAllIn{Q: "needle", Repo: fxHeld})
if c.seesHeld && err != nil {
t.Errorf("FAIL: as %q search.all refused the repository its admin may read: %v", c.who, err)
}
if !c.seesHeld && err == nil {
t.Errorf("FAIL: as %q search.all answered inside a held repository", c.who)
}
_, err = r.Invoke(ctx, "people.list", peopleListIn{Repo: fxHeld})
if c.seesHeld != (err == nil) {
t.Errorf("FAIL: as %q people.list on a held repository: err=%v, allowed=%v", c.who, err, c.seesHeld)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A listing's denominators are what the caller may see: a held
// repository moves neither the total nor the served count.
func TestRepoListAndPeopleCountsLeaveOutAHeldRepository(t *testing.T) {
d := fxDeps(t)
d.Pending = nil // listed as starting rows of their own, which is another test's count
r := fxRegistry(t, d)
for _, c := range fxCallers {
want := 1
for _, b := range []bool{c.seesPriv, c.seesHeld, c.seesHold} {
if b {
want++
}
}
rl := fxInvoke(t, r, c.who, "repo.list", repoListIn{}).(repoListOut)
if rl.Total != want || rl.Served != want {
t.Errorf("FAIL: as %q repo.list total=%d served=%d, want %d", c.who, rl.Total, rl.Served, want)
}
pl := fxInvoke(t, r, c.who, "people.list", peopleListIn{Limit: 50}).(peopleListOut)
if pl.Total != want {
t.Errorf("FAIL: as %q people.list total=%d, want %d", c.who, pl.Total, want)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A team's repository count is the number the caller may read, held ones
// left out.
func TestTeamCountsLeaveOutAHeldRepository(t *testing.T) {
r := fxRegistry(t, fxDeps(t))
for _, c := range fxCallers {
want := 1
for _, b := range []bool{c.seesPriv, c.seesHeld, c.seesHold} {
if b {
want++
}
}
tl := fxInvoke(t, r, c.who, "team.list", teamListIn{}).(teamListOut)
if len(tl.Teams) != 1 || tl.Teams[0].Repos != want {
t.Errorf("FAIL: as %q team.list counts %+v repositories, want %d", c.who, tl.Teams, want)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// The forge-wide stream and a repository's own stream ask the same
// question of each event's repository, so a takedown placed while one is
// open ends what it carries.
func TestTheEventStreamSkipsAHeldRepository(t *testing.T) {
d := fxDeps(t)
for _, c := range fxCallers {
ctx := context.Background()
if c.who != "" {
ctx = ops.WithUser(ctx, c.who)
}
visible := d.eventVisibility(ctx)
if visible(fxHeld) != c.seesHeld || visible(fxLegal) != c.seesHold || visible(fxPub) != true {
t.Errorf("FAIL: as %q the stream shows held=%v legal=%v pub=%v", c.who,
visible(fxHeld), visible(fxLegal), visible(fxPub))
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A notice about a held repository is not delivered to somebody the hold
// shuts out, whatever name was subscribed before it. The predicate is the
// whole gate fireNotify asks, so it is asked directly rather than raced.
func TestNoNoticeIsDeliveredFromAHeldRepository(t *testing.T) {
d := fxDeps(t)
for _, c := range fxCallers {
if c.who == "" {
continue
}
for repo, want := range map[string]bool{fxPub: true, fxPriv: c.seesPriv, fxHeld: c.seesHeld, fxLegal: c.seesHold} {
e := NotifyEvent{Workflow: "quarry-mention", To: c.who, Payload: map[string]any{"repo": repo}}
if got := d.noticeDeliverable(e); got != want {
t.Errorf("FAIL: a notice about %s to %q: deliverable=%v, want %v", repo, c.who, got, want)
}
}
}
if !d.noticeDeliverable(NotifyEvent{Workflow: "quarry-mention", To: fxStrang, Payload: map[string]any{}}) {
t.Error("FAIL: a notice naming no repository was withheld")
}
if !t.Failed() {
t.Log("ok")
}
}
// A notice addressed to a topic (everybody watching a repository, by
// mail or push) is no person's: it goes to people the hold may shut out,
// so a repository under either strength sends none. The site admins'
// own topic is the operator's and still carries it.
func TestHeldRepositoryTopicNoticeIsNotDelivered(t *testing.T) {
d := fxDeps(t)
for repo, want := range map[string]bool{fxPub: true, fxHeld: false, fxLegal: false} {
e := NotifyEvent{Workflow: "quarry-activity", To: "repo:" + repo, Payload: map[string]any{"repo": repo}}
if got := d.noticeDeliverable(e); got != want {
t.Errorf("FAIL: a topic notice about %s: deliverable=%v, want %v", repo, got, want)
}
}
e := NotifyEvent{Workflow: "quarry-activity", To: "admins", Payload: map[string]any{"repo": fxLegal}}
if !d.noticeDeliverable(e) {
t.Error("FAIL: the site admins' topic was withheld")
}
if !t.Failed() {
t.Log("ok")
}
}
type fxStream struct{ ids []uint64 }
func (f *fxStream) Emit(id uint64, _ any) error { f.ids = append(f.ids, id); return nil }
func (f *fxStream) Event(string, any) error { return nil }
func (f *fxStream) Ping() {}
// The attention stream replays the window on a reconnect: what was
// delivered before a hold must not come back to somebody it shuts out.
func TestMeAttentionSkipsAHeldRepository(t *testing.T) {
r := fxRegistry(t, fxDeps(t))
idOf := map[string]uint64{fxPub: 1, fxPriv: 2, fxHeld: 3, fxLegal: 4}
for _, c := range fxCallers {
if c.who == "" {
continue
}
s := &fxStream{}
if err := r.InvokeStream(ops.WithUser(context.Background(), c.who), "me.attention", meAttentionIn{}, s); err != nil {
t.Fatal(err)
}
got := map[uint64]bool{}
for _, id := range s.ids {
got[id] = true
}
for repo, want := range map[string]bool{fxPub: true, fxPriv: c.seesPriv, fxHeld: c.seesHeld, fxLegal: c.seesHold} {
if got[idOf[repo]] != want {
t.Errorf("FAIL: as %q the replay carries %s=%v, want %v", c.who, repo, got[idOf[repo]], want)
}
}
}
if !t.Failed() {
t.Log("ok")
}
}
// The badge counts what the list shows, from the same filtered rows, in
// both halves: a hidden message is not an unread one.
func TestInboxCountAgreesWithTheFilteredList(t *testing.T) {
r := fxRegistry(t, fxDeps(t))
for _, c := range fxCallers {
if c.who == "" {
continue
}
v := 1
for _, b := range []bool{c.seesPriv, c.seesHeld, c.seesHold} {
if b {
v++
}
}
// v repositories' mail, one release note, v repositories' local events.
want := 2*v + 1
// The address-keyed message is about the disabled repository, so it
// counts only for whoever reaches it. The mention whose link names
// no repository is withheld from everyone: it cannot be shown safe.
if c.seesHeld {
want++
}
got := fxInvoke(t, r, c.who, "inbox.count", inboxCountIn{}).(inboxCountOut).Unread
if got != want {
t.Errorf("FAIL: as %q inbox.count = %d, want %d", c.who, got, want)
}
rows := fxInvoke(t, r, c.who, "inbox.list", inboxListIn{Limit: 100}).(inboxListOut).Rows
notify := 0
for _, row := range rows {
if row.Source == "notify" {
notify++
}
}
if wantNotify := v + 1 + map[bool]int{true: 1, false: 0}[c.seesHeld]; notify != wantNotify {
t.Errorf("FAIL: as %q inbox.list shows %d notify rows, want %d", c.who, notify, wantNotify)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A repository its own admins still see is marked for them as down.
func TestAnAdminsListMarksADownRepository(t *testing.T) {
d := fxDeps(t)
d.TakenDown = func(repo string) string {
switch repo {
case fxHeld:
return "disabled"
case fxLegal:
return "hold"
}
return ""
}
r := fxRegistry(t, d)
for _, c := range []fxCaller{fxCallers[3], fxCallers[4]} {
rl := fxInvoke(t, r, c.who, "repo.list", repoListIn{}).(repoListOut)
marks := map[string]string{}
for _, row := range rl.Repos {
marks[row.Name] = row.TakenDown
}
if marks[fxPub] != "" || marks[fxHeld] != "disabled" {
t.Errorf("FAIL: as %q repo.list marks %v", c.who, marks)
}
}
mr := fxInvoke(t, r, fxOwner, "me.repos", meReposIn{}).(meReposOut)
for _, row := range mr.Repos {
if row.Name == fxHeld && row.TakenDown != "disabled" {
t.Errorf("FAIL: me.repos does not mark the disabled repository: %+v", row)
}
if row.Name == fxPub && row.TakenDown != "" {
t.Errorf("FAIL: me.repos marks a repository that is up: %+v", row)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A hold placed while a stream is open ends what it carries at once.
func TestAHoldPlacedMidStreamIsSeenAtOnce(t *testing.T) {
d := fxDeps(t)
held := false
d.Held = func(ctx context.Context, repo string) string {
if held && repo == fxPub {
return "unavailable for legal reasons"
}
return ""
}
visible := d.eventVisibility(ops.WithUser(context.Background(), fxStrang))
if !visible(fxPub) {
t.Fatal("FAIL: the repository was not visible before the hold")
}
held = true
d.takedownChanged()
if visible(fxPub) {
t.Error("FAIL: the stream kept serving a repository the moment after a hold")
}
if !t.Failed() {
t.Log("ok")
}
}
// Every op that reads without naming a repository in its route either
// declares it reads across repositories (and is then probed above) or is
// on this list with the reason it needs no hold. A new one is neither,
// and fails here until its author decides which.
var fxExempt = map[string]string{
// Commands with no repository in their route. None returns a repository's
// content or a list of repositories; each is the caller's own business or
// echoes what the caller sent, and the ones that act on a named repository
// refuse a held one themselves (refuseHeldRepo).
"agent.token.revoke_all": "the caller's own agent tokens",
"me.signin-link": "the caller's own sign-in link",
"account.agent": "the caller's own agent account",
"account.answerable": "the caller's own agent's answerable person",
"account.claim": "redeems an invite",
"agent.ask": "files a request; the repository is the caller's input and the op refuses a held one",
"agent.delete": "the caller's own agent",
"agent.grant": "refuses a held repository (refuseHeldRepo)",
"agent.inherit": "the caller's own agent",
"agent.new": "the caller's own agent",
"agent.setup": "refuses a held repository (refuseHeldRepo)",
"agent.token.new": "echoes the caller's own token request",
"agent.token.reissue": "the caller's own agent token",
"agent.token.repos": "echoes the caller's own input",
"agent.token.revoke": "the caller's own agent token",
"attention.read": "the caller's own read pointer",
"avatar.clear": "the caller's own avatar",
"avatar.set": "the caller's own avatar",
"inbox.mark": "the caller's own read marks",
"me.email.clear": "the caller's own address",
"me.email.confirm": "the caller's own address",
"me.email.set": "the caller's own address",
"me.passwd": "the caller's own password",
"me.prefs.set": "the caller's own settings",
"me.push.subscribe": "the caller's own device",
"me.push.test": "the caller's own device",
"me.push.unsubscribe": "the caller's own device",
"me.sync.token": "the caller's own sync token",
"me.sync.token.revoke": "the caller's own sync token",
"repo.add": "creates a repository",
"repo.import.confirm": "the caller's own import",
"request.plan": "an agent's own steps; each step's op refuses a held repository",
"session.end": "the caller's own session",
"setup.start.claim": "redeems a code; refuses a held repository (refuseHeldRepo)",
"setup.start.discard": "the caller's own start",
"team.chat.post": "a team's room; a repository line needs the room's repository",
"team.chat.render": "renders text the caller sent",
"team.create": "creates a team",
"team.delete": "a team",
"team.listed": "a member's own listing",
"team.member": "a team's membership",
"team.private": "a team's visibility",
"team.repo.add": "refuses a held repository (refuseHeldRepo)",
"team.repo.offer.accept": "refuses a held repository (refuseHeldRepo)",
"team.repo.offer.decline": "refuses a held repository (refuseHeldRepo)",
"team.repo.remove": "refuses a held repository (refuseHeldRepo)",
"team.text": "a team's text",
"team.unmember": "a team's membership",
"account.explain": "operator's account-capability read, behind Auth Admin",
"account.peek": "an invite token's own page",
"agent.token.list": "the caller's own agent tokens; names only",
"avatar.get": "an avatar image by name",
"changelog.get": "the forge's own release notes",
"me.account": "the caller's own account",
"me.email": "the caller's own address",
"me.prefs": "the caller's own notification settings",
"me.push.key": "a public key",
"me.sync.token.list": "the caller's own sync tokens",
"me.sync.token.state": "the caller's own sync token",
"meta.docs": "static documentation",
"repo.import": "the caller's own import, by id",
"repo.name": "whether a name is free, which a held repository still occupies",
"session.list": "the caller's own sessions",
"team.people": "a team's members",
}
func TestEveryReadAcrossRepositoriesIsMarkedOrExempt(t *testing.T) {
r := fxRegistry(t, fxDeps(t))
for _, d := range r.All() {
if strings.Contains(d.Pattern, "{repo}") || d.Scope == ops.ScopeRepo ||
d.Scope == ops.ScopeFleet || d.Auth == ops.Admin || d.CrossRepo {
continue
}
if _, ok := fxExempt[d.Name]; !ok {
t.Errorf("FAIL: %s reads without a repository in its route and is neither marked CrossRepo nor exempt: "+
"mark it, give it a probe in fxProbes, or add it to fxExempt with the reason", d.Name)
}
}
for name := range fxExempt {
if d, ok := r.Lookup(name); !ok || d.CrossRepo {
t.Errorf("FAIL: %s is exempt but is not a registered unmarked op: drop the entry", name)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A request about a held repository is absent to its owner unless the
// hold admits them, by id as in the list.
func TestSignOffGetHidesAHeldRepository(t *testing.T) {
r := fxRegistry(t, fxDeps(t))
for _, c := range fxCallers {
if c.who == "" || c.who == fxStrang {
continue
}
for repo, want := range map[string]bool{fxPub: true, fxHeld: c.seesHeld, fxLegal: c.seesHold} {
_, err := r.Invoke(ops.WithUser(context.Background(), c.who), "signoff.get",
signOffGetIn{ID: "so-" + repo + "-" + c.who})
_, derr := r.Invoke(ops.WithUser(context.Background(), c.who), "signoff.decide",
signOffDecideIn{ID: "so-" + repo + "-" + c.who, Approve: false})
if !want && derr == nil {
t.Errorf("FAIL: as %q signoff.decide closed a request about %s", c.who, repo)
}
if want != (err == nil) {
t.Errorf("FAIL: as %q signoff.get on a request about %s: err=%v, visible want %v", c.who, repo, err, want)
}
}
}
if !t.Failed() {
t.Log("ok")
}
}
// What a start may be set up on is the repositories its person may see;
// a held one is not offered, whoever the hold shuts out.
func TestSetupChoicesSkipAHeldRepository(t *testing.T) {
d := fxDeps(t)
d.CapsFor = func(string, string) CapSet { return oltp.CapSet("a") }
for _, c := range fxCallers {
if c.who == "" {
continue
}
choices, why := d.setupChoices(c.who, oltp.SetupStart{Name: "botb", Kind: oltp.SetupPush})
got := map[string]bool{}
for _, ch := range choices {
got[ch.Name] = true
}
if c.who == fxOwner && !got[fxPub] {
t.Errorf("FAIL: the probe offers its owner no repository at all, so it proves nothing: %v (%s)", got, why)
}
if (got[fxHeld] && !c.seesHeld) || (got[fxLegal] && !c.seesHold) {
t.Errorf("FAIL: as %q a start is offered a held repository: %v", c.who, got)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A notify row is kept unless it says it is about a repository and
// names one the caller may not see: a team room's mention links /t/...,
// which is no repository's address, and is kept for everybody.
func TestInboxRowsAreWithheldOnlyWhenTheyNameAHeldRepository(t *testing.T) {
d := fxDeps(t)
for _, c := range fxCallers {
if c.who == "" {
continue
}
ok := d.inboxFilter(ops.WithUser(context.Background(), c.who))
for name, tc := range map[string]struct {
m InboxMessage
want bool
}{
"team room mention": {InboxMessage{Workflow: "quarry-mention", Link: "/t/grove/chat"}, true},
"person page": {InboxMessage{Workflow: "quarry-mention", Link: "/people/x"}, true},
"no link, no repository": {InboxMessage{Workflow: "quarry-changelog"}, true},
"repository workflow, no link": {InboxMessage{Workflow: "quarry-mention"}, false},
"repository path, no such one": {InboxMessage{Workflow: "quarry-activity", Link: "/r/nowhere/x"}, false},
"held repository": {InboxMessage{Workflow: "quarry-mention", Link: "/r/" + fxHeld + "/x"}, c.seesHeld},
"held repository, by address": {InboxMessage{Workflow: "quarry-mention", Link: "/r/acme/" + fxHeld + "/x"}, c.seesHeld},
} {
if got := ok(tc.m); got != tc.want {
t.Errorf("FAIL: as %q the %s row is kept=%v, want %v", c.who, name, got, tc.want)
}
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A repository name wins over a namespace of the same name, as the
// router reads /r/A/B: A with B beneath it whenever A names a repository.
func TestALinkIsReadTheWayTheRouterReadsIt(t *testing.T) {
d := fxDeps(t)
d.Repos = NewRepos(map[string]*Repo{
"acme": {Code: "c1"},
fxHeld: {Code: "c2"},
})
book := func() map[string]string { return map[string]string{"acme/" + fxHeld: fxHeld, fxHeld: fxHeld} }
if got := d.repoOfLink("/r/acme/"+fxHeld+"/forum", book); got != "acme" {
t.Errorf("FAIL: /r/acme/%s resolved to %q, want the repository acme (a name always wins)", fxHeld, got)
}
if got := d.repoOfLink("/r/acme/nothing", book); got != "acme" {
t.Errorf("FAIL: /r/acme/nothing resolved to %q", got)
}
d.Repos = NewRepos(map[string]*Repo{fxHeld: {Code: "c2"}})
if got := d.repoOfLink("/r/acme/"+fxHeld+"/forum", book); got != fxHeld {
t.Errorf("FAIL: the address resolved to %q, want %s", got, fxHeld)
}
if !t.Failed() {
t.Log("ok")
}
}
// RFC 0023: a legal hold refuses writes "for everybody, so the evidence
// does not change". The router admits a site admin person to READ a held
// repository, so every command that names one is refused at the registry's
// one Invoke, whatever the surface; only the takedown acts (how a hold is
// lifted) pass. The walk covers every registered command that takes a
// repository, as a site admin person, so one added later is covered too.
func TestLegalHoldRefusesEveryRepositoryCommandForEverybody(t *testing.T) {
d := fxDeps(t)
d.LegalHold = func(repo string) bool { return repo == fxLegal }
r := fxRegistry(t, d)
refused, exempt := 0, 0
var names []string
for _, desc := range r.All() {
if desc.Kind != ops.Command {
continue
}
in := reflect.New(desc.In)
named := false
for i := 0; i < desc.In.NumField(); i++ {
name, _, _ := strings.Cut(desc.In.Field(i).Tag.Get("json"), ",")
if (name == "repo" || name == "name" && desc.Scope == ops.ScopeRepo) && desc.In.Field(i).Type.Kind() == reflect.String {
in.Elem().Field(i).SetString(fxLegal)
named = true
}
}
if !named {
continue
}
if takedownOps[desc.Name] {
exempt++
if err := d.legalHoldGate(ops.WithUser(context.Background(), fxAdmin), desc, in.Elem().Interface()); err != nil {
t.Errorf("FAIL: %s, how a hold is lifted, was refused: %v", desc.Name, err)
}
continue
}
for _, who := range []string{fxAdmin, fxOwner, ""} {
ctx := context.Background()
if who != "" {
ctx = ops.WithUser(ctx, who)
}
_, err := r.Invoke(ctx, desc.Name, in.Elem().Interface())
if !errors.Is(err, ops.ErrForbidden) || !strings.Contains(err.Error(), "legal hold") {
t.Errorf("FAIL: %s as %q on a legal hold answered %v", desc.Name, who, err)
}
}
refused++
names = append(names, desc.Name)
// The same command on a repository that is not held passes the gate.
other := reflect.New(desc.In)
other.Elem().Set(in.Elem())
for i := 0; i < desc.In.NumField(); i++ {
if name, _, _ := strings.Cut(desc.In.Field(i).Tag.Get("json"), ","); name == "repo" || name == "name" && desc.Scope == ops.ScopeRepo {
other.Elem().Field(i).SetString(fxPub)
}
}
if err := d.legalHoldGate(context.Background(), desc, other.Elem().Interface()); err != nil {
t.Errorf("FAIL: %s on a repository that is up was refused by the gate: %v", desc.Name, err)
}
}
if refused < 20 || exempt != 4 {
t.Errorf("FAIL: the walk covered %d commands and %d takedown acts; it should find the whole command set", refused, exempt)
}
if !t.Failed() {
t.Logf("ok: %d commands refused: %v", refused, names)
}
}
// writesNoRepository lists every command that names no repository to the
// legal-hold gate, each with why it writes none. A command is covered one
// of three ways: its input's `repo` (or `name` on a repository-scoped op),
// a declared Op.Writes, or this list. A new command that is none of them
// fails TestEveryCommandDeclaresTheRepositoriesItWrites, so it cannot
// slip past the gate by naming its field differently.
var writesNoRepository = map[string]string{
"account.add": "creates an account",
"account.agent": "an account's agent flag",
"account.answerable": "an account's sign-off answerer",
"account.claim": "claims an invited account",
"account.delete": "removes an account, not a repository",
"account.disable": "an account's state",
"account.email.set": "an account's address",
"account.invite": "invites a person",
"account.invite.withdraw": "withdraws an invitation",
"account.invite.withdraw_lapsed": "withdraws lapsed invitations",
"account.reset": "an account's password",
"agent.ask": "an agent's own setting",
"agent.delete": "ends an agent and its access; a removal must stay possible",
"agent.inherit": "an agent's own setting",
"agent.new": "creates an agent with no access",
"agent.token.reissue": "replaces a token with the same reach",
"agent.token.revoke": "ends a token; a removal must stay possible",
"agent.token.revoke_all": "ends every token; a removal must stay possible",
"attention.read": "the caller's own read mark",
"changelog.announce": "the forge's changelog",
"fleet.bucket.set": "the forge's own bucket",
"fleet.bucket.unset": "the forge's own bucket",
"fleet.exception.clear": "the forge's error journal",
"inbox.mark": "the caller's own inbox",
"me.email.clear": "the caller's own address",
"me.email.confirm": "the caller's own address",
"me.email.set": "the caller's own address",
"me.passwd": "the caller's own password",
"me.prefs.set": "the caller's own preferences",
"me.push.subscribe": "the caller's own device",
"me.push.test": "a test notification to the caller",
"me.push.unsubscribe": "the caller's own device",
"me.signin-link": "a sign-in link for the caller",
"me.sync.token": "mints the caller's own sync token (reach is set elsewhere)",
"ops.alert.test": "a test alert to the operator",
"repo.add": "creates a repository; names none that exists",
"repo.import.confirm": "confirms an import into a repository still being created",
"request.plan": "files a plan and runs nothing; each step is gated when decided",
"session.end": "ends a sign-in session",
"setup.start.discard": "discards a start code",
"setup.start.look": "reads a start code",
"team.create": "creates a team with no repositories",
"team.listed": "a team's listing flag; no repository's state",
"team.text": "a team's title and blurb; no repository's state",
}
func TestEveryCommandDeclaresTheRepositoriesItWrites(t *testing.T) {
d := fxDeps(t)
d.LegalHold = func(repo string) bool { return repo == fxLegal }
r := fxRegistry(t, d)
declared, exempt, byField := 0, 0, 0
seen := map[string]bool{}
for _, desc := range r.All() {
if desc.Kind != ops.Command {
continue
}
field := false
for i := 0; i < desc.In.NumField(); i++ {
n, _, _ := strings.Cut(desc.In.Field(i).Tag.Get("json"), ",")
field = field || n == "repo" || n == "name" && desc.Scope == ops.ScopeRepo
}
why, listed := writesNoRepository[desc.Name]
seen[desc.Name] = true
switch {
case desc.Writes != nil:
declared++
if listed {
t.Errorf("FAIL: %s declares its repositories and is also listed as writing none", desc.Name)
}
case field:
byField++
if listed {
t.Errorf("FAIL: %s names its repository in its input and is also listed as writing none", desc.Name)
}
case listed:
exempt++
if strings.TrimSpace(why) == "" {
t.Errorf("FAIL: %s is exempt with no reason", desc.Name)
}
default:
t.Errorf("FAIL: command %s declares no repositories (Op.Writes), names none in `repo`, and is not in writesNoRepository", desc.Name)
}
}
for name := range writesNoRepository {
if !seen[name] {
t.Errorf("FAIL: writesNoRepository lists %q, which is no command", name)
}
}
t.Logf("ok: %d by field, %d declared, %d exempt", byField, declared, exempt)
}
// The declared commands refuse on a legal hold for everybody, whichever
// way they reach it: a list, a team's repositories, a request's id, a mark.
func TestDeclaredCommandsRefuseOnALegalHold(t *testing.T) {
d := fxDeps(t)
d.LegalHold = func(repo string) bool { return repo == fxLegal }
r := fxRegistry(t, d)
cases := map[string]any{
"agent.setup": agentSetupIn{Name: "x", Kind: "read", Repos: fxPub + "," + fxLegal},
"agent.token.new": agentTokenNewIn{Agent: "bota", Repos: fxLegal},
"agent.token.repos": agentTokenReposIn{Agent: "bota", ID: "1", Repos: fxLegal},
"setup.start.claim": setupClaimIn{Code: "c", Repos: fxLegal},
"signoff.decide": signOffDecideIn{ID: "so-" + fxLegal + "-" + fxAdmin},
"avatar.set": avatarSetIn{Kind: "repo", Name: fxLegal, Body: "x"},
"avatar.clear": avatarClearIn{Kind: "repo", Name: fxLegal},
"team.delete": teamDeleteIn{Name: "grove", Confirm: "grove"},
"team.private": teamPrivateIn{Name: "grove", Private: true},
"team.member": teamMemberIn{Name: "grove", Account: fxStrang},
"team.unmember": teamMemberIn{Name: "grove", Account: fxStrang},
}
for name, in := range cases {
desc, ok := r.Lookup(name)
if !ok {
t.Errorf("FAIL: no command %s", name)
continue
}
for _, who := range []string{fxAdmin, fxOwner} {
ctx := ops.WithUser(context.Background(), who)
if _, err := r.Invoke(ctx, name, in); !errors.Is(err, ops.ErrForbidden) || !strings.Contains(fmt.Sprint(err), "legal hold") {
t.Errorf("FAIL: %s as %s on a legal hold answered %v", name, who, err)
}
}
_ = desc
}
// A name that is not held passes the gate.
desc, _ := r.Lookup("avatar.clear")
if err := d.legalHoldGate(context.Background(), desc, avatarClearIn{Kind: "repo", Name: fxPub}); err != nil {
t.Errorf("FAIL: a mark on a repository that is up was refused: %v", err)
}
if err := d.legalHoldGate(context.Background(), desc, avatarClearIn{Kind: "team", Name: fxLegal}); err != nil {
t.Errorf("FAIL: a team mark was refused for sharing a name: %v", err)
}
if !t.Failed() {
t.Log("ok")
}
}