oficina / base Public

Change a member's Ask link in one locked step, then revoke what it displaced

Astra's re-review: the web's Connect and Disconnect still acted on a
link read before their calls to Equipo. A Connect paused at Equipo
could replace a native renewal without revoking it, and a Disconnect
paused revoking the old device could report success while a renewal's
link stayed live.

The rule, for every change to a member's link: under the member's lock,
read the link as it is then, write the new state (or remove it, with the
host token) and move the connection generation on, in that one step;
after releasing the lock, revoke the device actually displaced. Nothing
decides what to revoke from a read taken before a call to Equipo.

- Connect (web): its Reconnect step marks the current ready link lost
  in one locked step, then revokes it; its save after BeginDevice
  replaces whatever link is current then, and revokes that.
- Approval (web): stores the bearer only if the link is still its
  pending device at that moment; otherwise gives its own bearer up.
- Disconnect: removes whatever link is current, with the host token
  (DisconnectEquipo no longer takes a device), then revokes it.
- Native save: keeps its generation check (overtaken: saves nothing,
  revokes its own new device); otherwise replaces and revokes the
  current link, read under the lock.
- A code that ends (expired, refused) or a failed store: deletes the
  link only if it is still that pending device.
hostFor stays outside the lock.

N = native save, W = web Connect's save, A = web approval, D =
Disconnect, E = a code ending. "Live" is a credential Equipo still takes.

