Harden the Ask relay: bounded streams, one exchange, keyed forms
Review fixes for the Ask Base chat. - Streams: the upstream stream has a 15s header timeout and a 45s idle timeout, every write to the browser has a 30s deadline, and a stream lives at most 10 minutes (the browser reconnects with its cursor). - Device flow: each poll is claimed by a conditional UPDATE only one caller wins; storing the bearer, deleting a link and marking it lost all require the same device. A bearer whose link was disconnected or replaced mid-exchange is revoked, not stored. - GET /ask/connect only shows. The exchange is POST /ask/connect/check (CSRF-checked): "Check again", and the page's script every 5 seconds. - Keys: every chat form carries a key made when the page is drawn; the panel keeps a key until the outcome is known, sends one request per form at a time, and reuses the key when retrying the same body. - Relay: Base parses SSE itself (LF, CRLF or bare CR), bounds each event to 512 KiB and 64 lines, validates the JSON, and writes its own frames with data projected to the conversation's shape; only question cards pass. Upstream lines never reach the browser.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
21 files changed,
+822
−145
docs/copy-pending.md+2 −2internal/browsertest/ask_test.go+57 −8internal/equipo/chat.go+23 −1internal/equipo/equipo.go+3 −1internal/equipo/equipo_test.go+15 −0internal/equipo/equipotest/chat.go+9 −1internal/equipo/equipotest/fake.go+31 −0internal/look/static/ask-connect.js+21 −0internal/look/static/ask.js+26 −4internal/store/equipo.go+36 −13internal/store/equipo_test.go+75 −6internal/web/app.go+4 −1internal/web/ask.go+11 −9internal/web/ask_connect.go+60 −23internal/web/ask_relay.go+201 −60internal/web/relay_internal_test.go+100 −0internal/web/templates/ask_connect.html+3 −3internal/web/templates/partials/chat.html+2 −2internal/webtest/ask_test.go+136 −9internal/webtest/harness_test.go+5 −1internal/webtest/oficina_harness_test.go+2 −1
diff --git a/docs/copy-pending.md b/docs/copy-pending.md| index 1421698..13a57d2 100644 |
| --- a/docs/copy-pending.md |
| +++ b/docs/copy-pending.md |
| @@ -247,8 +247,8 @@ Review 5 (pending): "Ask Base anything", the chat with Equipo's coordinator. |
| | internal/web/templates/ask_connect.html | Waiting for approval, body (the code below it) | In Equipo, check the request is from {device label}, then type this code: | |
| | internal/web/templates/ask_connect.html | The code's accessible name | Your code | |
| | internal/web/templates/ask_connect.html | Waiting for approval, button (Equipo's approval page, new tab) | Open Equipo | |
| -| internal/web/templates/ask_connect.html | Waiting for approval, note | This page checks every few seconds and moves on once you've approved it. | |
| -| internal/web/templates/ask_connect.html | Waiting for approval, button (checks now) | Check again | |
| +| internal/web/templates/ask_connect.html | Waiting for approval, note (with scripts on, the page also checks by itself every five seconds) | Once you've approved it, come back and press Check again. | |
| +| internal/web/templates/ask_connect.html | Waiting for approval, button (asks Equipo now) | Check again | |
| | internal/web/templates/ask_connect.html | Not connected, body | Connect Equipo, and its coordinator answers you in Base. | |
| | internal/web/templates/ask_connect.html | Code expired, body | That code expired. Start again to get a new one. | |
| | internal/web/templates/ask_connect.html | Equipo refused the exchange (403), body | Equipo didn't accept that request. Start again. | |
diff --git a/internal/browsertest/ask_test.go b/internal/browsertest/ask_test.go| index 71061ba..bc30655 100644 |
| --- a/internal/browsertest/ask_test.go |
| +++ b/internal/browsertest/ask_test.go |
| @@ -34,10 +34,11 @@ func TestAskFieldOffIsGlass(t *testing.T) { |
| } |
| } |
| -// The owner connects Equipo from Settings, opens the panel from Home, asks |
| -// one thing and sees the coordinator's reply stream in; Escape closes the |
| -// panel and gives focus back to the field. |
| -func TestAskPanel(t *testing.T) { |
| +// askBase is Base answered by a fake Equipo, the owner signed in and |
| +// connected to it from Settings: Connect Equipo, approve the code in |
| +// Equipo, Check again. |
| +func askBase(t *testing.T) (*harness.Rig, *equipotest.Fake) { |
| + t.Helper() |
| f := equipotest.New(t) |
| f.Reply = func(string) string { |
| return "You can ask me to plan work, check on a project, or start a task. What would you like to do?" |
| @@ -51,8 +52,6 @@ func TestAskPanel(t *testing.T) { |
| }) |
| signInByEmail(t, rig, rig.Origin, b.mail) |
| drive(t, rig, chromedp.EmulateViewport(1280, 800)) |
| - |
| - // Connect: Settings, then the code page; approve in Equipo, check again. |
| connect := `form[action="/ask/connect"] button` |
| drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(connect)), |
| chromedp.Click(chromedp.CSS(connect)), chromedp.WaitVisible(chromedp.CSS(`p.code`))) |
| @@ -67,13 +66,63 @@ func TestAskPanel(t *testing.T) { |
| if _, err := b.db.Exec(`UPDATE equipo_links SET polled_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil { |
| t.Fatal(err) |
| } |
| - drive(t, rig, chromedp.Click(chromedp.CSS(`a[href^="/ask/connect"]`)), |
| + drive(t, rig, chromedp.Click(chromedp.CSS(`form[action="/ask/connect/check"] button`)), |
| chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`))) |
| rig.Screen(".sheet", "Settings, Equipo connected") |
| + return rig, f |
| +} |
| - // Ask. |
| +// openPanel opens the panel from Home's Ask field. |
| +func openPanel(t *testing.T, rig *harness.Rig) { |
| + t.Helper() |
| drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`a.ask`)), |
| chromedp.Click(chromedp.CSS(`a.ask`)), chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`))) |
| +} |
| + |
| +// A double press sends once, and sending again after an answer was lost |
| +// on the way back reuses the key, so Equipo does the work once. |
| +func TestAskPanelSendsOnce(t *testing.T) { |
| + rig, f := askBase(t) |
| + openPanel(t, rig) |
| + send := `#ask-panel form.composer button` |
| + drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Build me a quick website"), |
| + chromedp.Evaluate[chromedp.Void](`(() => { const b = document.querySelector("`+send+`"); b.click(); b.click(); })()`), |
| + chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.person").length === 1`, chromedp.WithPollingTimeout(5*time.Second))) |
| + if n := len(f.Calls("/api/v1/messages")); n != 1 { |
| + t.Fatalf("a double press sent %d requests", n) |
| + } |
| + |
| + f.FailNextSend() |
| + drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Put a meeting in my calendar with doc@tito.io for 2pm on Tuesday"), |
| + chromedp.Click(chromedp.CSS(send)), |
| + chromedp.Poll[chromedp.Void](`document.querySelector("#ask-panel .ask-status").textContent.includes("didn't get that")`, chromedp.WithPollingTimeout(5*time.Second)), |
| + chromedp.Click(chromedp.CSS(send)), |
| + // A send that got its answer clears the field. |
| + chromedp.Poll[chromedp.Void](`document.querySelector("#ask-text").value === ""`, chromedp.WithPollingTimeout(5*time.Second))) |
| + if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 2 { |
| + t.Errorf("person messages shown: %d, want 2", got) |
| + } |
| + calls := f.Calls("/api/v1/messages") |
| + if len(calls) != 3 || calls[1].Header.Get("Idempotency-Key") != calls[2].Header.Get("Idempotency-Key") || |
| + calls[0].Header.Get("Idempotency-Key") == calls[1].Header.Get("Idempotency-Key") { |
| + t.Fatalf("keys: %v", keys(calls)) |
| + } |
| +} |
| + |
| +func keys(calls []equipotest.Call) []string { |
| + var out []string |
| + for _, c := range calls { |
| + out = append(out, c.Header.Get("Idempotency-Key")) |
| + } |
| + return out |
| +} |
| + |
| +// The owner opens the panel from Home, asks one thing and sees the |
| +// coordinator's reply stream in; Escape closes the panel and gives focus |
| +// back to the field. |
| +func TestAskPanel(t *testing.T) { |
| + rig, f := askBase(t) |
| + openPanel(t, rig) |
| if here := harness.Read(rig, chromedp.Location()); here != rig.Origin+"/" { |
| t.Fatalf("the field navigated to %s instead of opening the panel", here) |
| } |
diff --git a/internal/equipo/chat.go b/internal/equipo/chat.go| index 83c73a0..7d958fe 100644 |
| --- a/internal/equipo/chat.go |
| +++ b/internal/equipo/chat.go |
| @@ -2,6 +2,7 @@ package equipo |
| import ( |
| "context" |
| + "io" |
| "net/http" |
| "net/url" |
| "time" |
| @@ -109,25 +110,46 @@ func (c *Client) Answer(ctx context.Context, token, id, choice string, revision |
| } |
| // Events opens the person's event stream after cursor after ("" for from |
| -// now). The caller reads and closes the body; ctx ends the stream. |
| +// now). It gives up when the headers take longer than StreamHeaderTimeout. |
| +// The caller reads and closes the body; cancelling ctx ends the stream. |
| func (c *Client) Events(ctx context.Context, token, after string) (*http.Response, error) { |
| u := c.origin + "/api/v1/events" |
| if after != "" { |
| u += "?after=" + url.QueryEscape(after) |
| } |
| + ctx, cancel := context.WithCancel(ctx) |
| req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) |
| if err != nil { |
| + cancel() |
| return nil, err |
| } |
| req.Header.Set("Accept", "text/event-stream") |
| req.Header.Set("Authorization", "Bearer "+token) |
| + late := time.AfterFunc(c.StreamHeaderTimeout, cancel) |
| res, err := c.http.Do(req) |
| + if !late.Stop() && err == nil { |
| + res.Body.Close() |
| + err = context.DeadlineExceeded |
| + } |
| if err != nil { |
| + cancel() |
| return nil, err |
| } |
| if res.StatusCode != http.StatusOK { |
| res.Body.Close() |
| + cancel() |
| return nil, &Error{Status: res.StatusCode} |
| } |
| + res.Body = cancelOnClose{res.Body, cancel} |
| return res, nil |
| } |
| + |
| +type cancelOnClose struct { |
| + io.ReadCloser |
| + cancel context.CancelFunc |
| +} |
| + |
| +func (b cancelOnClose) Close() error { |
| + b.cancel() |
| + return b.ReadCloser.Close() |
| +} |
diff --git a/internal/equipo/equipo.go b/internal/equipo/equipo.go| index c2eede5..fb7a04d 100644 |
| --- a/internal/equipo/equipo.go |
| +++ b/internal/equipo/equipo.go |
| @@ -82,12 +82,14 @@ type Credential struct { |
| type Client struct { |
| origin string |
| http *http.Client |
| + // StreamHeaderTimeout bounds the wait for the event stream's headers. |
| + StreamHeaderTimeout time.Duration |
| } |
| // New is a client for the Equipo at origin. It never follows a redirect, |
| // so a bearer goes nowhere but origin. |
| func New(origin string) *Client { |
| - return &Client{origin: strings.TrimRight(origin, "/"), http: &http.Client{ |
| + return &Client{origin: strings.TrimRight(origin, "/"), StreamHeaderTimeout: 15 * time.Second, http: &http.Client{ |
| CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| }} |
| } |
diff --git a/internal/equipo/equipo_test.go b/internal/equipo/equipo_test.go| index f758b9a..da24c63 100644 |
| --- a/internal/equipo/equipo_test.go |
| +++ b/internal/equipo/equipo_test.go |
| @@ -6,9 +6,12 @@ import ( |
| "crypto/rand" |
| "encoding/json" |
| "errors" |
| + "net/http" |
| + "net/http/httptest" |
| "os" |
| "strings" |
| "testing" |
| + "time" |
| "amadan.net/rastrillo/rastrillo/budget" |
| @@ -128,3 +131,15 @@ func TestSealIsPerMember(t *testing.T) { |
| t.Fatal("another instance key opened it") |
| } |
| } |
| + |
| +// An Equipo that never answers the stream's headers does not hold Base. |
| +func TestEventsHeaderTimeout(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })) |
| + defer srv.Close() |
| + c := equipo.New(srv.URL) |
| + c.StreamHeaderTimeout = 100 * time.Millisecond |
| + start := time.Now() |
| + if _, err := c.Events(context.Background(), "token", ""); err == nil || time.Since(start) > 2*time.Second { |
| + t.Fatalf("Events: %v after %s", err, time.Since(start)) |
| + } |
| +} |
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go| index b39ebdd..3785b66 100644 |
| --- a/internal/equipo/equipotest/chat.go |
| +++ b/internal/equipo/equipotest/chat.go |
| @@ -206,7 +206,15 @@ func (f *Fake) send(w http.ResponseWriter, r *http.Request) { |
| m, t := f.ask(in.Text) |
| f.sent[in.IdempotencyKey] = m.ID |
| f.cmu.Unlock() |
| - writeJSON(w, 201, map[string]any{"message": m, "turn": t}) |
| + f.mu.Lock() |
| + lost := f.failSend |
| + f.failSend = false |
| + f.mu.Unlock() |
| + if lost { |
| + writeError(w, r, 503, "unavailable") |
| + } else { |
| + writeJSON(w, 201, map[string]any{"message": m, "turn": t}) |
| + } |
| go f.answerTurn(t.ID, in.Text) |
| } |
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go| index 7813115..2481c49 100644 |
| --- a/internal/equipo/equipotest/fake.go |
| +++ b/internal/equipo/equipotest/fake.go |
| @@ -54,9 +54,32 @@ type Fake struct { |
| mu sync.Mutex |
| calls []Call |
| devices map[string]*device |
| + // hold, when set, stops the next exchange until it is closed. |
| + hold chan struct{} |
| + entered chan struct{} |
| + failSend bool |
| chat |
| } |
| +// HoldNextExchange makes the next 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) HoldNextExchange() (entered <-chan struct{}, release func()) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.hold, f.entered = make(chan struct{}), make(chan struct{}) |
| + hold := f.hold |
| + return f.entered, func() { close(hold) } |
| +} |
| + |
| +// FailNextSend makes the next new message's answer a 503 after Equipo has |
| +// recorded it, as when the answer is lost on the way back. |
| +func (f *Fake) FailNextSend() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.failSend = true |
| +} |
| + |
| // New starts a fake Equipo, stopped when the test ends. |
| func New(t testing.TB) *Fake { |
| f := &Fake{Instance: "TEAM1", closing: make(chan struct{}), devices: map[string]*device{}, |
| @@ -215,6 +238,14 @@ func (f *Fake) exchange(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| f.mu.Lock() |
| + hold, entered := f.hold, f.entered |
| + f.hold, f.entered = nil, nil |
| + f.mu.Unlock() |
| + if hold != nil { |
| + close(entered) |
| + <-hold |
| + } |
| + f.mu.Lock() |
| defer f.mu.Unlock() |
| d, ok := f.devices[p.ID] |
| if !ok { |
diff --git a/internal/look/static/ask-connect.js b/internal/look/static/ask-connect.js| new file mode 100644 |
| index 0000000..9270034 |
| --- /dev/null |
| +++ b/internal/look/static/ask-connect.js |
| @@ -0,0 +1,21 @@ |
| +// The connect page: while the code waits, post "Check again" every five |
| +// seconds (Equipo's shortest interval) and move on when the state changes. |
| +// Without this script the person presses Check again themselves. |
| + |
| +const form = document.querySelector("form[data-connect-check]"); |
| +if (form) { |
| + setInterval(async () => { |
| + if (document.hidden) return; |
| + try { |
| + const res = await fetch(form.action, { |
| + method: "POST", |
| + headers: { Accept: "application/json" }, |
| + body: new URLSearchParams(new FormData(form)), |
| + }); |
| + const out = await res.json(); |
| + if (res.ok && out.state !== "pending") location.assign(out.location); |
| + } catch { |
| + // Equipo or Base is unreachable: try again on the next tick. |
| + } |
| + }, 5000); |
| +} |
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js| index 5180661..e56face 100644 |
| --- a/internal/look/static/ask.js |
| +++ b/internal/look/static/ask.js |
| @@ -183,19 +183,41 @@ function start(root) { |
| listen(s.cursor); |
| } |
| - // post sends a form by fetch and returns its JSON, or null when it failed |
| - // (and the panel says so). |
| + // Each form's request in flight or of unknown outcome: its key, and the |
| + // body it was made for. A form is sent once at a time; a retry of the |
| + // same body (after a lost answer, or Equipo not answering) reuses the |
| + // key, so Equipo does the work once. A known outcome forgets it. |
| + const sending = new WeakMap(); |
| + |
| + // post sends a form by fetch and returns its JSON, or null when it was |
| + // already on its way or failed (and the panel says so). |
| async function post(form, extra) { |
| const body = new URLSearchParams(new FormData(form)); |
| + body.delete("key"); |
| for (const [k, v] of Object.entries(extra || {})) body.set(k, v); |
| + const sig = body.toString(); |
| + let req = sending.get(form); |
| + if (req && req.busy) return null; |
| + if (!req || req.sig !== sig) req = { sig, key: key() }; |
| + req.busy = true; |
| + sending.set(form, req); |
| + body.set("key", req.key); |
| + let known = false; |
| try { |
| const res = await fetch(form.action, { method: "POST", headers: json, body }); |
| const out = await res.json(); |
| + known = res.status !== 502; |
| if (res.ok) return out; |
| - if (out.state && out.state !== "ready") show(out.state); |
| + // Lost the connection: the panel says what to do. Otherwise the |
| + // conversation stays, with a line to try again (a 409 is stale: the |
| + // next events show how things are). |
| + if (["connect", "pending", "reconnect"].includes(out.state)) show(out.state); |
| else if (res.status !== 409) status.textContent = "Equipo didn't get that. Try again."; |
| } catch { |
| status.textContent = "Equipo didn't get that. Try again."; |
| + } finally { |
| + req.busy = false; |
| + if (known) sending.delete(form); |
| } |
| return null; |
| } |
| @@ -203,7 +225,7 @@ function start(root) { |
| composer.addEventListener("submit", async (e) => { |
| e.preventDefault(); |
| if (!field.value.trim()) return; |
| - const sent = await post(composer, { key: key() }); |
| + const sent = await post(composer); |
| if (!sent) return; |
| field.value = ""; |
| addMessage(sent.message); |
diff --git a/internal/store/equipo.go b/internal/store/equipo.go| index 86b8ac5..3bc4599 100644 |
| --- a/internal/store/equipo.go |
| +++ b/internal/store/equipo.go |
| @@ -69,23 +69,46 @@ func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| return err |
| } |
| -// MarkEquipoPolled records when Base last asked Equipo whether a pending |
| -// sign-in was approved, so it never asks more often than Equipo allows. |
| -func MarkEquipoPolled(ctx context.Context, db *sql.DB, memberID string, at time.Time) error { |
| - _, err := db.ExecContext(ctx, `UPDATE equipo_links SET polled_at = ?, updated_at = ? WHERE member_id = ?`, |
| - at.UTC(), time.Now().UTC(), memberID) |
| - return err |
| +// 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()) |
| + return affected(res, 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 = ?`, |
| + EquipoConnected, sealed, expires.UTC(), revision, time.Now().UTC(), memberID, dev, EquipoPending) |
| + return affected(res, err) |
| +} |
| + |
| +func affected(res sql.Result, err error) (bool, error) { |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + return n == 1, err |
| } |
| -// SetEquipoLinkState moves the member's link to state. |
| -func SetEquipoLinkState(ctx context.Context, db *sql.DB, memberID, state string) error { |
| - _, err := db.ExecContext(ctx, `UPDATE equipo_links SET state = ?, updated_at = ? WHERE member_id = ?`, |
| - state, time.Now().UTC(), memberID) |
| +// SetEquipoLinkState moves the member's link to state, if it is still |
| +// device dev. |
| +func SetEquipoLinkState(ctx context.Context, db *sql.DB, memberID, dev, state string) error { |
| + _, err := db.ExecContext(ctx, `UPDATE equipo_links SET state = ?, updated_at = ? WHERE member_id = ? AND device_id = ?`, |
| + state, time.Now().UTC(), memberID, dev) |
| return err |
| } |
| -// DeleteEquipoLink forgets the member's link. |
| -func DeleteEquipoLink(ctx context.Context, db *sql.DB, memberID string) error { |
| - _, err := db.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ?`, memberID) |
| +// DeleteEquipoLink forgets the member's link, if it is still device dev. |
| +func DeleteEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error { |
| + _, err := db.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ? AND device_id = ?`, memberID, dev) |
| return err |
| } |
diff --git a/internal/store/equipo_test.go b/internal/store/equipo_test.go| index cf681f6..9e5eccd 100644 |
| --- a/internal/store/equipo_test.go |
| +++ b/internal/store/equipo_test.go |
| @@ -2,6 +2,7 @@ package store |
| import ( |
| "context" |
| + "database/sql" |
| "testing" |
| "time" |
| ) |
| @@ -27,10 +28,6 @@ func TestEquipoLinkRoundTrip(t *testing.T) { |
| string(got.Sealed) != "sealed" || got.PolledAt != nil { |
| t.Fatalf("got %+v %v %v", got, ok, err) |
| } |
| - at := time.Now().UTC().Truncate(time.Second) |
| - if err := MarkEquipoPolled(ctx, db, ana.ID, at); err != nil { |
| - t.Fatal(err) |
| - } |
| got.State, got.Sealed, got.Revision = EquipoConnected, []byte("token"), 3 |
| if err := SaveEquipoLink(ctx, db, got); err != nil { |
| t.Fatal(err) |
| @@ -39,13 +36,13 @@ func TestEquipoLinkRoundTrip(t *testing.T) { |
| if got.State != EquipoConnected || string(got.Sealed) != "token" || got.Revision != 3 { |
| t.Fatalf("replace: %+v", got) |
| } |
| - if err := SetEquipoLinkState(ctx, db, ana.ID, EquipoLost); err != nil { |
| + if err := SetEquipoLinkState(ctx, db, ana.ID, "DEV1", EquipoLost); err != nil { |
| t.Fatal(err) |
| } |
| if got, _, _ = EquipoLinkFor(ctx, db, ana.ID); got.State != EquipoLost { |
| t.Fatalf("state: %+v", got) |
| } |
| - if err := DeleteEquipoLink(ctx, db, ana.ID); err != nil { |
| + if err := DeleteEquipoLink(ctx, db, ana.ID, "DEV1"); err != nil { |
| t.Fatal(err) |
| } |
| if _, ok, _ := EquipoLinkFor(ctx, db, ana.ID); ok { |
| @@ -72,3 +69,75 @@ func TestRemoveMemberDeletesEquipoLink(t *testing.T) { |
| t.Fatalf("links left: %d %v", n, err) |
| } |
| } |
| + |
| +func pendingLink(t *testing.T, db *sql.DB, device string) Member { |
| + t.Helper() |
| + m, _, err := Invite(context.Background(), db, device+"@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := SaveEquipoLink(context.Background(), db, EquipoLink{MemberID: m.ID, Origin: "https://equipo.test", |
| + State: EquipoPending, DeviceID: device, Sealed: []byte("x"), ExpiresAt: time.Now().Add(time.Minute)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return m |
| +} |
| + |
| +// Two polls at once: exactly one claims the right to ask Equipo, and no |
| +// one may ask again inside the interval. |
| +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) |
| + 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 { |
| + 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 { |
| + t.Fatal("no claim after the interval") |
| + } |
| + if other, _ := ClaimEquipoPoll(ctx, db, m.ID, "D2", now.Add(time.Hour), 5*time.Second); other { |
| + t.Fatal("claimed for a device that is not the member's") |
| + } |
| +} |
| + |
| +// Completing an exchange needs the same pending device still there: a |
| +// Disconnect (or a new Connect) in the meantime wins. |
| +func TestConnectEquipoLinkNeedsSamePendingDevice(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + m := pendingLink(t, db, "D1") |
| + exp := time.Now().Add(time.Hour) |
| + if err := DeleteEquipoLink(ctx, db, m.ID, "D1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, err := ConnectEquipoLink(ctx, db, m.ID, "D1", []byte("bearer"), exp, 3); ok || err != nil { |
| + t.Fatalf("completed a disconnected link: %v %v", ok, err) |
| + } |
| + if _, found, _ := EquipoLinkFor(ctx, db, m.ID); found { |
| + t.Fatal("completing brought the link back") |
| + } |
| + m2 := pendingLink(t, db, "D2") |
| + if ok, _ := ConnectEquipoLink(ctx, db, m2.ID, "OLD", []byte("bearer"), exp, 3); ok { |
| + t.Fatal("completed for a replaced device") |
| + } |
| + if ok, _ := ConnectEquipoLink(ctx, db, m2.ID, "D2", []byte("bearer"), exp, 3); !ok { |
| + t.Fatal("did not complete the pending device") |
| + } |
| + l, _, _ := EquipoLinkFor(ctx, db, m2.ID) |
| + if l.State != EquipoConnected || string(l.Sealed) != "bearer" || l.Revision != 3 || l.UserCode != "" { |
| + t.Fatalf("link: %+v", l) |
| + } |
| + // Stale device ids change nothing. |
| + if err := SetEquipoLinkState(ctx, db, m2.ID, "OLD", EquipoLost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := DeleteEquipoLink(ctx, db, m2.ID, "OLD"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if l, found, _ := EquipoLinkFor(ctx, db, m2.ID); !found || l.State != EquipoConnected { |
| + t.Fatalf("a stale device id changed the link: %+v %v", l, found) |
| + } |
| +} |
diff --git a/internal/web/app.go b/internal/web/app.go| index 75b4aef..7153779 100644 |
| --- a/internal/web/app.go |
| +++ b/internal/web/app.go |
| @@ -7,6 +7,7 @@ import ( |
| "database/sql" |
| "embed" |
| "errors" |
| + "html/template" |
| "io/fs" |
| "log/slog" |
| "net/http" |
| @@ -26,6 +27,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo/webauthn" |
| "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/equipo" |
| "amadan.net/carlos/base/internal/issuer" |
| "amadan.net/carlos/base/internal/look" |
| "amadan.net/carlos/base/internal/store" |
| @@ -78,7 +80,8 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| if err != nil { |
| return nil, err |
| } |
| - pages, err := look.NewRenderer(sub, nil) |
| + // newKey gives each chat form its own request key when the page is drawn. |
| + pages, err := look.NewRenderer(sub, template.FuncMap{"newKey": equipo.NewKey}) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/web/ask.go b/internal/web/ask.go| index 76c7e9c..9c17fa8 100644 |
| --- a/internal/web/ask.go |
| +++ b/internal/web/ask.go |
| @@ -34,6 +34,7 @@ func (a *app) askRoutes(r chi.Router) { |
| r.Post("/ask/cards/{id}/answer", a.askAnswer) |
| r.Post("/ask/connect", a.askConnectStart) |
| r.Get("/ask/connect", a.askConnectPage) |
| + r.Post("/ask/connect/check", a.askConnectCheck) |
| r.Post("/ask/disconnect", a.askDisconnect) |
| } |
| @@ -103,9 +104,10 @@ func (a *app) askLink(ctx context.Context, me store.Member) (store.EquipoLink, d |
| return l, sec, askReconnect, nil |
| } |
| -// askLost records that Equipo refused the member's bearer. |
| -func (a *app) askLost(ctx context.Context, me store.Member) { |
| - if err := store.SetEquipoLinkState(ctx, a.db, me.ID, store.EquipoLost); err != nil { |
| +// askLost records that Equipo refused the bearer of the member's device |
| +// dev, unless the link has moved on to another device since. |
| +func (a *app) askLost(ctx context.Context, me store.Member, dev string) { |
| + if err := store.SetEquipoLinkState(ctx, a.db, me.ID, dev, store.EquipoLost); err != nil { |
| a.logger.Error("ask: mark lost", "err", err) |
| } |
| } |
| @@ -180,11 +182,11 @@ func (v *askView) fill(s equipo.Snapshot) { |
| // askSnapshot reads the member's conversation into v, moving v.State to |
| // reconnect or unavailable when Equipo refuses or does not answer. |
| -func (a *app) askSnapshot(r *http.Request, me store.Member, token string, v *askView) int64 { |
| +func (a *app) askSnapshot(r *http.Request, me store.Member, l store.EquipoLink, token string, v *askView) int64 { |
| s, err := a.ask.client.Snapshot(r.Context(), token) |
| switch { |
| case errors.Is(err, equipo.ErrUnauthenticated): |
| - a.askLost(r.Context(), me) |
| + a.askLost(r.Context(), me, l.DeviceID) |
| v.State = askReconnect |
| case err != nil: |
| a.logger.Warn("ask: snapshot", "err", err) |
| @@ -204,7 +206,7 @@ type askPage struct { |
| // with scripts off. |
| func (a *app) askPageView(w http.ResponseWriter, r *http.Request) { |
| me, _ := CurrentMember(r) |
| - _, sec, state, err := a.askLink(r.Context(), me) |
| + l, sec, state, err := a.askLink(r.Context(), me) |
| if err != nil { |
| a.logger.Error("ask: link", "err", err) |
| http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| @@ -212,7 +214,7 @@ func (a *app) askPageView(w http.ResponseWriter, r *http.Request) { |
| } |
| v := a.newAskView(homeState(state), "ask") |
| if state == askReady { |
| - a.askSnapshot(r, me, sec.Token, &v) |
| + a.askSnapshot(r, me, l, sec.Token, &v) |
| } |
| if r.URL.Query().Get("problem") != "" && v.State == askReady { |
| v.Problem = "Equipo didn't get that. Try again." |
| @@ -225,7 +227,7 @@ func (a *app) askPageView(w http.ResponseWriter, r *http.Request) { |
| // event stream starts after. |
| func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) { |
| me, _ := CurrentMember(r) |
| - _, sec, state, err := a.askLink(r.Context(), me) |
| + l, sec, state, err := a.askLink(r.Context(), me) |
| if err != nil { |
| a.logger.Error("ask: link", "err", err) |
| http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| @@ -234,7 +236,7 @@ func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) { |
| v := a.newAskView(homeState(state), "home") |
| var cursor int64 |
| if state == askReady { |
| - cursor = a.askSnapshot(r, me, sec.Token, &v) |
| + cursor = a.askSnapshot(r, me, l, sec.Token, &v) |
| } |
| out := struct { |
| State string `json:"state"` |
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go| index a92fab4..3c18f07 100644 |
| --- a/internal/web/ask_connect.go |
| +++ b/internal/web/ask_connect.go |
| @@ -82,40 +82,75 @@ func (a *app) verifyURI(ch equipo.Challenge) string { |
| return a.ask.client.Origin() + "/auth/devices/" + ch.ID |
| } |
| -// askConnectPage is GET /ask/connect: the code to approve while it waits, |
| -// finishing the exchange once the member has approved it. It refreshes |
| -// itself every five seconds, and asks Equipo no more often than that. |
| +// askConnectPage is GET /ask/connect. It only shows: the code to approve |
| +// while one waits, or what happened to it (?ended=expired or refused). The |
| +// exchange is POST /ask/connect/check, behind Base's CSRF check. |
| func (a *app) askConnectPage(w http.ResponseWriter, r *http.Request) { |
| me, _ := CurrentMember(r) |
| - next := nextOf(r.URL.Query().Get("next")) |
| + q := r.URL.Query() |
| + next := nextOf(q.Get("next")) |
| + l, _, state, err := a.askLink(r.Context(), me) |
| + if err != nil { |
| + a.fail(w, err) |
| + return |
| + } |
| + if state == askReady { |
| + http.Redirect(w, r, askNext[next], http.StatusSeeOther) |
| + return |
| + } |
| + v := connectView{State: state, Next: next, Code: l.UserCode, Verify: l.VerificationURI} |
| + if ended := q.Get("ended"); state == askConnect && (ended == askExpired || ended == askRefused) { |
| + v.State = ended |
| + } |
| + if q.Get("problem") != "" && state == askPending { |
| + v.Problem = "Equipo isn't answering. Base will keep trying." |
| + } |
| + a.renderConnect(w, r, http.StatusOK, v) |
| +} |
| + |
| +// askConnectCheck is POST /ask/connect/check: Check again, and what the |
| +// connect page's script posts every five seconds. It finishes the |
| +// exchange once the member has approved the code. The panel's script gets |
| +// JSON: the state, and the location the form would go to. |
| +func (a *app) askConnectCheck(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + next := nextOf(r.PostFormValue("next")) |
| l, sec, state, err := a.askLink(r.Context(), me) |
| if err != nil { |
| a.fail(w, err) |
| return |
| } |
| - v := connectView{State: state, Next: next} |
| + problem := false |
| if state == askPending { |
| - if v.State, err = a.poll(r.Context(), me, l, sec); err != nil { |
| + if state, err = a.poll(r.Context(), me, l, sec); err != nil { |
| a.logger.Warn("ask: exchange", "err", err) |
| - v.Problem = "Equipo isn't answering. Base will keep trying." |
| + problem = true |
| } |
| } |
| - if v.State == askReady { |
| - http.Redirect(w, r, askNext[next], http.StatusSeeOther) |
| + target := "/ask/connect?next=" + next |
| + switch { |
| + case state == askReady: |
| + target = askNext[next] |
| + case state == askExpired || state == askRefused: |
| + target += "&ended=" + state |
| + case problem: |
| + target += "&problem=1" |
| + } |
| + if wantsJSON(r) { |
| + writeJSON(w, http.StatusOK, map[string]string{"state": state, "next": askNext[next], "location": target}) |
| return |
| } |
| - v.Code, v.Verify = l.UserCode, l.VerificationURI |
| - a.renderConnect(w, r, http.StatusOK, v) |
| + http.Redirect(w, r, target, http.StatusSeeOther) |
| } |
| // poll asks Equipo whether the member approved the code, and stores the |
| -// bearer if so. It does not ask within pollEvery of the last time. |
| +// bearer if so. Only one caller can claim each poll, and not within |
| +// pollEvery of the last. The bearer is stored only while the link is still |
| +// 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) { |
| - now := time.Now() |
| - if l.PolledAt != nil && now.Sub(*l.PolledAt) < pollEvery { |
| - return askPending, nil |
| - } |
| - if err := store.MarkEquipoPolled(ctx, a.db, me.ID, now); err != nil { |
| + claimed, err := store.ClaimEquipoPoll(ctx, a.db, me.ID, l.DeviceID, time.Now(), pollEvery) |
| + if err != nil || !claimed { |
| return askPending, err |
| } |
| ch := equipo.Challenge{ID: l.DeviceID, DeviceSecret: sec.Secret, Challenge: sec.Challenge} |
| @@ -129,9 +164,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) |
| + return askExpired, 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) |
| + return askRefused, store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) |
| case err != nil: |
| return askPending, err |
| } |
| @@ -140,9 +175,11 @@ func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec |
| if err != nil { |
| return askPending, err |
| } |
| - l.State, l.Sealed, l.ExpiresAt, l.Revision, l.UserCode = store.EquipoConnected, sealed, cred.ExpiresAt, cred.Revision, "" |
| - if err := store.SaveEquipoLink(ctx, a.db, l); err != nil { |
| - 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 |
| } |
| return askReady, nil |
| } |
| @@ -167,7 +204,7 @@ func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) { |
| if state == askReady { |
| a.revoke(r.Context(), l, sec) |
| } |
| - if err := store.DeleteEquipoLink(r.Context(), a.db, me.ID); err != nil { |
| + if err := store.DeleteEquipoLink(r.Context(), a.db, me.ID, l.DeviceID); err != nil { |
| a.fail(w, err) |
| return |
| } |
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go| index 87e21a9..74b4642 100644 |
| --- a/internal/web/ask_relay.go |
| +++ b/internal/web/ask_relay.go |
| @@ -2,12 +2,14 @@ package web |
| import ( |
| "bufio" |
| + "context" |
| + "encoding/json" |
| "errors" |
| - "fmt" |
| "io" |
| "net/http" |
| "strconv" |
| "strings" |
| + "time" |
| "unicode/utf8" |
| "github.com/go-chi/chi/v5" |
| @@ -29,14 +31,14 @@ func wantsJSON(r *http.Request) bool { |
| // askBearer is the member's bearer for a relayed write. Without one it |
| // answers for the caller: the panel hears the state, a form goes to /ask. |
| -func (a *app) askBearer(w http.ResponseWriter, r *http.Request) (store.Member, string, bool) { |
| +func (a *app) askBearer(w http.ResponseWriter, r *http.Request) (askConn, bool) { |
| me, _ := CurrentMember(r) |
| r.Body = http.MaxBytesReader(w, r.Body, maxAskForm) |
| if err := r.ParseForm(); err != nil { |
| http.Error(w, "bad request", http.StatusBadRequest) |
| - return me, "", false |
| + return askConn{}, false |
| } |
| - _, sec, state, err := a.askLink(r.Context(), me) |
| + l, sec, state, err := a.askLink(r.Context(), me) |
| switch { |
| case err != nil: |
| a.logger.Error("ask: link", "err", err) |
| @@ -46,21 +48,27 @@ func (a *app) askBearer(w http.ResponseWriter, r *http.Request) (store.Member, s |
| case state != askReady: |
| http.Redirect(w, r, "/ask", http.StatusSeeOther) |
| default: |
| - return me, sec.Token, true |
| + return askConn{me, l.DeviceID, sec.Token}, true |
| } |
| - return me, "", false |
| + return askConn{}, false |
| +} |
| + |
| +// askConn is a member's live connection for one relayed write. |
| +type askConn struct { |
| + me store.Member |
| + device, token string |
| } |
| // askDone finishes a relayed write. A 401 from Equipo means the member must |
| // reconnect; a 409 (a card already answered, a turn already ended) is |
| // stale, and the conversation as it is now says so; anything else is a |
| // problem to try again. |
| -func (a *app) askDone(w http.ResponseWriter, r *http.Request, me store.Member, err error, out any) { |
| +func (a *app) askDone(w http.ResponseWriter, r *http.Request, c askConn, err error, out any) { |
| var e *equipo.Error |
| status, state := http.StatusOK, askReady |
| switch { |
| case errors.Is(err, equipo.ErrUnauthenticated): |
| - a.askLost(r.Context(), me) |
| + a.askLost(r.Context(), c.me, c.device) |
| status, state = http.StatusUnauthorized, askReconnect |
| case errors.As(err, &e) && e.Status == http.StatusConflict: |
| status = http.StatusConflict |
| @@ -83,8 +91,10 @@ func (a *app) askDone(w http.ResponseWriter, r *http.Request, me store.Member, e |
| writeJSON(w, status, out) |
| } |
| -// askKey is the message key the form carries, so pressing Send twice |
| -// sends once; a missing or unusable one gets a fresh key. |
| +// askKey is the key the form carries, made when the page was drawn (or by |
| +// the panel's script, kept until the outcome is known), so a form sent |
| +// twice is one request to Equipo; a missing or unusable one gets a fresh |
| +// key. |
| func askKey(k string) string { |
| if k == "" || len(k) > 128 || !utf8.ValidString(k) || strings.HasPrefix(k, "reply:") || strings.HasPrefix(k, "card:") { |
| return equipo.NewKey() |
| @@ -94,7 +104,7 @@ func askKey(k string) string { |
| // askSend is POST /ask/messages. |
| func (a *app) askSend(w http.ResponseWriter, r *http.Request) { |
| - me, token, ok := a.askBearer(w, r) |
| + c, ok := a.askBearer(w, r) |
| if !ok { |
| return |
| } |
| @@ -107,35 +117,43 @@ func (a *app) askSend(w http.ResponseWriter, r *http.Request) { |
| } |
| return |
| } |
| - sent, err := a.ask.client.Send(r.Context(), token, text, askKey(r.PostFormValue("key"))) |
| - a.askDone(w, r, me, err, sent) |
| + sent, err := a.ask.client.Send(r.Context(), c.token, text, askKey(r.PostFormValue("key"))) |
| + a.askDone(w, r, c, err, sent) |
| } |
| // askCancel is POST /ask/turns/{id}/cancel: Stop. |
| func (a *app) askCancel(w http.ResponseWriter, r *http.Request) { |
| - me, token, ok := a.askBearer(w, r) |
| + c, ok := a.askBearer(w, r) |
| if !ok { |
| return |
| } |
| - err := a.ask.client.Cancel(r.Context(), token, chi.URLParam(r, "id"), equipo.NewKey()) |
| - a.askDone(w, r, me, err, map[string]string{"state": askReady}) |
| + err := a.ask.client.Cancel(r.Context(), c.token, chi.URLParam(r, "id"), askKey(r.PostFormValue("key"))) |
| + a.askDone(w, r, c, err, map[string]string{"state": askReady}) |
| } |
| // askAnswer is POST /ask/cards/{id}/answer: one of a question's buttons. |
| func (a *app) askAnswer(w http.ResponseWriter, r *http.Request) { |
| - me, token, ok := a.askBearer(w, r) |
| + c, ok := a.askBearer(w, r) |
| if !ok { |
| return |
| } |
| rev, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) |
| - out, err := a.ask.client.Answer(r.Context(), token, chi.URLParam(r, "id"), r.PostFormValue("choice"), rev, equipo.NewKey()) |
| - a.askDone(w, r, me, err, out) |
| + out, err := a.ask.client.Answer(r.Context(), c.token, chi.URLParam(r, "id"), r.PostFormValue("choice"), rev, askKey(r.PostFormValue("key"))) |
| + a.askDone(w, r, c, err, out) |
| } |
| -// relayed are the event types the panel gets: the conversation's own. |
| -// Equipo's stream also carries runners, projects, tasks and the rest, |
| -// which Base keeps to Equipo. |
| -var relayed = map[string]bool{"message": true, "turn": true, "delta": true, "activity": true, "card": true} |
| +// Stream bounds. Equipo pings every 20 seconds, so a minute of silence |
| +// means it is gone; a stream lives at most streamLife, after which the |
| +// browser reconnects with its cursor; one event is at most maxEventBytes |
| +// and maxEventLines; a write to a browser that has stopped reading gives |
| +// up after writeWindow. |
| +const ( |
| + streamIdle = 45 * time.Second |
| + streamLife = 10 * time.Minute |
| + writeWindow = 30 * time.Second |
| + maxEventBytes = 512 << 10 |
| + maxEventLines = 64 |
| +) |
| // askEvents is GET /ask/events: Equipo's event stream for the member, |
| // relayed with their bearer. The cursor is Last-Event-ID when the browser |
| @@ -150,7 +168,7 @@ func (a *app) askEvents(w http.ResponseWriter, r *http.Request) { |
| http.Error(w, "bad request", http.StatusBadRequest) |
| return |
| } |
| - _, sec, state, err := a.askLink(r.Context(), me) |
| + l, sec, state, err := a.askLink(r.Context(), me) |
| if err != nil { |
| a.logger.Error("ask: link", "err", err) |
| http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| @@ -160,9 +178,11 @@ func (a *app) askEvents(w http.ResponseWriter, r *http.Request) { |
| endStream(w, homeState(state)) |
| return |
| } |
| - res, err := a.ask.client.Events(r.Context(), sec.Token, after) |
| + ctx, cancel := context.WithTimeout(r.Context(), streamLife) |
| + defer cancel() |
| + res, err := a.ask.client.Events(ctx, sec.Token, after) |
| if errors.Is(err, equipo.ErrUnauthenticated) { |
| - a.askLost(r.Context(), me) |
| + a.askLost(r.Context(), me, l.DeviceID) |
| endStream(w, askReconnect) |
| return |
| } |
| @@ -172,12 +192,27 @@ func (a *app) askEvents(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| defer res.Body.Close() |
| - rc := http.NewResponseController(w) |
| streamHeaders(w) |
| - if _, err := io.WriteString(w, "retry: 3000\n\n"); err != nil || rc.Flush() != nil { |
| + down := downstream{w, http.NewResponseController(w)} |
| + if down.send("retry: 3000\n\n") != nil { |
| return |
| } |
| - relay(w, rc, res.Body) |
| + relay(down, res.Body, streamIdle, cancel) |
| +} |
| + |
| +// downstream is the browser's end of a stream. |
| +type downstream struct { |
| + w io.Writer |
| + rc *http.ResponseController |
| +} |
| + |
| +// send writes s and flushes it, giving up after writeWindow. |
| +func (d downstream) send(s string) error { |
| + _ = d.rc.SetWriteDeadline(time.Now().Add(writeWindow)) |
| + if _, err := io.WriteString(d.w, s); err != nil { |
| + return err |
| + } |
| + return d.rc.Flush() |
| } |
| func streamHeaders(w http.ResponseWriter) { |
| @@ -191,42 +226,148 @@ func streamHeaders(w http.ResponseWriter) { |
| // saying why, so the panel shows it instead of retrying. |
| func endStream(w http.ResponseWriter, state string) { |
| streamHeaders(w) |
| - fmt.Fprintf(w, "event: state\ndata: {\"state\":%q}\n\n", state) |
| -} |
| - |
| -// relay copies the events in relayed from upstream to w as they come, |
| -// with their ids, and turns Equipo's pings into comments that keep the |
| -// connection open. |
| -func relay(w io.Writer, rc *http.ResponseController, upstream io.Reader) { |
| - sc := bufio.NewScanner(upstream) |
| - sc.Buffer(make([]byte, 64<<10), 1<<20) |
| - var block []string |
| - typ := "message" |
| - for sc.Scan() { |
| - line := sc.Text() |
| - if line != "" { |
| - if t, ok := strings.CutPrefix(line, "event:"); ok { |
| - typ = strings.TrimSpace(t) |
| - } |
| - if !strings.HasPrefix(line, ":") && !strings.HasPrefix(line, "retry:") { |
| - block = append(block, line) |
| - } |
| - continue |
| + raw, _ := json.Marshal(map[string]string{"state": state}) |
| + _ = downstream{w, http.NewResponseController(w)}.send("event: state\ndata: " + string(raw) + "\n\n") |
| +} |
| + |
| +// relay reads Equipo's events from upstream and writes the conversation's |
| +// to d as frames of its own (see frameFor); upstream's lines never reach |
| +// the browser. It parses lines as a browser does (LF, CRLF or a bare CR |
| +// ends one), and ends the stream at an event over the size bounds, at |
| +// idle without a byte from upstream (calling stop, which must make the |
| +// pending read fail), or when the browser stops reading. |
| +func relay(d downstream, upstream io.Reader, idle time.Duration, stop func()) { |
| + quiet := time.AfterFunc(idle, stop) |
| + defer quiet.Stop() |
| + in := bufio.NewReaderSize(upstream, 32<<10) |
| + var ev sseEvent |
| + size, lines := 0, 0 |
| + for { |
| + line, err := readLine(in, maxEventBytes-size) |
| + if err != nil { |
| + return |
| } |
| - out := "" |
| - switch { |
| - case len(block) == 0: |
| - case relayed[typ]: |
| - out = strings.Join(block, "\n") + "\n\n" |
| - case typ == "ping": |
| - out = ": ping\n\n" |
| + quiet.Reset(idle) |
| + size, lines = size+len(line)+1, lines+1 |
| + if lines > maxEventLines { |
| + return |
| } |
| - block, typ = nil, "message" |
| - if out == "" { |
| + if len(line) > 0 { |
| + ev.field(line) |
| continue |
| } |
| - if _, err := io.WriteString(w, out); err != nil || rc.Flush() != nil { |
| + out := ev.frame() |
| + ev, size, lines = sseEvent{}, 0, 0 |
| + if out != "" && d.send(out) != nil { |
| return |
| } |
| } |
| } |
| + |
| +// readLine reads one line of at most max bytes, ended by LF, CRLF or CR. |
| +func readLine(in *bufio.Reader, max int) ([]byte, error) { |
| + var line []byte |
| + for { |
| + b, err := in.ReadByte() |
| + if err != nil { |
| + return nil, err |
| + } |
| + switch b { |
| + case '\n': |
| + return line, nil |
| + case '\r': |
| + if next, err := in.Peek(1); err == nil && next[0] == '\n' { |
| + _, _ = in.ReadByte() |
| + } |
| + return line, nil |
| + } |
| + if len(line) >= max { |
| + return nil, errors.New("ask: event too large") |
| + } |
| + line = append(line, b) |
| + } |
| +} |
| + |
| +// sseEvent is one upstream event's fields. |
| +type sseEvent struct { |
| + typ, id string |
| + data []string |
| +} |
| + |
| +func (e *sseEvent) field(line []byte) { |
| + if line[0] == ':' { |
| + return |
| + } |
| + name, value, _ := strings.Cut(string(line), ":") |
| + value = strings.TrimPrefix(value, " ") |
| + switch name { |
| + case "event": |
| + e.typ = value |
| + case "id": |
| + e.id = value |
| + case "data": |
| + e.data = append(e.data, value) |
| + } |
| +} |
| + |
| +// frame is what the browser gets for the event: a ping as a comment, a |
| +// conversation event as a fresh frame with a numeric id and its data |
| +// projected (project), and nothing for anything else. |
| +func (e sseEvent) frame() string { |
| + if e.typ == "ping" { |
| + return ": ping\n\n" |
| + } |
| + if _, err := strconv.ParseUint(e.id, 10, 63); err != nil || len(e.data) == 0 { |
| + return "" |
| + } |
| + var env struct { |
| + Data json.RawMessage `json:"data"` |
| + } |
| + if err := json.Unmarshal([]byte(strings.Join(e.data, "\n")), &env); err != nil { |
| + return "" |
| + } |
| + data, ok := project(e.typ, env.Data) |
| + if !ok { |
| + return "" |
| + } |
| + raw, err := json.Marshal(struct { |
| + Type string `json:"type"` |
| + Data any `json:"data"` |
| + }{e.typ, data}) |
| + if err != nil { |
| + return "" |
| + } |
| + return "id: " + e.id + "\nevent: " + e.typ + "\ndata: " + string(raw) + "\n\n" |
| +} |
| + |
| +// project reduces an event's data to the conversation's shape, the one |
| +// /ask/state uses; ok is false for every other kind of event, and for |
| +// cards that are not questions (projects, tasks and the rest stay in |
| +// Equipo). |
| +func project(typ string, raw json.RawMessage) (any, bool) { |
| + switch typ { |
| + case "message": |
| + var m equipo.Message |
| + return m, json.Unmarshal(raw, &m) == nil && m.ID != "" |
| + case "turn": |
| + var t equipo.Turn |
| + return t, json.Unmarshal(raw, &t) == nil && t.ID != "" |
| + case "card": |
| + var c equipo.Card |
| + return c, json.Unmarshal(raw, &c) == nil && c.ID != "" && c.Kind == "question" |
| + case "delta": |
| + var d struct { |
| + TurnID string `json:"turn_id"` |
| + Offset int64 `json:"offset"` |
| + Text string `json:"text"` |
| + } |
| + return d, json.Unmarshal(raw, &d) == nil && d.TurnID != "" |
| + case "activity": |
| + var a struct { |
| + TurnID string `json:"turn_id"` |
| + Label string `json:"label"` |
| + } |
| + return a, json.Unmarshal(raw, &a) == nil && a.TurnID != "" |
| + } |
| + return nil, false |
| +} |
diff --git a/internal/web/relay_internal_test.go b/internal/web/relay_internal_test.go| new file mode 100644 |
| index 0000000..247189f |
| --- /dev/null |
| +++ b/internal/web/relay_internal_test.go |
| @@ -0,0 +1,100 @@ |
| +package web |
| + |
| +import ( |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +const ( |
| + turnEvent = `{"cursor":41,"type":"turn","resource":"turn","id":"t_1","revision":2,"turn_id":"t_1","data":{"id":"t_1","revision":2,"kind":"","state":"running","reason":"","attempt":1,"message_ids":["m_1"],"reply_id":"","connection":"cn_secret","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z","timing":null}}` |
| + msgEvent = `{"cursor":42,"type":"message","resource":"message","id":"m_2","revision":1,"turn_id":"t_1","message_id":"m_2","data":{"id":"m_2","revision":1,"role":"coordinator","text":"Hello","turn_id":"t_1","created_at":"2026-11-06T10:00:02Z","switched":null}}` |
| +) |
| + |
| +func frame(id, typ, data string) string { |
| + return "id: " + id + "\nevent: " + typ + "\ndata: " + data + "\n\n" |
| +} |
| + |
| +// relayTo runs relay over upstream and returns what reached the browser. |
| +func relayTo(t *testing.T, upstream io.Reader, idle time.Duration, stop func()) string { |
| + t.Helper() |
| + rec := httptest.NewRecorder() |
| + done := make(chan struct{}) |
| + go func() { |
| + relay(downstream{rec, http.NewResponseController(rec)}, upstream, idle, stop) |
| + close(done) |
| + }() |
| + select { |
| + case <-done: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("the relay did not end") |
| + } |
| + return rec.Body.String() |
| +} |
| + |
| +// An upstream that goes quiet (no event, no ping) ends the stream; the |
| +// browser reconnects with its cursor. |
| +func TestRelayEndsOnStalledUpstream(t *testing.T) { |
| + pr, pw := io.Pipe() |
| + go io.WriteString(pw, frame("42", "message", msgEvent)) |
| + out := relayTo(t, pr, 100*time.Millisecond, func() { pr.CloseWithError(io.ErrClosedPipe) }) |
| + if !strings.Contains(out, "id: 42\nevent: message\n") { |
| + t.Fatalf("relayed:\n%q", out) |
| + } |
| +} |
| + |
| +// An event past the size bound ends the stream and never reaches the browser. |
| +func TestRelayEndsOnOversizedEvent(t *testing.T) { |
| + big := `{"cursor":43,"type":"message","data":{"id":"m_3","role":"coordinator","text":"` + strings.Repeat("a", 2<<20) + `"}}` |
| + many := strings.Repeat("data: 1\n", 5000) |
| + for name, bad := range map[string]string{"bytes": frame("43", "message", big), "lines": "id: 43\nevent: message\n" + many + "\n"} { |
| + upstream := frame("42", "message", msgEvent) + bad + frame("44", "message", strings.Replace(msgEvent, "m_2", "m_4", -1)) |
| + out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| + if !strings.Contains(out, "id: 42\n") || strings.Contains(out, "id: 43") || strings.Contains(out, "id: 44") || len(out) > 4096 { |
| + t.Errorf("%s: relayed %d bytes:\n%.300q", name, len(out), out) |
| + } |
| + } |
| +} |
| + |
| +// A bare CR ends a line for the browser, so the relay must read it so too: |
| +// here it turns a turn event into a runner event, which is not relayed, |
| +// and no CR ever reaches the browser. |
| +func TestRelayParsesBareCR(t *testing.T) { |
| + upstream := "id: 41\nevent: turn\ndata: " + turnEvent + "\revent: runner\n\n" + |
| + "id: 42\revent: message\rdata: " + msgEvent + "\r\r" |
| + out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| + if strings.Contains(out, "\r") || strings.Contains(out, "runner") || strings.Contains(out, "id: 41") { |
| + t.Fatalf("relayed:\n%q", out) |
| + } |
| + if !strings.Contains(out, "id: 42\nevent: message\ndata: ") { |
| + t.Fatalf("lost the CR-framed message:\n%q", out) |
| + } |
| +} |
| + |
| +// Frames are Base's own: known types only, data projected to the |
| +// conversation's shape, bad JSON and bad ids dropped. |
| +func TestRelayWritesItsOwnFrames(t *testing.T) { |
| + project := `{"cursor":45,"type":"card","data":{"id":"c_1","revision":1,"kind":"project","state":"added","project_id":"p_1","name":"oficina/sample"}}` |
| + question := `{"cursor":46,"type":"card","data":{"id":"c_2","revision":1,"kind":"question","state":"open","turn_id":"t_1","project_id":"p_9","question":"Which branch?","options":["main"],"task_id":"tk_9"}}` |
| + upstream := frame("41", "turn", turnEvent) + frame("44", "message", `{"cursor":44,"data":{oops`) + |
| + frame("x1", "message", msgEvent) + frame("45", "card", project) + frame("46", "card", question) + |
| + "event: ping\ndata: {\"type\":\"ping\"}\n\n" + ": comment\nretry: 1\n\n" |
| + out := relayTo(t, strings.NewReader(upstream), time.Second, func() {}) |
| + for _, banned := range []string{"cn_secret", "oops", "x1", "p_1", "p_9", "tk_9", "oficina/sample", "retry: 1", "comment"} { |
| + if strings.Contains(out, banned) { |
| + t.Errorf("relayed %q:\n%s", banned, out) |
| + } |
| + } |
| + for _, want := range []string{ |
| + "id: 41\nevent: turn\ndata: {\"type\":\"turn\",\"data\":{\"id\":\"t_1\",\"kind\":\"\",\"state\":\"running\",\"reason\":\"\"}}\n\n", |
| + "id: 46\nevent: card\ndata: {\"type\":\"card\",\"data\":{\"id\":\"c_2\",\"revision\":1,\"kind\":\"question\",\"state\":\"open\",\"question\":\"Which branch?\",\"options\":[\"main\"],\"choice\":\"\"}}\n\n", |
| + ": ping\n\n", |
| + } { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("relay lacks %q:\n%s", want, out) |
| + } |
| + } |
| +} |
diff --git a/internal/web/templates/ask_connect.html b/internal/web/templates/ask_connect.html| index bc32b9c..752356d 100644 |
| --- a/internal/web/templates/ask_connect.html |
| +++ b/internal/web/templates/ask_connect.html |
| @@ -1,5 +1,4 @@ |
| {{define "title"}}Connect Equipo · {{.Name}}{{end}} |
| -{{define "head"}}{{if eq .State "pending"}}<meta http-equiv="refresh" content="5">{{end}}{{end}} |
| {{define "main"}}<main class="signin"> |
| <div class="card glass"> |
| <div class="wordmark">base</div> |
| @@ -7,8 +6,9 @@ |
| {{if eq .State "pending"}}<p>In Equipo, check the request is from {{.Label}}, then type this code:</p> |
| <p class="code" aria-label="Your code">{{.Code}}</p> |
| <a class="btn full" href="{{.Verify}}" target="_blank" rel="noopener">Open Equipo</a> |
| -<p class="alt">This page checks every few seconds and moves on once you've approved it.</p> |
| -<a class="btn ghost full" href="/ask/connect?next={{.Next}}">Check again</a> |
| +<p class="alt">Once you've approved it, come back and press Check again.</p> |
| +<form method="post" action="/ask/connect/check" data-connect-check><input type="hidden" name="next" value="{{.Next}}"><button class="btn ghost full" type="submit">Check again</button></form> |
| +<script type="module" src="{{asset "static/ask-connect.js"}}"></script> |
| {{else}}<p>{{if eq .State "expired"}}That code expired. Start again to get a new one.{{else if eq .State "refused"}}Equipo didn't accept that request. Start again.{{else if eq .State "reconnect"}}Base's connection to Equipo expired or was removed.{{else}}Connect Equipo, and its coordinator answers you in Base.{{end}}</p> |
| <form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn full" type="submit">{{if eq .State "connect"}}Connect Equipo{{else if eq .State "reconnect"}}Reconnect Equipo{{else}}Start again{{end}}</button></form> |
| <a class="btn ghost full" href="{{.Back}}">Back</a> |
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html| index b682d43..e312cc3 100644 |
| --- a/internal/web/templates/partials/chat.html |
| +++ b/internal/web/templates/partials/chat.html |
| @@ -21,13 +21,13 @@ |
| <div class="ask-chat" data-when="ready"{{if not (.Shows "ready")}} hidden{{end}}> |
| <ol class="thread" role="log" aria-label="Conversation"> |
| {{range .Messages}}<li class="msg {{.Role}}" data-id="{{.ID}}">{{.Text}}</li> |
| -{{end}}{{range .Cards}}<li class="msg card" data-card="{{.ID}}"><p>{{.Question}}</p><form class="choices" method="post" action="/ask/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<button class="btn ghost" type="submit" name="choice" value="{{.}}">{{.}}</button>{{end}}</form></li> |
| +{{end}}{{range .Cards}}<li class="msg card" data-card="{{.ID}}"><p>{{.Question}}</p><form class="choices" method="post" action="/ask/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="key" value="{{newKey}}">{{range .Options}}<button class="btn ghost" type="submit" name="choice" value="{{.}}">{{.}}</button>{{end}}</form></li> |
| {{end}}</ol> |
| <p class="ask-empty" data-empty{{if or .Messages .Cards}} hidden{{end}}>Ask about your work, or ask Base to get something done.</p> |
| {{with .Problem}}<p class="ask-problem" role="alert">{{.}}</p>{{end}} |
| <div class="ask-foot"> |
| <p class="ask-status" role="status">{{.Status}}</p> |
| -<form class="stop" method="post" action="{{with .Turn}}/ask/turns/{{.ID}}/cancel{{else}}/ask{{end}}"{{if not .Turn}} hidden{{end}}><button class="btn ghost" type="submit">Stop</button></form> |
| +<form class="stop" method="post" action="{{with .Turn}}/ask/turns/{{.ID}}/cancel{{else}}/ask{{end}}"{{if not .Turn}} hidden{{end}}><input type="hidden" name="key" value="{{newKey}}"><button class="btn ghost" type="submit">Stop</button></form> |
| </div> |
| <form class="composer" method="post" action="/ask/messages"><input type="hidden" name="key" value="{{.Key}}"><label class="sr-only" for="ask-text">Message</label><textarea class="input" id="ask-text" name="text" rows="1" required maxlength="16000" placeholder="Ask Base anything"></textarea><button class="btn" type="submit">Send</button></form> |
| </div>{{end}} |
diff --git a/internal/webtest/ask_test.go b/internal/webtest/ask_test.go| index a22c794..5bb6e8d 100644 |
| --- a/internal/webtest/ask_test.go |
| +++ b/internal/webtest/ask_test.go |
| @@ -71,7 +71,7 @@ func (a *testApp) connectEquipo(f *equipotest.Fake) string { |
| a.t.Fatal(err) |
| } |
| a.pollable() |
| - if r := a.get("/ask/connect?next=settings"); r.Code != 303 || r.Location() != "/settings" { |
| + if r := a.check("settings"); r.Code != 303 || r.Location() != "/settings" { |
| a.t.Fatalf("after approval: %d %q\n%s", r.Code, r.Location(), r.Body) |
| } |
| tokens := f.Tokens() |
| @@ -81,6 +81,12 @@ func (a *testApp) connectEquipo(f *equipotest.Fake) string { |
| return tokens[0] |
| } |
| +// check presses "Check again" on the connect page. |
| +func (a *testApp) check(next string) Resp { |
| + a.t.Helper() |
| + return a.post("/ask/connect/check", url.Values{"next": {next}}) |
| +} |
| + |
| // noLeak fails if any response so far carried token: body, header or cookie. |
| func (a *testApp) noLeak(token string) { |
| a.t.Helper() |
| @@ -145,24 +151,24 @@ func TestConnectEquipo(t *testing.T) { |
| if m == nil || f.Label(m[1]) != "Base (Acme)" { |
| t.Fatalf("no user code:\n%s", page.Body) |
| } |
| - for _, want := range []string{f.URL + "/auth/devices/", `http-equiv="refresh" content="5"`, `href="/ask/connect?next=settings"`} { |
| + for _, want := range []string{f.URL + "/auth/devices/", `<form method="post" action="/ask/connect/check"`, ">Check again</button>"} { |
| if !strings.Contains(html.UnescapeString(page.Body), want) { |
| t.Errorf("pending page lacks %q:\n%s", want, page.Body) |
| } |
| } |
| - // It asked once; a refresh inside Equipo's five seconds does not ask. |
| - if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 { |
| - t.Fatalf("exchanges after first look: %d", n) |
| + // Checking asks once; checking again inside Equipo's five seconds does not. |
| + if r := a.check("settings"); r.Code != 303 || r.Location() != "/ask/connect?next=settings" { |
| + t.Fatalf("check while pending: %d %q", r.Code, r.Location()) |
| } |
| - a.get(r.Location()) |
| + a.check("settings") |
| if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 { |
| - t.Fatalf("polled within five seconds: %d exchanges", n) |
| + t.Fatalf("exchanges: %d, want 1", n) |
| } |
| if err := f.Approve(m[1]); err != nil { |
| t.Fatal(err) |
| } |
| a.pollable() |
| - if r := a.get(r.Location()); r.Code != 303 || r.Location() != "/settings" { |
| + if r := a.check("settings"); r.Code != 303 || r.Location() != "/settings" { |
| t.Fatalf("after approval: %d %q", r.Code, r.Location()) |
| } |
| token := f.Tokens()[0] |
| @@ -180,16 +186,137 @@ func TestConnectEquipo(t *testing.T) { |
| a.noLeak(token) |
| } |
| -func TestConnectCodeExpires(t *testing.T) { |
| +// GET /ask/connect only shows: a cross-site link or prefetch cannot finish |
| +// the exchange. The JSON check is what the page's script posts. |
| +func TestConnectPageIsReadOnly(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 m == nil { |
| + t.Fatal("no code") |
| + } |
| + if err := f.Approve(m[1]); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.pollable() |
| + if page := a.get(r.Location()); page.Code != 200 || codeRE.FindString(page.Body) == "" { |
| + t.Fatalf("page: %d", page.Code) |
| + } |
| + if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 0 { |
| + t.Fatalf("GET exchanged %d times", n) |
| + } |
| + if r := a.postFrom("https://evil.example", "/ask/connect/check", url.Values{"next": {"ask"}}); r.Code != 403 { |
| + t.Fatalf("cross-site check: %d", r.Code) |
| + } |
| + req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/connect/check", strings.NewReader("next=ask")) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", a.origin) |
| + req.Header.Set("Accept", "application/json") |
| + res := a.do(req) |
| + if res.Code != 200 || !strings.Contains(res.Body, `"state":"ready"`) || !strings.Contains(res.Body, `"next":"/ask"`) { |
| + t.Fatalf("JSON check: %d %s", res.Code, res.Body) |
| + } |
| +} |
| + |
| +// Two checks at once: only one asks Equipo. |
| +func TestConnectConcurrentChecksExchangeOnce(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") }() |
| + 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") |
| + } |
| + a.check("ask") |
| + release() |
| + <-done |
| + if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 { |
| + t.Fatalf("exchanges: %d, want 1", n) |
| + } |
| +} |
| + |
| +// Disconnect while an exchange is in flight: the bearer that exchange |
| +// brings back is revoked, not stored. |
| +func TestDisconnectDuringExchangeLeavesNoBearer(t *testing.T) { |
| + a, f := newAskApp(t) |
| + r := a.post("/ask/connect", url.Values{"next": {"settings"}}) |
| + 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("settings") }() |
| + 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") |
| + } |
| + if d := a.post("/ask/disconnect", nil); d.Code != 303 { |
| + t.Fatalf("disconnect: %d", d.Code) |
| + } |
| + release() |
| + if c := <-done; c.Location() == "/settings" && c.Code != 303 { |
| + t.Fatalf("check: %d", c.Code) |
| + } |
| + if _, found, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); found { |
| + t.Fatal("the exchange brought the link back after Disconnect") |
| + } |
| + if !f.Revoked(l.DeviceID) { |
| + t.Fatal("the bearer from the late exchange was not revoked") |
| + } |
| +} |
| + |
| +func TestConnectCodeExpires(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.post("/ask/connect", url.Values{"next": {"ask"}}) |
| f.Expire() |
| + r := a.check("ask") |
| + if r.Code != 303 { |
| + t.Fatalf("check: %d", r.Code) |
| + } |
| page := a.get(r.Location()) |
| if page.Code != 200 || !strings.Contains(page.Body, "That code expired.") || !strings.Contains(page.Body, `action="/ask/connect"`) { |
| t.Fatalf("expired: %d\n%s", page.Code, page.Body) |
| } |
| } |
| +// Every chat form carries a key made when the page was drawn, which Base |
| +// relays as the Idempotency-Key: a resubmitted form is the same request. |
| +func TestAskFormsCarryKeys(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + id := f.AskQuestion("Which branch?", "main") |
| + f.Hold = true |
| + a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}}) |
| + page := a.get("/ask").Body |
| + answer := formFields(t, page, "/ask/cards/"+id+"/answer") |
| + cancel := regexp.MustCompile(`action="(/ask/turns/[^/"]+/cancel)"`).FindStringSubmatch(page) |
| + if answer.Get("key") == "" || cancel == nil { |
| + t.Fatalf("forms:\n%s", page) |
| + } |
| + stop := formFields(t, page, cancel[1]) |
| + if stop.Get("key") == "" || stop.Get("key") == answer.Get("key") { |
| + t.Fatalf("stop key %q, answer key %q", stop.Get("key"), answer.Get("key")) |
| + } |
| + answer.Set("choice", "main") |
| + a.post("/ask/cards/"+id+"/answer", answer) |
| + a.post(cancel[1], stop) |
| + for path, key := range map[string]string{"/api/v1/cards/" + id + "/answer": answer.Get("key"), "/api/v1" + strings.TrimPrefix(cancel[1], "/ask"): stop.Get("key")} { |
| + if c := f.Calls(path); len(c) != 1 || c[0].Header.Get("Idempotency-Key") != key { |
| + t.Errorf("%s: %+v, want key %q", path, c, key) |
| + } |
| + } |
| +} |
| + |
| func TestAskSendRelaysWithBearer(t *testing.T) { |
| a, f := newAskApp(t) |
| token := a.connectEquipo(f) |
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go| index ca8c075..a300c77 100644 |
| --- a/internal/webtest/harness_test.go |
| +++ b/internal/webtest/harness_test.go |
| @@ -92,6 +92,8 @@ type testApp struct { |
| // seen is every response so far, for checks that a secret never |
| // reached the browser. |
| seen []Resp |
| + // seenMu guards seen; a pointer, so newBrowser's copy shares it. |
| + seenMu *sync.Mutex |
| } |
| // newApp builds the whole app per test over its own copy of the migrated |
| @@ -137,7 +139,7 @@ func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Insta |
| t.Cleanup(srv.Close) |
| jar, _ := cookiejar.New(nil) |
| client := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| - return &testApp{t: t, srv: srv, client: client, mail: mailer, DB: d.Writer(), base: srv.URL, origin: testOrigin, localSignin: "/signin"} |
| + return &testApp{seenMu: &sync.Mutex{}, t: t, srv: srv, client: client, mail: mailer, DB: d.Writer(), base: srv.URL, origin: testOrigin, localSignin: "/signin"} |
| } |
| func (a *testApp) do(req *http.Request) Resp { |
| @@ -149,7 +151,9 @@ func (a *testApp) do(req *http.Request) Resp { |
| defer res.Body.Close() |
| b, _ := io.ReadAll(res.Body) |
| out := Resp{res.StatusCode, res.Header, string(b)} |
| + a.seenMu.Lock() |
| a.seen = append(a.seen, out) |
| + a.seenMu.Unlock() |
| return out |
| } |
diff --git a/internal/webtest/oficina_harness_test.go b/internal/webtest/oficina_harness_test.go| index de8cb7e..e4767f6 100644 |
| --- a/internal/webtest/oficina_harness_test.go |
| +++ b/internal/webtest/oficina_harness_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "net/url" |
| "regexp" |
| "strings" |
| + "sync" |
| "time" |
| "testing" |
| @@ -87,7 +88,7 @@ func newHomeApp(t *testing.T) *testApp { |
| if err != nil { |
| t.Fatalf("web.App: %v", err) |
| } |
| - return &testApp{t: t, client: inProcessClient(h), mail: mailer, DB: d.Writer(), |
| + return &testApp{seenMu: &sync.Mutex{}, t: t, client: inProcessClient(h), mail: mailer, DB: d.Writer(), |
| base: homeOrigin, origin: homeOrigin, localSignin: "/signin/local", home: &oficina{key: key, cfg: cfg}} |
| } |