oficina / base Public

Set Ask up with Oficina ID from the native app

POST /api/v1/ask/oficina {assertion, verifier}, from a native session
only, completes Equipo's own native sign-in for the member: Equipo's
POST /native/oficina-id (no Origin, no cookie), then
POST /api/v1/auth/devices/native with that session's cookie, Equipo's
Origin, a fresh Ed25519 key and Base's device label. The person
credential it returns is the code flow's kind; Base seals it in the same
equipo_links row, with the Equipo session cookie beside it in the sealed
secrets, and registers the Assistant's host as Connect does, so the relay
can't tell the two apart. Base never signs that session out: it would
end the key.

The answer is 200 {state:"ready", renew_after} (five days after the
seven-day session began), 409 not_linked when Equipo hasn't linked the
Oficina ID, 422 failed for an assertion Equipo refused, 400, 403 for a
browser session, 502/503. It never answers 401, which the kit reads as
Base's own session ending. Any failure stores nothing; a second post
replaces the key and revokes the old device; two posts for one member
run one at a time. /ask/state gains renew_after ("" for code-flow keys)
and equipo_origin.

equipotest fakes Equipo's two native routes; the README and
docs/api/base-native-v1.md say how it works and what it answers.

make ci: 16 packages ran, 0 failed; test step 10.4s of 60s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev aeb67583831279f7344074d129e5b9a7977af1d3 parent 890c309
9 files changed, +902 −19
  • README.md +18 −0
  • docs/api/base-native-v1.md +35 −2
  • internal/equipo/equipotest/fake.go +9 −0
  • internal/equipo/equipotest/native.go +243 −0
  • internal/equipo/native.go +127 −0
  • internal/web/ask.go +33 −14
  • internal/web/ask_oficina_native.go +170 −0
  • internal/webtest/ask_native_contract_test.go +3 −3
  • internal/webtest/ask_oficina_native_test.go +264 −0