| Pair | Finishes first | End state | Test |
|---|---|---|---|
| N, D | N, then D | no link, 0 live (D revokes N's) | TestDisconnectRevokesOficinaKey |
| N, D | D while N waits at Equipo | no link, 0 live (N revokes its own) | TestAskOficinaSetupOvertakenByDisconnect |
| N, D | D's step, N saves while D revokes | no link, 0 live | TestRaceDisconnectWhileNativeRenewalSaves (Astra b) |
| N, W+A | W and A while N waits | web link, 1 live (web); N revokes its own | TestAskOficinaSetupOvertakenByWebConnect |
| N, W | N while W waits at BeginDevice | pending web link; N's revoked; after A, 1 live (web) | TestRaceWebConnectSavesAfterNativeRenewal (Astra a) |
| N, A | N while A's exchange waits | native link, 1 live (native); A gives its bearer up | TestRaceNativeSavesWhileWebApprovalExchanges |
| N, N | either | 1 live, the later; the earlier revoked | TestAskOficinaRenew |
| W, D | D while W waits at BeginDevice | pending web link, 0 live | TestRaceDisconnectWhileWebConnectBegins |
| A, D | D while A's exchange waits | no link, 0 live | TestDisconnectDuringExchangeLeavesNoBearer |
| A, D | A, then D | no link, 0 live | TestDisconnectRevokesDevice |
| W, A | a new W while the old A's exchange waits | newer pending link, 0 live | TestRaceReconnectWhileWebApprovalExchanges |
| E, N | E while N waits | no link, 0 live (N revokes its own) | TestRaceCodeEndsWhileNativeSetupWaits |
| E, N | N, then the old code ends | native link, 1 live | TestRaceNativeSavesWhileWebApprovalExchanges |
| lost, N | N replaces a key Base stopped using | 1 live (N); the old revoked | TestAskOficinaRenewRevokesWhatItReplaces |

The two Astra rows fail at cdfeac7 and pass here. equipotest can hold
the next device sign-in start and the next revocation, and lists live
credentials.

make ci: 16 packages ran, 0 failed; test step 11.0s of 60s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev bffe60973f040af9f30ec4dff0183d9f9c618f53 parent cdfeac7
7 files changed, +357 −38
  • internal/equipo/equipotest/fake.go +44 −0
  • internal/equipo/equipotest/native.go +14 −0
  • internal/store/equipo.go +3 −3
  • internal/store/hosttokens_test.go +1 −1
  • internal/web/ask_connect.go +62 −31
  • internal/web/ask_oficina_native.go +1 −3
  • internal/webtest/ask_link_race_test.go +232 −0
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go
index 14f17b2..3169cc8 100644
--- a/internal/equipo/equipotest/fake.go
+++ b/internal/equipo/equipotest/fake.go
@@ -64,6 +64,9 @@ type Fake struct {
failSend bool
// failBegin makes the next device sign-in start answer 503.
failBegin bool
+ // beginHold and revokeHold do for the next sign-in start and the next
+ // revocation what hold does for the next exchange.
+ beginHold, beginEntered, revokeHold, revokeEntered chan struct{}
// failSnapshot makes every snapshot answer 503.
failSnapshot bool
// snapHold and snapEntered do for the next snapshot what hold and
@@ -95,6 +98,39 @@ func (f *Fake) HoldNextSnapshot() (entered <-chan struct{}, release func()) {
return f.snapEntered, func() { close(hold) }
}
+// HoldNextBegin makes the next device sign-in start (POST
+// /api/v1/auth/devices) wait, once it has arrived and before it answers,
+// until release is called. entered is closed when it arrives.
+func (f *Fake) HoldNextBegin() (entered <-chan struct{}, release func()) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.beginHold, f.beginEntered = make(chan struct{}), make(chan struct{})
+ hold := f.beginHold
+ return f.beginEntered, func() { close(hold) }
+}
+
+// HoldNextRevoke does the same for the next device revocation (DELETE
+// /api/v1/auth/devices/{id}).
+func (f *Fake) HoldNextRevoke() (entered <-chan struct{}, release func()) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.revokeHold, f.revokeEntered = make(chan struct{}), make(chan struct{})
+ hold := f.revokeHold
+ return f.revokeEntered, func() { close(hold) }
+}
+
+// waitHeld waits at a hold taken from f, if there is one.
+func (f *Fake) waitHeld(hold, entered chan struct{}) {
+ if hold == nil {
+ return
+ }
+ close(entered)
+ select {
+ case <-hold:
+ case <-f.closing:
+ }
+}
+
// FailNextBegin makes the next device sign-in start (POST
// /api/v1/auth/devices) answer 503, as when Equipo is down.
func (f *Fake) FailNextBegin() {
@@ -233,7 +269,10 @@ func (f *Fake) begin(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
fail := f.failBegin
f.failBegin = false
+ hold, entered := f.beginHold, f.beginEntered
+ f.beginHold, f.beginEntered = nil, nil
f.mu.Unlock()
+ f.waitHeld(hold, entered)
if fail {
writeError(w, r, 503, "unavailable")
return
@@ -342,6 +381,11 @@ func (f *Fake) Expire() {
}
func (f *Fake) revoke(w http.ResponseWriter, r *http.Request, id string) {
+ f.mu.Lock()
+ hold, entered := f.revokeHold, f.revokeEntered
+ f.revokeHold, f.revokeEntered = nil, nil
+ f.mu.Unlock()
+ f.waitHeld(hold, entered)
d, ok := f.bearer(r)
if !ok {
writeError(w, r, 401, "unauthenticated")
diff --git a/internal/equipo/equipotest/native.go b/internal/equipo/equipotest/native.go
index 1fbe38c..3c914d7 100644
--- a/internal/equipo/equipotest/native.go
+++ b/internal/equipo/equipotest/native.go
@@ -136,6 +136,20 @@ func (f *Fake) DeviceSession(id string) string {
return ""
}
+// LiveCredentials are the ids of the devices holding a credential Equipo
+// still takes: exchanged or registered, and not revoked.
+func (f *Fake) LiveCredentials() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []string
+ for id, d := range f.devices {
+ if d.token != "" && !d.revoked {
+ out = append(out, id)
+ }
+ }
+ return out
+}
+
// Devices are the ids of every device the fake knows.
func (f *Fake) Devices() []string {
f.mu.Lock()
diff --git a/internal/store/equipo.go b/internal/store/equipo.go
index cf612b1..b00579b 100644
--- a/internal/store/equipo.go
+++ b/internal/store/equipo.go
@@ -155,11 +155,11 @@ func LoseEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error
})
}
-// DisconnectEquipo forgets the member's link, if it is still device dev,
+// DisconnectEquipo forgets the member's link, whichever device it is now,
// and their host token, in one transaction: both go or neither does.
-func DisconnectEquipo(ctx context.Context, db *sql.DB, memberID, dev string) error {
+func DisconnectEquipo(ctx context.Context, db *sql.DB, memberID 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 {
+ if _, err := tx.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ?`, memberID); err != nil {
return err
}
_, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID)
diff --git a/internal/store/hosttokens_test.go b/internal/store/hosttokens_test.go
index 5055d05..5e04853 100644
--- a/internal/store/hosttokens_test.go
+++ b/internal/store/hosttokens_test.go
@@ -179,7 +179,7 @@ func TestHostTokenFollowsTheLink(t *testing.T) {
t.Fatal(err)
}
tok = mint()
- if err := DisconnectEquipo(ctx, db, ana.ID, "DEV1"); err != nil || names(tok) {
+ if err := DisconnectEquipo(ctx, db, ana.ID); err != nil || names(tok) {
t.Fatalf("disconnecting kept the token: %v", err)
}
link := func(dev, state string) error {
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
index c189de4..5cded9b 100644
--- a/internal/web/ask_connect.go
+++ b/internal/web/ask_connect.go
@@ -45,16 +45,24 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
me, _ := CurrentMember(r)
next := nextOf(r.PostFormValue("next"))
ctx := r.Context()
- if old, sec, state, err := a.askLink(ctx, me); err == nil && state == askReady {
- a.revoke(ctx, old, sec)
- // The old connection is over: its link is lost and its host token
- // goes with it, in one transaction, before anything below can fail.
- err = a.changeLink(me.ID, func() error { return store.LoseEquipoLink(ctx, a.db, me.ID, old.DeviceID) })
- if err != nil {
- a.fail(w, err)
- return
+ // Reconnecting ends the connection there is now, before anything below
+ // can fail: read and marked lost (its host token going with it) in one
+ // locked step, then its device revoked.
+ var ended store.EquipoLink
+ var endedSec deviceSecrets
+ err := a.changeLink(me.ID, func() error {
+ l, sec, state, e := a.askLink(ctx, me)
+ if e != nil || state != askReady {
+ return e
}
+ ended, endedSec = l, sec
+ return store.LoseEquipoLink(ctx, a.db, me.ID, l.DeviceID)
+ })
+ if err != nil {
+ a.fail(w, err)
+ return
}
+ a.revokeDisplaced(ctx, ended, endedSec, "")
pub, key, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
a.fail(w, err)
@@ -77,9 +85,16 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
if exp.IsZero() {
exp = time.Now().Add(10 * time.Minute)
}
- // Saving the new link forgets the host token with it: a new connection
- // may be another Equipo person.
- err = a.changeLink(me.ID, func() error {
+ // The new link replaces whatever link there is now (a connection made
+ // with Oficina ID while Equipo answered, say), read in the same locked
+ // step, whose device is then revoked. Saving it forgets the host token
+ // with it: a new connection may be another Equipo person.
+ var old store.EquipoLink
+ var oldSec deviceSecrets
+ err = a.changeLink(me.ID, func() (e error) {
+ if old, oldSec, _, e = a.askLink(ctx, me); e != nil {
+ return e
+ }
return 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})
@@ -88,6 +103,7 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
a.fail(w, err)
return
}
+ a.revokeDisplaced(ctx, old, oldSec, ch.ID)
http.Redirect(w, r, "/ask/connect?next="+next, http.StatusSeeOther)
}
@@ -214,22 +230,25 @@ func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec
l.Revision = cred.Revision
sealed, err := a.sealSecrets(me.ID, sec)
if err == nil {
- var stored bool
+ // Only while the link is still this pending device, as it is at
+ // that moment: after Disconnect, or once anything else replaced
+ // it, the bearer is this device's alone to give up.
+ var stored, duplicate bool
err = a.changeLink(me.ID, func() (e error) {
- stored, e = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision)
+ if stored, e = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision); stored || e != nil {
+ return e
+ }
+ now, found, e := store.EquipoLinkFor(ctx, a.db, me.ID)
+ duplicate = found && now.DeviceID == l.DeviceID && now.State == store.EquipoConnected
return e
})
- if stored {
+ switch {
+ case stored:
a.hostFor(ctx, me, l.DeviceID, cred.Token, true)
return askReady
- }
- }
- if err == nil {
- now, found, e := store.EquipoLinkFor(ctx, a.db, me.ID)
- if e == nil && found && now.DeviceID == l.DeviceID && now.State == store.EquipoConnected {
+ case duplicate:
return askReady
- }
- if err = e; err == nil {
+ case err == nil:
a.revoke(ctx, l, sec)
return askConnect
}
@@ -253,23 +272,35 @@ func (a *app) revoke(ctx context.Context, l store.EquipoLink, sec deviceSecrets)
}
}
+// revokeDisplaced revokes the device of link old, which a change to the
+// member's link has just replaced or removed, read in that change's locked
+// step: unless it is the device that replaced it (kept), or never had a
+// bearer (a code never approved, which Equipo lets lapse).
+func (a *app) revokeDisplaced(ctx context.Context, old store.EquipoLink, sec deviceSecrets, kept string) {
+ if old.DeviceID != "" && old.DeviceID != kept && sec.Token != "" {
+ a.revoke(ctx, old, sec)
+ }
+}
+
// askDisconnect is POST /ask/disconnect, from Settings.
func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) {
me, _ := CurrentMember(r)
- l, sec, state, err := a.askLink(r.Context(), me)
- if err != nil {
- a.fail(w, err)
- return
- }
- if state == askReady {
- a.revoke(r.Context(), l, sec)
- }
- // The link and the host token go together, or Disconnect fails.
- err = a.changeLink(me.ID, func() error { return store.DisconnectEquipo(r.Context(), a.db, me.ID, l.DeviceID) })
+ ctx := r.Context()
+ // Whatever link there is at that moment goes, with the host token, in
+ // one locked step, or Disconnect fails; then its device is revoked.
+ var old store.EquipoLink
+ var oldSec deviceSecrets
+ err := a.changeLink(me.ID, func() (e error) {
+ if old, oldSec, _, e = a.askLink(ctx, me); e != nil {
+ return e
+ }
+ return store.DisconnectEquipo(ctx, a.db, me.ID)
+ })
if err != nil {
a.fail(w, err)
return
}
+ a.revokeDisplaced(ctx, old, oldSec, "")
http.Redirect(w, r, "/settings", http.StatusSeeOther)
}
diff --git a/internal/web/ask_oficina_native.go b/internal/web/ask_oficina_native.go
index 6bbbc65..f489495 100644
--- a/internal/web/ask_oficina_native.go
+++ b/internal/web/ask_oficina_native.go
@@ -137,9 +137,7 @@ func (a *app) askOficina(w http.ResponseWriter, r *http.Request) {
}
// The key it replaced is over, ready or not: revoke it in Equipo, as
// Connect does. A key Equipo already refused refuses this too.
- if old.DeviceID != "" && old.DeviceID != cred.ID && oldSec.Token != "" {
- a.revoke(ctx, old, oldSec)
- }
+ a.revokeDisplaced(ctx, old, oldSec, cred.ID)
a.hostFor(ctx, me, cred.ID, cred.Token, true)
writeJSON(w, http.StatusOK, map[string]string{"state": askReady, "renew_after": renewAfter(l, deviceSecrets{Via: viaOficina}).Format(time.RFC3339)})
}
diff --git a/internal/webtest/ask_link_race_test.go b/internal/webtest/ask_link_race_test.go
new file mode 100644
index 0000000..0b0a89a
--- /dev/null
+++ b/internal/webtest/ask_link_race_test.go
@@ -0,0 +1,232 @@
+package webtest
+
+import (
+ "net/url"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+)
+
+// Every change to a member's Ask link (the native set-up's save, the web's
+// Connect and its approval, Disconnect, a code that ends) reads the link as
+// it is at that moment, under the member's lock, changes it in that one
+// step, and only then revokes the device it displaced. Whichever of two
+// finishes first, Base ends with at most one live credential in Equipo, the
+// one it holds, and every credential it forgot is revoked. One test per
+// interleaving; the rest are elsewhere (see the commit that added this).
+
+// background runs call and returns where its answer will come.
+func background(call func() Resp) <-chan Resp {
+ out := make(chan Resp, 1)
+ go func() { out <- call() }()
+ return out
+}
+
+// arrived waits for a held call to reach Equipo.
+func arrived(t *testing.T, entered <-chan struct{}, what string) {
+ t.Helper()
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s never reached Equipo", what)
+ }
+}
+
+// startWebConnect presses Connect on the web and returns the code shown.
+func (a *testApp) startWebConnect() string {
+ a.t.Helper()
+ r := a.post("/ask/connect", url.Values{"next": {"settings"}})
+ if r.Code != 303 {
+ a.t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ m := codeRE.FindStringSubmatch(a.get(r.Location()).Body)
+ if m == nil {
+ a.t.Fatal("no code shown")
+ }
+ return m[1]
+}
+
+// approveAndCheck approves code in Equipo and presses Check again.
+func (a *testApp) approveAndCheck(f *equipotest.Fake, code string) Resp {
+ a.t.Helper()
+ if err := f.Approve(code); err != nil {
+ a.t.Fatal(err)
+ }
+ a.pollable()
+ return a.check("settings")
+}
+
+// wantLive fails unless exactly the devices in want hold a live credential.
+func wantLive(t *testing.T, f *equipotest.Fake, want ...string) {
+ t.Helper()
+ got := f.LiveCredentials()
+ sort.Strings(got)
+ sort.Strings(want)
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Fatalf("live credentials %v, want %v", got, want)
+ }
+}
+
+// Astra's (a): the web's Connect, paused at Equipo, saves after a native
+// renewal did. It replaces the renewal's link and revokes its device.
+func TestRaceWebConnectSavesAfterNativeRenewal(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ f.RevokeAll()
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Fatalf("state: %s", s.State)
+ }
+ entered, release := f.HoldNextBegin()
+ started := background(func() Resp { return web.post("/ask/connect", url.Values{"next": {"settings"}}) })
+ arrived(t, entered, "the web's Connect")
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("renewal: %d %s", r.Code, r.Body)
+ }
+ renewed := f.LiveCredentials()
+ release()
+ if r := <-started; r.Code != 303 {
+ t.Fatalf("web connect: %d %s", r.Code, r.Body)
+ }
+ if len(renewed) != 1 || !f.Revoked(renewed[0]) {
+ t.Fatalf("the renewal's device %v is still live after the web replaced it", renewed)
+ }
+ m := codeRE.FindStringSubmatch(web.get("/ask/connect?next=settings").Body)
+ if m == nil {
+ t.Fatal("no code")
+ }
+ if r := web.approveAndCheck(f, m[1]); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("check: %d %q", r.Code, r.Location())
+ }
+ if live := f.LiveCredentials(); len(live) != 1 || live[0] == renewed[0] || web.equipoLinks() != 1 {
+ t.Fatalf("live %v, links %d", live, web.equipoLinks())
+ }
+}
+
+// Astra's (b): Disconnect, paused revoking the old device, and a native
+// renewal released meanwhile. Disconnect removed the link there was when it
+// ran; the renewal, overtaken, saves nothing and revokes its own device.
+func TestRaceDisconnectWhileNativeRenewalSaves(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ renewal, releaseRenewal := startHeldSetup(t, app, f)
+ entered, releaseRevoke := f.HoldNextRevoke()
+ disconnected := background(func() Resp { return app.post("/ask/disconnect", nil) })
+ arrived(t, entered, "Disconnect's revocation")
+ releaseRenewal()
+ wantBody(t, "renewal", <-renewal, 409, `{"state":"superseded"}`)
+ releaseRevoke()
+ if r := <-disconnected; r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ wantLive(t, f)
+ if n := app.equipoLinks(); n != 0 {
+ t.Fatalf("links: %d", n)
+ }
+ if hosts := f.Hosts(); len(hosts) != 1 {
+ t.Errorf("hosts registered: %d", len(hosts))
+ }
+}
+
+// A native set-up saves while the web's approval waits at Equipo's
+// exchange: the approval finds its code replaced and gives its bearer up.
+func TestRaceNativeSavesWhileWebApprovalExchanges(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ code := web.startWebConnect()
+ if err := f.Approve(code); err != nil {
+ t.Fatal(err)
+ }
+ web.pollable()
+ entered, release := f.HoldNextExchange()
+ checked := background(func() Resp { return web.check("settings") })
+ arrived(t, entered, "the web's exchange")
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("native: %d %s", r.Code, r.Body)
+ }
+ native := f.LiveCredentials()
+ release()
+ <-checked
+ wantLive(t, f, native...)
+ s, r := app.askState()
+ if s.State != "ready" || strings.Contains(r.Body, `"renew_after":""`) {
+ t.Fatalf("state: %s", r.Body)
+ }
+ // The old code ending later changes nothing.
+ f.Expire()
+ web.pollable()
+ web.check("settings")
+ wantLive(t, f, native...)
+}
+
+// Disconnect while the web's Connect waits at Equipo: the Connect, the
+// later of the two, saves its code; the connection Disconnect removed is
+// revoked, and nothing is live.
+func TestRaceDisconnectWhileWebConnectBegins(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ entered, release := f.HoldNextBegin()
+ started := background(func() Resp { return web.post("/ask/connect", url.Values{"next": {"settings"}}) })
+ arrived(t, entered, "the web's Connect")
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ release()
+ if r := <-started; r.Code != 303 {
+ t.Fatalf("web connect: %d", r.Code)
+ }
+ wantLive(t, f)
+ if s, _ := app.askState(); s.State != "pending" {
+ t.Errorf("state: %s", s.State)
+ }
+}
+
+// The web's code ends (expired) while a native set-up waits at Equipo:
+// the set-up, overtaken, saves nothing and revokes its device.
+func TestRaceCodeEndsWhileNativeSetupWaits(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ web.startWebConnect()
+ setup, release := startHeldSetup(t, app, f)
+ f.Expire()
+ web.pollable()
+ web.check("settings")
+ if n := web.equipoLinks(); n != 0 {
+ t.Fatalf("the expired code's link stays: %d", n)
+ }
+ release()
+ wantBody(t, "set-up", <-setup, 409, `{"state":"superseded"}`)
+ wantLive(t, f)
+}
+
+// A second Connect while the first's approval waits at Equipo: the
+// first's bearer is given up, and only the newer code stands.
+func TestRaceReconnectWhileWebApprovalExchanges(t *testing.T) {
+ web, _, f := newNativeAskApp(t)
+ code := web.startWebConnect()
+ if err := f.Approve(code); err != nil {
+ t.Fatal(err)
+ }
+ web.pollable()
+ entered, release := f.HoldNextExchange()
+ checked := background(func() Resp { return web.check("settings") })
+ arrived(t, entered, "the web's exchange")
+ web.startWebConnect()
+ release()
+ <-checked
+ wantLive(t, f)
+ if r := web.nativeGet("/ask/state"); !strings.Contains(r.Body, `"state":"pending"`) {
+ t.Errorf("state: %s", r.Body)
+ }
+}