Clear Ask's Disconnect only when a connection is stored; read auto strictly
Fable's review of 4b1c585. 1. The flag cleared when the web's Connect made a code, before anything was connected: a code that then expired or was refused left the member unflagged, and the app's next automatic set-up connected them; an automatic set-up could also overtake a waiting code. Now SaveEquipoLink (a pending code) leaves the flag as it is. It clears only where a connection is stored, in the same transaction: ConnectEquipoLink when the web's approved code is stored, and the native explicit save (SaveConnectedEquipoLink, explicit). 2. "auto": null read as explicit, and a repeated key took the last value. The body is now decoded with go-json-experiment/json: unknown or repeated names refused, names matched exactly, and auto only absent, true or false; anything else is 400 invalid. 3. An automatic save is checked against the stored flag inside its own transaction (ErrAskDisconnected -> 409 disconnected, its new device revoked), not only through this process's connection generation, and never clears it. The generation now moves only when a save succeeds. Tests: a code that expires or is refused leaves the member disconnected and the automatic set-up refused; an automatic set-up leaves a waiting code alone, whose approval then clears the flag; pressing Connect alone leaves it; the automatic set-up overtaken by Disconnect, and a late web approval after Disconnect, leave it stored and nothing live; a flag stored while an automatic set-up waits at Equipo (the generation unmoved) still wins; null, repeated, misspelt and mistyped auto are 400; TestFailedDisconnectLeavesNoFlag now fails the flag's own UPDATE and checks the link and host token survive; a store test covers each writer; the contract test asserts disconnected:true and 409 disconnected. docs/api/base-native-v1.md says all of it. make ci: 16 packages ran, 0 failed; test step 6.5s of 60s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+365
−68
docs/api/base-native-v1.md+18 −10go.mod+1 −1internal/store/disconnected_test.go+64 −0internal/store/equipo.go+65 −25internal/store/members.go+2 −1internal/web/ask_oficina_native.go+57 −25internal/webtest/ask_disconnect_test.go+143 −6internal/webtest/ask_native_contract_test.go+15 −0
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md| index cfa319a..620fa6d 100644 |
| --- a/docs/api/base-native-v1.md |
| +++ b/docs/api/base-native-v1.md |
| @@ -127,9 +127,10 @@ for a form). Every answer is `no-store`. |
| - `equipo_origin` is the Equipo instance Ask relays to: the audience of the |
| assertion for Ask set-up. |
| - `disconnected` is `true` once the member has disconnected Ask, on any |
| - device or the web, until they connect it themselves. While it is, no |
| - client sets Ask up by itself; the app offers Connect instead. `state` is |
| - then `connect`, as after any Disconnect. |
| + device or the web, until a connection they make themselves is stored. |
| + While it is, no client sets Ask up by itself; the app offers Connect |
| + instead. `state` is then `connect`, as after any Disconnect, or `pending` |
| + while a code from the web's Connect waits for approval (still `true`). |
| **Message** `{"id", "role": "person"|"assistant", "text", "turn_id", "created_at"}`. |
| An assistant's `text` may carry the little Markdown `ask.js` draws (lists, |
| @@ -218,10 +219,15 @@ way it was made, and marks Ask disconnected by the member (`disconnected` |
| in `/ask/state`), for every device and the web. It answers `303 /settings`. |
| A Disconnect that fails changes nothing, the mark included. |
| -Only an explicit connect clears the mark, in the same step that saves the |
| -new connection: the web's Connect (or Reconnect), or |
| -`POST /api/v1/ask/oficina` without `"auto": true`. An explicit set-up that |
| -fails leaves it set. |
| +Only a connection the member makes clears the mark, in the same |
| +transaction that stores it: |
| +- the web's code flow once the code is approved and the key stored (pressing |
| + Connect or Reconnect alone leaves it set; a code that expires, is refused |
| + or is abandoned leaves it set); |
| +- `POST /api/v1/ask/oficina` without `"auto": true`, once its key is stored. |
| + |
| +Any set-up that fails leaves it set. An automatic set-up never clears it, |
| +and the save itself refuses while it is set. |
| ## Ask set-up with Oficina ID |
| @@ -231,7 +237,9 @@ JSON `{"assertion", "verifier", "auto"?}`: an assertion the kit fetched |
| from Oficina ID addressed to `equipo_origin`, and its verifier. `auto` is |
| `true` for a set-up the app starts by itself (after sign-in, or to renew |
| after `renew_after`); leave it out, or send `false`, when the person asked |
| -to connect. Only a native session may |
| +to connect. `auto` must be exactly `true` or `false`: `null`, any other |
| +type, a repeated key or another spelling (`"AUTO"`) is `400 invalid`, as is |
| +any unknown or repeated name. Only a native session may |
| 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 |
| @@ -242,11 +250,11 @@ 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":"disconnected"}` | `auto` was `true`, and the member has disconnected Ask. Nothing was done, at Equipo or here. Show Connect; post again without `auto` only when the person asks. | |
| +| `409` | `{"state":"disconnected"}` | `auto` was `true`, and the member has disconnected Ask (also while a web code waits for approval). Nothing is stored; if the member disconnected while this set-up was at Equipo, the device Equipo made was revoked. Show Connect; post again without `auto` only when the person asks. | |
| | `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 `auto` not a boolean), or Equipo couldn't read it. | |
| +| `400` | `{"state":"invalid"}` | Not JSON, an unknown, repeated or missing name, `auto` not exactly `true` or `false`, or Equipo couldn't read it. | |
| | `403` | `{"state":"forbidden"}` | Not a native session: the web keeps its code flow. | |
| | `502` | `{"state":"unavailable"}` | Equipo didn't answer, or refused the device. Try again later. | |
| | `503` | `{"state":"unavailable"}` | Base couldn't read or store the connection. | |
diff --git a/go.mod b/go.mod| index d416e8a..72610f4 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -9,6 +9,7 @@ require ( |
| github.com/chromedp/cdproto v0.158.6 |
| github.com/chromedp/chromedp v0.21.0 |
| github.com/go-chi/chi/v5 v5.3.2 |
| + github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 |
| ) |
| require ( |
| @@ -17,7 +18,6 @@ require ( |
| amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect |
| github.com/BurntSushi/toml v1.6.0 // indirect |
| github.com/dustin/go-humanize v1.0.1 // indirect |
| - github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect |
| github.com/google/uuid v1.6.0 // indirect |
| github.com/jinzhu/inflection v1.0.0 // indirect |
| github.com/jinzhu/now v1.1.5 // indirect |
diff --git a/internal/store/disconnected_test.go b/internal/store/disconnected_test.go| new file mode 100644 |
| index 0000000..7d5b6f7 |
| --- /dev/null |
| +++ b/internal/store/disconnected_test.go |
| @@ -0,0 +1,64 @@ |
| +package store |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// AskDisconnected is set by Disconnect and cleared only where a connection |
| +// is made: an explicit connected save, or an approval stored. A pending |
| +// code leaves it, and an automatic save refuses while it is set. |
| +func TestAskDisconnectedClearsOnlyOnAConnection(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + ana, _, err := Invite(ctx, db, "ana@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + flag := func() bool { |
| + t.Helper() |
| + v, err := AskDisconnected(ctx, db, ana.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v |
| + } |
| + link := func(dev, state string) EquipoLink { |
| + return EquipoLink{MemberID: ana.ID, Origin: "https://equipo.test", State: state, DeviceID: dev, |
| + Sealed: []byte("s"), ExpiresAt: time.Now().Add(time.Hour)} |
| + } |
| + if err := DisconnectEquipo(ctx, db, ana.ID); err != nil || !flag() { |
| + t.Fatalf("disconnect: %v, flag %v", err, flag()) |
| + } |
| + // A pending code is not a connection. |
| + if err := SaveEquipoLink(ctx, db, link("CODE", EquipoPending)); err != nil || !flag() { |
| + t.Fatalf("pending code: %v, flag %v", err, flag()) |
| + } |
| + // An automatic save refuses, writing nothing. |
| + if err := SaveConnectedEquipoLink(ctx, db, link("AUTO", EquipoConnected), false); !errors.Is(err, ErrAskDisconnected) { |
| + t.Fatalf("automatic save while disconnected: %v", err) |
| + } |
| + if l, _, _ := EquipoLinkFor(ctx, db, ana.ID); l.DeviceID != "CODE" || !flag() { |
| + t.Fatalf("the refused automatic save wrote: %+v, flag %v", l, flag()) |
| + } |
| + // The approval of the code is the connection. |
| + if ok, err := ConnectEquipoLink(ctx, db, ana.ID, "CODE", []byte("b"), time.Now().Add(time.Hour), 3); !ok || err != nil || flag() { |
| + t.Fatalf("approval: %v %v, flag %v", ok, err, flag()) |
| + } |
| + // An approval that stores nothing clears nothing. |
| + if err := DisconnectEquipo(ctx, db, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, _ := ConnectEquipoLink(ctx, db, ana.ID, "CODE", []byte("b"), time.Now().Add(time.Hour), 3); ok || !flag() { |
| + t.Fatalf("a late approval: stored %v, flag %v", ok, flag()) |
| + } |
| + // An explicit connected save clears it. |
| + if err := SaveConnectedEquipoLink(ctx, db, link("NATIVE", EquipoConnected), true); err != nil || flag() { |
| + t.Fatalf("explicit save: %v, flag %v", err, flag()) |
| + } |
| + // And an automatic one, not disconnected, saves. |
| + if err := SaveConnectedEquipoLink(ctx, db, link("RENEW", EquipoConnected), false); err != nil || flag() { |
| + t.Fatalf("automatic renewal: %v, flag %v", err, flag()) |
| + } |
| +} |
diff --git a/internal/store/equipo.go b/internal/store/equipo.go| index 37b8256..04b11b2 100644 |
| --- a/internal/store/equipo.go |
| +++ b/internal/store/equipo.go |
| @@ -53,34 +53,62 @@ func EquipoLinkFor(ctx context.Context, db *sql.DB, memberID string) (l EquipoLi |
| return l, true, nil |
| } |
| +// ErrAskDisconnected: the member has disconnected Ask, so an automatic |
| +// save stores nothing (SaveConnectedEquipoLink). |
| +var ErrAskDisconnected = errors.New("store: Ask disconnected by the member") |
| + |
| // 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. |
| -// It is how the member connects Ask, so it also clears AskDisconnected. |
| +// It leaves AskDisconnected as it is: a pending code is not a connection. |
| func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| + return inTx(ctx, db, func(tx *sql.Tx) error { return saveEquipoLink(ctx, tx, l) }) |
| +} |
| + |
| +// SaveConnectedEquipoLink is SaveEquipoLink for a connected link, made in |
| +// one go (Ask set up with Oficina ID). An explicit one, which the member |
| +// asked for, clears AskDisconnected in the same transaction. An automatic |
| +// one leaves it, and while it is set stores nothing and answers |
| +// ErrAskDisconnected: the flag is checked where the link is written, not |
| +// only by the caller. |
| +func SaveConnectedEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink, explicit bool) error { |
| + return inTx(ctx, db, func(tx *sql.Tx) error { |
| + if explicit { |
| + if _, err := tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 0 WHERE id = ?`, l.MemberID); err != nil { |
| + return err |
| + } |
| + } else { |
| + var disconnected bool |
| + if err := tx.QueryRowContext(ctx, `SELECT ask_disconnected FROM members WHERE id = ?`, l.MemberID).Scan(&disconnected); err != nil { |
| + return err |
| + } |
| + if disconnected { |
| + return ErrAskDisconnected |
| + } |
| + } |
| + return saveEquipoLink(ctx, tx, l) |
| + }) |
| +} |
| + |
| +func saveEquipoLink(ctx context.Context, tx *sql.Tx, l EquipoLink) error { |
| var polled any |
| if l.PolledAt != nil { |
| polled = l.PolledAt.UTC() |
| } |
| - 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 |
| - } |
| - if _, err := tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 0 WHERE 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, |
| - verification_uri = excluded.verification_uri, sealed = excluded.sealed, |
| - 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()) |
| + 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, |
| + verification_uri = excluded.verification_uri, sealed = excluded.sealed, |
| + 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 |
| } |
| func inTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error { |
| @@ -120,12 +148,24 @@ func ReleaseEquipoPoll(ctx context.Context, db *sql.DB, memberID, dev string) er |
| // 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 = '', 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) |
| +// revoke the bearer instead. Stored, it is the member's connection, made |
| +// with their approval in Equipo, so it clears AskDisconnected in the same |
| +// transaction. |
| +func ConnectEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string, sealed []byte, expires time.Time, revision int64) (stored bool, err error) { |
| + err = inTx(ctx, db, func(tx *sql.Tx) error { |
| + res, err := tx.ExecContext(ctx, `UPDATE equipo_links SET state = ?, sealed = ?, expires_at = ?, revision = ?, |
| + 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) |
| + if stored, err = affected(res, err); err != nil || !stored { |
| + return err |
| + } |
| + _, err = tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 0 WHERE id = ?`, memberID) |
| + return err |
| + }) |
| + if err != nil { |
| + stored = false |
| + } |
| + return stored, err |
| } |
| func affected(res sql.Result, err error) (bool, error) { |
diff --git a/internal/store/members.go b/internal/store/members.go| index 7726f23..04fdd58 100644 |
| --- a/internal/store/members.go |
| +++ b/internal/store/members.go |
| @@ -25,7 +25,8 @@ type Member struct { |
| // beside Home on a wide screen, until they open it again. |
| AskClosed bool |
| // AskDisconnected is true once the member has disconnected Ask Base, |
| - // until they connect it themselves (DisconnectEquipo, SaveEquipoLink): |
| + // until a connection they make themselves is stored (DisconnectEquipo, |
| + // ConnectEquipoLink, SaveConnectedEquipoLink): |
| // no app sets it up again by itself meanwhile. |
| AskDisconnected bool |
| } |
diff --git a/internal/web/ask_oficina_native.go b/internal/web/ask_oficina_native.go| index 13032c7..a65b868 100644 |
| --- a/internal/web/ask_oficina_native.go |
| +++ b/internal/web/ask_oficina_native.go |
| @@ -4,13 +4,15 @@ import ( |
| "context" |
| "crypto/ed25519" |
| "crypto/rand" |
| - "encoding/json" |
| "errors" |
| "io" |
| "net/http" |
| "sync" |
| "time" |
| + jsonv2 "github.com/go-json-experiment/json" |
| + "github.com/go-json-experiment/json/jsontext" |
| + |
| "amadan.net/oficina/home/connect" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| @@ -82,16 +84,8 @@ func (a *app) askOficina(w http.ResponseWriter, r *http.Request) { |
| writeJSON(w, http.StatusForbidden, map[string]string{"state": "forbidden"}) |
| return |
| } |
| - var in struct { |
| - Assertion string `json:"assertion"` |
| - Verifier string `json:"verifier"` |
| - // Auto is a set-up the app starts by itself (after sign-in, or to |
| - // renew), which yields to the member's Disconnect; without it the |
| - // person asked, and it connects Ask again. |
| - Auto bool `json:"auto"` |
| - } |
| - if !isJSONBody(r) || decodeStrict(http.MaxBytesReader(w, r.Body, 16<<10), &in) != nil || |
| - in.Assertion == "" || len(in.Assertion) > 8192 || in.Verifier == "" || len(in.Verifier) > 256 { |
| + in, ok := readAskOficina(w, r) |
| + if !ok { |
| writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"}) |
| return |
| } |
| @@ -140,14 +134,18 @@ func (a *app) askOficina(w http.ResponseWriter, r *http.Request) { |
| var old store.EquipoLink |
| var oldSec deviceSecrets |
| if err == nil { |
| - superseded, old, oldSec, err = a.saveOficinaLink(ctx, me, gen, l) |
| + superseded, old, oldSec, err = a.saveOficinaLink(ctx, me, gen, l, !in.Auto) |
| } |
| if err != nil || superseded { |
| // Nothing was saved: the device made for it goes. |
| a.revoke(ctx, l, deviceSecrets{Token: cred.Token}) |
| - if superseded { |
| + switch { |
| + case superseded: |
| writeJSON(w, http.StatusConflict, map[string]string{"state": askSuperseded}) |
| return |
| + case errors.Is(err, store.ErrAskDisconnected): |
| + writeJSON(w, http.StatusConflict, map[string]string{"state": askDisconnected}) |
| + return |
| } |
| a.logger.Error("ask oficina: store", "device", cred.ID, "err", err) |
| writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable}) |
| @@ -163,8 +161,10 @@ func (a *app) askOficina(w http.ResponseWriter, r *http.Request) { |
| // 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) { |
| +// Saving forgets the old host token with it. An explicit save clears the |
| +// member's Disconnect; an automatic one is refused while it stands |
| +// (store.ErrAskDisconnected), checked again in the save's own transaction. |
| +func (a *app) saveOficinaLink(ctx context.Context, me store.Member, gen uint64, l store.EquipoLink, explicit bool) (superseded bool, old store.EquipoLink, oldSec deviceSecrets, err error) { |
| c := a.memberConn(me.ID) |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| @@ -174,8 +174,11 @@ func (a *app) saveOficinaLink(ctx context.Context, me store.Member, gen uint64, |
| if old, oldSec, _, err = a.askLink(ctx, me); err != nil { |
| return false, store.EquipoLink{}, deviceSecrets{}, err |
| } |
| + if err = store.SaveConnectedEquipoLink(ctx, a.db, l, explicit); err != nil { |
| + return false, store.EquipoLink{}, deviceSecrets{}, err |
| + } |
| c.gen++ |
| - return false, old, oldSec, store.SaveEquipoLink(ctx, a.db, l) |
| + return false, old, oldSec, nil |
| } |
| // askOficinaRefused answers for a step of Equipo's sign-in that failed, |
| @@ -200,15 +203,44 @@ func (a *app) askOficinaRefused(w http.ResponseWriter, step string, err error) { |
| } |
| } |
| -// decodeStrict decodes exactly one JSON object with no unknown fields. |
| -func decodeStrict(r io.Reader, v any) error { |
| - d := json.NewDecoder(r) |
| - d.DisallowUnknownFields() |
| - if err := d.Decode(v); err != nil { |
| - return err |
| +// askOficinaIn is POST /api/v1/ask/oficina's body. |
| +type askOficinaIn struct { |
| + Assertion, Verifier string |
| + // Auto is a set-up the app starts by itself (after sign-in, or to |
| + // renew), which yields to the member's Disconnect; without it the |
| + // person asked, and it connects Ask again. |
| + Auto bool |
| +} |
| + |
| +// readAskOficina reads the body strictly: one JSON object with exactly the |
| +// names assertion, verifier and, optionally, auto, each once and spelt so; |
| +// auto only true or false (never null, which a client might send for "not |
| +// set", and which must not read as the person asking). |
| +func readAskOficina(w http.ResponseWriter, r *http.Request) (askOficinaIn, bool) { |
| + if !isJSONBody(r) { |
| + return askOficinaIn{}, false |
| + } |
| + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 16<<10)) |
| + if err != nil { |
| + return askOficinaIn{}, false |
| } |
| - if d.Decode(new(json.RawMessage)) != io.EOF { |
| - return errors.New("trailing JSON") |
| + var in struct { |
| + Assertion string `json:"assertion"` |
| + Verifier string `json:"verifier"` |
| + Auto jsontext.Value `json:"auto"` |
| + } |
| + if jsonv2.Unmarshal(raw, &in, jsonv2.RejectUnknownMembers(true)) != nil || |
| + in.Assertion == "" || len(in.Assertion) > 8192 || in.Verifier == "" || len(in.Verifier) > 256 { |
| + return askOficinaIn{}, false |
| + } |
| + out := askOficinaIn{Assertion: in.Assertion, Verifier: in.Verifier} |
| + switch string(in.Auto) { |
| + case "": |
| + case "true": |
| + out.Auto = true |
| + case "false": |
| + default: |
| + return askOficinaIn{}, false |
| } |
| - return nil |
| + return out, true |
| } |
diff --git a/internal/webtest/ask_disconnect_test.go b/internal/webtest/ask_disconnect_test.go| index c0a1d1a..0f26f1f 100644 |
| --- a/internal/webtest/ask_disconnect_test.go |
| +++ b/internal/webtest/ask_disconnect_test.go |
| @@ -93,10 +93,21 @@ func TestExplicitSetUpSaysSo(t *testing.T) { |
| if r := app.nativePost("/api/v1/ask/oficina", string(body)); r.Code != 200 { |
| t.Fatalf("auto false: %d %s", r.Code, r.Body) |
| } |
| - wantBody(t, "auto not a boolean", app.nativePost("/api/v1/ask/oficina", `{"assertion":"x","verifier":"y","auto":"yes"}`), 400, `{"state":"invalid"}`) |
| + // Only absent, true or false: anything else is refused, whatever it |
| + // might have meant, so no client undoes a Disconnect by accident. |
| + app.post("/ask/disconnect", nil) |
| + for _, auto := range []string{`"auto":null`, `"auto":"true"`, `"auto":1`, `"auto":{}`, `"auto":true,"auto":false`, `"auto":false,"auto":true`, `"AUTO":true`, `"Auto":false`} { |
| + a, v := f.OficinaAssertion("subject-owner") |
| + body := `{"assertion":"` + a + `","verifier":"` + v + `",` + auto + `}` |
| + wantBody(t, auto, app.nativePost("/api/v1/ask/oficina", body), 400, `{"state":"invalid"}`) |
| + } |
| + if !app.storedDisconnected(ownerAddress) || app.equipoLinks() != 0 { |
| + t.Fatal("a refused body connected Ask") |
| + } |
| } |
| -// The web's Connect is explicit too, and an explicit set-up that fails |
| +// The web's Connect clears the flag once the connection is made (its code |
| +// approved), not when the code is shown; an explicit set-up that fails |
| // leaves the flag as it was. |
| func TestWebConnectClearsDisconnected(t *testing.T) { |
| web, app, f := newNativeAskApp(t) |
| @@ -109,10 +120,109 @@ func TestWebConnectClearsDisconnected(t *testing.T) { |
| if !app.askDisconnected() { |
| t.Fatal("a failed explicit set-up cleared the flag") |
| } |
| - web.approveEquipo(f) |
| + code := web.startWebConnect() |
| + if !app.askDisconnected() || !app.storedDisconnected(ownerAddress) { |
| + t.Fatal("pressing Connect cleared the flag before anything was connected") |
| + } |
| + if r := web.approveAndCheck(f, code); r.Code != 303 || r.Location() != "/settings" { |
| + t.Fatalf("approval: %d %q", r.Code, r.Location()) |
| + } |
| if app.askDisconnected() || app.storedDisconnected(ownerAddress) { |
| - t.Fatal("the web's Connect left the flag set") |
| + t.Fatal("the web's approved connection left the flag set") |
| + } |
| +} |
| + |
| +// Fable's P4: a code that is never approved (it expires, or Equipo refuses |
| +// it) leaves the member disconnected, and the app does not connect them. |
| +func TestUnapprovedWebCodeLeavesDisconnected(t *testing.T) { |
| + for _, end := range []string{"expired", "refused"} { |
| + t.Run(end, func(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + f.LinkOficinaID("subject-owner", ownerAddress) |
| + web.approveEquipo(f) |
| + web.post("/ask/disconnect", nil) |
| + web.startWebConnect() |
| + if end == "expired" { |
| + f.Expire() |
| + } else { |
| + f.RevokeAll() |
| + } |
| + web.pollable() |
| + web.check("settings") |
| + if s, _ := app.askState(); s.State != "connect" || !app.askDisconnected() { |
| + t.Fatalf("after the code %s: state %s, disconnected %v", end, s.State, app.askDisconnected()) |
| + } |
| + wantBody(t, "automatic set-up", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`) |
| + wantLive(t, f) |
| + }) |
| + } |
| +} |
| + |
| +// Fable's P4b: while the code waits, the app's automatic set-up does not |
| +// overtake it. |
| +func TestAutomaticSetUpLeavesAWaitingCode(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + f.LinkOficinaID("subject-owner", ownerAddress) |
| + web.approveEquipo(f) |
| + web.post("/ask/disconnect", nil) |
| + code := web.startWebConnect() |
| + wantBody(t, "automatic set-up while a code waits", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`) |
| + if s, _ := app.askState(); s.State != "pending" { |
| + t.Fatalf("the waiting code went: %s", s.State) |
| + } |
| + if r := web.approveAndCheck(f, code); r.Code != 303 || r.Location() != "/settings" { |
| + t.Fatalf("approval: %d %q", r.Code, r.Location()) |
| + } |
| + if app.askDisconnected() || len(f.LiveCredentials()) != 1 { |
| + t.Fatalf("after approval: disconnected %v, live %v", app.askDisconnected(), f.LiveCredentials()) |
| + } |
| +} |
| + |
| +// An automatic set-up waiting at Equipo when Disconnect lands: overtaken, |
| +// nothing live, the flag stored, and the next automatic set-up refused. |
| +func TestAutomaticSetUpOvertakenByDisconnect(t *testing.T) { |
| + _, app, f := newNativeAskApp(t) |
| + f.LinkOficinaID("subject-owner", ownerAddress) |
| + if r := app.connectAuto(f, "subject-owner"); r.Code != 200 { |
| + t.Fatalf("connect: %d %s", r.Code, r.Body) |
| + } |
| + entered, release := f.HoldNextNativeExchange() |
| + done := background(func() Resp { return app.connectAuto(f, "subject-owner") }) |
| + arrived(t, entered, "the automatic set-up") |
| + if r := app.post("/ask/disconnect", nil); r.Code != 303 { |
| + t.Fatalf("disconnect: %d", r.Code) |
| + } |
| + release() |
| + wantBody(t, "overtaken automatic set-up", <-done, 409, `{"state":"superseded"}`) |
| + if n := app.equipoLinks(); n != 0 || !app.storedDisconnected(ownerAddress) { |
| + t.Fatalf("links %d, flag %v", n, app.storedDisconnected(ownerAddress)) |
| + } |
| + wantLive(t, f) |
| + wantBody(t, "next automatic set-up", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`) |
| +} |
| + |
| +// The web's approval landing after Disconnect stores nothing and leaves |
| +// the flag set. |
| +func TestLateWebApprovalAfterDisconnect(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.post("/ask/disconnect", nil); r.Code != 303 { |
| + t.Fatalf("disconnect: %d", r.Code) |
| + } |
| + release() |
| + <-checked |
| + if n := app.equipoLinks(); n != 0 || !app.storedDisconnected(ownerAddress) { |
| + t.Fatalf("links %d, flag %v", n, app.storedDisconnected(ownerAddress)) |
| } |
| + wantLive(t, f) |
| } |
| func TestDisconnectedIsPerMember(t *testing.T) { |
| @@ -137,11 +247,15 @@ func TestDisconnectedIsPerMember(t *testing.T) { |
| wantBody(t, "the owner's", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`) |
| } |
| -// A Disconnect that fails leaves the flag as it was. |
| +// A Disconnect that fails as it sets the flag, after the link and host |
| +// token were deleted, undoes all three: one transaction. |
| func TestFailedDisconnectLeavesNoFlag(t *testing.T) { |
| web, app, f := newNativeAskApp(t) |
| web.approveEquipo(f) |
| - if _, err := web.DB.Exec(`CREATE TRIGGER keep_link BEFORE DELETE ON equipo_links BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil { |
| + if web.hostRows() != 1 { |
| + t.Fatalf("host tokens: %d", web.hostRows()) |
| + } |
| + if _, err := web.DB.Exec(`CREATE TRIGGER keep_flag BEFORE UPDATE OF ask_disconnected ON members BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil { |
| t.Fatal(err) |
| } |
| if r := web.post("/ask/disconnect", nil); r.Code == 303 { |
| @@ -150,6 +264,9 @@ func TestFailedDisconnectLeavesNoFlag(t *testing.T) { |
| if app.askDisconnected() || web.storedDisconnected(ownerAddress) { |
| t.Fatal("a failed Disconnect set the flag") |
| } |
| + if web.equipoLinks() != 1 || web.hostRows() != 1 { |
| + t.Fatalf("a failed Disconnect removed the link (%d) or host token (%d)", web.equipoLinks(), web.hostRows()) |
| + } |
| } |
| // The web shows what it always showed after Disconnect: the connect state. |
| @@ -165,3 +282,23 @@ func TestWebAfterDisconnectShowsConnect(t *testing.T) { |
| t.Fatalf("Settings after Disconnect: %d", r.Code) |
| } |
| } |
| + |
| +// The save's own transaction checks the flag, not only this process's |
| +// generation: a Disconnect another Base process stored while an automatic |
| +// set-up waited at Equipo (the generation here unmoved) still wins. |
| +func TestAutomaticSaveChecksTheStoredFlag(t *testing.T) { |
| + _, app, f := newNativeAskApp(t) |
| + f.LinkOficinaID("subject-owner", ownerAddress) |
| + entered, release := f.HoldNextNativeExchange() |
| + done := background(func() Resp { return app.connectAuto(f, "subject-owner") }) |
| + arrived(t, entered, "the automatic set-up") |
| + if _, err := app.DB.Exec(`UPDATE members SET ask_disconnected = 1 WHERE email = ?`, ownerAddress); err != nil { |
| + t.Fatal(err) |
| + } |
| + release() |
| + wantBody(t, "automatic set-up", <-done, 409, `{"state":"disconnected"}`) |
| + if n := app.equipoLinks(); n != 0 || !app.storedDisconnected(ownerAddress) { |
| + t.Fatalf("links %d, flag %v", n, app.storedDisconnected(ownerAddress)) |
| + } |
| + wantLive(t, f) |
| +} |
diff --git a/internal/webtest/ask_native_contract_test.go b/internal/webtest/ask_native_contract_test.go| index bf87478..f7f92f0 100644 |
| --- a/internal/webtest/ask_native_contract_test.go |
| +++ b/internal/webtest/ask_native_contract_test.go |
| @@ -379,6 +379,21 @@ var keySeq int |
| func equipoKey() string { keySeq++; return "never-401-" + strconv.Itoa(keySeq) } |
| +// After the member disconnects Ask, /ask/state says so and an automatic |
| +// set-up is refused with 409 disconnected. |
| +func TestAskContractDisconnected(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + f.LinkOficinaID("subject-owner", ownerAddress) |
| + web.approveEquipo(f) |
| + web.post("/ask/disconnect", nil) |
| + _, r := app.askState() |
| + wantKeys(t, "state", r.Body, stateKeys...) |
| + if !strings.Contains(r.Body, `"state":"connect"`) || !strings.Contains(r.Body, `"disconnected":true`) { |
| + t.Fatalf("state after Disconnect: %s", r.Body) |
| + } |
| + wantBody(t, "automatic set-up", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`) |
| +} |
| + |
| // sseFrame is one frame of an event stream, as the native client parses it. |
| type sseFrame struct { |
| ID, Event, Data, Retry string |