diff --git a/README.md b/README.md
index 876de92..9eeabb7 100644
--- a/README.md
+++ b/README.md
@@ -88,6 +88,24 @@ email and passkeys stay below it. Everyone signs in with their email once and
connects their Oficina account from Settings; after that, Oficina signs them
in. Only members get in, and inviting people is still by email.
+Base's Mac and iPhone app signs in with Oficina ID too, through
+`POST /native/oficina-id`; its session lasts seven days, and the app renews
+it. Someone must have signed in to Base on the web with Oficina ID once
+before the app lets them in. The app reads and calls what
+`docs/api/base-native-v1.md` describes.
+
+The app connects Ask Base with Oficina ID, so there's no code to approve in
+Equipo. Base signs the person in to Equipo with Oficina ID on their behalf
+and keeps the Equipo key sealed, as it does one from the code. This works
+only for someone Equipo has already linked to their Oficina ID (they've
+signed in to Equipo with it); for anyone else the app shows that Ask isn't
+set up for them yet, and they can connect it with a code from Base on the
+web. A key made this way lasts seven days, not thirty: it ends with the
+Equipo session it was made with, or sooner if the person signs out of
+Equipo or leaves the team there. The app makes a new one after five days,
+without asking. Base never signs that Equipo session out, because doing so
+would end the key.
+
To install apps, Base also needs to reach the Platform. Without these five and
`BASE_ASSERTION_KEY`, it still runs and logs that installs are off.
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
index 0716ded..002d52a 100644
--- a/docs/api/base-native-v1.md
+++ b/docs/api/base-native-v1.md
@@ -51,7 +51,8 @@ this document breaks the web too.
- `appearance` is `system`, `light` or `dark`. Change it with the web's
`POST /settings/appearance`, form field `theme` (`system`, `light` or
`dark`), which answers `303 /settings`.
-- `equipo_origin` is `null` when Ask Base is off.
+- `equipo_origin` is `null` when Ask Base is off. The app asks Oficina ID
+ for an assertion addressed to it (Ask set-up, below).
### `GET /api/v1/home`
@@ -99,12 +100,13 @@ for a form). Every answer is `no-store`.
| `norunner`, `oldrunner` | Connected, but the person has no runner that can answer (none, or too old). The conversation shows, with a note. |
| `reconnect` | Equipo refused the key, or it expired. |
| `unavailable` | Equipo didn't answer. |
+| `not_linked` | (Only from `POST /api/v1/ask/oficina`.) Equipo has no member linked to this Oficina ID. |
### `GET /ask/state`
```json
{"state": "ready", "messages": [Message…], "jobs": [Job…], "cards": [Card…], "turn": Turn|null,
- "status": "Thinking…", "cursor": 42}
+ "status": "Thinking…", "cursor": 42, "renew_after": "2026-11-28T10:00:00Z", "equipo_origin": "https://equipo.acme.example"}
```
- `messages`, `jobs` and `cards` are never `null`. Outside `ready`,
@@ -114,6 +116,11 @@ for a form). Every answer is `no-store`.
conversation while it runs: `"Thinking…"`, `"Ask Base can't answer right
now. It will as soon as it can."` (turn `waiting`), or `""`.
- `cursor` is where `/ask/events` starts.
+- `renew_after` (RFC 3339, UTC) is set when Ask was connected with Oficina
+ ID: from then on, the app sets Ask up again with a fresh assertion
+ (below), silently. `""` for a key from the web's code flow, or none.
+- `equipo_origin` is the Equipo instance Ask relays to: the audience of the
+ assertion for Ask set-up.
**Message** `{"id", "role": "person"|"assistant", "text", "turn_id", "created_at"}`.
An assistant's `text` may carry the little Markdown `ask.js` draws (lists,
@@ -199,3 +206,29 @@ Form: `choice` (an option's `value`), `revision` (the card's, as seen) and
Ends the person's Ask connection, revoking the key in Equipo, whichever
way it was made. It answers `303 /settings`.
+
+## Ask set-up with Oficina ID
+
+### `POST /api/v1/ask/oficina`
+
+JSON `{"assertion", "verifier"}`: an assertion the kit fetched from Oficina
+ID addressed to `equipo_origin`, and its verifier. 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
+web's code flow keeps one, and registers the Assistant's host with it.
+Two posts for the same person run one at a time.
+
+| status | body | meaning |
+|---|---|---|
+| `200` | `{"state":"ready","renew_after":"<RFC 3339>"}` | Ask is ready. The key ends with Equipo's session, seven days after it was made; `renew_after` is five days after. After it, post a fresh assertion: that replaces the key and revokes the old one in Equipo. |
+| `409` | `{"state":"not_linked"}` | Equipo has no member linked to this Oficina ID. Show Ask's "not set up for you yet" state, with the web's code flow; don't retry in a loop. |
+| `422` | `{"state":"failed"}` | Equipo didn't accept the assertion (expired, wrong audience or verifier, already used). Get a fresh one and try once more. |
+| `400` | `{"state":"invalid"}` | Not JSON, an unknown or missing field, or Equipo couldn't read it. |
+| `403` | `{"state":"forbidden"}` | Not a native session: the web keeps its code flow. |
+| `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. |
+
+Every failure stores nothing and leaves an existing connection as it was.
+The route answers `404` when Ask Base is off. It never answers `401` for
+Equipo's sake: a `401` is always Base's own session.
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go
index b3121e6..14f17b2 100644
--- a/internal/equipo/equipotest/fake.go
+++ b/internal/equipo/equipotest/fake.go
@@ -39,6 +39,9 @@ type device struct {
nonce, token string
revision int64
expires time.Time
+ // session is the native session cookie a device registered with
+ // Oficina ID ends with; "" for one from the code flow.
+ session string
}
// Fake is a running fake Equipo. URL is its origin.
@@ -67,6 +70,7 @@ type Fake struct {
// entered do for the next exchange.
snapHold, snapEntered chan struct{}
chat
+ nativeState
}
// HoldNextExchange makes the next exchange wait, once it has arrived and
@@ -120,6 +124,7 @@ func New(t testing.TB) *Fake {
f := &Fake{Instance: "TEAM1", closing: make(chan struct{}), devices: map[string]*device{},
Reply: func(string) string { return "Hello. What shall we work on?" }}
f.chat.init()
+ f.nativeState.init()
f.srv = httptest.NewServer(http.HandlerFunc(f.serve))
f.URL = f.srv.URL
t.Cleanup(func() {
@@ -197,6 +202,10 @@ func (f *Fake) serve(w http.ResponseWriter, r *http.Request) {
f.calls = append(f.calls, Call{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(body)})
f.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
+ // Equipo's native sign-in has rules of its own (native.go).
+ if f.serveNative(w, r) {
+ return
+ }
// Equipo refuses a request from another site, and any cookie on a
// device route; a server-to-server request carries neither.
if r.Header.Get("Origin") != "" || r.Header.Get("Cookie") != "" {
diff --git a/internal/equipo/equipotest/native.go b/internal/equipo/equipotest/native.go
new file mode 100644
index 0000000..d47879a
--- /dev/null
+++ b/internal/equipo/equipotest/native.go
@@ -0,0 +1,243 @@
+package equipotest
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "mime"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+)
+
+// Equipo's own native sign-in with Oficina ID, as Base completes it for a
+// person (Equipo's internal/equipo/oficinaid/native.go and
+// personapi/native_device.go):
+//
+// - POST /native/oficina-id trades an assertion Oficina ID made for
+// Equipo, and its verifier, for a seven-day native session, only for a
+// subject Equipo has linked to a roster member. It refuses anything a
+// browser sends (Origin, Sec-Fetch-Site), and answers
+// {name, value, expires_at}, or {"state": …} with 400, 401 failed,
+// 403 unknown or 503.
+// - POST /api/v1/auth/devices/native, with that session's cookie and
+// Equipo's own Origin, registers a device key and answers its person
+// credential, which ends with the session.
+//
+// The fake does not verify signatures: OficinaAssertion hands out an opaque
+// assertion and its verifier, as Oficina ID would for Equipo, and the
+// exchange accepts each once.
+
+// SessionCookie is the name of the fake's session cookie.
+const SessionCookie = "__Host-equipo_session"
+
+// nativeLifetime is how long Equipo's native session, and every device
+// registered with it, lasts.
+const nativeLifetime = 7 * 24 * time.Hour
+
+type nativeSession struct {
+ subject, address string
+ at time.Time
+ ended bool
+}
+
+type assertionGrant struct {
+ subject, verifier string
+ used bool
+}
+
+type nativeState struct {
+ nmu sync.Mutex
+ links map[string]string // Oficina subject → roster address
+ assertions map[string]*assertionGrant
+ sessions map[string]*nativeSession // cookie value → session
+ failNative int // the next exchange's status, once
+}
+
+func (n *nativeState) init() {
+ n.links, n.assertions, n.sessions = map[string]string{}, map[string]*assertionGrant{}, map[string]*nativeSession{}
+}
+
+// LinkOficinaID links the Oficina ID subject to the roster member address,
+// as signing in to Equipo with Oficina ID once does.
+func (f *Fake) LinkOficinaID(subject, address string) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ f.links[subject] = address
+}
+
+// OficinaAssertion is an assertion Oficina ID made for Equipo about
+// subject, and its verifier, as the native app fetches them.
+func (f *Fake) OficinaAssertion(subject string) (assertion, verifier string) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ assertion, verifier = "oficina."+rand.Text()+rand.Text(), rand.Text()+rand.Text()
+ f.assertions[assertion] = &assertionGrant{subject: subject, verifier: verifier}
+ return assertion, verifier
+}
+
+// FailNextNativeExchange makes the next native exchange answer status
+// (with its state), as Equipo does when it is down (503).
+func (f *Fake) FailNextNativeExchange(status int) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ f.failNative = status
+}
+
+// NativeSessions is how many native sessions the fake has minted.
+func (f *Fake) NativeSessions() int {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ return len(f.sessions)
+}
+
+// EndNativeSession ends the native session whose cookie is value, as
+// signing out of Equipo does, and revokes every device registered with it.
+func (f *Fake) EndNativeSession(value string) {
+ f.nmu.Lock()
+ if s := f.sessions[value]; s != nil {
+ s.ended = true
+ }
+ f.nmu.Unlock()
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for _, d := range f.devices {
+ if d.session == value {
+ d.revoked = true
+ }
+ }
+}
+
+// DeviceSession is the native session cookie the device with id was
+// registered with ("" for a device from the code flow).
+func (f *Fake) DeviceSession(id string) string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if d := f.devices[id]; d != nil {
+ return d.session
+ }
+ return ""
+}
+
+// Devices are the ids of every device the fake knows.
+func (f *Fake) Devices() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []string
+ for id := range f.devices {
+ out = append(out, id)
+ }
+ return out
+}
+
+func nativeAnswer(w http.ResponseWriter, status int, state string) {
+ writeJSON(w, status, map[string]string{"state": state})
+}
+
+// serveNative answers the two native routes, and reports whether r was
+// one of them.
+func (f *Fake) serveNative(w http.ResponseWriter, r *http.Request) bool {
+ switch {
+ case r.Method == http.MethodPost && r.URL.Path == "/native/oficina-id":
+ f.nativeExchange(w, r)
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/auth/devices/native":
+ f.nativeDevice(w, r)
+ default:
+ return false
+ }
+ return true
+}
+
+func (f *Fake) nativeExchange(w http.ResponseWriter, r *http.Request) {
+ u, _ := url.Parse(f.URL)
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if r.Host != u.Host || r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 ||
+ len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Authorization")) != 0 || err != nil || media != "application/json" {
+ nativeAnswer(w, 400, "invalid")
+ return
+ }
+ var in struct {
+ Assertion string `json:"assertion"`
+ Verifier string `json:"verifier"`
+ }
+ if strict(r, &in) != nil || in.Assertion == "" || in.Verifier == "" {
+ nativeAnswer(w, 400, "invalid")
+ return
+ }
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ if status := f.failNative; status != 0 {
+ f.failNative = 0
+ state, ok := map[int]string{400: "invalid", 401: "failed", 403: "unknown"}[status]
+ if !ok {
+ state = "unavailable"
+ }
+ nativeAnswer(w, status, state)
+ return
+ }
+ g := f.assertions[in.Assertion]
+ if g == nil || g.used || g.verifier != in.Verifier {
+ nativeAnswer(w, 401, "failed")
+ return
+ }
+ address, linked := f.links[g.subject]
+ if !linked {
+ nativeAnswer(w, 403, "unknown")
+ return
+ }
+ g.used = true
+ value := rand.Text() + rand.Text()
+ now := time.Now().UTC().Truncate(time.Second)
+ f.sessions[value] = &nativeSession{subject: g.subject, address: address, at: now}
+ writeJSON(w, 200, map[string]any{"name": SessionCookie, "value": value, "expires_at": now.Add(nativeLifetime).Unix()})
+}
+
+func (f *Fake) nativeDevice(w http.ResponseWriter, r *http.Request) {
+ // A browser-style request: the session cookie, and Equipo's own
+ // Origin, which its CSRF check wants on a cookie mutation.
+ if r.Header.Get("Origin") != f.URL || len(r.Header.Values("Authorization")) != 0 || len(r.Header.Values("Idempotency-Key")) > 1 {
+ writeError(w, r, 403, "forbidden")
+ return
+ }
+ c, err := r.Cookie(SessionCookie)
+ if err != nil || len(r.Cookies()) != 1 {
+ writeError(w, r, 401, "unauthenticated")
+ return
+ }
+ var in struct {
+ PublicKey string `json:"public_key"`
+ Label string `json:"label"`
+ }
+ if strict(r, &in) != nil {
+ writeError(w, r, 422, "invalid_input")
+ return
+ }
+ raw, err := base64.RawURLEncoding.Strict().DecodeString(in.PublicKey)
+ if err != nil || len(raw) != ed25519.PublicKeySize || in.Label == "" || len(in.Label) > 128 || !utf8.ValidString(in.Label) || strings.ContainsAny(in.Label, "\x00\r\n") {
+ writeError(w, r, 422, "invalid_input")
+ return
+ }
+ f.nmu.Lock()
+ s := f.sessions[c.Value]
+ live := s != nil && !s.ended && time.Now().Before(s.at.Add(nativeLifetime))
+ var at time.Time
+ if live {
+ at = s.at
+ }
+ f.nmu.Unlock()
+ if !live {
+ writeError(w, r, 401, "unauthenticated")
+ return
+ }
+ d := &device{id: rand.Text(), publicKey: in.PublicKey, label: in.Label, approved: true, revision: 1,
+ token: personAudience + "." + rand.Text(), expires: at.Add(nativeLifetime), session: c.Value}
+ f.mu.Lock()
+ f.devices[d.id] = d
+ f.mu.Unlock()
+ w.Header().Set("ETag", `"1"`)
+ writeJSON(w, 200, map[string]any{"id": d.id, "token": d.token, "audience": personAudience,
+ "instance_id": f.Instance, "expires_at": d.expires})
+}
diff --git a/internal/equipo/native.go b/internal/equipo/native.go
new file mode 100644
index 0000000..7a15799
--- /dev/null
+++ b/internal/equipo/native.go
@@ -0,0 +1,127 @@
+package equipo
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Equipo's own native sign-in with Oficina ID, which Base completes for a
+// member whose native app hands it an assertion addressed to Equipo
+// (Equipo's internal/equipo/oficinaid/native.go and
+// personapi/native_device.go). It ends in the same person credential the
+// code flow does, which lasts only as long as the Equipo session it was
+// registered with: seven days, or until the person signs out of Equipo, is
+// relinked or leaves the roster.
+
+var (
+ // ErrNotLinked: Equipo has no roster member linked to the assertion's
+ // Oficina ID (403 unknown).
+ ErrNotLinked = &Error{Status: http.StatusForbidden, Code: "unknown"}
+ // ErrAssertionFailed: Equipo did not accept the assertion (bad,
+ // expired, wrong audience or verifier, or already used): a fresh one
+ // may be tried (401 failed).
+ ErrAssertionFailed = &Error{Status: http.StatusUnauthorized, Code: "failed"}
+ // ErrAssertionInvalid: Equipo could not read the request (400 invalid).
+ ErrAssertionInvalid = &Error{Status: http.StatusBadRequest, Code: "invalid"}
+)
+
+// NativeSession is Equipo's native session: its cookie, and when it ends.
+type NativeSession struct {
+ Name string
+ Value string
+ ExpiresAt time.Time
+}
+
+// Cookie is the session as a Cookie header's value.
+func (s NativeSession) Cookie() string { return s.Name + "=" + s.Value }
+
+// NativeExchange trades an Oficina ID assertion addressed to Equipo, with
+// its verifier, for an Equipo native session. Like the native app it
+// stands in for, it sends no Origin and no cookie. A refusal is an *Error
+// whose Code is Equipo's state (ErrNotLinked, ErrAssertionFailed,
+// ErrAssertionInvalid, or a 503 "unavailable").
+func (c *Client) NativeExchange(ctx context.Context, assertion, verifier string) (NativeSession, error) {
+ ctx, cancel := context.WithTimeout(ctx, callTimeout)
+ defer cancel()
+ raw, err := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
+ if err != nil {
+ return NativeSession{}, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.origin+"/native/oficina-id", bytes.NewReader(raw))
+ if err != nil {
+ return NativeSession{}, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ res, err := c.http.Do(req)
+ if err != nil {
+ return NativeSession{}, err
+ }
+ defer res.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
+ if err != nil {
+ return NativeSession{}, err
+ }
+ if res.StatusCode != http.StatusOK {
+ var e struct {
+ State string `json:"state"`
+ }
+ _ = json.Unmarshal(body, &e)
+ return NativeSession{}, &Error{Status: res.StatusCode, Code: e.State}
+ }
+ var out struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ ExpiresAt int64 `json:"expires_at"`
+ }
+ if err := json.Unmarshal(body, &out); err != nil {
+ return NativeSession{}, fmt.Errorf("equipo: native exchange: %w", err)
+ }
+ if !cookieToken(out.Name) || !cookieToken(out.Value) || out.ExpiresAt <= 0 {
+ return NativeSession{}, fmt.Errorf("equipo: native exchange: an unusable session")
+ }
+ return NativeSession{Name: out.Name, Value: out.Value, ExpiresAt: time.Unix(out.ExpiresAt, 0).UTC()}, nil
+}
+
+// cookieToken reports whether s may stand in a Cookie header as a name or
+// value: 1 to 4096 printable ASCII characters, none of them a separator.
+func cookieToken(s string) bool {
+ if s == "" || len(s) > 4096 {
+ return false
+ }
+ for _, r := range s {
+ if r <= ' ' || r >= 0x7f || strings.ContainsRune(`";,\=`, r) {
+ return false
+ }
+ }
+ return true
+}
+
+// RegisterNative registers a device key pub, labelled label, with the
+// person's Equipo native session s, and returns its credential: the same
+// kind as the code flow's (audience equipo.person.v1), ending with s. It
+// sends s's cookie and Equipo's own Origin, as Equipo's CSRF check wants
+// on a cookie mutation, and nothing of Base's.
+func (c *Client) RegisterNative(ctx context.Context, s NativeSession, pub ed25519.PublicKey, label string) (Credential, error) {
+ var out Credential
+ h := http.Header{"Cookie": {s.Cookie()}, "Origin": {c.origin}}
+ in := map[string]string{"public_key": base64.RawURLEncoding.EncodeToString(pub), "label": label}
+ hdr, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices/native", "", NewKey(), h, in, &out)
+ if err != nil {
+ return Credential{}, err
+ }
+ if out.ID == "" || out.Token == "" {
+ return Credential{}, fmt.Errorf("equipo: native device: no credential")
+ }
+ out.Revision, _ = strconv.ParseInt(strings.Trim(hdr.Get("ETag"), `"`), 10, 64)
+ return out, nil
+}
diff --git a/internal/web/ask.go b/internal/web/ask.go
index 2723ab3..9272cca 100644
--- a/internal/web/ask.go
+++ b/internal/web/ask.go
@@ -27,6 +27,9 @@ type asker struct {
// hosts holds a *sync.Mutex per member id, held while their
// connection changes or their host is registered (lockMember).
hosts sync.Map
+ // oficina holds a *sync.Mutex per member id, held while Ask is set up
+ // with Oficina ID for them (askOficinaLock).
+ oficina sync.Map
}
// askRoutes mounts the chat, behind the member gate and Base's CSRF check.
@@ -44,6 +47,7 @@ func (a *app) askRoutes(r chi.Router) {
r.Post("/ask/dock", a.askDock)
r.Get("/ask/oficina/connect", a.askOficinaConnect)
r.Get("/ask/oficina/done", a.askOficinaDone)
+ r.Post(askOficinaPath, a.askOficina)
}
// askDock is POST /ask/dock: on a wide screen the X closes Ask Base, docked
@@ -105,13 +109,19 @@ func chatting(state string) bool {
// deviceSecrets is what Base keeps sealed for a member's Equipo device:
// the Ed25519 seed, the device secret, the challenge and the nonce it
// proves with (kept, so a lost exchange answer can be asked for again),
-// and the bearer once it has one.
+// and the bearer once it has one. A key set up with Oficina ID (Via
+// "oficina") has no secret, challenge or nonce; it keeps instead the
+// cookie of the Equipo session it ends with, which Base never sends
+// anywhere again and never signs out (signing out would end the key).
type deviceSecrets struct {
- Seed []byte `json:"seed"`
- Secret string `json:"secret"`
- Challenge string `json:"challenge"`
- Nonce string `json:"nonce"`
- Token string `json:"token,omitempty"`
+ Seed []byte `json:"seed"`
+ Secret string `json:"secret"`
+ Challenge string `json:"challenge"`
+ Nonce string `json:"nonce"`
+ Token string `json:"token,omitempty"`
+ Via string `json:"via,omitempty"`
+ SessionName string `json:"session_name,omitempty"`
+ SessionValue string `json:"session_value,omitempty"`
}
func (a *app) sealSecrets(memberID string, s deviceSecrets) ([]byte, error) {
@@ -543,15 +553,24 @@ func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) {
if state == askReady {
cursor = a.askSnapshot(r, me, l, sec.Token, &v)
}
+ // RenewAfter is when the native app should set Ask up again with a
+ // fresh Oficina ID assertion: "" for a key from the code flow.
+ renew := ""
+ if at := renewAfter(l, sec); !at.IsZero() && state != askConnect {
+ renew = at.Format(time.RFC3339)
+ }
out := struct {
- State string `json:"state"`
- Messages []equipo.Message `json:"messages"`
- Jobs []jobView `json:"jobs"`
- Cards []equipo.Card `json:"cards"`
- Turn *equipo.Turn `json:"turn"`
- Status string `json:"status"`
- Cursor int64 `json:"cursor"`
- }{v.State, append([]equipo.Message{}, v.Messages...), append([]jobView{}, v.Jobs...), append([]equipo.Card{}, v.Cards...), v.Turn, v.Status, cursor}
+ State string `json:"state"`
+ Messages []equipo.Message `json:"messages"`
+ Jobs []jobView `json:"jobs"`
+ Cards []equipo.Card `json:"cards"`
+ Turn *equipo.Turn `json:"turn"`
+ Status string `json:"status"`
+ Cursor int64 `json:"cursor"`
+ RenewAfter string `json:"renew_after"`
+ EquipoOrigin string `json:"equipo_origin"`
+ }{v.State, append([]equipo.Message{}, v.Messages...), append([]jobView{}, v.Jobs...), append([]equipo.Card{}, v.Cards...), v.Turn, v.Status, cursor,
+ renew, a.ask.client.Origin()}
writeJSON(w, http.StatusOK, out)
}
diff --git a/internal/web/ask_oficina_native.go b/internal/web/ask_oficina_native.go
new file mode 100644
index 0000000..a7f53f1
--- /dev/null
+++ b/internal/web/ask_oficina_native.go
@@ -0,0 +1,170 @@
+package web
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/sessions"
+
+ "amadan.net/carlos/base/internal/equipo"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// Ask set up with Oficina ID, for the native app: the app fetches an
+// assertion addressed to Equipo and posts it here, and Base completes
+// Equipo's own native sign-in for the member (equipo.NativeExchange, then
+// RegisterNative). The key it gets is the same kind the code flow gets and
+// is kept the same way, so the relay cannot tell the two apart. It ends with
+// the Equipo session it was registered with, seven days on (or when the
+// person signs out of Equipo, is relinked or leaves the roster), so Base
+// keeps that session's cookie sealed beside the key, never signs it out,
+// and tells the app when to send a fresh assertion (renewAfter).
+
+// askOficinaPath is where the native app posts the assertion.
+const askOficinaPath = "/api/v1/ask/oficina"
+
+// viaOficina marks a key set up with Oficina ID (deviceSecrets.Via).
+const viaOficina = "oficina"
+
+// renewBefore is how long before the Equipo session ends the app should
+// renew: five days after a seven-day session was minted.
+const renewBefore = 2 * 24 * time.Hour
+
+// askOficinaTimeout bounds the whole set-up, which carries on if the app
+// goes away: Equipo may already have made the device.
+const askOficinaTimeout = 45 * time.Second
+
+// askNotLinked is the answer for a person Equipo has not linked to their
+// Oficina ID. It is this route's alone: /ask/state never says it.
+const askNotLinked = "not_linked"
+
+// renewAfter is when the app should send a fresh assertion for link l,
+// zero for a key from the code flow.
+func renewAfter(l store.EquipoLink, sec deviceSecrets) time.Time {
+ if sec.Via != viaOficina {
+ return time.Time{}
+ }
+ return l.ExpiresAt.Add(-renewBefore).UTC()
+}
+
+// askOficinaLock is the member's lock for setting Ask up with Oficina ID:
+// two posts for the same person run one at a time. It is not lockMember,
+// which the set-up takes itself while it stores and registers.
+func (a *app) askOficinaLock(id string) func() {
+ mu, _ := a.ask.oficina.LoadOrStore(id, &sync.Mutex{})
+ mu.(*sync.Mutex).Lock()
+ return mu.(*sync.Mutex).Unlock
+}
+
+// askOficina is POST /api/v1/ask/oficina, {assertion, verifier}, from a
+// native session only (docs/api/base-native-v1.md).
+func (a *app) askOficina(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ if s, ok := sessions.Current(r); !ok || s.Method != connect.NativeMethod {
+ writeJSON(w, http.StatusForbidden, map[string]string{"state": "forbidden"})
+ return
+ }
+ var in struct {
+ Assertion string `json:"assertion"`
+ Verifier string `json:"verifier"`
+ }
+ 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 {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"})
+ return
+ }
+ defer a.askOficinaLock(me.ID)()
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), askOficinaTimeout)
+ defer cancel()
+
+ old, oldSec, oldState, err := a.askLink(ctx, me)
+ if err != nil {
+ a.logger.Error("ask oficina: link", "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable})
+ return
+ }
+ sess, err := a.ask.client.NativeExchange(ctx, in.Assertion, in.Verifier)
+ if err != nil {
+ a.askOficinaRefused(w, "exchange", err)
+ return
+ }
+ pub, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ a.fail(w, err)
+ return
+ }
+ cred, err := a.ask.client.RegisterNative(ctx, sess, pub, a.ask.label)
+ if err != nil {
+ a.askOficinaRefused(w, "device", err)
+ return
+ }
+ exp := cred.ExpiresAt
+ if exp.IsZero() || exp.After(sess.ExpiresAt) {
+ exp = sess.ExpiresAt
+ }
+ sealed, err := a.sealSecrets(me.ID, deviceSecrets{Seed: key.Seed(), Token: cred.Token, Via: viaOficina,
+ SessionName: sess.Name, SessionValue: sess.Value})
+ l := store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), State: store.EquipoConnected,
+ DeviceID: cred.ID, Sealed: sealed, ExpiresAt: exp, Revision: cred.Revision}
+ if err == nil {
+ // Saving the new link forgets the old host token with it.
+ unlock := a.lockMember(me.ID)
+ err = store.SaveEquipoLink(ctx, a.db, l)
+ unlock()
+ }
+ if err != nil {
+ a.logger.Error("ask oficina: store", "device", cred.ID, "err", err)
+ a.revoke(ctx, l, deviceSecrets{Token: cred.Token})
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable})
+ return
+ }
+ // The key it replaces is over: revoke it in Equipo, as Connect does.
+ if oldState == askReady && old.DeviceID != cred.ID {
+ a.revoke(ctx, old, oldSec)
+ }
+ a.hostFor(ctx, me, cred.ID, cred.Token, true)
+ writeJSON(w, http.StatusOK, map[string]string{"state": askReady, "renew_after": renewAfter(l, deviceSecrets{Via: viaOficina}).Format(time.RFC3339)})
+}
+
+// askOficinaRefused answers for a step of Equipo's sign-in that failed,
+// having stored nothing. The app never hears a 401 here: that would read
+// as Base's own session ending.
+func (a *app) askOficinaRefused(w http.ResponseWriter, step string, err error) {
+ var e *equipo.Error
+ switch {
+ case step == "exchange" && errors.Is(err, equipo.ErrNotLinked):
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askNotLinked})
+ case step == "exchange" && errors.Is(err, equipo.ErrAssertionFailed):
+ writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": "failed"})
+ case step == "exchange" && errors.Is(err, equipo.ErrAssertionInvalid):
+ writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"})
+ default:
+ if errors.As(err, &e) {
+ a.logger.Warn("ask oficina: equipo refused", "step", step, "status", e.Status, "code", e.Code)
+ } else {
+ a.logger.Warn("ask oficina: equipo", "step", step, "err", err)
+ }
+ writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable})
+ }
+}
+
+// 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
+ }
+ if d.Decode(new(json.RawMessage)) != io.EOF {
+ return errors.New("trailing JSON")
+ }
+ return nil
+}
diff --git a/internal/webtest/ask_native_contract_test.go b/internal/webtest/ask_native_contract_test.go
index ca7e517..1d6a828 100644
--- a/internal/webtest/ask_native_contract_test.go
+++ b/internal/webtest/ask_native_contract_test.go
@@ -100,13 +100,13 @@ func (a *testApp) askState() (askState, Resp) {
return s, r
}
-var stateKeys = []string{"state", "messages", "jobs", "cards", "turn", "status", "cursor"}
+var stateKeys = []string{"state", "messages", "jobs", "cards", "turn", "status", "cursor", "renew_after", "equipo_origin"}
func TestAskContractBeforeConnecting(t *testing.T) {
- _, app, _ := newNativeAskApp(t)
+ _, app, f := newNativeAskApp(t)
s, r := app.askState()
wantKeys(t, "state", r.Body, stateKeys...)
- if strings.TrimSpace(r.Body) != `{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0}` || s.State != "connect" {
+ if strings.TrimSpace(r.Body) != `{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"renew_after":"","equipo_origin":"`+f.URL+`"}` || s.State != "connect" {
t.Errorf("not connected: %s", r.Body)
}
wantBody(t, "send", app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"k1"}}), 409, `{"state":"connect"}`)
diff --git a/internal/webtest/ask_oficina_native_test.go b/internal/webtest/ask_oficina_native_test.go
new file mode 100644
index 0000000..ea6fc43
--- /dev/null
+++ b/internal/webtest/ask_oficina_native_test.go
@@ -0,0 +1,264 @@
+package webtest
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+)
+
+// Ask set up with Oficina ID (docs/api/base-native-v1.md): the native app
+// posts an assertion addressed to Equipo, and Base completes Equipo's own
+// native sign-in for the person, keeping the key where the code flow does.
+
+// connectWithOficina posts what the native app posts for subject.
+func (a *testApp) connectWithOficina(f *equipotest.Fake, subject string) Resp {
+ a.t.Helper()
+ assertion, verifier := f.OficinaAssertion(subject)
+ body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
+ return a.nativePost("/api/v1/ask/oficina", string(body))
+}
+
+type askReadyAnswer struct {
+ State string `json:"state"`
+ RenewAfter string `json:"renew_after"`
+}
+
+// equipoLinks is how many Equipo links Base holds.
+func (a *testApp) equipoLinks() int {
+ a.t.Helper()
+ var n int
+ if err := a.DB.QueryRow(`SELECT count(*) FROM equipo_links`).Scan(&n); err != nil {
+ a.t.Fatal(err)
+ }
+ return n
+}
+
+// liveDevice is the one device the fake holds that is not revoked.
+func liveDevice(t *testing.T, f *equipotest.Fake) string {
+ t.Helper()
+ var live []string
+ for _, id := range f.Devices() {
+ if !f.Revoked(id) {
+ live = append(live, id)
+ }
+ }
+ if len(live) != 1 {
+ t.Fatalf("live devices: %v", live)
+ }
+ return live[0]
+}
+
+func TestAskOficinaConnect(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ r := app.connectWithOficina(f, "subject-owner")
+ if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ wantKeys(t, "connect", r.Body, "state", "renew_after")
+ out := decode[askReadyAnswer](t, r)
+ renew, err := time.Parse(time.RFC3339, out.RenewAfter)
+ if out.State != "ready" || err != nil || renew.Sub(time.Now().Add(5*24*time.Hour)).Abs() > time.Minute {
+ t.Fatalf("connect: %s", r.Body)
+ }
+
+ // Equipo's exchange: what a native app sends, no Origin, no cookie.
+ ex := f.Calls("/native/oficina-id")
+ if len(ex) != 1 || ex[0].Header.Get("Origin") != "" || ex[0].Header.Get("Cookie") != "" || ex[0].Header.Get("Authorization") != "" ||
+ ex[0].Header.Get("Content-Type") != "application/json" || len(keysOf(t, ex[0].Body)) != 2 {
+ t.Fatalf("exchange: %+v", ex)
+ }
+ // Then the device, with that session's cookie (and nothing of Base's),
+ // Equipo's own Origin, a fresh key and Base's label.
+ dev := f.Calls("/api/v1/auth/devices/native")
+ if len(dev) != 1 {
+ t.Fatalf("device calls: %d", len(dev))
+ }
+ h := dev[0].Header
+ if !strings.HasPrefix(h.Get("Cookie"), equipotest.SessionCookie+"=") || strings.Contains(h.Get("Cookie"), sessionCookie) ||
+ strings.Contains(h.Get("Cookie"), ";") || h.Get("Origin") != f.URL || h.Get("Authorization") != "" {
+ t.Fatalf("device headers: %v", h)
+ }
+ var in struct {
+ PublicKey string `json:"public_key"`
+ Label string `json:"label"`
+ }
+ _ = json.Unmarshal([]byte(dev[0].Body), &in)
+ if pub, err := base64.RawURLEncoding.DecodeString(in.PublicKey); err != nil || len(pub) != 32 || in.Label != "Base (Acme)" {
+ t.Fatalf("device body: %s", dev[0].Body)
+ }
+ device := liveDevice(t, f)
+ if f.DeviceSession(device) == "" {
+ t.Fatal("the key is not the native session's")
+ }
+ // The Assistant's host is registered with the new key, as Connect does.
+ hosts := f.Hosts()
+ if len(hosts) != 1 || !strings.HasPrefix(hosts[0].Header.Get("Authorization"), "Bearer equipo.person.v1.") {
+ t.Fatalf("hosts: %+v", hosts)
+ }
+ // Ask is ready, and the relay uses the key.
+ s, raw := app.askState()
+ if s.State != "ready" || !strings.Contains(raw.Body, `"renew_after":"`+out.RenewAfter+`"`) {
+ t.Fatalf("state: %s", raw.Body)
+ }
+ if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"o-1"}}); sent.Code != 200 {
+ t.Fatalf("send: %d %s", sent.Code, sent.Body)
+ }
+ if c := f.Calls("/api/v1/assistant/messages"); len(c) != 1 || c[0].Header.Get("Authorization") != hosts[0].Header.Get("Authorization") {
+ t.Fatalf("relayed with: %+v", c)
+ }
+ // Neither the key nor Equipo's session ever reaches the app.
+ app.noLeak(strings.TrimPrefix(hosts[0].Header.Get("Authorization"), "Bearer "))
+ app.noLeak(f.DeviceSession(device))
+ // Base never signs Equipo's session out.
+ for _, c := range f.Calls("") {
+ if strings.Contains(c.Path, "signout") {
+ t.Errorf("Base called %s", c.Path)
+ }
+ }
+}
+
+// A person Equipo has not linked to their Oficina ID: not_linked, and
+// nothing is stored.
+func TestAskOficinaUnknown(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ wantBody(t, "unlinked", app.connectWithOficina(f, "subject-owner"), 409, `{"state":"not_linked"}`)
+ if n := app.equipoLinks(); n != 0 || len(f.Devices()) != 0 || len(f.Calls("/api/v1/auth/devices/native")) != 0 {
+ t.Fatalf("stored %d links, %d devices", n, len(f.Devices()))
+ }
+ if s, _ := app.askState(); s.State != "connect" {
+ t.Errorf("state: %s", s.State)
+ }
+}
+
+// Equipo's other refusals store nothing either, and never answer 401,
+// which the app would read as Base's own session ending.
+func TestAskOficinaEquipoRefusals(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ f.FailNextNativeExchange(503)
+ wantBody(t, "Equipo down", app.connectWithOficina(f, "subject-owner"), 502, `{"state":"unavailable"}`)
+ // An assertion Equipo refuses (here, one already used).
+ assertion, verifier := f.OficinaAssertion("subject-owner")
+ body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
+ if r := app.nativePost("/api/v1/ask/oficina", string(body)); r.Code != 200 {
+ t.Fatalf("first use: %d %s", r.Code, r.Body)
+ }
+ wantBody(t, "replayed", app.nativePost("/api/v1/ask/oficina", string(body)), 422, `{"state":"failed"}`)
+ if len(f.Devices()) != 1 {
+ t.Errorf("devices: %d", len(f.Devices()))
+ }
+ // What Base can't read.
+ for _, bad := range []string{``, `{}`, `{"assertion":"x"}`, `{"assertion":"x","verifier":"y","extra":1}`, `[1]`} {
+ wantBody(t, "body "+bad, app.nativePost("/api/v1/ask/oficina", bad), 400, `{"state":"invalid"}`)
+ }
+}
+
+// A second post replaces the key and Equipo session, and revokes the old
+// device in Equipo.
+func TestAskOficinaRenew(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("first: %d %s", r.Code, r.Body)
+ }
+ first := liveDevice(t, f)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("renew: %d %s", r.Code, r.Body)
+ }
+ second := liveDevice(t, f)
+ if second == first || !f.Revoked(first) || f.DeviceSession(second) == f.DeviceSession(first) || f.NativeSessions() != 2 {
+ t.Fatalf("renew: first %s (revoked %v), second %s", first, f.Revoked(first), second)
+ }
+ if n := app.equipoLinks(); n != 1 {
+ t.Errorf("links: %d", n)
+ }
+ if hosts := f.Hosts(); len(hosts) != 2 {
+ t.Errorf("hosts registered: %d", len(hosts))
+ }
+ if s, _ := app.askState(); s.State != "ready" {
+ t.Errorf("state: %s", s.State)
+ }
+ // Two at once run one at a time: one device is left.
+ var wg sync.WaitGroup
+ for range 2 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Errorf("concurrent: %d %s", r.Code, r.Body)
+ }
+ }()
+ }
+ wg.Wait()
+ liveDevice(t, f)
+}
+
+// The web keeps its code flow: only a native session may post here.
+func TestAskOficinaRefusesWeb(t *testing.T) {
+ web, _, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ browser := web.newBrowser()
+ browser.signInWithOficina("subject-owner")
+ for name, b := range map[string]*testApp{"local": web, "Oficina in a browser": browser} {
+ wantBody(t, name, b.connectWithOficina(f, "subject-owner"), 403, `{"state":"forbidden"}`)
+ }
+ if len(f.Calls("/native/oficina-id")) != 0 {
+ t.Fatal("a browser session reached Equipo")
+ }
+ // From another site it never gets that far.
+ req, _ := http.NewRequest(http.MethodPost, homeOrigin+"/api/v1/ask/oficina", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Origin", "https://evil.test")
+ if r := web.do(req); r.Code != http.StatusForbidden {
+ t.Errorf("cross-site: %d", r.Code)
+ }
+}
+
+func TestAskStateSaysWhenToRenew(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ // A key from the code flow: no renew_after.
+ web.approveEquipo(f)
+ _, r := app.askState()
+ if !strings.Contains(r.Body, `"renew_after":""`) || !strings.Contains(r.Body, `"equipo_origin":"`+f.URL+`"`) {
+ t.Fatalf("code flow: %s", r.Body)
+ }
+ // With Oficina ID: five days after Equipo's session began.
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ out := decode[askReadyAnswer](t, app.connectWithOficina(f, "subject-owner"))
+ _, r = app.askState()
+ if out.RenewAfter == "" || !strings.Contains(r.Body, `"renew_after":"`+out.RenewAfter+`"`) {
+ t.Fatalf("oficina: %s (answered %+v)", r.Body, out)
+ }
+ // It replaced the code flow's key, which is revoked: one key is live.
+ // Equipo ending its session ends the key: Ask asks to reconnect.
+ f.EndNativeSession(f.DeviceSession(liveDevice(t, f)))
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Errorf("after Equipo's session ended: %s", s.State)
+ }
+}
+
+func TestDisconnectRevokesOficinaKey(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ device := liveDevice(t, f)
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("disconnect: %d %q", r.Code, r.Location())
+ }
+ if !f.Revoked(device) || app.equipoLinks() != 0 {
+ t.Fatalf("revoked %v, links %d", f.Revoked(device), app.equipoLinks())
+ }
+ if s, _ := app.askState(); s.State != "connect" {
+ t.Errorf("state: %s", s.State)
+ }
+}