Hold the Equipo exchange claim until the exchange ends
A poll's claim expired after the 5-second poll interval, but an exchange can take 20, so two could overlap; and when both succeeded, the second revoked the device the first had just connected. ClaimEquipoPoll now also sets exchanging_until (now + 30s: the client's 20s call timeout and a margin), and no poll claims the link until that exchange releases it or the time passes. A new Connect clears it. When an exchange's bearer cannot be stored, Base revokes it only if the link was deleted or replaced; the same device already connected stays.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+143
−19
internal/store/equipo.go+19 −8internal/store/equipo_test.go+30 −4internal/store/migrations/0006_equipo_exchanging.sql+4 −0internal/web/ask_connect.go+33 −7internal/webtest/ask_test.go+57 −0
diff --git a/internal/store/equipo.go b/internal/store/equipo.go| index 3bc4599..deef816 100644 |
| --- a/internal/store/equipo.go |
| +++ b/internal/store/equipo.go |
| @@ -63,7 +63,7 @@ func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| device_id = excluded.device_id, user_code = excluded.user_code, |
| verification_uri = excluded.verification_uri, sealed = excluded.sealed, |
| expires_at = excluded.expires_at, revision = excluded.revision, |
| - polled_at = excluded.polled_at, updated_at = excluded.updated_at`, |
| + polled_at = excluded.polled_at, 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, time.Now().UTC()) |
| return err |
| @@ -71,22 +71,33 @@ func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| // ClaimEquipoPoll claims the right to ask Equipo now whether the member's |
| // pending device dev was approved. Only one caller wins: the claim moves |
| -// polled_at, and no one can claim again until every has passed. It fails |
| -// for a link that is not that pending device. |
| -func ClaimEquipoPoll(ctx context.Context, db *sql.DB, memberID, dev string, now time.Time, every time.Duration) (bool, error) { |
| - res, err := db.ExecContext(ctx, `UPDATE equipo_links SET polled_at = ?, updated_at = ? |
| - WHERE member_id = ? AND device_id = ? AND state = ? AND (polled_at IS NULL OR polled_at <= ?)`, |
| - now.UTC(), time.Now().UTC(), memberID, dev, EquipoPending, now.Add(-every).UTC()) |
| +// polled_at and holds the link until now+hold (exchanging_until), so no |
| +// one claims again while that exchange is in flight, nor until every has |
| +// passed since it began. Release (or ConnectEquipoLink) ends the hold; |
| +// hold should outlast the exchange's own timeout. It fails for a link |
| +// that is not that pending device. |
| +func ClaimEquipoPoll(ctx context.Context, db *sql.DB, memberID, dev string, now time.Time, every, hold time.Duration) (bool, error) { |
| + res, err := db.ExecContext(ctx, `UPDATE equipo_links SET polled_at = ?, exchanging_until = ?, updated_at = ? |
| + WHERE member_id = ? AND device_id = ? AND state = ? |
| + AND (polled_at IS NULL OR polled_at <= ?) AND (exchanging_until IS NULL OR exchanging_until <= ?)`, |
| + now.UTC(), now.Add(hold).UTC(), time.Now().UTC(), memberID, dev, EquipoPending, now.Add(-every).UTC(), now.UTC()) |
| return affected(res, err) |
| } |
| +// ReleaseEquipoPoll ends the hold of an exchange on device dev. |
| +func ReleaseEquipoPoll(ctx context.Context, db *sql.DB, memberID, dev string) error { |
| + _, err := db.ExecContext(ctx, `UPDATE equipo_links SET exchanging_until = NULL WHERE member_id = ? AND device_id = ?`, |
| + memberID, dev) |
| + return err |
| +} |
| + |
| // ConnectEquipoLink stores the bearer an exchange brought back, sealed, but |
| // only while the member's link is still that pending device. false means |
| // it is not (disconnected, or replaced by a newer Connect): the caller must |
| // revoke the bearer instead. |
| func ConnectEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string, sealed []byte, expires time.Time, revision int64) (bool, error) { |
| res, err := db.ExecContext(ctx, `UPDATE equipo_links SET state = ?, sealed = ?, expires_at = ?, revision = ?, |
| - user_code = '', updated_at = ? WHERE member_id = ? AND device_id = ? AND state = ?`, |
| + user_code = '', exchanging_until = NULL, updated_at = ? WHERE member_id = ? AND device_id = ? AND state = ?`, |
| EquipoConnected, sealed, expires.UTC(), revision, time.Now().UTC(), memberID, dev, EquipoPending) |
| return affected(res, err) |
| } |
diff --git a/internal/store/equipo_test.go b/internal/store/equipo_test.go| index 9e5eccd..b69f947 100644 |
| --- a/internal/store/equipo_test.go |
| +++ b/internal/store/equipo_test.go |
| @@ -89,17 +89,20 @@ func TestClaimEquipoPollOnce(t *testing.T) { |
| ctx, db := context.Background(), open(t) |
| m := pendingLink(t, db, "D1") |
| now := time.Now() |
| - first, err := ClaimEquipoPoll(ctx, db, m.ID, "D1", now, 5*time.Second) |
| + first, err := ClaimEquipoPoll(ctx, db, m.ID, "D1", now, 5*time.Second, 30*time.Second) |
| if err != nil || !first { |
| t.Fatalf("first claim: %v %v", first, err) |
| } |
| - if again, _ := ClaimEquipoPoll(ctx, db, m.ID, "D1", now, 5*time.Second); again { |
| + if again, _ := ClaimEquipoPoll(ctx, db, m.ID, "D1", now, 5*time.Second, 30*time.Second); again { |
| t.Fatal("a second poll claimed inside the interval") |
| } |
| - if later, _ := ClaimEquipoPoll(ctx, db, m.ID, "D1", now.Add(6*time.Second), 5*time.Second); !later { |
| + if err := ReleaseEquipoPoll(ctx, db, m.ID, "D1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if later, _ := ClaimEquipoPoll(ctx, db, m.ID, "D1", now.Add(6*time.Second), 5*time.Second, 30*time.Second); !later { |
| t.Fatal("no claim after the interval") |
| } |
| - if other, _ := ClaimEquipoPoll(ctx, db, m.ID, "D2", now.Add(time.Hour), 5*time.Second); other { |
| + if other, _ := ClaimEquipoPoll(ctx, db, m.ID, "D2", now.Add(time.Hour), 5*time.Second, 30*time.Second); other { |
| t.Fatal("claimed for a device that is not the member's") |
| } |
| } |
| @@ -141,3 +144,26 @@ func TestConnectEquipoLinkNeedsSamePendingDevice(t *testing.T) { |
| t.Fatalf("a stale device id changed the link: %+v %v", l, found) |
| } |
| } |
| + |
| +// A claim holds the link for the whole exchange, which may outlast the |
| +// poll interval: no one else claims until it is released or runs out. |
| +func TestClaimEquipoPollHeldDuringExchange(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + m := pendingLink(t, db, "D1") |
| + now := time.Now() |
| + if ok, err := ClaimEquipoPoll(ctx, db, m.ID, "D1", now, 5*time.Second, 30*time.Second); !ok || err != nil { |
| + t.Fatalf("first claim: %v %v", ok, err) |
| + } |
| + if ok, _ := ClaimEquipoPoll(ctx, db, m.ID, "D1", now.Add(6*time.Second), 5*time.Second, 30*time.Second); ok { |
| + t.Fatal("claimed while an exchange was in flight") |
| + } |
| + if ok, _ := ClaimEquipoPoll(ctx, db, m.ID, "D1", now.Add(31*time.Second), 5*time.Second, 30*time.Second); !ok { |
| + t.Fatal("a claim that ran out still held the link") |
| + } |
| + if err := ReleaseEquipoPoll(ctx, db, m.ID, "D1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, _ := ClaimEquipoPoll(ctx, db, m.ID, "D1", now.Add(37*time.Second), 5*time.Second, 30*time.Second); !ok { |
| + t.Fatal("no claim after release and the interval") |
| + } |
| +} |
diff --git a/internal/store/migrations/0006_equipo_exchanging.sql b/internal/store/migrations/0006_equipo_exchanging.sql| new file mode 100644 |
| index 0000000..eca8ccd |
| --- /dev/null |
| +++ b/internal/store/migrations/0006_equipo_exchanging.sql |
| @@ -0,0 +1,4 @@ |
| +-- While Base exchanges a member's approved code for a bearer, no other |
| +-- poll may start one: exchanging_until holds the link until that exchange |
| +-- ends (it is cleared then) or the time passes. |
| +ALTER TABLE equipo_links ADD COLUMN exchanging_until datetime; |
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go| index 3c18f07..d218fea 100644 |
| --- a/internal/web/ask_connect.go |
| +++ b/internal/web/ask_connect.go |
| @@ -24,7 +24,12 @@ func nextOf(v string) string { |
| } |
| // pollEvery is Equipo's shortest interval between two exchange attempts. |
| -const pollEvery = 5 * time.Second |
| +// exchangeHold keeps other polls off the link while one exchange runs: the |
| +// client's 20-second call timeout and a margin. |
| +const ( |
| + pollEvery = 5 * time.Second |
| + exchangeHold = 30 * time.Second |
| +) |
| type connectView struct { |
| Name, Label, State, Next string |
| @@ -149,10 +154,16 @@ func (a *app) askConnectCheck(w http.ResponseWriter, r *http.Request) { |
| // this pending device; if it is not (Disconnect, or a newer Connect, came |
| // in between), the bearer is revoked at once. |
| func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec deviceSecrets) (string, error) { |
| - claimed, err := store.ClaimEquipoPoll(ctx, a.db, me.ID, l.DeviceID, time.Now(), pollEvery) |
| + claimed, err := store.ClaimEquipoPoll(ctx, a.db, me.ID, l.DeviceID, time.Now(), pollEvery, exchangeHold) |
| if err != nil || !claimed { |
| return askPending, err |
| } |
| + // Whatever happens, the next poll may go once this one has ended. |
| + defer func() { |
| + if err := store.ReleaseEquipoPoll(context.WithoutCancel(ctx), a.db, me.ID, l.DeviceID); err != nil { |
| + a.logger.Error("ask: release poll", "err", err) |
| + } |
| + }() |
| ch := equipo.Challenge{ID: l.DeviceID, DeviceSecret: sec.Secret, Challenge: sec.Challenge} |
| proof, err := equipo.Prove(ed25519.NewKeyFromSeed(sec.Seed), ch, sec.Nonce) |
| if err != nil { |
| @@ -176,12 +187,27 @@ func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec |
| return askPending, err |
| } |
| stored, err := store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision) |
| - if err != nil || !stored { |
| - l.Revision = cred.Revision |
| - a.revoke(context.WithoutCancel(ctx), l, sec) |
| - return askConnect, err |
| + if err != nil || stored { |
| + return askReady, err |
| + } |
| + return a.unstored(ctx, me, l, sec, cred) |
| +} |
| + |
| +// unstored handles a bearer the link would not take. If the link is |
| +// still this device it is already connected (a duplicate exchange won), |
| +// and that connection stays. If the device was disconnected or replaced, |
| +// the bearer is revoked, so nothing live is left behind. |
| +func (a *app) unstored(ctx context.Context, me store.Member, l store.EquipoLink, sec deviceSecrets, cred equipo.Credential) (string, error) { |
| + now, found, err := store.EquipoLinkFor(ctx, a.db, me.ID) |
| + if err != nil { |
| + return askPending, err |
| + } |
| + if found && now.DeviceID == l.DeviceID { |
| + return askReady, nil |
| } |
| - return askReady, nil |
| + l.Revision = cred.Revision |
| + a.revoke(context.WithoutCancel(ctx), l, sec) |
| + return askConnect, nil |
| } |
| // revoke revokes the member's device in Equipo, as itself. It is best |
diff --git a/internal/webtest/ask_test.go b/internal/webtest/ask_test.go| index 5bb6e8d..d26a7c2 100644 |
| --- a/internal/webtest/ask_test.go |
| +++ b/internal/webtest/ask_test.go |
| @@ -517,3 +517,60 @@ func TestAskEventsRelay(t *testing.T) { |
| t.Fatalf("upstream: %+v", up) |
| } |
| } |
| + |
| +// waitEntered waits for a held exchange to reach Equipo. |
| +func waitEntered(t *testing.T, entered <-chan struct{}, done <-chan Resp) { |
| + t.Helper() |
| + select { |
| + case <-entered: |
| + case r := <-done: |
| + t.Fatalf("the check never reached Equipo's exchange: %d %q", r.Code, r.Location()) |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the check never reached Equipo's exchange") |
| + } |
| +} |
| + |
| +// An exchange slower than the poll interval still holds the link: a check |
| +// after the interval does not start a second one. |
| +func TestCheckDuringSlowExchangeDoesNotExchange(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.post("/ask/connect", url.Values{"next": {"ask"}}) |
| + entered, release := f.HoldNextExchange() |
| + done := make(chan Resp) |
| + go func() { done <- a.check("ask") }() |
| + waitEntered(t, entered, done) |
| + a.pollable() // the interval has passed; the exchange has not ended |
| + a.check("ask") |
| + release() |
| + <-done |
| + if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 { |
| + t.Fatalf("exchanges: %d, want 1", n) |
| + } |
| +} |
| + |
| +// When the link is already connected to the same device (a duplicate |
| +// exchange succeeded first), a late success leaves that connection alone. |
| +func TestDuplicateExchangeKeepsConnection(t *testing.T) { |
| + a, f := newAskApp(t) |
| + r := a.post("/ask/connect", url.Values{"next": {"ask"}}) |
| + m := codeRE.FindStringSubmatch(a.get(r.Location()).Body) |
| + if err := f.Approve(m[1]); err != nil { |
| + t.Fatal(err) |
| + } |
| + l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()) |
| + entered, release := f.HoldNextExchange() |
| + done := make(chan Resp) |
| + go func() { done <- a.check("ask") }() |
| + waitEntered(t, entered, done) |
| + if _, err := a.DB.Exec(`UPDATE equipo_links SET state = ?`, store.EquipoConnected); err != nil { |
| + t.Fatal(err) |
| + } |
| + release() |
| + <-done |
| + if f.Revoked(l.DeviceID) { |
| + t.Fatal("a duplicate success revoked the live connection") |
| + } |
| + if got, found, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); !found || got.State != store.EquipoConnected { |
| + t.Fatalf("link: %+v %v", got, found) |
| + } |
| +} |