oficina / base Public

Let Disconnect and the web's Connect overtake a native Ask set-up

Astra's review: the native set-up read the old link before calling
Equipo and then saved unconditionally, so a set-up paused at Equipo
could undo a Disconnect, or overwrite a connection the web completed
meanwhile and leave that device live with its bearer forgotten.

Every change to a member's link (Connect, its approval, expiry or
refusal, Disconnect, the native set-up) now goes through changeLink,
which holds the member's lock and moves a per-member connection
generation on. The native set-up notes the generation before calling
Equipo; when it saves, under the same lock, a moved generation means it
was overtaken: it saves nothing, revokes the device it just made, and
answers 409 {"state":"superseded"}. Otherwise it reads the link it is
replacing under that lock and revokes that device (ready or not) once
saved. Equipo refusing a key (askLost) does not move the generation, so
a renewal still replaces a lost key. The member lock is never held
across a call to Equipo or hostFor.

Tests: a set-up held at Equipo's exchange, then Disconnect, then
released, leaves no link and the new device revoked; the same with the
web's code flow completing in between leaves one live device, the web's;
a renewal revokes the expired key it replaces. equipotest can hold the
next native exchange.

make ci: 16 packages ran, 0 failed; test step 7.6s of 60s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 04c24e2a6346ad26e34c3f3d690060fbe4985913 parent aeb6758
6 files changed, +243 −38
  • docs/api/base-native-v1.md +3 −1
  • internal/equipo/equipotest/native.go +26 −0
  • internal/web/ask.go +3 −2
  • internal/web/ask_connect.go +54 −20
  • internal/web/ask_oficina_native.go +43 −15
  • internal/webtest/ask_oficina_native_test.go +114 −0
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
index 002d52a..c514a66 100644
--- a/docs/api/base-native-v1.md
+++ b/docs/api/base-native-v1.md
@@ -217,12 +217,14 @@ call it (with `Origin`, as every POST). Base completes Equipo's own native
sign-in for the person (Equipo's `POST /native/oficina-id`, then
`POST /api/v1/auth/devices/native`), keeps the key it gets sealed where the
web's code flow keeps one, and registers the Assistant's host with it.
-Two posts for the same person run one at a time.
+Two posts for the same person run one at a time, and a set-up yields to
+anything else that changes the person's connection meanwhile.
| status | body | meaning |
|---|---|---|
| `200` | `{"state":"ready","renew_after":"<RFC 3339>"}` | Ask is ready. The key ends with Equipo's session, seven days after it was made; `renew_after` is five days after. After it, post a fresh assertion: that replaces the key and revokes the old one in Equipo. |
| `409` | `{"state":"not_linked"}` | Equipo has no member linked to this Oficina ID. Show Ask's "not set up for you yet" state, with the web's code flow; don't retry in a loop. |
+| `409` | `{"state":"superseded"}` | Ask's connection changed while Equipo answered (Disconnect, or a connection from the web): nothing was saved, and the device Equipo made was revoked. Reload `/ask/state`; don't retry at once. |
| `422` | `{"state":"failed"}` | Equipo didn't accept the assertion (expired, wrong audience or verifier, already used). Get a fresh one and try once more. |
| `400` | `{"state":"invalid"}` | Not JSON, an unknown or missing field, or Equipo couldn't read it. |
| `403` | `{"state":"forbidden"}` | Not a native session: the web keeps its code flow. |
diff --git a/internal/equipo/equipotest/native.go b/internal/equipo/equipotest/native.go
index d47879a..1fbe38c 100644
--- a/internal/equipo/equipotest/native.go
+++ b/internal/equipo/equipotest/native.go
@@ -55,6 +55,9 @@ type nativeState struct {
assertions map[string]*assertionGrant
sessions map[string]*nativeSession // cookie value → session
failNative int // the next exchange's status, once
+ // nativeHold, when set, stops the next exchange until it is closed;
+ // nativeEntered is closed when that exchange arrives.
+ nativeHold, nativeEntered chan struct{}
}
func (n *nativeState) init() {
@@ -87,6 +90,17 @@ func (f *Fake) FailNextNativeExchange(status int) {
f.failNative = status
}
+// HoldNextNativeExchange makes the next native exchange wait, once it has
+// arrived and before it answers, until release is called: a test can act
+// in between. entered is closed when it arrives.
+func (f *Fake) HoldNextNativeExchange() (entered <-chan struct{}, release func()) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ f.nativeHold, f.nativeEntered = make(chan struct{}), make(chan struct{})
+ hold := f.nativeHold
+ return f.nativeEntered, func() { close(hold) }
+}
+
// NativeSessions is how many native sessions the fake has minted.
func (f *Fake) NativeSessions() int {
f.nmu.Lock()
@@ -168,6 +182,18 @@ func (f *Fake) nativeExchange(w http.ResponseWriter, r *http.Request) {
return
}
f.nmu.Lock()
+ hold, entered := f.nativeHold, f.nativeEntered
+ f.nativeHold, f.nativeEntered = nil, nil
+ f.nmu.Unlock()
+ if hold != nil {
+ close(entered)
+ select {
+ case <-hold:
+ case <-f.closing:
+ return
+ }
+ }
+ f.nmu.Lock()
defer f.nmu.Unlock()
if status := f.failNative; status != 0 {
f.failNative = 0
diff --git a/internal/web/ask.go b/internal/web/ask.go
index 9272cca..7b06cf4 100644
--- a/internal/web/ask.go
+++ b/internal/web/ask.go
@@ -24,8 +24,9 @@ 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
- // connection changes or their host is registered (lockMember).
+ // hosts holds a *memberConn per member id: their lock, held while
+ // their connection changes or their host is registered (lockMember),
+ // and their connection's generation (changeLink).
hosts sync.Map
// oficina holds a *sync.Mutex per member id, held while Ask is set up
// with Oficina ID for them (askOficinaLock).
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
index b170928..c189de4 100644
--- a/internal/web/ask_connect.go
+++ b/internal/web/ask_connect.go
@@ -49,9 +49,7 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
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.
- unlock := a.lockMember(me.ID)
- err = store.LoseEquipoLink(ctx, a.db, me.ID, old.DeviceID)
- unlock()
+ 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
@@ -81,11 +79,11 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
}
// 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})
- unlock()
+ err = a.changeLink(me.ID, func() error {
+ 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})
+ })
if err != nil {
a.fail(w, err)
return
@@ -190,9 +188,9 @@ func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec
case errors.Is(err, equipo.ErrPending), errors.Is(err, equipo.ErrSlowDown):
return askPending, nil
case errors.Is(err, equipo.ErrExpired):
- return askExpired, store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID)
+ return askExpired, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) })
case errors.As(err, &e) && e.Status == http.StatusForbidden:
- return askRefused, store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID)
+ return askRefused, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) })
case err != nil:
return askPending, err
}
@@ -217,7 +215,11 @@ func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec
sealed, err := a.sealSecrets(me.ID, 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 {
+ err = a.changeLink(me.ID, func() (e error) {
+ stored, e = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision)
+ return e
+ })
+ if stored {
a.hostFor(ctx, me, l.DeviceID, cred.Token, true)
return askReady
}
@@ -234,7 +236,7 @@ func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec
}
a.logger.Error("ask: store bearer", "device", l.DeviceID, "err", err)
a.revoke(ctx, l, sec)
- if e := store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID); e != nil {
+ if e := a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) }); e != nil {
a.logger.Error("ask: forget device", "device", l.DeviceID, "err", e)
}
return askFailed
@@ -263,9 +265,7 @@ func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) {
a.revoke(r.Context(), l, sec)
}
// 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()
+ err = a.changeLink(me.ID, func() error { return store.DisconnectEquipo(r.Context(), a.db, me.ID, l.DeviceID) })
if err != nil {
a.fail(w, err)
return
@@ -318,12 +318,46 @@ func (a *app) hostFor(ctx context.Context, me store.Member, dev, token string, f
}
}
-// lockMember takes the member's lock, held while their connection
-// changes or their host is registered, and returns its release.
+// memberConn is a member's lock, held while their connection changes or
+// their host is registered, and their connection's generation, which every
+// change to their link moves on (changeLink). The lock is not reentrant:
+// nothing holding it calls hostFor.
+type memberConn struct {
+ mu sync.Mutex
+ gen uint64
+}
+
+func (a *app) memberConn(id string) *memberConn {
+ c, _ := a.ask.hosts.LoadOrStore(id, &memberConn{})
+ return c.(*memberConn)
+}
+
+// lockMember takes the member's lock 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
+ c := a.memberConn(id)
+ c.mu.Lock()
+ return c.mu.Unlock
+}
+
+// changeLink runs change, which changes the member's link (Connect, its
+// approval or end, Disconnect, Ask set up with Oficina ID), under their
+// lock, and moves their connection's generation on: a set-up with Oficina
+// ID that began before it then yields (askOficina). Equipo refusing a key
+// (askLost) is not a change of this kind: a set-up may replace that key.
+func (a *app) changeLink(id string, change func() error) error {
+ c := a.memberConn(id)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.gen++
+ return change()
+}
+
+// linkGen is the member's connection generation now.
+func (a *app) linkGen(id string) uint64 {
+ c := a.memberConn(id)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.gen
}
func (a *app) renderConnect(w http.ResponseWriter, r *http.Request, status int, v connectView) {
diff --git a/internal/web/ask_oficina_native.go b/internal/web/ask_oficina_native.go
index a7f53f1..6bbbc65 100644
--- a/internal/web/ask_oficina_native.go
+++ b/internal/web/ask_oficina_native.go
@@ -46,6 +46,11 @@ const askOficinaTimeout = 45 * time.Second
// Oficina ID. It is this route's alone: /ask/state never says it.
const askNotLinked = "not_linked"
+// askSuperseded is the answer for a set-up that something else overtook
+// while Equipo answered (Disconnect, or a connection from the web): it
+// saved nothing, and revoked the device it made.
+const askSuperseded = "superseded"
+
// renewAfter is when the app should send a fresh assertion for link l,
// zero for a key from the code flow.
func renewAfter(l store.EquipoLink, sec deviceSecrets) time.Time {
@@ -57,7 +62,8 @@ func renewAfter(l store.EquipoLink, sec deviceSecrets) time.Time {
// askOficinaLock is the member's lock for setting Ask up with Oficina ID:
// two posts for the same person run one at a time. It is not lockMember,
-// which the set-up takes itself while it stores and registers.
+// which is never held across a call to Equipo: the set-up takes that only
+// to compare its connection's generation and save (saveOficinaLink).
func (a *app) askOficinaLock(id string) func() {
mu, _ := a.ask.oficina.LoadOrStore(id, &sync.Mutex{})
mu.(*sync.Mutex).Lock()
@@ -85,12 +91,10 @@ func (a *app) askOficina(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), askOficinaTimeout)
defer cancel()
- old, oldSec, oldState, err := a.askLink(ctx, me)
- if err != nil {
- a.logger.Error("ask oficina: link", "err", err)
- writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable})
- return
- }
+ // The connection as the set-up begins. Anything that changes it while
+ // Equipo answers (Disconnect, the web's Connect or its approval) wins:
+ // the set-up then saves nothing.
+ gen := a.linkGen(me.ID)
sess, err := a.ask.client.NativeExchange(ctx, in.Assertion, in.Verifier)
if err != nil {
a.askOficinaRefused(w, "exchange", err)
@@ -114,26 +118,50 @@ func (a *app) askOficina(w http.ResponseWriter, r *http.Request) {
SessionName: sess.Name, SessionValue: sess.Value})
l := store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), State: store.EquipoConnected,
DeviceID: cred.ID, Sealed: sealed, ExpiresAt: exp, Revision: cred.Revision}
+ var superseded bool
+ var old store.EquipoLink
+ var oldSec deviceSecrets
if err == nil {
- // Saving the new link forgets the old host token with it.
- unlock := a.lockMember(me.ID)
- err = store.SaveEquipoLink(ctx, a.db, l)
- unlock()
+ superseded, old, oldSec, err = a.saveOficinaLink(ctx, me, gen, l)
}
- if err != nil {
- a.logger.Error("ask oficina: store", "device", cred.ID, "err", err)
+ if err != nil || superseded {
+ // Nothing was saved: the device made for it goes.
a.revoke(ctx, l, deviceSecrets{Token: cred.Token})
+ if superseded {
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askSuperseded})
+ return
+ }
+ a.logger.Error("ask oficina: store", "device", cred.ID, "err", err)
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable})
return
}
- // The key it replaces is over: revoke it in Equipo, as Connect does.
- if oldState == askReady && old.DeviceID != cred.ID {
+ // 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.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)})
}
+// saveOficinaLink stores l as the member's link, unless their connection
+// has changed since generation gen (superseded, and nothing is stored). It
+// answers the link it replaced, read under the member's lock as it saves.
+// Saving forgets the old host token with it.
+func (a *app) saveOficinaLink(ctx context.Context, me store.Member, gen uint64, l store.EquipoLink) (superseded bool, old store.EquipoLink, oldSec deviceSecrets, err error) {
+ c := a.memberConn(me.ID)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.gen != gen {
+ return true, old, oldSec, nil
+ }
+ if old, oldSec, _, err = a.askLink(ctx, me); err != nil {
+ return false, store.EquipoLink{}, deviceSecrets{}, err
+ }
+ c.gen++
+ return false, old, oldSec, store.SaveEquipoLink(ctx, a.db, l)
+}
+
// askOficinaRefused answers for a step of Equipo's sign-in that failed,
// having stored nothing. The app never hears a 401 here: that would read
// as Base's own session ending.
diff --git a/internal/webtest/ask_oficina_native_test.go b/internal/webtest/ask_oficina_native_test.go
index ea6fc43..09b8f33 100644
--- a/internal/webtest/ask_oficina_native_test.go
+++ b/internal/webtest/ask_oficina_native_test.go
@@ -262,3 +262,117 @@ func TestDisconnectRevokesOficinaKey(t *testing.T) {
t.Errorf("state: %s", s.State)
}
}
+
+// startHeldSetup starts a native set-up that waits at Equipo's exchange,
+// and returns where its answer will come.
+func startHeldSetup(t *testing.T, app *testApp, f *equipotest.Fake) (done <-chan Resp, release func()) {
+ t.Helper()
+ entered, release := f.HoldNextNativeExchange()
+ out := make(chan Resp, 1)
+ go func() { out <- app.connectWithOficina(f, "subject-owner") }()
+ select {
+ case <-entered:
+ case r := <-out:
+ t.Fatalf("the set-up never reached Equipo: %d %s", r.Code, r.Body)
+ case <-time.After(5 * time.Second):
+ t.Fatal("the set-up never reached Equipo")
+ }
+ return out, release
+}
+
+// newDevice is the one device the fake holds that is not in before.
+func newDevice(t *testing.T, f *equipotest.Fake, before []string) string {
+ t.Helper()
+ old := map[string]bool{}
+ for _, id := range before {
+ old[id] = true
+ }
+ var made []string
+ for _, id := range f.Devices() {
+ if !old[id] {
+ made = append(made, id)
+ }
+ }
+ if len(made) != 1 {
+ t.Fatalf("new devices: %v", made)
+ }
+ return made[0]
+}
+
+// A renewal that Disconnect overtakes saves nothing, and revokes the
+// device it made: Disconnect stays done.
+func TestAskOficinaSetupOvertakenByDisconnect(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)
+ }
+ first := liveDevice(t, f)
+ done, release := startHeldSetup(t, app, f)
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ release()
+ wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`)
+ made := newDevice(t, f, []string{first})
+ if n := app.equipoLinks(); n != 0 || !f.Revoked(first) || !f.Revoked(made) {
+ t.Fatalf("links %d, first revoked %v, new revoked %v", n, f.Revoked(first), f.Revoked(made))
+ }
+ if hosts := f.Hosts(); len(hosts) != 1 {
+ t.Errorf("hosts registered: %d", len(hosts))
+ }
+ if s, _ := app.askState(); s.State != "connect" {
+ t.Errorf("state: %s", s.State)
+ }
+}
+
+// A set-up that the web's code flow overtakes saves nothing and revokes
+// its device; the web's connection stays, the one live device.
+func TestAskOficinaSetupOvertakenByWebConnect(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ done, release := startHeldSetup(t, app, f)
+ web.approveEquipo(f)
+ webDevice := liveDevice(t, f)
+ release()
+ wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`)
+ made := newDevice(t, f, []string{webDevice})
+ if live := liveDevice(t, f); live != webDevice || !f.Revoked(made) {
+ t.Fatalf("live %s (web %s), new revoked %v", live, webDevice, f.Revoked(made))
+ }
+ if n := app.equipoLinks(); n != 1 {
+ t.Errorf("links: %d", n)
+ }
+ s, r := app.askState()
+ if s.State != "ready" || !strings.Contains(r.Body, `"renew_after":""`) {
+ t.Errorf("state: %s", r.Body)
+ }
+ if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"w-1"}}); sent.Code != 200 {
+ t.Errorf("send on the web's key: %d %s", sent.Code, sent.Body)
+ }
+}
+
+// A renewal revokes the device it replaces, read as it saves, ready or
+// not: here a key Base no longer uses (it expired here first) but Equipo
+// would still take.
+func TestAskOficinaRenewRevokesWhatItReplaces(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)
+ }
+ first := liveDevice(t, f)
+ if _, err := app.DB.Exec(`UPDATE equipo_links SET expires_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil {
+ t.Fatal(err)
+ }
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Fatalf("state: %s", s.State)
+ }
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("renew: %d %s", r.Code, r.Body)
+ }
+ if !f.Revoked(first) {
+ t.Fatal("the replaced device is still live in Equipo")
+ }
+ liveDevice(t, f)
+}