Keep host tokens bound to a live connection, and drop them atomically
A chat read that outlived a Disconnect or a new Connect could mint a host token for a connection that was gone. Minting now happens in one statement that requires the member's link to be that device, connected (store.MintHostTokenFor), and connection changes and registrations take the same per-member lock. Disconnect, a lost bearer and a new Connect now remove the host token in the same transaction as the link change, and Disconnect fails (503) rather than report success while the token could stay. The Equipo client test builds its fake host token at runtime, and .gitleaksignore lists the one fingerprint for the literal already in 35754ba.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+293
−52
.gitleaksignore+1 −0internal/equipo/equipo_test.go+5 −2internal/equipo/equipotest/chat.go+8 −0internal/equipo/equipotest/fake.go+14 −0internal/store/equipo.go+51 −5internal/store/hosttokens.go+30 −4internal/store/hosttokens_test.go+64 −0internal/web/ask.go+7 −10internal/web/ask_connect.go+40 −31internal/webtest/ask_test.go+73 −0
diff --git a/.gitleaksignore b/.gitleaksignore| new file mode 100644 |
| index 0000000..38c92a0 |
| --- /dev/null |
| +++ b/.gitleaksignore |
| @@ -0,0 +1 @@ |
| +35754bab1193d97a3482d61c31a1920322b8a82b:internal/equipo/equipo_test.go:generic-api-key:209 |
diff --git a/internal/equipo/equipo_test.go b/internal/equipo/equipo_test.go| index b65cf6d..60ee4d5 100644 |
| --- a/internal/equipo/equipo_test.go |
| +++ b/internal/equipo/equipo_test.go |
| @@ -172,7 +172,10 @@ func TestClientUsesAssistantRoutes(t *testing.T) { |
| t.Fatal(err) |
| } |
| res.Body.Close() |
| - if err := c.RegisterHost(ctx, cred.Token, "https://base.example.test", "bh_0123456789abcdefghij"); err != nil { |
| + // A fake host token, built here so no token-shaped literal lands in |
| + // the repository. |
| + hostToken := "bh_" + strings.Repeat("A", 43) |
| + if err := c.RegisterHost(ctx, cred.Token, "https://base.example.test", hostToken); err != nil { |
| t.Fatal(err) |
| } |
| want := map[string]string{ |
| @@ -206,7 +209,7 @@ func TestClientUsesAssistantRoutes(t *testing.T) { |
| } |
| } |
| hosts := f.Hosts() |
| - if len(hosts) != 1 || strings.TrimSpace(hosts[0].Body) != `{"origin":"https://base.example.test","token":"bh_0123456789abcdefghij"}` { |
| + if len(hosts) != 1 || strings.TrimSpace(hosts[0].Body) != `{"origin":"https://base.example.test","token":"`+hostToken+`"}` { |
| t.Fatalf("hosts: %+v", hosts) |
| } |
| } |
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go| index a6efeff..65b942f 100644 |
| --- a/internal/equipo/equipotest/chat.go |
| +++ b/internal/equipo/equipotest/chat.go |
| @@ -248,6 +248,14 @@ func (f *Fake) tail() []message { |
| } |
| func (f *Fake) snapshot(w http.ResponseWriter) { |
| + f.mu.Lock() |
| + hold, entered := f.snapHold, f.snapEntered |
| + f.snapHold, f.snapEntered = nil, nil |
| + f.mu.Unlock() |
| + if hold != nil { |
| + close(entered) |
| + <-hold |
| + } |
| f.cmu.Lock() |
| defer f.cmu.Unlock() |
| turns := []turn{} |
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go| index fd80046..b5a398f 100644 |
| --- a/internal/equipo/equipotest/fake.go |
| +++ b/internal/equipo/equipotest/fake.go |
| @@ -59,6 +59,9 @@ type Fake struct { |
| hold chan struct{} |
| entered chan struct{} |
| failSend bool |
| + // snapHold and snapEntered do for the next snapshot what hold and |
| + // entered do for the next exchange. |
| + snapHold, snapEntered chan struct{} |
| chat |
| } |
| @@ -73,6 +76,17 @@ func (f *Fake) HoldNextExchange() (entered <-chan struct{}, release func()) { |
| return f.entered, func() { close(hold) } |
| } |
| +// HoldNextSnapshot makes the next snapshot wait, once its bearer has |
| +// passed and before it answers, until release is called. entered is |
| +// closed when it arrives. |
| +func (f *Fake) HoldNextSnapshot() (entered <-chan struct{}, release func()) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.snapHold, f.snapEntered = make(chan struct{}), make(chan struct{}) |
| + hold := f.snapHold |
| + return f.snapEntered, func() { close(hold) } |
| +} |
| + |
| // FailNextSend makes the next new message's answer a 503 after Equipo has |
| // recorded it, as when the answer is lost on the way back. |
| func (f *Fake) FailNextSend() { |
diff --git a/internal/store/equipo.go b/internal/store/equipo.go| index 2d445f6..cf612b1 100644 |
| --- a/internal/store/equipo.go |
| +++ b/internal/store/equipo.go |
| @@ -53,13 +53,19 @@ func EquipoLinkFor(ctx context.Context, db *sql.DB, memberID string) (l EquipoLi |
| return l, true, nil |
| } |
| -// SaveEquipoLink stores l as the member's only link, replacing any other. |
| +// SaveEquipoLink stores l as the member's only link, replacing any other, |
| +// and forgets the member's host token in the same transaction: a new |
| +// connection may be another Equipo person, and gets its own once ready. |
| func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| var polled any |
| if l.PolledAt != nil { |
| polled = l.PolledAt.UTC() |
| } |
| - _, err := db.ExecContext(ctx, `INSERT INTO equipo_links (`+equipoCols+`, updated_at) |
| + return inTx(ctx, db, func(tx *sql.Tx) error { |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, l.MemberID); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, `INSERT INTO equipo_links (`+equipoCols+`, updated_at) |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| ON CONFLICT (member_id) DO UPDATE SET origin = excluded.origin, state = excluded.state, |
| device_id = excluded.device_id, user_code = excluded.user_code, |
| @@ -67,9 +73,22 @@ func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| expires_at = excluded.expires_at, revision = excluded.revision, |
| polled_at = excluded.polled_at, person = excluded.person, |
| exchanging_until = NULL, updated_at = excluded.updated_at`, |
| - l.MemberID, l.Origin, l.State, l.DeviceID, l.UserCode, l.VerificationURI, |
| - l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, l.Person, time.Now().UTC()) |
| - return err |
| + l.MemberID, l.Origin, l.State, l.DeviceID, l.UserCode, l.VerificationURI, |
| + l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, l.Person, time.Now().UTC()) |
| + return err |
| + }) |
| +} |
| + |
| +func inTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error { |
| + tx, err := db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if err := fn(tx); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| } |
| // ClaimEquipoPoll claims the right to ask Equipo now whether the member's |
| @@ -121,6 +140,33 @@ func SetEquipoLinkState(ctx context.Context, db *sql.DB, memberID, dev, state st |
| return err |
| } |
| +// LoseEquipoLink records that Equipo refused the bearer of the member's |
| +// device dev, and forgets their host token, in one transaction; it does |
| +// neither if the link has moved on to another device. |
| +func LoseEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error { |
| + return inTx(ctx, db, func(tx *sql.Tx) error { |
| + ok, err := affected(tx.ExecContext(ctx, `UPDATE equipo_links SET state = ?, updated_at = ? WHERE member_id = ? AND device_id = ?`, |
| + EquipoLost, time.Now().UTC(), memberID, dev)) |
| + if err != nil || !ok { |
| + return err |
| + } |
| + _, err = tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID) |
| + return err |
| + }) |
| +} |
| + |
| +// DisconnectEquipo forgets the member's link, if it is still device dev, |
| +// and their host token, in one transaction: both go or neither does. |
| +func DisconnectEquipo(ctx context.Context, db *sql.DB, memberID, dev string) error { |
| + return inTx(ctx, db, func(tx *sql.Tx) error { |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ? AND device_id = ?`, memberID, dev); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID) |
| + return err |
| + }) |
| +} |
| + |
| // SetEquipoPerson records the Equipo address the member's device dev |
| // speaks for, if the link is still that device. |
| func SetEquipoPerson(ctx context.Context, db *sql.DB, memberID, dev, person string) error { |
diff --git a/internal/store/hosttokens.go b/internal/store/hosttokens.go| index 9e12a85..825b6c4 100644 |
| --- a/internal/store/hosttokens.go |
| +++ b/internal/store/hosttokens.go |
| @@ -32,12 +32,11 @@ func hashHostToken(token string) string { |
| // new one counts as not yet registered with Equipo. The token itself is |
| // never stored: hand it straight to Equipo. |
| func MintHostToken(ctx context.Context, db *sql.DB, memberID string) (string, error) { |
| - b := make([]byte, hostTokenBytes) |
| - if _, err := rand.Read(b); err != nil { |
| + token, err := newHostToken() |
| + if err != nil { |
| return "", err |
| } |
| - token := hostTokenPrefix + base64.RawURLEncoding.EncodeToString(b) |
| - _, err := db.ExecContext(ctx, `INSERT INTO host_tokens (member_id, token_hash, created_at) VALUES (?, ?, ?) |
| + _, err = db.ExecContext(ctx, `INSERT INTO host_tokens (member_id, token_hash, created_at) VALUES (?, ?, ?) |
| ON CONFLICT (member_id) DO UPDATE SET token_hash = excluded.token_hash, |
| created_at = excluded.created_at, registered_at = NULL`, |
| memberID, hashHostToken(token), time.Now().UTC()) |
| @@ -47,6 +46,33 @@ func MintHostToken(ctx context.Context, db *sql.DB, memberID string) (string, er |
| return token, nil |
| } |
| +// MintHostTokenFor is MintHostToken for a member whose Equipo link is |
| +// device dev, connected: the check and the mint are one statement, so a |
| +// Disconnect or a new Connect that came first leaves nothing to mint |
| +// (ok false), and one that comes after deletes what was minted. |
| +func MintHostTokenFor(ctx context.Context, db *sql.DB, memberID, dev string) (token string, ok bool, err error) { |
| + if token, err = newHostToken(); err != nil { |
| + return "", false, err |
| + } |
| + res, err := db.ExecContext(ctx, `INSERT INTO host_tokens (member_id, token_hash, created_at) |
| + SELECT ?, ?, ? WHERE EXISTS (SELECT 1 FROM equipo_links WHERE member_id = ? AND device_id = ? AND state = ?) |
| + ON CONFLICT (member_id) DO UPDATE SET token_hash = excluded.token_hash, |
| + created_at = excluded.created_at, registered_at = NULL`, |
| + memberID, hashHostToken(token), time.Now().UTC(), memberID, dev, EquipoConnected) |
| + if ok, err = affected(res, err); !ok { |
| + return "", false, err |
| + } |
| + return token, true, nil |
| +} |
| + |
| +func newHostToken() (string, error) { |
| + b := make([]byte, hostTokenBytes) |
| + if _, err := rand.Read(b); err != nil { |
| + return "", err |
| + } |
| + return hostTokenPrefix + base64.RawURLEncoding.EncodeToString(b), nil |
| +} |
| + |
| // MemberByHostToken is the member whose current host token is token; ok is |
| // false for anything else, including the token of a member who was removed. |
| func MemberByHostToken(ctx context.Context, db *sql.DB, token string) (Member, bool, error) { |
diff --git a/internal/store/hosttokens_test.go b/internal/store/hosttokens_test.go| index 194c35a..5055d05 100644 |
| --- a/internal/store/hosttokens_test.go |
| +++ b/internal/store/hosttokens_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "regexp" |
| "strings" |
| "testing" |
| + "time" |
| ) |
| var hostTokenRE = regexp.MustCompile(`^bh_[A-Za-z0-9_-]{43}$`) |
| @@ -133,3 +134,66 @@ func TestHostTokenRoundTrip(t *testing.T) { |
| t.Fatalf("registered with no token = %v, %v", reg, err) |
| } |
| } |
| + |
| +// A host token is minted for a device only while it is the member's |
| +// connected one, and goes with the link when it is lost, disconnected or |
| +// replaced. |
| +func TestHostTokenFollowsTheLink(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + ana := pendingLink(t, db, "DEV1") |
| + if _, ok, err := MintHostTokenFor(ctx, db, ana.ID, "DEV1"); err != nil || ok { |
| + t.Fatalf("minted for a pending device: %v %v", ok, err) |
| + } |
| + if ok, err := ConnectEquipoLink(ctx, db, ana.ID, "DEV1", []byte("s"), time.Now().Add(time.Hour), 3); err != nil || !ok { |
| + t.Fatal(ok, err) |
| + } |
| + if _, ok, err := MintHostTokenFor(ctx, db, ana.ID, "OTHER"); err != nil || ok { |
| + t.Fatalf("minted for another device: %v %v", ok, err) |
| + } |
| + mint := func() string { |
| + t.Helper() |
| + tok, ok, err := MintHostTokenFor(ctx, db, ana.ID, "DEV1") |
| + if err != nil || !ok { |
| + t.Fatalf("mint: %v %v", ok, err) |
| + } |
| + return tok |
| + } |
| + names := func(tok string) bool { |
| + _, ok, err := MemberByHostToken(ctx, db, tok) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return ok |
| + } |
| + tok := mint() |
| + if err := LoseEquipoLink(ctx, db, ana.ID, "OTHER"); err != nil || !names(tok) { |
| + t.Fatalf("losing another device dropped the token: %v", err) |
| + } |
| + if err := LoseEquipoLink(ctx, db, ana.ID, "DEV1"); err != nil || names(tok) { |
| + t.Fatalf("a lost link kept its token: %v", err) |
| + } |
| + if _, ok, _ := MintHostTokenFor(ctx, db, ana.ID, "DEV1"); ok { |
| + t.Fatal("minted for a lost link") |
| + } |
| + if _, err := db.Exec(`UPDATE equipo_links SET state = ?`, EquipoConnected); err != nil { |
| + t.Fatal(err) |
| + } |
| + tok = mint() |
| + if err := DisconnectEquipo(ctx, db, ana.ID, "DEV1"); err != nil || names(tok) { |
| + t.Fatalf("disconnecting kept the token: %v", err) |
| + } |
| + link := func(dev, state string) error { |
| + return SaveEquipoLink(ctx, db, EquipoLink{MemberID: ana.ID, Origin: "https://equipo.test", State: state, |
| + DeviceID: dev, Sealed: []byte("s"), ExpiresAt: time.Now().Add(time.Hour)}) |
| + } |
| + if err := link("DEV2", EquipoConnected); err != nil { |
| + t.Fatal(err) |
| + } |
| + tok, _, _ = MintHostTokenFor(ctx, db, ana.ID, "DEV2") |
| + if !names(tok) { |
| + t.Fatal("no token for DEV2") |
| + } |
| + if err := link("DEV3", EquipoPending); err != nil || names(tok) { |
| + t.Fatalf("a new Connect kept the token: %v", err) |
| + } |
| +} |
diff --git a/internal/web/ask.go b/internal/web/ask.go| index a03eddd..a412356 100644 |
| --- a/internal/web/ask.go |
| +++ b/internal/web/ask.go |
| @@ -23,8 +23,8 @@ type asker struct { |
| seal equipo.Sealer |
| // label is the device name a member sees when approving Base in Equipo. |
| label string |
| - // hosts holds a *sync.Mutex per member id, held while their host is |
| - // registered with Equipo (hostFor). |
| + // hosts holds a *sync.Mutex per member id, held while their |
| + // connection changes or their host is registered (lockMember). |
| hosts sync.Map |
| } |
| @@ -120,15 +120,12 @@ func (a *app) askLink(ctx context.Context, me store.Member) (store.EquipoLink, d |
| } |
| // askLost records that Equipo refused the bearer of the member's device |
| -// dev, unless the link has moved on to another device since, and forgets |
| -// the member's host token: Equipo no longer speaks for them. |
| +// dev, and forgets the member's host token (Equipo no longer speaks for |
| +// them), unless the link has moved on to another device since. |
| func (a *app) askLost(ctx context.Context, me store.Member, dev string) { |
| - if err := store.SetEquipoLinkState(ctx, a.db, me.ID, dev, store.EquipoLost); err != nil { |
| + defer a.lockMember(me.ID)() |
| + if err := store.LoseEquipoLink(context.WithoutCancel(ctx), a.db, me.ID, dev); err != nil { |
| a.logger.Error("ask: mark lost", "err", err) |
| - return |
| - } |
| - if l, ok, err := store.EquipoLinkFor(ctx, a.db, me.ID); err == nil && ok && l.DeviceID == dev { |
| - a.dropHost(ctx, me) |
| } |
| } |
| @@ -229,7 +226,7 @@ func (a *app) askSnapshot(r *http.Request, me store.Member, l store.EquipoLink, |
| a.logger.Error("ask: equipo person", "err", err) |
| } |
| } |
| - a.hostFor(r.Context(), me, token, false) |
| + a.hostFor(r.Context(), me, l.DeviceID, token, false) |
| return s.Cursor |
| } |
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go| index a49c888..b0e6fae 100644 |
| --- a/internal/web/ask_connect.go |
| +++ b/internal/web/ask_connect.go |
| @@ -48,9 +48,6 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) { |
| if old, sec, state, err := a.askLink(ctx, me); err == nil && state == askReady { |
| a.revoke(ctx, old, sec) |
| } |
| - // A new connection may be another Equipo person: until it is ready, |
| - // no one holds a host token for this member. |
| - a.dropHost(ctx, me) |
| pub, key, err := ed25519.GenerateKey(rand.Reader) |
| if err != nil { |
| a.fail(w, err) |
| @@ -73,9 +70,14 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) { |
| if exp.IsZero() { |
| exp = time.Now().Add(10 * time.Minute) |
| } |
| - if err := store.SaveEquipoLink(ctx, a.db, store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), |
| + // Saving the new link forgets the host token with it: a new connection |
| + // may be another Equipo person. |
| + unlock := a.lockMember(me.ID) |
| + err = store.SaveEquipoLink(ctx, a.db, store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), |
| State: store.EquipoPending, DeviceID: ch.ID, UserCode: ch.UserCode, |
| - VerificationURI: a.verifyURI(ch), Sealed: sealed, ExpiresAt: exp}); err != nil { |
| + VerificationURI: a.verifyURI(ch), Sealed: sealed, ExpiresAt: exp}) |
| + unlock() |
| + if err != nil { |
| a.fail(w, err) |
| return |
| } |
| @@ -207,7 +209,7 @@ func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec |
| if err == nil { |
| var stored bool |
| if stored, err = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision); stored { |
| - a.hostFor(ctx, me, cred.Token, true) |
| + a.hostFor(ctx, me, l.DeviceID, cred.Token, true) |
| return askReady |
| } |
| } |
| @@ -251,21 +253,27 @@ func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) { |
| if state == askReady { |
| a.revoke(r.Context(), l, sec) |
| } |
| - if err := store.DeleteEquipoLink(r.Context(), a.db, me.ID, l.DeviceID); err != nil { |
| + // The link and the host token go together, or Disconnect fails. |
| + unlock := a.lockMember(me.ID) |
| + err = store.DisconnectEquipo(r.Context(), a.db, me.ID, l.DeviceID) |
| + unlock() |
| + if err != nil { |
| a.fail(w, err) |
| return |
| } |
| - a.dropHost(r.Context(), me) |
| http.Redirect(w, r, "/settings", http.StatusSeeOther) |
| } |
| -// registerHost gives Equipo a new host token for the member, with their |
| -// bearer token: where Base's operations live (Base's own origin) and what |
| -// the Assistant presents to call them for this member. The new token |
| -// replaces the member's last one, which names nobody from then on. |
| -func (a *app) registerHost(ctx context.Context, me store.Member, token string) error { |
| - host, err := store.MintHostToken(ctx, a.db, me.ID) |
| - if err != nil { |
| +// registerHost gives Equipo a new host token for the member, with the |
| +// bearer token of their device dev: where Base's operations live (Base's |
| +// own origin) and what the Assistant presents to call them for this |
| +// member. The new token replaces the member's last one, which names |
| +// nobody from then on. It mints nothing unless dev is still the member's |
| +// connected device: a read that outlived a Disconnect or a new Connect |
| +// leaves no token behind. |
| +func (a *app) registerHost(ctx context.Context, me store.Member, dev, token string) error { |
| + host, ok, err := store.MintHostTokenFor(ctx, a.db, me.ID, dev) |
| + if err != nil || !ok { |
| return err |
| } |
| if err := a.ask.client.RegisterHost(ctx, token, a.cfg.Origin, host); err != nil { |
| @@ -274,18 +282,18 @@ func (a *app) registerHost(ctx context.Context, me store.Member, token string) e |
| return store.MarkHostRegistered(ctx, a.db, me.ID) |
| } |
| -// hostFor registers the member's host with Equipo: always when fresh (a |
| -// connection that just became ready), else only if Equipo does not hold |
| -// their current token yet. One registration runs per member at a time, |
| -// so two reads cannot leave Equipo holding a token Base has replaced. A |
| -// failure is logged (never a token) and tried again on the next read: it |
| -// neither breaks the chat nor disconnects anyone. |
| -func (a *app) hostFor(ctx context.Context, me store.Member, token string, fresh bool) { |
| +// hostFor registers the host of the member's device dev with Equipo: |
| +// always when fresh (a connection that just became ready), else only if |
| +// Equipo does not hold their current token yet. It holds the member's |
| +// lock (lockMember), so registrations, Connect, Disconnect and a lost |
| +// bearer happen one at a time for each member, and two reads cannot |
| +// leave Equipo holding a token Base has replaced. A failure is logged |
| +// (never a token) and tried again on the next read: it neither breaks |
| +// the chat nor disconnects anyone. |
| +func (a *app) hostFor(ctx context.Context, me store.Member, dev, token string, fresh bool) { |
| ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout) |
| defer cancel() |
| - mu, _ := a.ask.hosts.LoadOrStore(me.ID, &sync.Mutex{}) |
| - mu.(*sync.Mutex).Lock() |
| - defer mu.(*sync.Mutex).Unlock() |
| + defer a.lockMember(me.ID)() |
| if !fresh { |
| done, err := store.HostRegistered(ctx, a.db, me.ID) |
| if err != nil { |
| @@ -296,16 +304,17 @@ func (a *app) hostFor(ctx context.Context, me store.Member, token string, fresh |
| return |
| } |
| } |
| - if err := a.registerHost(ctx, me, token); err != nil { |
| + if err := a.registerHost(ctx, me, dev, token); err != nil { |
| a.logger.Warn("ask: register host", "err", err) |
| } |
| } |
| -// dropHost forgets the member's host token, so it names nobody. |
| -func (a *app) dropHost(ctx context.Context, me store.Member) { |
| - if err := store.DeleteHostToken(context.WithoutCancel(ctx), a.db, me.ID); err != nil { |
| - a.logger.Error("ask: forget host token", "err", err) |
| - } |
| +// lockMember takes the member's lock, held while their connection |
| +// changes or their host is registered, and returns its release. |
| +func (a *app) lockMember(id string) func() { |
| + mu, _ := a.ask.hosts.LoadOrStore(id, &sync.Mutex{}) |
| + mu.(*sync.Mutex).Lock() |
| + return mu.(*sync.Mutex).Unlock |
| } |
| func (a *app) renderConnect(w http.ResponseWriter, r *http.Request, status int, v connectView) { |
diff --git a/internal/webtest/ask_test.go b/internal/webtest/ask_test.go| index 764a545..e679168 100644 |
| --- a/internal/webtest/ask_test.go |
| +++ b/internal/webtest/ask_test.go |
| @@ -1027,3 +1027,76 @@ func TestAskNoRunner(t *testing.T) { |
| t.Fatal("a refused message shows") |
| } |
| } |
| + |
| +// hostRows is how many host tokens the owner has (0 or 1). |
| +func (a *testApp) hostRows() int { |
| + a.t.Helper() |
| + var n int |
| + if err := a.DB.QueryRow(`SELECT count(*) FROM host_tokens WHERE member_id = ?`, a.ownerID()).Scan(&n); err != nil { |
| + a.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// A read of the chat that was already under way when the member |
| +// disconnected, or started connecting again, finishes after it: it must |
| +// not leave a host token behind for a connection that is gone. |
| +func TestStaleReadLeavesNoHostToken(t *testing.T) { |
| + a, f := newAskApp(t) |
| + for _, step := range []struct { |
| + name string |
| + act func() Resp |
| + }{ |
| + {"disconnect", func() Resp { return a.post("/ask/disconnect", nil) }}, |
| + {"connect again", func() Resp { return a.post("/ask/connect", url.Values{"next": {"settings"}}) }}, |
| + } { |
| + a.approveEquipo(f) |
| + if err := store.DeleteHostToken(context.Background(), a.DB, a.ownerID()); err != nil { |
| + t.Fatal(err) |
| + } |
| + entered, release := f.HoldNextSnapshot() |
| + done := make(chan Resp) |
| + go func() { done <- a.get("/ask") }() |
| + waitEntered(t, entered, done) |
| + if r := step.act(); r.Code != 303 { |
| + t.Fatalf("%s: %d", step.name, r.Code) |
| + } |
| + release() |
| + <-done |
| + if n := a.hostRows(); n != 0 { |
| + t.Fatalf("after %s, a stale read left %d host token", step.name, n) |
| + } |
| + } |
| + for i := range f.Hosts() { |
| + if tok, _, _ := hostOf(t, f, i); a.hostMember(tok) != "" { |
| + t.Fatalf("host token %d still names the member", i) |
| + } |
| + } |
| +} |
| + |
| +// Disconnect succeeds only if the host token goes with the link: when |
| +// Base cannot forget the token, the member stays connected and is told |
| +// it didn't work. |
| +func TestDisconnectFailsWhileTokenStays(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + token, _, _ := hostOf(t, f, -1) |
| + if _, err := a.DB.Exec(`CREATE TRIGGER keep_host BEFORE DELETE ON host_tokens BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := a.post("/ask/disconnect", nil); r.Code == 303 { |
| + t.Fatal("Disconnect reported success while the host token stays") |
| + } |
| + if a.hostMember(token) != a.ownerID() { |
| + t.Fatal("the token went although forgetting it failed") |
| + } |
| + if s := a.get("/settings").Body; !strings.Contains(s, `action="/ask/disconnect"`) { |
| + t.Fatalf("Settings says disconnected while Base still holds the token:\n%s", s) |
| + } |
| + if _, err := a.DB.Exec(`DROP TRIGGER keep_host`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := a.post("/ask/disconnect", nil); r.Code != 303 || a.hostMember(token) != "" { |
| + t.Fatalf("disconnect: %d, token names %q", r.Code, a.hostMember(token)) |
| + } |
| +} |