oficina / docs Public

WIP: tests for the link move against databases main left behind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 992a428ef0e63bff1059c54f8fbb0a7929cb6a2a parent 4bbffa7
1 file changed, +612 −0
  • internal/docs/home_links_move_test.go +612 −0
diff --git a/internal/docs/home_links_move_test.go b/internal/docs/home_links_move_test.go
new file mode 100644
index 0000000..e75c969
--- /dev/null
+++ b/internal/docs/home_links_move_test.go
@@ -0,0 +1,612 @@
+package docs
+
+// The one-time move of Docs' own Home links onto home/connect
+// (home_links_move.go), against databases as main (7c9122f) left them:
+// team mode off, as on docs.oficina.works, and on, as on a team instance.
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "net/http"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ connectlinks "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "github.com/carlosframework/docs/internal/docs/principalstore"
+)
+
+// legacyLinks is a database main left behind, holding links, and the
+// configuration to boot it with.
+type legacyLinks struct {
+ t *testing.T
+ cfg Config
+ team bool
+ fix *teamRouterFixture // the keys that sign assertions for cfg
+ ledger []ledgerRow
+ high int64 // docs_link_clock's high-water mark
+ // People: Paul (linked, owns "Paul's plan"), Bob (linked, owns "Bob's
+ // notes"), Carol (local only). In team mode also a Home-only member
+ // (owns "Home-only notes"), which main made through principalstore.
+ paul, bob, carol, homeOnly int64
+ // tokens are sessions main minted, by who holds them.
+ tokens map[string]string
+}
+
+var (
+ paulSubject = teamSubject('a')
+ bobSubject = teamSubject('b')
+ homeOnlySubject = teamSubject('c')
+)
+
+// newLegacyLinks builds the database at a fresh path. Team mode on, it is
+// legacyTeamDatabase (main's schema, the old team set and its marker);
+// off, main's schema alone. Either way the rows are written as main's code
+// wrote them, with SQL, since that code is gone.
+func newLegacyLinks(t *testing.T, team bool) *legacyLinks {
+ t.Helper()
+ f := newTeamRouterFixture(t)
+ l := &legacyLinks{t: t, cfg: f.cfg, team: team, fix: f, tokens: map[string]string{}}
+ l.cfg.DBPath = filepath.Join(t.TempDir(), "legacy.db")
+ if team {
+ legacyTeamDatabase(t, l.cfg.DBPath, "", roster.Bindings{Issuer: bridgeIssuer, Directory: "https://home.example", Consumer: "router-docs", App: "docs", Team: "TeamA", Audience: bridgeOrigin})
+ } else {
+ l.cfg.Team = nil
+ l.cfg.AllowedAddresses = "paul@tito.io,bob@example.com,carol@example.com"
+ }
+ d, err := db.Open(l.cfg.DBPath, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ if !team {
+ if _, err = migrate.Apply(t.Context(), d, mainBootSchema); err != nil {
+ t.Fatal(err)
+ }
+ }
+ w := d.Writer()
+ person := func(address string) int64 {
+ r, err := w.Exec(`INSERT INTO people(email,created_at) VALUES(?,CURRENT_TIMESTAMP)`, address)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id, _ := r.LastInsertId()
+ return id
+ }
+ document := func(owner int64, sqid, title string) {
+ if _, err := w.Exec(`INSERT INTO documents(sqid,title,guid,client_id,created_at,updated_at,owner_id) VALUES(?,?,?,1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,?)`, sqid, title, "guid-"+sqid, owner); err != nil {
+ t.Fatal(err)
+ }
+ }
+ l.paul, l.bob, l.carol = person("paul@tito.io"), person("bob@example.com"), person("carol@example.com")
+ document(l.paul, "paulplan", "Paul's plan")
+ document(l.bob, "bobnotes", "Bob's notes")
+ for subject, id := range map[string]int64{paulSubject: l.paul, bobSubject: l.bob} {
+ if _, err = w.Exec(`INSERT INTO docs_identity_links VALUES(?,?,?)`, bridgeIssuer, subject, id); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Ahead of now, within connect's 30-second tolerance: the carried mark
+ // is then visible, since connect's own Sweep at boot writes now.
+ l.high = time.Now().Unix() + 20
+ if _, err = w.Exec(`UPDATE docs_link_clock SET high_water=? WHERE id=1`, l.high); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = w.Exec(`INSERT INTO docs_link_flows VALUES('in-flight','init',?,x'00')`, time.Now().Unix()+300); err != nil {
+ t.Fatal(err)
+ }
+ if team {
+ // principalstore.EnsureHome, as main ran it.
+ l.homeOnly = principalstore.HomeIDMin
+ for _, q := range []string{
+ fmt.Sprintf(`UPDATE docs_home_allocator SET high_water=%d WHERE singleton=1`, l.homeOnly),
+ fmt.Sprintf(`INSERT INTO docs_principals VALUES(%d,'home',CURRENT_TIMESTAMP)`, l.homeOnly),
+ fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, homeOnlySubject, l.homeOnly),
+ } {
+ if _, err = w.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ document(l.homeOnly, "homeonly", "Home-only notes")
+ }
+ store, err := sessions.New(sessions.Config{DB: w, Origin: bridgeOrigin})
+ if err != nil {
+ t.Fatal(err)
+ }
+ mint := func(name, subject, method string) {
+ token, err := store.Mint(sessions.Session{Subject: subject, Method: method, AuthTime: time.Now().Add(-time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ l.tokens[name] = token
+ }
+ mint("paul", paulSubject, "home-assertion")
+ mint("bob", bobSubject, "home-assertion")
+ mint("carol", "carol@example.com", "magiclink")
+ if team {
+ mint("homeOnly", homeOnlySubject, "home-assertion")
+ }
+ l.ledger = readLedger(t, w)
+ return l
+}
+
+// boot is New on the database, as a fixture whose browsers sign
+// assertions with the configured key.
+func (l *legacyLinks) boot() *routerHomeFixture {
+ l.t.Helper()
+ app, err := New(l.cfg)
+ if err != nil {
+ l.t.Fatal("a database main left behind did not boot:", err)
+ }
+ l.t.Cleanup(func() { app.Close() })
+ sess, err := sessions.New(sessions.Config{DB: app.db.Writer(), Origin: bridgeOrigin})
+ if err != nil {
+ l.t.Fatal(err)
+ }
+ return &routerHomeFixture{app: app, key: l.fix.key, keyID: l.fix.keyID, sessions: sess}
+}
+
+// holding is a browser holding a session main minted.
+func (l *legacyLinks) holding(f *routerHomeFixture, name string) *routerBrowser {
+ b := f.browser()
+ b.cookies[f.sessions.CookieName()] = &http.Cookie{Name: f.sessions.CookieName(), Value: l.tokens[name]}
+ return b
+}
+
+func tableNamed(t *testing.T, q *sql.DB, name string) bool {
+ t.Helper()
+ var n int
+ if err := q.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE name=?`, name).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n == 1
+}
+
+type linkRow struct {
+ Issuer, Subject string
+ Person int64
+ Binding string
+}
+
+func connectLinks(t *testing.T, q *sql.DB) []linkRow {
+ t.Helper()
+ rows, err := q.Query(`SELECT issuer, subject, person_id, person_binding FROM home_identity_links ORDER BY subject`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []linkRow
+ for rows.Next() {
+ var r linkRow
+ if err := rows.Scan(&r.Issuer, &r.Subject, &r.Person, &r.Binding); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+func oldLinks(t *testing.T, q *sql.DB) []linkRow {
+ t.Helper()
+ rows, err := q.Query(`SELECT issuer, subject, person_id FROM docs_identity_links ORDER BY subject`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []linkRow
+ for rows.Next() {
+ var r linkRow
+ if err := rows.Scan(&r.Issuer, &r.Subject, &r.Person); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+func linkClock(t *testing.T, q *sql.DB, table string) int64 {
+ t.Helper()
+ var high int64
+ if err := q.QueryRow(`SELECT high_water FROM ` + table + ` WHERE id=1`).Scan(&high); err != nil {
+ t.Fatal(err)
+ }
+ return high
+}
+
+// schemaDump is every object in the database, as SQLite stores it.
+func schemaDump(t *testing.T, q *sql.DB) []string {
+ t.Helper()
+ rows, err := q.Query(`SELECT type||' '||name||' ON '||tbl_name||': '||COALESCE(sql,'') FROM sqlite_master ORDER BY type, name`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var s string
+ if err := rows.Scan(&s); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, s)
+ }
+ return out
+}
+
+// requireMoved: the old tables are gone, every link is in connect's table
+// with a binding, for the same person, the clock is carried, and the
+// ledger is main's plus only what is new.
+func (l *legacyLinks) requireMoved(f *routerHomeFixture) {
+ t := l.t
+ t.Helper()
+ w := f.app.db.Writer()
+ for _, table := range []string{"docs_identity_links", "docs_link_flows", "docs_link_clock"} {
+ if tableNamed(t, w, table) {
+ t.Fatal("the old table is still there:", table)
+ }
+ }
+ got := connectLinks(t, w)
+ if len(got) != 2 || got[0].Subject != paulSubject || got[0].Person != l.paul || got[1].Subject != bobSubject || got[1].Person != l.bob {
+ t.Fatalf("links not carried: %+v", got)
+ }
+ for _, r := range got {
+ if r.Issuer != bridgeIssuer || len(r.Binding) != 64 {
+ t.Fatalf("link carried without a binding: %+v", r)
+ }
+ }
+ if high := linkClock(t, w, "home_link_clock"); high != l.high {
+ t.Fatal("the link clock was not carried", high, l.high)
+ }
+ schema, mainSchema := BootSchema, mainBootSchema
+ if l.team {
+ schema, mainSchema = TeamBootSchema, migrate.Merge(mainBootSchema, principalstore.Schema, teamState.Schema())
+ }
+ requireLedgerKept(t, l.ledger, readLedger(t, w), schema, mainSchema)
+}
+
+// requireSignsIn: the session main minted for name still signs in, as the
+// same person, and sees their document.
+func (l *legacyLinks) requireSignsIn(f *routerHomeFixture, name, title string) {
+ l.t.Helper()
+ page := l.holding(f, name).do("GET", "/", "")
+ if page.Code != 200 || !strings.Contains(page.Body.String(), title) {
+ l.t.Fatalf("%s's session did not survive the move: %d", name, page.Code)
+ }
+}
+
+// Paul's docs.oficina.works: Home sign-in, team mode off. His account and
+// Bob's are linked; Carol's is local. After the move every link resolves,
+// every session main minted still signs in as the same person, and a new
+// Home sign-in reaches the same account.
+func TestLinksMoveOntoConnectWithTeamModeOff(t *testing.T) {
+ l := newLegacyLinks(t, false)
+ f := l.boot()
+ l.requireMoved(f)
+ l.requireSignsIn(f, "paul", "Paul&#39;s plan")
+ l.requireSignsIn(f, "bob", "Bob&#39;s notes")
+ l.requireSignsIn(f, "carol", "")
+ if page := l.holding(f, "paul").do("GET", "/", ""); strings.Contains(page.Body.String(), "Bob&#39;s notes") {
+ t.Fatal("Paul's session reached Bob's document")
+ }
+ fresh := f.browser()
+ nonce := fresh.start(t, "/auth/start?return_to=%2F", "")
+ routerRedirect(t, fresh.exchange(t, nonce, paulSubject, time.Now().Add(-time.Minute)), "/")
+ if page := fresh.do("GET", "/", ""); page.Code != 200 || !strings.Contains(page.Body.String(), "Paul&#39;s plan") {
+ t.Fatal("a new Home sign-in did not reach Paul's account", page.Code)
+ }
+ // The menu still knows Paul is linked when he signs in by email.
+ local := f.browser()
+ local.localSignin(t, "paul@tito.io")
+ if local.menuOffersConnect(t) {
+ t.Fatal("a linked account is offered Connect again")
+ }
+}
+
+// A team instance: links, a Home-only member, the marker. The disjointness
+// triggers now name connect's table, and the Home-only member still signs
+// in through connect's HomeOnly hook.
+func TestLinksMoveOntoConnectWithTeamModeOn(t *testing.T) {
+ l := newLegacyLinks(t, true)
+ f := l.boot()
+ l.requireMoved(f)
+ l.requireSignsIn(f, "paul", "Paul&#39;s plan")
+ l.requireSignsIn(f, "bob", "Bob&#39;s notes")
+ l.requireSignsIn(f, "homeOnly", "Home-only notes")
+ w := f.app.db.Writer()
+ triggers := map[string]string{}
+ rows, err := w.Query(`SELECT name, tbl_name, sql FROM sqlite_master WHERE type='trigger' AND (sql LIKE '%identity_links%')`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for rows.Next() {
+ var name, table, body string
+ if err := rows.Scan(&name, &table, &body); err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(body, "docs_identity_links") {
+ t.Fatal("a trigger still names the old table:", name)
+ }
+ triggers[name] = table
+ }
+ rows.Close()
+ want := map[string]string{"docs_home_identity_unique": "docs_home_identities", "docs_local_identity_unique": "home_identity_links", "docs_home_links_keep_update": "home_identity_links", "docs_home_links_keep_delete": "home_identity_links"}
+ if !reflect.DeepEqual(triggers, want) {
+ t.Fatalf("triggers not re-pointed: %v", triggers)
+ }
+ // They hold: a Home-only subject cannot be linked, nor a linked one
+ // become Home-only, and a link cannot change.
+ for _, q := range []string{
+ fmt.Sprintf(`INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('%s','%s',%d)`, bridgeIssuer, homeOnlySubject, l.carol),
+ fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, paulSubject, l.homeOnly),
+ `UPDATE home_identity_links SET person_id=person_id`,
+ `DELETE FROM home_identity_links`,
+ } {
+ if _, err := w.Exec(q); err == nil {
+ t.Fatal("accepted:", q)
+ }
+ }
+ // Bob's link gives his local sign-in his team standing, as before.
+ local := f.browser()
+ local.localSignin(t, "bob@example.com")
+ if page := local.do("POST", "/documents", "title=Made+by+a+member"); page.Code != 303 {
+ t.Fatal("a linked member signing in by email lost the team rung", page.Code)
+ }
+}
+
+// A second boot finds nothing to move and changes nothing.
+func TestLinksMoveIsANoOpOnceDone(t *testing.T) {
+ for _, team := range []bool{false, true} {
+ t.Run(fmt.Sprint("team=", team), func(t *testing.T) {
+ l := newLegacyLinks(t, team)
+ f := l.boot()
+ w := f.app.db.Writer()
+ schema, links, high, ledger := schemaDump(t, w), connectLinks(t, w), linkClock(t, w, "home_link_clock"), readLedger(t, w)
+ if err := f.app.Close(); err != nil {
+ t.Fatal(err)
+ }
+ again := l.boot()
+ w = again.app.db.Writer()
+ if !reflect.DeepEqual(schema, schemaDump(t, w)) || !reflect.DeepEqual(links, connectLinks(t, w)) || high != linkClock(t, w, "home_link_clock") || !reflect.DeepEqual(ledger, readLedger(t, w)) {
+ t.Fatal("a second boot changed the database")
+ }
+ if err := moveLinksOntoConnect(t.Context(), w, adoptFunc(func(context.Context, *sql.Tx, string, string, int64) error {
+ t.Fatal("a move with nothing to move adopted a row")
+ return nil
+ })); err != nil {
+ t.Fatal(err)
+ }
+ l.requireSignsIn(again, "paul", "Paul&#39;s plan")
+ })
+ }
+}
+
+type adoptFunc func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error
+
+func (f adoptFunc) Adopt(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
+ return f(ctx, tx, issuer, subject, person)
+}
+
+// openLegacy is the database with this code's schema applied and connect's
+// Bridge over it, the move not yet run: the state New is in just before it.
+func (l *legacyLinks) openLegacy() (*db.DB, *homeRoutes) {
+ l.t.Helper()
+ d, err := db.Open(l.cfg.DBPath, nil)
+ if err != nil {
+ l.t.Fatal(err)
+ }
+ l.t.Cleanup(func() { d.Close() })
+ schema := BootSchema
+ if l.team {
+ schema = TeamBootSchema
+ }
+ if _, err = migrate.Apply(l.t.Context(), d, schema); err != nil {
+ l.t.Fatal(err)
+ }
+ settings, err := validatedHomeConfig(l.cfg.Home, bridgeOrigin)
+ if err != nil {
+ l.t.Fatal(err)
+ }
+ h, err := newHome(settings, bridgeOrigin, d.Writer(), &Store{db: d.G}, l.team)
+ if err != nil {
+ l.t.Fatal(err)
+ }
+ return d, h
+}
+
+// A move that stops partway, by an error or a cancelled context, leaves
+// the database as it found it, and the next attempt redoes all of it.
+func TestLinksMoveThatStopsPartwayLeavesTheOldState(t *testing.T) {
+ l := newLegacyLinks(t, true)
+ d, h := l.openLegacy()
+ w := d.Writer()
+ before, rows, clock := schemaDump(t, w), oldLinks(t, w), linkClock(t, w, "docs_link_clock")
+ newClock := linkClock(t, w, "home_link_clock")
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ for name, stop := range map[string]func(context.Context, *sql.Tx, string, string, int64) error{
+ "storage": func(context.Context, *sql.Tx, string, string, int64) error { return connectlinks.ErrStorage },
+ "cancelled": func(context.Context, *sql.Tx, string, string, int64) error {
+ cancel()
+ return context.Canceled
+ },
+ } {
+ adopted := 0
+ err := moveLinksOntoConnect(ctx, w, adoptFunc(func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
+ if adopted++; adopted == 2 {
+ return stop(ctx, tx, issuer, subject, person)
+ }
+ return h.bridge.Adopt(ctx, tx, issuer, subject, person)
+ }))
+ if !errors.Is(err, errLinksUnavailable) || adopted != 2 {
+ t.Fatal(name, "move did not stop", err, adopted)
+ }
+ if !reflect.DeepEqual(before, schemaDump(t, w)) || !reflect.DeepEqual(rows, oldLinks(t, w)) || clock != linkClock(t, w, "docs_link_clock") || newClock != linkClock(t, w, "home_link_clock") || len(connectLinks(t, w)) != 0 {
+ t.Fatal(name, "a stopped move left a half state")
+ }
+ }
+ if err := moveLinksOntoConnect(t.Context(), w, h.bridge); err != nil {
+ t.Fatal("the redo failed", err)
+ }
+ if got := connectLinks(t, w); len(got) != 2 || tableNamed(t, w, "docs_identity_links") {
+ t.Fatal("the redo did not move everything", got)
+ }
+}
+
+// A link connect refuses (here, from an issuer Docs no longer trusts)
+// aborts the whole move: Docs does not start, and no row is dropped.
+func TestLinksMoveAbortsOnARefusedLink(t *testing.T) {
+ for _, team := range []bool{false, true} {
+ t.Run(fmt.Sprint("team=", team), func(t *testing.T) {
+ l := newLegacyLinks(t, team)
+ d, err := db.Open(l.cfg.DBPath, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = d.Writer().Exec(`INSERT INTO docs_identity_links VALUES('https://old-id.example',?,?)`, "opaque-carol", l.carol); err != nil {
+ t.Fatal(err)
+ }
+ rows := oldLinks(t, d.Writer())
+ d.Close()
+ if app, err := New(l.cfg); !errors.Is(err, errLinksRefused) {
+ if app != nil {
+ app.Close()
+ }
+ t.Fatal("a refused link did not stop the boot", err)
+ }
+ d, h := l.openLegacy()
+ w := d.Writer()
+ if !reflect.DeepEqual(rows, oldLinks(t, w)) || len(rows) != 3 || len(connectLinks(t, w)) != 0 || !tableNamed(t, w, "docs_link_clock") {
+ t.Fatal("a refused move dropped or moved rows")
+ }
+ if err := moveLinksOntoConnect(t.Context(), w, h.bridge); !errors.Is(err, errLinksRefused) || !strings.Contains(err.Error(), fmt.Sprintf("person %d", l.carol)) {
+ t.Fatal("the refusal does not name the person", err)
+ }
+ })
+ }
+}
+
+// In a team database the re-pointed disjointness trigger guards every
+// adopted row, inside Adopt's own insert. A subject that is both linked
+// and Home-only (main's triggers forbade it; here it is forced) is a
+// RAISE, which connect reports as ErrStorage, not ErrRefused (Fable, home
+// #99 note 7): the move still aborts and leaves everything as it was.
+func TestLinksMoveAbortsWhenTheDisjointnessTriggerRefuses(t *testing.T) {
+ l := newLegacyLinks(t, true)
+ d, err := db.Open(l.cfg.DBPath, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var trigger string
+ if err = d.Writer().QueryRow(`SELECT sql FROM sqlite_master WHERE name='docs_home_identity_unique'`).Scan(&trigger); err != nil {
+ t.Fatal(err)
+ }
+ for _, q := range []string{
+ `DROP TRIGGER docs_home_identity_unique`,
+ fmt.Sprintf(`UPDATE docs_home_allocator SET high_water=%d WHERE singleton=1`, l.homeOnly+1),
+ fmt.Sprintf(`INSERT INTO docs_principals VALUES(%d,'home',CURRENT_TIMESTAMP)`, l.homeOnly+1),
+ fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, bobSubject, l.homeOnly+1),
+ trigger,
+ } {
+ if _, err = d.Writer().Exec(q); err != nil {
+ t.Fatal(q, err)
+ }
+ }
+ d.Close()
+ if app, err := New(l.cfg); err == nil || errors.Is(err, errLinksRefused) || !errors.Is(err, errLinksUnavailable) {
+ if app != nil {
+ app.Close()
+ }
+ t.Fatal("the trigger's refusal did not abort as a storage failure", err)
+ }
+ d, h := l.openLegacy()
+ w := d.Writer()
+ var refusal error
+ err = moveLinksOntoConnect(t.Context(), w, adoptFunc(func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
+ err := h.bridge.Adopt(ctx, tx, issuer, subject, person)
+ if subject == bobSubject {
+ refusal = err
+ }
+ return err
+ }))
+ if !errors.Is(refusal, connectlinks.ErrStorage) || !errors.Is(err, errLinksUnavailable) {
+ t.Fatal("the re-pointed trigger did not fire inside Adopt", refusal, err)
+ }
+ if len(oldLinks(t, w)) != 2 || len(connectLinks(t, w)) != 0 {
+ t.Fatal("an aborted move changed the links")
+ }
+ var table string
+ if err = w.QueryRow(`SELECT tbl_name FROM sqlite_master WHERE name='docs_local_identity_unique'`).Scan(&table); err != nil || table != "docs_identity_links" {
+ t.Fatal("an aborted move kept the re-pointed triggers", table, err)
+ }
+}
+
+// LookupPerson is a plain read of people: it neither asks the roster nor
+// the allowlist, so the move succeeds with the roster unknown (the
+// directory down from the first fetch) and with an empty allowlist.
+func TestLinksMoveNeedsNeitherTheRosterNorTheAllowlist(t *testing.T) {
+ l := newLegacyLinks(t, true)
+ l.fix.directory.change(nil, true)
+ l.cfg.AllowedAddresses = "nobody@example.com"
+ f := l.boot()
+ l.requireMoved(f)
+ for _, id := range []int64{l.paul, l.bob} {
+ if _, err := linkedAddress(t.Context(), f.app.db.Writer(), id); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := linkedAddress(t.Context(), f.app.db.Writer(), l.homeOnly); !errors.Is(err, sql.ErrNoRows) {
+ t.Fatal("a Home-only principal has an address", err)
+ }
+}
+
+// A database that moved its links with team mode off can still turn team
+// mode on later: principalstore's first migration needs the old table, so
+// linkstore.ForPrincipals puts it back, empty, and the move re-points the
+// triggers and drops it again. The links and Paul's session survive.
+func TestTeamModeTurnedOnAfterTheMove(t *testing.T) {
+ l := newLegacyLinks(t, false)
+ f := l.boot()
+ l.requireMoved(f)
+ links := connectLinks(t, f.app.db.Writer())
+ if err := f.app.Close(); err != nil {
+ t.Fatal(err)
+ }
+ l.cfg.Team = l.fix.cfg.Team
+ l.team = true
+ team := l.boot()
+ w := team.app.db.Writer()
+ if tableNamed(t, w, "docs_identity_links") || !reflect.DeepEqual(links, connectLinks(t, w)) {
+ t.Fatal("turning team mode on lost or kept the wrong tables")
+ }
+ var table string
+ if err := w.QueryRow(`SELECT tbl_name FROM sqlite_master WHERE name='docs_local_identity_unique'`).Scan(&table); err != nil || table != "home_identity_links" {
+ t.Fatal("the triggers were not re-pointed", table, err)
+ }
+ l.requireSignsIn(team, "paul", "Paul&#39;s plan")
+}
+
+// The resolver gives team standing only for a link connect would resolve:
+// one made for another address (its binding no longer matches) signs
+// nobody in, so it is not a Home identity for the local account either.
+func TestTeamStandingNeedsALinkConnectResolves(t *testing.T) {
+ f := newTeamRouterFixture(t)
+ w := f.app.db.Writer()
+ if _, err := w.Exec(`INSERT INTO home_identity_links(issuer,subject,person_id,person_binding) VALUES(?,?,?,?)`, bridgeIssuer, teamSubject('a'), f.alice, strings.Repeat("0", 64)); err != nil {
+ t.Fatal(err)
+ }
+ b := f.browser()
+ b.localSignin(t, "alice@example.com")
+ if page := b.do("POST", "/documents", "title=Team+rung"); page.Code == 303 {
+ t.Fatal("a link connect refuses gave team standing")
+ }
+ if _, err := f.app.store.team.home.bridge.Resolve(t.Context(), teamSubject('a')); !errors.Is(err, connectlinks.ErrRefused) {
+ t.Fatal("fixture: connect resolved the stale link", err)
+ }
+}