oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3// The one-time move of Docs' own Home links onto home/connect
4// (home_links_move.go), against databases as main (7c9122f) left them:
5// team mode off, as on docs.oficina.works, and on, as on a team instance.
6
7import (
8 "context"
9 "database/sql"
10 "errors"
11 "fmt"
12 "net/http"
13 "path/filepath"
14 "reflect"
15 "strings"
16 "testing"
17 "time"
18
19 connectlinks "amadan.net/oficina/home/connect/linkstore"
20 "amadan.net/oficina/home/roster"
21 "amadan.net/rastrillo/rastrillo/db"
22 "amadan.net/rastrillo/rastrillo/migrate"
23 "amadan.net/rastrillo/rastrillo/sessions"
24 "github.com/carlosframework/docs/internal/docs/principalstore"
25)
26
27// legacyLinks is a database main left behind, holding links, and the
28// configuration to boot it with.
29type legacyLinks struct {
30 t *testing.T
31 cfg Config
32 team bool
33 fix *teamRouterFixture // the keys that sign assertions for cfg
34 ledger []ledgerRow
35 high int64 // docs_link_clock's high-water mark
36 // People: Paul (linked, owns "Paul's plan"), Bob (linked, owns "Bob's
37 // notes"), Carol (local only). In team mode also a Home-only member
38 // (owns "Home-only notes"), which main made through principalstore.
39 paul, bob, carol, homeOnly int64
40 // tokens are sessions main minted, by who holds them.
41 tokens map[string]string
42}
43
44var (
45 paulSubject = teamSubject('a')
46 bobSubject = teamSubject('b')
47 homeOnlySubject = teamSubject('c')
48)
49
50// newLegacyLinks builds the database at a fresh path. Team mode on, it is
51// legacyTeamDatabase (main's schema, the old team set and its marker);
52// off, main's schema alone. Either way the rows are written as main's code
53// wrote them, with SQL, since that code is gone.
54func newLegacyLinks(t *testing.T, team bool) *legacyLinks {
55 t.Helper()
56 f := newTeamRouterFixture(t)
57 l := &legacyLinks{t: t, cfg: f.cfg, team: team, fix: f, tokens: map[string]string{}}
58 l.cfg.DBPath = filepath.Join(t.TempDir(), "legacy.db")
59 if team {
60 legacyTeamDatabase(t, l.cfg.DBPath, "", roster.Bindings{Issuer: bridgeIssuer, Directory: "https://home.example", Consumer: "router-docs", App: "docs", Team: "TeamA", Audience: bridgeOrigin})
61 } else {
62 l.cfg.Team = nil
63 l.cfg.AllowedAddresses = "paul@tito.io,bob@example.com,carol@example.com"
64 }
65 d, err := db.Open(l.cfg.DBPath, nil)
66 if err != nil {
67 t.Fatal(err)
68 }
69 defer d.Close()
70 if !team {
71 if _, err = migrate.Apply(t.Context(), d, mainBootSchema); err != nil {
72 t.Fatal(err)
73 }
74 }
75 w := d.Writer()
76 person := func(address string) int64 {
77 r, err := w.Exec(`INSERT INTO people(email,created_at) VALUES(?,CURRENT_TIMESTAMP)`, address)
78 if err != nil {
79 t.Fatal(err)
80 }
81 id, _ := r.LastInsertId()
82 return id
83 }
84 document := func(owner int64, sqid, title string) {
85 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 {
86 t.Fatal(err)
87 }
88 }
89 l.paul, l.bob, l.carol = person("paul@tito.io"), person("bob@example.com"), person("carol@example.com")
90 document(l.paul, "paulplan", "Paul's plan")
91 document(l.bob, "bobnotes", "Bob's notes")
92 for subject, id := range map[string]int64{paulSubject: l.paul, bobSubject: l.bob} {
93 if _, err = w.Exec(`INSERT INTO docs_identity_links VALUES(?,?,?)`, bridgeIssuer, subject, id); err != nil {
94 t.Fatal(err)
95 }
96 }
97 // Ahead of now, within connect's 30-second tolerance: the carried mark
98 // is then visible, since connect's own Sweep at boot writes now.
99 l.high = time.Now().Unix() + 20
100 if _, err = w.Exec(`UPDATE docs_link_clock SET high_water=? WHERE id=1`, l.high); err != nil {
101 t.Fatal(err)
102 }
103 if _, err = w.Exec(`INSERT INTO docs_link_flows VALUES('in-flight','init',?,x'00')`, time.Now().Unix()+300); err != nil {
104 t.Fatal(err)
105 }
106 if team {
107 // principalstore.EnsureHome, as main ran it.
108 l.homeOnly = principalstore.HomeIDMin
109 for _, q := range []string{
110 fmt.Sprintf(`UPDATE docs_home_allocator SET high_water=%d WHERE singleton=1`, l.homeOnly),
111 fmt.Sprintf(`INSERT INTO docs_principals VALUES(%d,'home',CURRENT_TIMESTAMP)`, l.homeOnly),
112 fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, homeOnlySubject, l.homeOnly),
113 } {
114 if _, err = w.Exec(q); err != nil {
115 t.Fatal(err)
116 }
117 }
118 document(l.homeOnly, "homeonly", "Home-only notes")
119 }
120 store, err := sessions.New(sessions.Config{DB: w, Origin: bridgeOrigin})
121 if err != nil {
122 t.Fatal(err)
123 }
124 mint := func(name, subject, method string) {
125 token, err := store.Mint(sessions.Session{Subject: subject, Method: method, AuthTime: time.Now().Add(-time.Hour)})
126 if err != nil {
127 t.Fatal(err)
128 }
129 l.tokens[name] = token
130 }
131 mint("paul", paulSubject, "home-assertion")
132 mint("bob", bobSubject, "home-assertion")
133 mint("carol", "carol@example.com", "magiclink")
134 if team {
135 mint("homeOnly", homeOnlySubject, "home-assertion")
136 }
137 l.ledger = readLedger(t, w)
138 return l
139}
140
141// boot is New on the database, as a fixture whose browsers sign
142// assertions with the configured key.
143func (l *legacyLinks) boot() *routerHomeFixture {
144 l.t.Helper()
145 app, err := New(l.cfg)
146 if err != nil {
147 l.t.Fatal("a database main left behind did not boot:", err)
148 }
149 l.t.Cleanup(func() { app.Close() })
150 sess, err := sessions.New(sessions.Config{DB: app.db.Writer(), Origin: bridgeOrigin})
151 if err != nil {
152 l.t.Fatal(err)
153 }
154 return &routerHomeFixture{app: app, key: l.fix.key, keyID: l.fix.keyID, sessions: sess}
155}
156
157// holding is a browser holding a session main minted.
158func (l *legacyLinks) holding(f *routerHomeFixture, name string) *routerBrowser {
159 b := f.browser()
160 b.cookies[f.sessions.CookieName()] = &http.Cookie{Name: f.sessions.CookieName(), Value: l.tokens[name]}
161 return b
162}
163
164func tableNamed(t *testing.T, q *sql.DB, name string) bool {
165 t.Helper()
166 var n int
167 if err := q.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE name=?`, name).Scan(&n); err != nil {
168 t.Fatal(err)
169 }
170 return n == 1
171}
172
173type linkRow struct {
174 Issuer, Subject string
175 Person int64
176 Binding string
177}
178
179func connectLinks(t *testing.T, q *sql.DB) []linkRow {
180 t.Helper()
181 rows, err := q.Query(`SELECT issuer, subject, person_id, person_binding FROM home_identity_links ORDER BY subject`)
182 if err != nil {
183 t.Fatal(err)
184 }
185 defer rows.Close()
186 var out []linkRow
187 for rows.Next() {
188 var r linkRow
189 if err := rows.Scan(&r.Issuer, &r.Subject, &r.Person, &r.Binding); err != nil {
190 t.Fatal(err)
191 }
192 out = append(out, r)
193 }
194 return out
195}
196
197func oldLinks(t *testing.T, q *sql.DB) []linkRow {
198 t.Helper()
199 rows, err := q.Query(`SELECT issuer, subject, person_id FROM docs_identity_links ORDER BY subject`)
200 if err != nil {
201 t.Fatal(err)
202 }
203 defer rows.Close()
204 var out []linkRow
205 for rows.Next() {
206 var r linkRow
207 if err := rows.Scan(&r.Issuer, &r.Subject, &r.Person); err != nil {
208 t.Fatal(err)
209 }
210 out = append(out, r)
211 }
212 return out
213}
214
215func linkClock(t *testing.T, q *sql.DB, table string) int64 {
216 t.Helper()
217 var high int64
218 if err := q.QueryRow(`SELECT high_water FROM ` + table + ` WHERE id=1`).Scan(&high); err != nil {
219 t.Fatal(err)
220 }
221 return high
222}
223
224// schemaDump is every object in the database, as SQLite stores it.
225func schemaDump(t *testing.T, q *sql.DB) []string {
226 t.Helper()
227 rows, err := q.Query(`SELECT type||' '||name||' ON '||tbl_name||': '||COALESCE(sql,'') FROM sqlite_master ORDER BY type, name`)
228 if err != nil {
229 t.Fatal(err)
230 }
231 defer rows.Close()
232 var out []string
233 for rows.Next() {
234 var s string
235 if err := rows.Scan(&s); err != nil {
236 t.Fatal(err)
237 }
238 out = append(out, s)
239 }
240 return out
241}
242
243// requireMoved: the old tables are gone, every link is in connect's table
244// with a binding, for the same person, the clock is carried, and the
245// ledger is main's plus only what is new.
246func (l *legacyLinks) requireMoved(f *routerHomeFixture) {
247 t := l.t
248 t.Helper()
249 w := f.app.db.Writer()
250 for _, table := range []string{"docs_identity_links", "docs_link_flows", "docs_link_clock"} {
251 if tableNamed(t, w, table) {
252 t.Fatal("the old table is still there:", table)
253 }
254 }
255 got := connectLinks(t, w)
256 if len(got) != 2 || got[0].Subject != paulSubject || got[0].Person != l.paul || got[1].Subject != bobSubject || got[1].Person != l.bob {
257 t.Fatalf("links not carried: %+v", got)
258 }
259 for _, r := range got {
260 if r.Issuer != bridgeIssuer || len(r.Binding) != 64 {
261 t.Fatalf("link carried without a binding: %+v", r)
262 }
263 }
264 if high := linkClock(t, w, "home_link_clock"); high != l.high {
265 t.Fatal("the link clock was not carried", high, l.high)
266 }
267 schema, mainSchema := BootSchema, mainBootSchema
268 if l.team {
269 schema, mainSchema = TeamBootSchema, migrate.Merge(mainBootSchema, principalstore.Schema, teamState.Schema())
270 }
271 requireLedgerKept(t, l.ledger, readLedger(t, w), schema, mainSchema)
272}
273
274// requireSignsIn: the session main minted for name still signs in, as the
275// same person, and sees their document.
276func (l *legacyLinks) requireSignsIn(f *routerHomeFixture, name, title string) {
277 l.t.Helper()
278 page := l.holding(f, name).do("GET", "/", "")
279 if page.Code != 200 || !strings.Contains(page.Body.String(), title) {
280 l.t.Fatalf("%s's session did not survive the move: %d", name, page.Code)
281 }
282}
283
284// Paul's docs.oficina.works: Home sign-in, team mode off. His account and
285// Bob's are linked; Carol's is local. After the move every link resolves,
286// every session main minted still signs in as the same person, and a new
287// Home sign-in reaches the same account.
288func TestLinksMoveOntoConnectWithTeamModeOff(t *testing.T) {
289 l := newLegacyLinks(t, false)
290 f := l.boot()
291 l.requireMoved(f)
292 l.requireSignsIn(f, "paul", "Paul's plan")
293 l.requireSignsIn(f, "bob", "Bob's notes")
294 l.requireSignsIn(f, "carol", "")
295 if page := l.holding(f, "paul").do("GET", "/", ""); strings.Contains(page.Body.String(), "Bob's notes") {
296 t.Fatal("Paul's session reached Bob's document")
297 }
298 fresh := f.browser()
299 nonce := fresh.start(t, "/auth/start?return_to=%2F", "")
300 routerRedirect(t, fresh.exchange(t, nonce, paulSubject, time.Now().Add(-time.Minute)), "/")
301 if page := fresh.do("GET", "/", ""); page.Code != 200 || !strings.Contains(page.Body.String(), "Paul's plan") {
302 t.Fatal("a new Home sign-in did not reach Paul's account", page.Code)
303 }
304 // The menu still knows Paul is linked when he signs in by email.
305 local := f.browser()
306 local.localSignin(t, "paul@tito.io")
307 if local.menuOffersConnect(t) {
308 t.Fatal("a linked account is offered Connect again")
309 }
310}
311
312// A team instance: links, a Home-only member, the marker. The disjointness
313// triggers now name connect's table, and the Home-only member still signs
314// in through connect's HomeOnly hook.
315func TestLinksMoveOntoConnectWithTeamModeOn(t *testing.T) {
316 l := newLegacyLinks(t, true)
317 f := l.boot()
318 l.requireMoved(f)
319 l.requireSignsIn(f, "paul", "Paul's plan")
320 l.requireSignsIn(f, "bob", "Bob's notes")
321 l.requireSignsIn(f, "homeOnly", "Home-only notes")
322 w := f.app.db.Writer()
323 triggers := map[string]string{}
324 rows, err := w.Query(`SELECT name, tbl_name, sql FROM sqlite_master WHERE type='trigger' AND (sql LIKE '%identity_links%')`)
325 if err != nil {
326 t.Fatal(err)
327 }
328 for rows.Next() {
329 var name, table, body string
330 if err := rows.Scan(&name, &table, &body); err != nil {
331 t.Fatal(err)
332 }
333 if strings.Contains(body, "docs_identity_links") {
334 t.Fatal("a trigger still names the old table:", name)
335 }
336 triggers[name] = table
337 }
338 rows.Close()
339 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"}
340 if !reflect.DeepEqual(triggers, want) {
341 t.Fatalf("triggers not re-pointed: %v", triggers)
342 }
343 // They hold: a Home-only subject cannot be linked, nor a linked one
344 // become Home-only, and a link cannot change.
345 for _, q := range []string{
346 fmt.Sprintf(`INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('%s','%s',%d)`, bridgeIssuer, homeOnlySubject, l.carol),
347 fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, paulSubject, l.homeOnly),
348 `UPDATE home_identity_links SET person_id=person_id`,
349 `DELETE FROM home_identity_links`,
350 } {
351 if _, err := w.Exec(q); err == nil {
352 t.Fatal("accepted:", q)
353 }
354 }
355 // Bob's link gives his local sign-in his team standing, as before.
356 local := f.browser()
357 local.localSignin(t, "bob@example.com")
358 if page := local.do("POST", "/documents", "title=Made+by+a+member"); page.Code != 303 {
359 t.Fatal("a linked member signing in by email lost the team rung", page.Code)
360 }
361}
362
363// A second boot finds nothing to move and changes nothing.
364func TestLinksMoveIsANoOpOnceDone(t *testing.T) {
365 for _, team := range []bool{false, true} {
366 t.Run(fmt.Sprint("team=", team), func(t *testing.T) {
367 l := newLegacyLinks(t, team)
368 f := l.boot()
369 w := f.app.db.Writer()
370 schema, links, high, ledger := schemaDump(t, w), connectLinks(t, w), linkClock(t, w, "home_link_clock"), readLedger(t, w)
371 if err := f.app.Close(); err != nil {
372 t.Fatal(err)
373 }
374 again := l.boot()
375 w = again.app.db.Writer()
376 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)) {
377 t.Fatal("a second boot changed the database")
378 }
379 if err := moveLinksOntoConnect(t.Context(), w, adoptFunc(func(context.Context, *sql.Tx, string, string, int64) error {
380 t.Fatal("a move with nothing to move adopted a row")
381 return nil
382 })); err != nil {
383 t.Fatal(err)
384 }
385 l.requireSignsIn(again, "paul", "Paul's plan")
386 })
387 }
388}
389
390type adoptFunc func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error
391
392func (f adoptFunc) Adopt(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
393 return f(ctx, tx, issuer, subject, person)
394}
395
396// openLegacy is the database with this code's schema applied and connect's
397// Bridge over it, the move not yet run: the state New is in just before it.
398func (l *legacyLinks) openLegacy() (*db.DB, *homeRoutes) {
399 l.t.Helper()
400 d, err := db.Open(l.cfg.DBPath, nil)
401 if err != nil {
402 l.t.Fatal(err)
403 }
404 l.t.Cleanup(func() { d.Close() })
405 schema := BootSchema
406 if l.team {
407 schema = TeamBootSchema
408 }
409 if _, err = migrate.Apply(l.t.Context(), d, schema); err != nil {
410 l.t.Fatal(err)
411 }
412 settings, err := validatedHomeConfig(l.cfg.Home, bridgeOrigin)
413 if err != nil {
414 l.t.Fatal(err)
415 }
416 h, err := newHome(settings, bridgeOrigin, d.Writer(), &Store{db: d.G}, l.team)
417 if err != nil {
418 l.t.Fatal(err)
419 }
420 return d, h
421}
422
423// A move that stops partway, by an error or a cancelled context, leaves
424// the database as it found it, and the next attempt redoes all of it.
425func TestLinksMoveThatStopsPartwayLeavesTheOldState(t *testing.T) {
426 l := newLegacyLinks(t, true)
427 d, h := l.openLegacy()
428 w := d.Writer()
429 before, rows, clock := schemaDump(t, w), oldLinks(t, w), linkClock(t, w, "docs_link_clock")
430 newClock := linkClock(t, w, "home_link_clock")
431 for _, name := range []string{"storage", "cancelled"} {
432 ctx, cancel := context.WithCancel(t.Context())
433 defer cancel()
434 stop := func(context.Context, *sql.Tx, string, string, int64) error { return connectlinks.ErrStorage }
435 if name == "cancelled" {
436 stop = func(context.Context, *sql.Tx, string, string, int64) error {
437 cancel()
438 return context.Canceled
439 }
440 }
441 adopted := 0
442 err := moveLinksOntoConnect(ctx, w, adoptFunc(func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
443 if adopted++; adopted == 2 {
444 return stop(ctx, tx, issuer, subject, person)
445 }
446 return h.bridge.Adopt(ctx, tx, issuer, subject, person)
447 }))
448 if !errors.Is(err, errLinksUnavailable) || adopted != 2 {
449 t.Fatal(name, "move did not stop", err, adopted)
450 }
451 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 {
452 t.Fatal(name, "a stopped move left a half state")
453 }
454 }
455 if err := moveLinksOntoConnect(t.Context(), w, h.bridge); err != nil {
456 t.Fatal("the redo failed", err)
457 }
458 if got := connectLinks(t, w); len(got) != 2 || tableNamed(t, w, "docs_identity_links") {
459 t.Fatal("the redo did not move everything", got)
460 }
461}
462
463// A link connect refuses (here, from an issuer Docs no longer trusts)
464// aborts the whole move: Docs does not start, and no row is dropped.
465func TestLinksMoveAbortsOnARefusedLink(t *testing.T) {
466 for _, team := range []bool{false, true} {
467 t.Run(fmt.Sprint("team=", team), func(t *testing.T) {
468 l := newLegacyLinks(t, team)
469 d, err := db.Open(l.cfg.DBPath, nil)
470 if err != nil {
471 t.Fatal(err)
472 }
473 if _, err = d.Writer().Exec(`INSERT INTO docs_identity_links VALUES('https://old-id.example',?,?)`, "opaque-carol", l.carol); err != nil {
474 t.Fatal(err)
475 }
476 rows := oldLinks(t, d.Writer())
477 d.Close()
478 if app, err := New(l.cfg); !errors.Is(err, errLinksRefused) {
479 if app != nil {
480 app.Close()
481 }
482 t.Fatal("a refused link did not stop the boot", err)
483 }
484 d, h := l.openLegacy()
485 w := d.Writer()
486 if !reflect.DeepEqual(rows, oldLinks(t, w)) || len(rows) != 3 || len(connectLinks(t, w)) != 0 || !tableNamed(t, w, "docs_link_clock") {
487 t.Fatal("a refused move dropped or moved rows")
488 }
489 if err := moveLinksOntoConnect(t.Context(), w, h.bridge); !errors.Is(err, errLinksRefused) || !strings.Contains(err.Error(), fmt.Sprintf("person %d", l.carol)) {
490 t.Fatal("the refusal does not name the person", err)
491 }
492 })
493 }
494}
495
496// In a team database the re-pointed disjointness trigger guards every
497// adopted row, inside Adopt's own insert. A subject that is both linked
498// and Home-only (main's triggers forbade it; here it is forced) is a
499// RAISE, which connect reports as ErrStorage, not ErrRefused (Fable, home
500// #99 note 7): the move still aborts and leaves everything as it was.
501func TestLinksMoveAbortsWhenTheDisjointnessTriggerRefuses(t *testing.T) {
502 l := newLegacyLinks(t, true)
503 d, err := db.Open(l.cfg.DBPath, nil)
504 if err != nil {
505 t.Fatal(err)
506 }
507 var trigger string
508 if err = d.Writer().QueryRow(`SELECT sql FROM sqlite_master WHERE name='docs_home_identity_unique'`).Scan(&trigger); err != nil {
509 t.Fatal(err)
510 }
511 for _, q := range []string{
512 `DROP TRIGGER docs_home_identity_unique`,
513 fmt.Sprintf(`UPDATE docs_home_allocator SET high_water=%d WHERE singleton=1`, l.homeOnly+1),
514 fmt.Sprintf(`INSERT INTO docs_principals VALUES(%d,'home',CURRENT_TIMESTAMP)`, l.homeOnly+1),
515 fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, bobSubject, l.homeOnly+1),
516 trigger,
517 } {
518 if _, err = d.Writer().Exec(q); err != nil {
519 t.Fatal(q, err)
520 }
521 }
522 d.Close()
523 if app, err := New(l.cfg); err == nil || errors.Is(err, errLinksRefused) || !errors.Is(err, errLinksUnavailable) {
524 if app != nil {
525 app.Close()
526 }
527 t.Fatal("the trigger's refusal did not abort as a storage failure", err)
528 }
529 d, h := l.openLegacy()
530 w := d.Writer()
531 var refusal error
532 err = moveLinksOntoConnect(t.Context(), w, adoptFunc(func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
533 err := h.bridge.Adopt(ctx, tx, issuer, subject, person)
534 if subject == bobSubject {
535 refusal = err
536 }
537 return err
538 }))
539 if !errors.Is(refusal, connectlinks.ErrStorage) || !errors.Is(err, errLinksUnavailable) {
540 t.Fatal("the re-pointed trigger did not fire inside Adopt", refusal, err)
541 }
542 if len(oldLinks(t, w)) != 2 || len(connectLinks(t, w)) != 0 {
543 t.Fatal("an aborted move changed the links")
544 }
545 var table string
546 if err = w.QueryRow(`SELECT tbl_name FROM sqlite_master WHERE name='docs_local_identity_unique'`).Scan(&table); err != nil || table != "docs_identity_links" {
547 t.Fatal("an aborted move kept the re-pointed triggers", table, err)
548 }
549}
550
551// LookupPerson is a plain read of people: it neither asks the roster nor
552// the allowlist, so the move succeeds with the roster unknown (the
553// directory down from the first fetch) and with an empty allowlist.
554func TestLinksMoveNeedsNeitherTheRosterNorTheAllowlist(t *testing.T) {
555 l := newLegacyLinks(t, true)
556 l.fix.directory.change(nil, true)
557 l.cfg.AllowedAddresses = "nobody@example.com"
558 f := l.boot()
559 l.requireMoved(f)
560 for _, id := range []int64{l.paul, l.bob} {
561 if _, err := linkedAddress(t.Context(), f.app.db.Writer(), id); err != nil {
562 t.Fatal(err)
563 }
564 }
565 if _, err := linkedAddress(t.Context(), f.app.db.Writer(), l.homeOnly); !errors.Is(err, sql.ErrNoRows) {
566 t.Fatal("a Home-only principal has an address", err)
567 }
568}
569
570// A database that moved its links with team mode off can still turn team
571// mode on later: principalstore's first migration needs the old table, so
572// linkstore.ForPrincipals puts it back, empty, and the move re-points the
573// triggers and drops it again. The links and Paul's session survive.
574func TestTeamModeTurnedOnAfterTheMove(t *testing.T) {
575 l := newLegacyLinks(t, false)
576 f := l.boot()
577 l.requireMoved(f)
578 links := connectLinks(t, f.app.db.Writer())
579 if err := f.app.Close(); err != nil {
580 t.Fatal(err)
581 }
582 l.cfg.Team = l.fix.cfg.Team
583 l.team = true
584 team := l.boot()
585 w := team.app.db.Writer()
586 if tableNamed(t, w, "docs_identity_links") || !reflect.DeepEqual(links, connectLinks(t, w)) {
587 t.Fatal("turning team mode on lost or kept the wrong tables")
588 }
589 var table string
590 if err := w.QueryRow(`SELECT tbl_name FROM sqlite_master WHERE name='docs_local_identity_unique'`).Scan(&table); err != nil || table != "home_identity_links" {
591 t.Fatal("the triggers were not re-pointed", table, err)
592 }
593 l.requireSignsIn(team, "paul", "Paul's plan")
594}
595
596// The resolver gives team standing only for a link connect would resolve:
597// one made for another address (its binding no longer matches) signs
598// nobody in, so it is not a Home identity for the local account either.
599func TestTeamStandingNeedsALinkConnectResolves(t *testing.T) {
600 f := newTeamRouterFixture(t)
601 w := f.app.db.Writer()
602 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 {
603 t.Fatal(err)
604 }
605 b := f.browser()
606 b.localSignin(t, "alice@example.com")
607 if page := b.do("POST", "/documents", "title=Team+rung"); page.Code == 303 {
608 t.Fatal("a link connect refuses gave team standing")
609 }
610 if _, err := f.app.store.team.home.bridge.Resolve(t.Context(), teamSubject('a')); !errors.Is(err, connectlinks.ErrRefused) {
611 t.Fatal("fixture: connect resolved the stale link", err)
612 }
613 // Nor does a Home session for that subject sign in as Alice.
614 token, err := f.sessions.Mint(sessions.Session{Subject: teamSubject('a'), Method: "home-assertion", AuthTime: time.Now()})
615 if err != nil {
616 t.Fatal(err)
617 }
618 home := f.browser()
619 home.cookies[f.sessions.CookieName()] = &http.Cookie{Name: f.sessions.CookieName(), Value: token}
620 if page := home.do("GET", "/", ""); page.Code == 200 {
621 t.Fatal("a Home session signed in through a link connect refuses")
622 }
623 // The control: a link connect made does give standing.
624 other := f.browser()
625 other.localSignin(t, "bob@example.com")
626 other.linkProof(t, teamSubject('b'), "bob@example.com")
627 routerRedirect(t, other.do("POST", "/account/home/confirm", ""), connectedURL("/"))
628 if page := other.do("POST", "/documents", "title=Team+rung"); page.Code != 303 {
629 t.Fatal("a link connect made gave no team standing", page.Code)
630 }
631}
632