Add an Equipo person API client and per-member device links
BASE_EQUIPO_ORIGIN names the Equipo whose coordinator answers "Ask Base anything" (https, or http on loopback); unset leaves the chat off. internal/equipo signs a device in with Equipo's device flow (begin, an Ed25519-signed exchange, revoke) and calls the chat routes with the member's bearer: snapshot, send, cancel, answer and the event stream. Every mutation carries an Idempotency-Key, and a message also carries it as its idempotency_key. Sealer seals what Base keeps per member with AES-256-GCM under an HKDF key derived from BASE_INSTANCE_KEY and the member's id. equipotest is an httptest fake mirroring Equipo's handlers. equipo_links holds each member's link (pending, connected or lost) and goes with the member on removal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+1,440
−0
internal/config/config.go+19 −0internal/config/config_test.go+28 −0internal/equipo/chat.go+133 −0internal/equipo/equipo.go+204 −0internal/equipo/equipo_test.go+130 −0internal/equipo/equipotest/chat.go+380 −0internal/equipo/equipotest/fake.go+335 −0internal/equipo/seal.go+28 −0internal/store/equipo.go+91 −0internal/store/equipo_test.go+74 −0internal/store/migrations/0005_equipo_links.sql+18 −0
diff --git a/internal/config/config.go b/internal/config/config.go| index 86fc4af..d0ab6e7 100644 |
| --- a/internal/config/config.go |
| +++ b/internal/config/config.go |
| @@ -46,6 +46,9 @@ type Config struct { |
| // InstanceKey seals sign-in state (BASE_INSTANCE_KEY). Keep it secret and |
| // stable: changing it invalidates links and sign-ins in flight. |
| InstanceKey string |
| + // EquipoOrigin is the Equipo instance whose coordinator answers "Ask |
| + // Base anything" (BASE_EQUIPO_ORIGIN). Empty leaves the chat off. |
| + EquipoOrigin string |
| // Home turns on sign-in with Oficina ID. Nil (no BASE_HOME_* settings) |
| // leaves it off; LoadHome sets it. |
| Home *connect.DecodedCredentials |
| @@ -105,6 +108,9 @@ func Load(getenv func(string) string) (Config, error) { |
| return Config{}, fmt.Errorf("BASE_ASSERTION_KEY: %w", err) |
| } |
| } |
| + if cfg.EquipoOrigin, err = equipoOrigin(get("EQUIPO_ORIGIN")); err != nil { |
| + return Config{}, err |
| + } |
| if cfg.AppsDomain != "" { |
| if err := checkAssertionOrigins(cfg, local); err != nil { |
| return Config{}, err |
| @@ -163,3 +169,16 @@ func originIsLocal(origin string) (bool, error) { |
| } |
| return local, nil |
| } |
| + |
| +// equipoOrigin checks BASE_EQUIPO_ORIGIN: empty, or a scheme and host only, |
| +// https (http only on a loopback host, for a local Equipo). |
| +func equipoOrigin(raw string) (string, error) { |
| + raw = strings.TrimRight(raw, "/") |
| + if raw == "" { |
| + return "", nil |
| + } |
| + if _, err := originIsLocal(raw); err != nil { |
| + return "", fmt.Errorf("BASE_EQUIPO_ORIGIN %q must be an https origin: a scheme and host only (http only on loopback)", raw) |
| + } |
| + return raw, nil |
| +} |
diff --git a/internal/config/config_test.go b/internal/config/config_test.go| index 732acb5..6eb8740 100644 |
| --- a/internal/config/config_test.go |
| +++ b/internal/config/config_test.go |
| @@ -122,3 +122,31 @@ func TestLoadChecksOriginsAgainstTheAssertionRules(t *testing.T) { |
| t.Errorf("no installs configured: %v", err) |
| } |
| } |
| + |
| +func TestEquipoOrigin(t *testing.T) { |
| + cfg, err := Load(env(valid())) |
| + if err != nil || cfg.EquipoOrigin != "" { |
| + t.Fatalf("unset: %q, %v; want chat off", cfg.EquipoOrigin, err) |
| + } |
| + for raw, want := range map[string]string{ |
| + "https://equipo.bds.oncarlos.com": "https://equipo.bds.oncarlos.com", |
| + "https://equipo.bds.oncarlos.com/": "https://equipo.bds.oncarlos.com", |
| + "http://127.0.0.1:9000": "http://127.0.0.1:9000", |
| + "http://equipo.example.com": "", |
| + "https://equipo.example.com/chat": "", |
| + "https://user@equipo.example.com": "", |
| + "equipo.example.com": "", |
| + } { |
| + m := valid() |
| + m["BASE_EQUIPO_ORIGIN"] = raw |
| + cfg, err := Load(env(m)) |
| + switch { |
| + case want == "" && err == nil: |
| + t.Errorf("%q accepted as %q", raw, cfg.EquipoOrigin) |
| + case want == "" && !strings.Contains(err.Error(), "BASE_EQUIPO_ORIGIN"): |
| + t.Errorf("%q: error %v does not name the setting", raw, err) |
| + case want != "" && (err != nil || cfg.EquipoOrigin != want): |
| + t.Errorf("%q: got %q, %v; want %q", raw, cfg.EquipoOrigin, err, want) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/chat.go b/internal/equipo/chat.go| new file mode 100644 |
| index 0000000..83c73a0 |
| --- /dev/null |
| +++ b/internal/equipo/chat.go |
| @@ -0,0 +1,133 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/url" |
| + "time" |
| +) |
| + |
| +// Turn states (wire.Turn*). A turn ends replied, failed or cancelled. |
| +const ( |
| + TurnQueued = "queued" |
| + TurnRunning = "running" |
| + TurnWaiting = "waiting" |
| + TurnReplied = "replied" |
| + TurnFailed = "failed" |
| + TurnCancelled = "cancelled" |
| +) |
| + |
| +// InFlight reports whether a turn in state has not ended. |
| +func InFlight(state string) bool { |
| + return state == TurnQueued || state == TurnRunning || state == TurnWaiting |
| +} |
| + |
| +// Message is one line of the conversation; Role is person or coordinator. |
| +type Message struct { |
| + ID string `json:"id"` |
| + Role string `json:"role"` |
| + Text string `json:"text"` |
| + TurnID string `json:"turn_id"` |
| + CreatedAt time.Time `json:"created_at"` |
| +} |
| + |
| +// Turn is the coordinator's answer to the person's messages. |
| +type Turn struct { |
| + ID string `json:"id"` |
| + Kind string `json:"kind"` |
| + State string `json:"state"` |
| + Reason string `json:"reason"` |
| +} |
| + |
| +// Card is something in the conversation to act on. Base shows only open |
| +// question cards (Kind "question", State "open"), each Option a button. |
| +type Card struct { |
| + ID string `json:"id"` |
| + Revision int64 `json:"revision"` |
| + Kind string `json:"kind"` |
| + State string `json:"state"` |
| + Question string `json:"question"` |
| + Options []string `json:"options"` |
| + Choice string `json:"choice"` |
| +} |
| + |
| +// Open reports whether the card is a question waiting for an answer. |
| +func (c Card) Open() bool { return c.Kind == "question" && c.State == "open" } |
| + |
| +// Snapshot is the part of GET /api/v1/snapshot Base shows: the |
| +// conversation's tail, its turns, its cards and the event cursor they |
| +// were read at, so the stream picks up exactly after them. |
| +type Snapshot struct { |
| + Messages []Message `json:"messages"` |
| + Turns []Turn `json:"turns"` |
| + Cards []Card `json:"cards"` |
| + Cursor int64 `json:"cursor"` |
| +} |
| + |
| +// Sent is POST /api/v1/messages's answer. |
| +type Sent struct { |
| + Message Message `json:"message"` |
| + Turn Turn `json:"turn"` |
| +} |
| + |
| +// Answered is POST /api/v1/cards/{id}/answer's answer. |
| +type Answered struct { |
| + Card Card `json:"card"` |
| + Message Message `json:"message"` |
| + Turn Turn `json:"turn"` |
| +} |
| + |
| +// Snapshot reads the person's conversation in one go. |
| +func (c *Client) Snapshot(ctx context.Context, token string) (Snapshot, error) { |
| + var out Snapshot |
| + _, err := c.call(ctx, http.MethodGet, "/api/v1/snapshot", token, "", nil, nil, &out) |
| + return out, err |
| +} |
| + |
| +// Send sends the person's message. key makes a retry safe: Equipo keeps |
| +// one message per key. It goes as the body's idempotency_key, and as the |
| +// Idempotency-Key header every mutation carries. |
| +func (c *Client) Send(ctx context.Context, token, text, key string) (Sent, error) { |
| + var out Sent |
| + in := map[string]string{"text": text, "idempotency_key": key} |
| + _, err := c.call(ctx, http.MethodPost, "/api/v1/messages", token, key, nil, in, &out) |
| + return out, err |
| +} |
| + |
| +// Cancel stops a turn that has not ended. |
| +func (c *Client) Cancel(ctx context.Context, token, turnID, key string) error { |
| + _, err := c.call(ctx, http.MethodPost, "/api/v1/turns/"+url.PathEscape(turnID)+"/cancel", token, key, nil, struct{}{}, nil) |
| + return err |
| +} |
| + |
| +// Answer answers question card id with choice, at the card's revision. |
| +func (c *Client) Answer(ctx context.Context, token, id, choice string, revision int64, key string) (Answered, error) { |
| + var out Answered |
| + in := map[string]any{"choice": choice, "revision": revision} |
| + _, err := c.call(ctx, http.MethodPost, "/api/v1/cards/"+url.PathEscape(id)+"/answer", token, key, nil, in, &out) |
| + return out, err |
| +} |
| + |
| +// Events opens the person's event stream after cursor after ("" for from |
| +// now). The caller reads and closes the body; 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) |
| + } |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + req.Header.Set("Accept", "text/event-stream") |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + res, err := c.http.Do(req) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if res.StatusCode != http.StatusOK { |
| + res.Body.Close() |
| + return nil, &Error{Status: res.StatusCode} |
| + } |
| + return res, nil |
| +} |
diff --git a/internal/equipo/equipo.go b/internal/equipo/equipo.go| new file mode 100644 |
| index 0000000..c2eede5 |
| --- /dev/null |
| +++ b/internal/equipo/equipo.go |
| @@ -0,0 +1,204 @@ |
| +// Package equipo is Base's client for Equipo's person API (v1): signing a |
| +// device in for a member, and the coordinator chat behind "Ask Base |
| +// anything". Base calls Equipo server to server with the member's bearer; |
| +// the bearer never reaches a browser. |
| +// |
| +// The shapes mirror Equipo's handlers on main (internal/wire/api.go, |
| +// internal/equipo/personapi/devices.go), reading only the fields Base uses. |
| +package equipo |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// Error is a non-2xx answer from Equipo: its status and error code. |
| +type Error struct { |
| + Status int |
| + Code string |
| +} |
| + |
| +func (e *Error) Error() string { return fmt.Sprintf("equipo: %d %s", e.Status, e.Code) } |
| + |
| +// Is lets errors.Is match the sentinel errors below by status and code. |
| +func (e *Error) Is(target error) bool { |
| + t, ok := target.(*Error) |
| + return ok && t.Status == e.Status && (t.Code == "" || t.Code == e.Code) |
| +} |
| + |
| +var ( |
| + // ErrUnauthenticated: the bearer is revoked, expired or its person |
| + // removed. The member must reconnect. |
| + ErrUnauthenticated = &Error{Status: 401} |
| + // ErrPending: the sign-in code is not approved yet. |
| + ErrPending = &Error{Status: 409, Code: "authorization_pending"} |
| + // ErrSlowDown: asked again too soon. |
| + ErrSlowDown = &Error{Status: 429} |
| + // ErrExpired: the sign-in code expired; start again. |
| + ErrExpired = &Error{Status: 410} |
| +) |
| + |
| +// Challenge is POST /api/v1/auth/devices's answer. |
| +type Challenge struct { |
| + ID string `json:"id"` |
| + DeviceSecret string `json:"device_secret"` |
| + UserCode string `json:"user_code"` |
| + Challenge string `json:"challenge"` |
| + VerificationURI string `json:"verification_uri"` |
| + ExpiresAt time.Time `json:"expires_at"` |
| +} |
| + |
| +// Proof is the body of POST /api/v1/auth/devices/exchange. |
| +type Proof struct { |
| + ID string `json:"id"` |
| + DeviceSecret string `json:"device_secret"` |
| + Challenge string `json:"challenge"` |
| + Nonce string `json:"nonce"` |
| + Signature string `json:"signature"` |
| +} |
| + |
| +// Credential is a device's bearer. Revision is the device's revision (the |
| +// exchange's ETag), which revoking it must name. |
| +type Credential struct { |
| + ID string `json:"id"` |
| + Token string `json:"token"` |
| + ExpiresAt time.Time `json:"expires_at"` |
| + Revision int64 `json:"-"` |
| +} |
| + |
| +// Client calls one Equipo instance. |
| +type Client struct { |
| + origin string |
| + http *http.Client |
| +} |
| + |
| +// 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{ |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + }} |
| +} |
| + |
| +// Origin is the instance's origin. |
| +func (c *Client) Origin() string { return c.origin } |
| + |
| +// callTimeout bounds every call but the event stream. |
| +const callTimeout = 20 * time.Second |
| + |
| +// call sends one request. token is the bearer ("" for the device routes); |
| +// key, when set, is the Idempotency-Key. A 2xx body is decoded into out. |
| +func (c *Client) call(ctx context.Context, method, path, token, key string, header http.Header, in, out any) (http.Header, error) { |
| + ctx, cancel := context.WithTimeout(ctx, callTimeout) |
| + defer cancel() |
| + var body io.Reader |
| + if in != nil { |
| + raw, err := json.Marshal(in) |
| + if err != nil { |
| + return nil, err |
| + } |
| + body = bytes.NewReader(raw) |
| + } |
| + req, err := http.NewRequestWithContext(ctx, method, c.origin+path, body) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for k, v := range header { |
| + req.Header[k] = v |
| + } |
| + if in != nil { |
| + req.Header.Set("Content-Type", "application/json") |
| + } |
| + req.Header.Set("Accept", "application/json") |
| + if token != "" { |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + } |
| + if key != "" { |
| + req.Header.Set("Idempotency-Key", key) |
| + } |
| + res, err := c.http.Do(req) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer res.Body.Close() |
| + raw, err := io.ReadAll(io.LimitReader(res.Body, 4<<20)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if res.StatusCode < 200 || res.StatusCode > 299 { |
| + var e struct { |
| + Code string `json:"code"` |
| + } |
| + _ = json.Unmarshal(raw, &e) |
| + return res.Header, &Error{Status: res.StatusCode, Code: e.Code} |
| + } |
| + if out != nil && len(raw) > 0 { |
| + if err := json.Unmarshal(raw, out); err != nil { |
| + return nil, fmt.Errorf("equipo: %s %s: %w", method, path, err) |
| + } |
| + } |
| + return res.Header, nil |
| +} |
| + |
| +// NewKey is a fresh request key: Idempotency-Key, or a message's key. |
| +func NewKey() string { return rand.Text() } |
| + |
| +// BeginDevice asks Equipo to sign in a device with public key pub; label |
| +// is what the person sees when approving it. |
| +func (c *Client) BeginDevice(ctx context.Context, pub ed25519.PublicKey, label string) (Challenge, error) { |
| + var out Challenge |
| + in := map[string]string{"public_key": base64.RawURLEncoding.EncodeToString(pub), "label": label} |
| + _, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices", "", NewKey(), nil, in, &out) |
| + return out, err |
| +} |
| + |
| +// Prove signs ch with the device's key and nonce, as the exchange wants: |
| +// Ed25519 over the compact JSON array |
| +// ["equipo.person.device.v1", instance, id, challenge, nonce], where the |
| +// instance is the first element of the decoded challenge. |
| +func Prove(key ed25519.PrivateKey, ch Challenge, nonce string) (Proof, error) { |
| + raw, err := base64.RawURLEncoding.DecodeString(ch.Challenge) |
| + if err != nil { |
| + return Proof{}, fmt.Errorf("equipo: challenge: %w", err) |
| + } |
| + var parts []string |
| + if err := json.Unmarshal(raw, &parts); err != nil || len(parts) == 0 { |
| + return Proof{}, errors.New("equipo: challenge is not a JSON array") |
| + } |
| + p := Proof{ID: ch.ID, DeviceSecret: ch.DeviceSecret, Challenge: ch.Challenge, Nonce: nonce} |
| + msg, _ := json.Marshal([]string{"equipo.person.device.v1", parts[0], p.ID, p.Challenge, p.Nonce}) |
| + p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, msg)) |
| + return p, nil |
| +} |
| + |
| +// Exchange trades an approved proof for a bearer: ErrPending until the |
| +// person approves, ErrSlowDown when asked too soon, ErrExpired once the |
| +// code has expired. The same proof and nonce may be sent again. |
| +func (c *Client) Exchange(ctx context.Context, p Proof) (Credential, error) { |
| + var out Credential |
| + h, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices/exchange", "", NewKey(), nil, p, &out) |
| + if err != nil { |
| + return Credential{}, err |
| + } |
| + out.Revision, _ = strconv.ParseInt(strings.Trim(h.Get("ETag"), `"`), 10, 64) |
| + return out, nil |
| +} |
| + |
| +// RevokeDevice revokes device id, signed in as itself, at revision. |
| +func (c *Client) RevokeDevice(ctx context.Context, token, id string, revision int64) error { |
| + h := http.Header{"If-Match": {`"` + strconv.FormatInt(revision, 10) + `"`}} |
| + _, err := c.call(ctx, http.MethodDelete, "/api/v1/auth/devices/"+url.PathEscape(id), token, NewKey(), h, struct{}{}, nil) |
| + return err |
| +} |
diff --git a/internal/equipo/equipo_test.go b/internal/equipo/equipo_test.go| new file mode 100644 |
| index 0000000..f758b9a |
| --- /dev/null |
| +++ b/internal/equipo/equipo_test.go |
| @@ -0,0 +1,130 @@ |
| +package equipo_test |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + |
| + "amadan.net/carlos/base/internal/equipo" |
| + "amadan.net/carlos/base/internal/equipo/equipotest" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +// signIn runs the device flow against f, approving the code at once. |
| +func signIn(t *testing.T, f *equipotest.Fake, c *equipo.Client) equipo.Credential { |
| + t.Helper() |
| + ctx := context.Background() |
| + pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| + ch, err := c.BeginDevice(ctx, pub, "Base (Acme)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + proof, err := equipo.Prove(key, ch, rand.Text()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := c.Exchange(ctx, proof); !errors.Is(err, equipo.ErrPending) { |
| + t.Fatalf("before approval: %v, want ErrPending", err) |
| + } |
| + if err := f.Approve(ch.UserCode); err != nil { |
| + t.Fatal(err) |
| + } |
| + cred, err := c.Exchange(ctx, proof) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return cred |
| +} |
| + |
| +func TestDeviceFlowAndRevoke(t *testing.T) { |
| + f := equipotest.New(t) |
| + c := equipo.New(f.URL) |
| + cred := signIn(t, f, c) |
| + if !strings.HasPrefix(cred.Token, "equipo.person.v1.") || cred.Revision != 3 || cred.ExpiresAt.IsZero() { |
| + t.Fatalf("credential: %+v", cred) |
| + } |
| + for _, call := range f.Calls("") { |
| + if call.Header.Get("Idempotency-Key") == "" || call.Header.Get("Cookie") != "" || call.Header.Get("Origin") != "" { |
| + t.Errorf("%s %s headers: %v", call.Method, call.Path, call.Header) |
| + } |
| + } |
| + ctx := context.Background() |
| + if _, err := c.Snapshot(ctx, cred.Token); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := c.RevokeDevice(ctx, cred.Token, cred.ID, cred.Revision); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := c.Snapshot(ctx, cred.Token); !errors.Is(err, equipo.ErrUnauthenticated) { |
| + t.Fatalf("after revoke: %v, want ErrUnauthenticated", err) |
| + } |
| +} |
| + |
| +func TestExpiredCode(t *testing.T) { |
| + f := equipotest.New(t) |
| + c := equipo.New(f.URL) |
| + ctx := context.Background() |
| + pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| + ch, err := c.BeginDevice(ctx, pub, "Base") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.Expire() |
| + proof, _ := equipo.Prove(key, ch, rand.Text()) |
| + if _, err := c.Exchange(ctx, proof); !errors.Is(err, equipo.ErrExpired) { |
| + t.Fatalf("expired: %v", err) |
| + } |
| +} |
| + |
| +func TestSendCarriesBearerAndKey(t *testing.T) { |
| + f := equipotest.New(t) |
| + c := equipo.New(f.URL) |
| + cred := signIn(t, f, c) |
| + sent, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if sent.Message.Text != "What can I do" || sent.Turn.ID == "" || sent.Turn.State != "queued" { |
| + t.Fatalf("sent: %+v", sent) |
| + } |
| + calls := f.Calls("/api/v1/messages") |
| + if len(calls) != 1 { |
| + t.Fatalf("calls: %+v", calls) |
| + } |
| + h := calls[0].Header |
| + if h.Get("Authorization") != "Bearer "+cred.Token || h.Get("Idempotency-Key") != "k-1" { |
| + t.Errorf("headers: %v", h) |
| + } |
| + var body map[string]string |
| + if err := json.Unmarshal([]byte(calls[0].Body), &body); err != nil || body["idempotency_key"] != "k-1" { |
| + t.Errorf("body: %s", calls[0].Body) |
| + } |
| +} |
| + |
| +func TestSealIsPerMember(t *testing.T) { |
| + s := equipo.NewSealer("instance-key") |
| + blob, err := s.Seal("member-a", []byte("equipo.person.v1.secret")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(blob), "secret") { |
| + t.Fatal("sealed blob holds the plaintext") |
| + } |
| + if got, err := s.Open("member-a", blob); err != nil || string(got) != "equipo.person.v1.secret" { |
| + t.Fatalf("open: %q %v", got, err) |
| + } |
| + if _, err := s.Open("member-b", blob); err == nil { |
| + t.Fatal("another member's key opened it") |
| + } |
| + if _, err := equipo.NewSealer("other-key").Open("member-a", blob); err == nil { |
| + t.Fatal("another instance key opened it") |
| + } |
| +} |
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go| new file mode 100644 |
| index 0000000..b39ebdd |
| --- /dev/null |
| +++ b/internal/equipo/equipotest/chat.go |
| @@ -0,0 +1,380 @@ |
| +package equipotest |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| + "unicode/utf8" |
| +) |
| + |
| +// The chat's resources in wire's JSON shapes (Message, Turn, Card, Event). |
| +type message struct { |
| + ID string `json:"id"` |
| + Revision int64 `json:"revision"` |
| + Role string `json:"role"` |
| + Text string `json:"text"` |
| + TurnID string `json:"turn_id"` |
| + CreatedAt time.Time `json:"created_at"` |
| + Switched *struct{} `json:"switched"` |
| +} |
| + |
| +type turn struct { |
| + ID string `json:"id"` |
| + Revision int64 `json:"revision"` |
| + Kind string `json:"kind"` |
| + State string `json:"state"` |
| + Reason string `json:"reason"` |
| + Attempt int64 `json:"attempt"` |
| + MessageIDs []string `json:"message_ids"` |
| + ReplyID string `json:"reply_id"` |
| + Connection string `json:"connection"` |
| + CreatedAt time.Time `json:"created_at"` |
| + UpdatedAt time.Time `json:"updated_at"` |
| + Timing *struct{} `json:"timing"` |
| +} |
| + |
| +type card struct { |
| + ID string `json:"id"` |
| + Revision int64 `json:"revision"` |
| + Kind string `json:"kind"` |
| + State string `json:"state"` |
| + TurnID string `json:"turn_id"` |
| + ProjectID string `json:"project_id"` |
| + Name string `json:"name"` |
| + Question string `json:"question"` |
| + Options []string `json:"options"` |
| + Choice string `json:"choice"` |
| + TaskID string `json:"task_id"` |
| + CreatedAt time.Time `json:"created_at"` |
| + UpdatedAt time.Time `json:"updated_at"` |
| +} |
| + |
| +type event struct { |
| + Cursor int64 `json:"cursor"` |
| + Type string `json:"type"` |
| + Resource string `json:"resource"` |
| + ID string `json:"id"` |
| + Revision int64 `json:"revision"` |
| + TurnID string `json:"turn_id,omitempty"` |
| + MessageID string `json:"message_id,omitempty"` |
| + Attempt int64 `json:"attempt,omitempty"` |
| + Data any `json:"data"` |
| +} |
| + |
| +// chat is one person's conversation with the coordinator. |
| +type chat struct { |
| + cmu sync.Mutex |
| + seq int |
| + messages []message |
| + turns map[string]*turn |
| + cards []*card |
| + events []event |
| + sent map[string]string // idempotency key to message id |
| + wake chan struct{} // closed at each new event |
| +} |
| + |
| +func (c *chat) init() { |
| + c.turns, c.sent, c.wake = map[string]*turn{}, map[string]string{}, make(chan struct{}) |
| +} |
| + |
| +func (c *chat) next(prefix string) string { c.seq++; return fmt.Sprintf("%s_%04d", prefix, c.seq) } |
| + |
| +// emit records an event; the caller holds cmu. |
| +func (c *chat) emit(typ, resource, id string, rev int64, turnID string, data any) { |
| + c.events = append(c.events, event{Cursor: int64(len(c.events) + 41), Type: typ, Resource: resource, |
| + ID: id, Revision: rev, TurnID: turnID, Attempt: 1, Data: data}) |
| + close(c.wake) |
| + c.wake = make(chan struct{}) |
| +} |
| + |
| +// Emit adds an event of any type, such as one Base must not pass on. |
| +func (f *Fake) Emit(typ string, data any) { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + f.emit(typ, typ, "x", 1, "", data) |
| +} |
| + |
| +// AskQuestion puts an open question card in the conversation. |
| +func (f *Fake) AskQuestion(question string, options ...string) string { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + now := time.Now().UTC() |
| + c := &card{ID: f.next("c"), Revision: 1, Kind: "question", State: "open", Question: question, |
| + Options: options, CreatedAt: now, UpdatedAt: now} |
| + f.cards = append(f.cards, c) |
| + f.emit("card", "card", c.ID, c.Revision, "", *c) |
| + return c.ID |
| +} |
| + |
| +// Turn is the state of the turn with id ("" when there is none). |
| +func (f *Fake) Turn(id string) string { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + if t, ok := f.turns[id]; ok { |
| + return t.State |
| + } |
| + return "" |
| +} |
| + |
| +func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := f.bearer(r); !ok { |
| + writeError(w, r, 401, "unauthenticated") |
| + return |
| + } |
| + p := strings.TrimPrefix(r.URL.Path, "/api/v1") |
| + switch { |
| + case r.Method == http.MethodGet && p == "/snapshot": |
| + f.snapshot(w) |
| + case r.Method == http.MethodGet && p == "/messages": |
| + f.cmu.Lock() |
| + writeJSON(w, 200, map[string]any{"items": f.tail(), "before": ""}) |
| + f.cmu.Unlock() |
| + case r.Method == http.MethodPost && p == "/messages": |
| + f.send(w, r) |
| + case r.Method == http.MethodPost && strings.HasPrefix(p, "/turns/") && strings.HasSuffix(p, "/cancel"): |
| + f.cancel(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/turns/"), "/cancel")) |
| + case r.Method == http.MethodPost && strings.HasPrefix(p, "/cards/") && strings.HasSuffix(p, "/answer"): |
| + f.answer(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/cards/"), "/answer")) |
| + case r.Method == http.MethodGet && p == "/events": |
| + f.stream(w, r) |
| + default: |
| + writeError(w, r, 404, "not_found") |
| + } |
| +} |
| + |
| +func (f *Fake) tail() []message { |
| + out := append([]message{}, f.messages...) |
| + if len(out) > 50 { |
| + out = out[len(out)-50:] |
| + } |
| + return out |
| +} |
| + |
| +func (f *Fake) snapshot(w http.ResponseWriter) { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + turns := []turn{} |
| + for _, t := range f.turns { |
| + turns = append(turns, *t) |
| + } |
| + cards := []card{} |
| + for _, c := range f.cards { |
| + cards = append(cards, *c) |
| + } |
| + writeJSON(w, 200, map[string]any{ |
| + "me": map[string]any{"id": "paul@tito.io", "address": "paul@tito.io", "role": "owner", "team_id": f.Instance}, |
| + "messages": f.tail(), "turns": turns, "runner": map[string]any{"id": "R1", "online": true}, |
| + "projects": []any{}, "cards": cards, "tasks": []any{}, |
| + "coordinator": map[string]any{"id": "paul@tito.io", "revision": 2, "state": "ready"}, |
| + "connections": nil, "housekeeping_summary": map[string]any{}, "cursor": int64(len(f.events) + 40), |
| + "runners": []any{}, |
| + }) |
| +} |
| + |
| +func (f *Fake) send(w http.ResponseWriter, r *http.Request) { |
| + var in struct { |
| + Text string `json:"text"` |
| + IdempotencyKey string `json:"idempotency_key"` |
| + Attachments []string `json:"attachments,omitempty"` |
| + } |
| + if strict(r, &in) != nil { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + in.Text = strings.TrimSpace(in.Text) |
| + if in.Text == "" || len(in.Text) > 16<<10 || !utf8.ValidString(in.Text) || |
| + len(in.IdempotencyKey) < 1 || len(in.IdempotencyKey) > 128 || |
| + strings.HasPrefix(in.IdempotencyKey, "reply:") || strings.HasPrefix(in.IdempotencyKey, "card:") { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + f.cmu.Lock() |
| + if id, ok := f.sent[in.IdempotencyKey]; ok { |
| + for _, m := range f.messages { |
| + if m.ID == id { |
| + writeJSON(w, 200, map[string]any{"message": m, "turn": *f.turns[m.TurnID]}) |
| + } |
| + } |
| + f.cmu.Unlock() |
| + return |
| + } |
| + 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}) |
| + go f.answerTurn(t.ID, in.Text) |
| +} |
| + |
| +// ask records the person's message and a queued turn; the caller holds cmu. |
| +func (f *Fake) ask(text string) (message, turn) { |
| + now := time.Now().UTC() |
| + t := &turn{ID: f.next("t"), Revision: 1, State: "queued", Attempt: 1, CreatedAt: now, UpdatedAt: now} |
| + m := message{ID: f.next("m"), Revision: 1, Role: "person", Text: text, TurnID: t.ID, CreatedAt: now} |
| + t.MessageIDs = []string{m.ID} |
| + f.turns[t.ID] = t |
| + f.messages = append(f.messages, m) |
| + f.emit("message", "message", m.ID, 1, t.ID, m) |
| + f.emit("turn", "turn", t.ID, t.Revision, t.ID, *t) |
| + return m, *t |
| +} |
| + |
| +// answerTurn runs the turn: running, the reply streamed in deltas, the |
| +// reply message, replied. With Hold it stops at running. |
| +func (f *Fake) answerTurn(id, text string) { |
| + f.setTurn(id, "running", "") |
| + if f.Hold { |
| + return |
| + } |
| + reply := f.Reply(text) |
| + words := strings.SplitAfter(reply, " ") |
| + offset := 0 |
| + for _, part := range words { |
| + select { |
| + case <-f.closing: |
| + return |
| + case <-time.After(15 * time.Millisecond): |
| + } |
| + f.cmu.Lock() |
| + if f.turns[id].State != "running" { |
| + f.cmu.Unlock() |
| + return |
| + } |
| + f.emit("delta", "turn", id, 0, id, map[string]any{"turn_id": id, "offset": offset, "text": part}) |
| + f.cmu.Unlock() |
| + offset += len(part) |
| + } |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + if f.turns[id].State != "running" { |
| + return |
| + } |
| + m := message{ID: f.next("m"), Revision: 1, Role: "coordinator", Text: reply, TurnID: id, CreatedAt: time.Now().UTC()} |
| + f.messages = append(f.messages, m) |
| + f.emit("message", "message", m.ID, 1, id, m) |
| + t := f.turns[id] |
| + t.State, t.ReplyID, t.Revision, t.UpdatedAt = "replied", m.ID, t.Revision+1, time.Now().UTC() |
| + f.emit("turn", "turn", id, t.Revision, id, *t) |
| +} |
| + |
| +func (f *Fake) setTurn(id, state, reason string) { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + t := f.turns[id] |
| + t.State, t.Reason, t.Revision, t.UpdatedAt = state, reason, t.Revision+1, time.Now().UTC() |
| + f.emit("turn", "turn", id, t.Revision, id, *t) |
| +} |
| + |
| +func (f *Fake) cancel(w http.ResponseWriter, r *http.Request, id string) { |
| + f.cmu.Lock() |
| + t, ok := f.turns[id] |
| + if !ok { |
| + f.cmu.Unlock() |
| + writeError(w, r, 404, "not_found") |
| + return |
| + } |
| + if t.State != "queued" && t.State != "running" && t.State != "waiting" { |
| + f.cmu.Unlock() |
| + writeError(w, r, 409, "turn_ended") |
| + return |
| + } |
| + f.cmu.Unlock() |
| + f.setTurn(id, "cancelled", "") |
| + writeJSON(w, http.StatusAccepted, map[string]any{"attempt": 1}) |
| +} |
| + |
| +func (f *Fake) answer(w http.ResponseWriter, r *http.Request, id string) { |
| + var in struct { |
| + Choice string `json:"choice"` |
| + Revision int64 `json:"revision"` |
| + } |
| + if strict(r, &in) != nil { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + f.cmu.Lock() |
| + var c *card |
| + for _, x := range f.cards { |
| + if x.ID == id { |
| + c = x |
| + } |
| + } |
| + if c == nil { |
| + f.cmu.Unlock() |
| + writeError(w, r, 404, "not_found") |
| + return |
| + } |
| + if c.State != "open" || c.Revision != in.Revision { |
| + code := "card_answered" |
| + if c.State == "open" { |
| + code = "card_stale" |
| + } |
| + writeJSON(w, 409, map[string]any{"code": code, "copy_key": "api." + code, "request_id": r.Header.Get("Idempotency-Key"), "card": *c}) |
| + f.cmu.Unlock() |
| + return |
| + } |
| + c.State, c.Choice, c.Revision, c.UpdatedAt = "answered", in.Choice, c.Revision+1, time.Now().UTC() |
| + f.emit("card", "card", c.ID, c.Revision, c.TurnID, *c) |
| + m, t := f.ask(in.Choice) |
| + f.cmu.Unlock() |
| + writeJSON(w, 200, map[string]any{"card": *c, "message": m, "turn": t}) |
| + go f.answerTurn(t.ID, in.Choice) |
| +} |
| + |
| +// stream is GET /api/v1/events: Server-Sent Events after ?after= (or |
| +// Last-Event-ID), as Equipo writes them. |
| +func (f *Fake) stream(w http.ResponseWriter, r *http.Request) { |
| + raw := r.URL.Query().Get("after") |
| + if raw == "" { |
| + raw = r.Header.Get("Last-Event-ID") |
| + } |
| + f.cmu.Lock() |
| + after := int64(len(f.events) + 40) |
| + f.cmu.Unlock() |
| + if raw != "" { |
| + n, err := strconv.ParseInt(raw, 10, 64) |
| + if err != nil || n < 0 { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + after = n |
| + } |
| + rc := http.NewResponseController(w) |
| + w.Header().Set("Content-Type", "text/event-stream") |
| + w.WriteHeader(200) |
| + if _, err := io.WriteString(w, "retry: 2000\n: ok\n\n"); err != nil || rc.Flush() != nil { |
| + return |
| + } |
| + for { |
| + f.cmu.Lock() |
| + var batch []event |
| + for _, e := range f.events { |
| + if e.Cursor > after { |
| + batch = append(batch, e) |
| + } |
| + } |
| + wake := f.wake |
| + f.cmu.Unlock() |
| + for _, e := range batch { |
| + raw, _ := json.Marshal(e) |
| + if _, err := fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", e.Cursor, e.Type, raw); err != nil { |
| + return |
| + } |
| + after = e.Cursor |
| + } |
| + if rc.Flush() != nil { |
| + return |
| + } |
| + select { |
| + case <-r.Context().Done(): |
| + return |
| + case <-f.closing: |
| + return |
| + case <-wake: |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go| new file mode 100644 |
| index 0000000..7813115 |
| --- /dev/null |
| +++ b/internal/equipo/equipotest/fake.go |
| @@ -0,0 +1,335 @@ |
| +// Package equipotest is a fake Equipo for Base's tests: the person API's |
| +// device sign-in and coordinator chat routes, in the shapes Equipo's |
| +// handlers write (amadan.net/oficina/equipo, internal/wire and |
| +// internal/equipo/personapi on main). It runs on 127.0.0.1 only. |
| +package equipotest |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +const ( |
| + personAudience = "equipo.person.v1" |
| + deviceAudience = "equipo.person.device.v1" |
| +) |
| + |
| +// Call is one request the fake received, as it arrived. |
| +type Call struct { |
| + Method, Path, Query string |
| + Header http.Header |
| + Body string |
| +} |
| + |
| +type device struct { |
| + id, publicKey, label, secret, code, challenge string |
| + approved, revoked bool |
| + nonce, token string |
| + revision int64 |
| + expires time.Time |
| +} |
| + |
| +// Fake is a running fake Equipo. URL is its origin. |
| +type Fake struct { |
| + URL string |
| + Instance string |
| + // Reply is what the coordinator answers to a message. Hold keeps every |
| + // new turn running until Finish, so a test can cancel one. |
| + Reply func(text string) string |
| + Hold bool |
| + |
| + srv *httptest.Server |
| + closing chan struct{} |
| + mu sync.Mutex |
| + calls []Call |
| + devices map[string]*device |
| + chat |
| +} |
| + |
| +// 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{}, |
| + Reply: func(string) string { return "Hello. What shall we work on?" }} |
| + f.chat.init() |
| + f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) |
| + f.URL = f.srv.URL |
| + t.Cleanup(func() { |
| + close(f.closing) |
| + f.srv.CloseClientConnections() |
| + f.srv.Close() |
| + }) |
| + return f |
| +} |
| + |
| +// Calls are the requests to path (every request when path is ""), oldest |
| +// first. |
| +func (f *Fake) Calls(path string) []Call { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var out []Call |
| + for _, c := range f.calls { |
| + if path == "" || c.Path == path { |
| + out = append(out, c) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// Approve approves the device waiting with userCode, as its person would in |
| +// Equipo's browser page. |
| +func (f *Fake) Approve(userCode string) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + for _, d := range f.devices { |
| + if d.code == userCode { |
| + d.approved = true |
| + d.revision = 2 |
| + return nil |
| + } |
| + } |
| + return fmt.Errorf("equipotest: no device waiting with code %q", userCode) |
| +} |
| + |
| +// Tokens are the bearers the fake has issued. |
| +func (f *Fake) Tokens() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var out []string |
| + for _, d := range f.devices { |
| + if d.token != "" { |
| + out = append(out, d.token) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// RevokeAll revokes every device, as removing the person from the roster |
| +// would: their bearers get 401 from then on. |
| +func (f *Fake) RevokeAll() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + for _, d := range f.devices { |
| + d.revoked = true |
| + } |
| +} |
| + |
| +// Revoked reports whether the device with id is revoked. |
| +func (f *Fake) Revoked(id string) bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + d, ok := f.devices[id] |
| + return ok && d.revoked |
| +} |
| + |
| +func (f *Fake) serve(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(io.LimitReader(r.Body, 64<<10)) |
| + r.Body = io.NopCloser(bytes.NewReader(body)) |
| + f.mu.Lock() |
| + 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 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") != "" { |
| + writeError(w, r, http.StatusForbidden, "forbidden") |
| + return |
| + } |
| + if r.Method != http.MethodGet && len(r.Header.Values("Idempotency-Key")) != 1 && |
| + strings.HasPrefix(r.URL.Path, "/api/v1/auth/") { |
| + writeError(w, r, http.StatusUnprocessableEntity, "invalid_input") |
| + return |
| + } |
| + switch p := r.URL.Path; { |
| + case r.Method == http.MethodPost && p == "/api/v1/auth/devices": |
| + f.begin(w, r) |
| + case r.Method == http.MethodPost && p == "/api/v1/auth/devices/exchange": |
| + f.exchange(w, r) |
| + case r.Method == http.MethodDelete && strings.HasPrefix(p, "/api/v1/auth/devices/"): |
| + f.revoke(w, r, strings.TrimPrefix(p, "/api/v1/auth/devices/")) |
| + default: |
| + f.serveChat(w, r) |
| + } |
| +} |
| + |
| +func (f *Fake) begin(w http.ResponseWriter, r *http.Request) { |
| + var in struct { |
| + PublicKey string `json:"public_key"` |
| + Label string `json:"label"` |
| + } |
| + if strict(r, &in) != nil { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + if pub, err := base64.RawURLEncoding.DecodeString(in.PublicKey); err != nil || |
| + len(pub) != ed25519.PublicKeySize || in.Label == "" || len(in.Label) > 128 { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + id := rand.Text() |
| + data, _ := json.Marshal([]string{f.Instance, rand.Text()}) |
| + d := &device{id: id, publicKey: in.PublicKey, label: in.Label, secret: deviceAudience + "." + rand.Text(), |
| + code: strings.ToUpper(rand.Text()[:8]), challenge: base64.RawURLEncoding.EncodeToString(data), |
| + revision: 1, expires: time.Now().Add(10 * time.Minute)} |
| + f.mu.Lock() |
| + f.devices[id] = d |
| + f.mu.Unlock() |
| + w.Header().Set("ETag", `"1"`) |
| + writeJSON(w, 200, map[string]any{"id": id, "device_secret": d.secret, "user_code": d.code, |
| + "challenge": d.challenge, "verification_uri": f.URL + "/auth/devices/" + id, |
| + "expires_at": d.expires.UTC(), "poll_interval_seconds": 5}) |
| +} |
| + |
| +// Label is the label the device with userCode asked to be approved under. |
| +func (f *Fake) Label(userCode string) string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + for _, d := range f.devices { |
| + if d.code == userCode { |
| + return d.label |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +func (f *Fake) exchange(w http.ResponseWriter, r *http.Request) { |
| + var p struct { |
| + ID string `json:"id"` |
| + DeviceSecret string `json:"device_secret"` |
| + Challenge string `json:"challenge"` |
| + Nonce string `json:"nonce"` |
| + Signature string `json:"signature"` |
| + } |
| + if strict(r, &p) != nil || len(p.Nonce) < 16 { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + d, ok := f.devices[p.ID] |
| + if !ok { |
| + writeError(w, r, 403, "forbidden") |
| + return |
| + } |
| + pub, _ := base64.RawURLEncoding.DecodeString(d.publicKey) |
| + sig, _ := base64.RawURLEncoding.DecodeString(p.Signature) |
| + msg, _ := json.Marshal([]string{deviceAudience, f.Instance, p.ID, p.Challenge, p.Nonce}) |
| + switch { |
| + case p.DeviceSecret != d.secret || p.Challenge != d.challenge || !ed25519.Verify(pub, msg, sig): |
| + writeError(w, r, 403, "forbidden") |
| + return |
| + case d.revoked: |
| + writeError(w, r, 403, "forbidden") |
| + return |
| + case d.token != "" && p.Nonce != d.nonce: |
| + writeError(w, r, 403, "forbidden") |
| + return |
| + case d.token == "" && time.Now().After(d.expires): |
| + writeError(w, r, 410, "device_expired") |
| + return |
| + case !d.approved: |
| + writeError(w, r, 409, "authorization_pending") |
| + return |
| + } |
| + if d.token == "" { |
| + d.token, d.nonce, d.revision = personAudience+"."+rand.Text(), p.Nonce, 3 |
| + } |
| + w.Header().Set("ETag", fmt.Sprintf(`"%d"`, d.revision)) |
| + writeJSON(w, 200, map[string]any{"id": d.id, "token": d.token, "audience": personAudience, |
| + "instance_id": f.Instance, "expires_at": time.Now().Add(30 * 24 * time.Hour).UTC()}) |
| +} |
| + |
| +// Expire makes every pending sign-in code expire. |
| +func (f *Fake) Expire() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + for _, d := range f.devices { |
| + d.expires = time.Now().Add(-time.Second) |
| + } |
| +} |
| + |
| +func (f *Fake) revoke(w http.ResponseWriter, r *http.Request, id string) { |
| + d, ok := f.bearer(r) |
| + if !ok { |
| + writeError(w, r, 401, "unauthenticated") |
| + return |
| + } |
| + var empty struct{} |
| + if strict(r, &empty) != nil { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if d.id != id { |
| + writeError(w, r, 404, "not_found") |
| + return |
| + } |
| + if r.Header.Get("If-Match") != fmt.Sprintf(`"%d"`, d.revision) { |
| + writeError(w, r, 409, "revision_conflict") |
| + return |
| + } |
| + d.revoked = true |
| + d.revision++ |
| + w.Header().Set("ETag", fmt.Sprintf(`"%d"`, d.revision)) |
| + writeJSON(w, 200, map[string]any{"revision": d.revision}) |
| +} |
| + |
| +// bearer is the live device behind the request's bearer. |
| +func (f *Fake) bearer(r *http.Request) (*device, bool) { |
| + h := r.Header.Values("Authorization") |
| + if len(h) != 1 || !strings.HasPrefix(h[0], "Bearer ") { |
| + return nil, false |
| + } |
| + token := strings.TrimPrefix(h[0], "Bearer ") |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + for _, d := range f.devices { |
| + if d.token != "" && d.token == token && !d.revoked { |
| + return d, true |
| + } |
| + } |
| + return nil, false |
| +} |
| + |
| +// strict decodes exactly one JSON object with no unknown fields, as |
| +// Equipo's wire.Strict does, from a body declared as JSON. |
| +func strict(r *http.Request, v any) error { |
| + if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { |
| + return fmt.Errorf("content type %q", ct) |
| + } |
| + d := json.NewDecoder(r.Body) |
| + d.DisallowUnknownFields() |
| + if err := d.Decode(v); err != nil { |
| + return err |
| + } |
| + if d.Decode(new(json.RawMessage)) != io.EOF { |
| + return fmt.Errorf("trailing JSON") |
| + } |
| + return nil |
| +} |
| + |
| +func writeJSON(w http.ResponseWriter, status int, v any) { |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(v) |
| +} |
| + |
| +// writeError writes Equipo's error body: {code, copy_key, request_id}. |
| +func writeError(w http.ResponseWriter, r *http.Request, status int, code string) { |
| + request := r.Header.Get("Idempotency-Key") |
| + if request == "" { |
| + request = rand.Text() |
| + } |
| + writeJSON(w, status, map[string]any{"code": code, "copy_key": "api." + code, "request_id": request}) |
| +} |
diff --git a/internal/equipo/seal.go b/internal/equipo/seal.go| new file mode 100644 |
| index 0000000..d364496 |
| --- /dev/null |
| +++ b/internal/equipo/seal.go |
| @@ -0,0 +1,28 @@ |
| +package equipo |
| + |
| +import "amadan.net/rastrillo/rastrillo/crypto" |
| + |
| +// Sealer encrypts what Base keeps for a member's Equipo device (its |
| +// private key, its secret and its bearer) at rest. The key is derived |
| +// from BASE_INSTANCE_KEY with HKDF-SHA256, separately for each member, and |
| +// the cipher is AES-256-GCM (rastrillo's crypto.SealSym): a sealed blob |
| +// opens only for the member it was sealed for, under the same instance |
| +// key. Changing BASE_INSTANCE_KEY disconnects everyone from Equipo. |
| +type Sealer struct{ key []byte } |
| + |
| +// NewSealer derives the sealing key from the instance key. |
| +func NewSealer(instanceKey string) Sealer { |
| + return Sealer{key: crypto.Derive([]byte(instanceKey), "base/equipo-device/v1")} |
| +} |
| + |
| +func (s Sealer) member(id string) []byte { return crypto.Derive(s.key, "member/"+id) } |
| + |
| +// Seal encrypts plaintext for member id. |
| +func (s Sealer) Seal(id string, plaintext []byte) ([]byte, error) { |
| + return crypto.SealSym(s.member(id), plaintext) |
| +} |
| + |
| +// Open decrypts a blob Seal made for member id. |
| +func (s Sealer) Open(id string, sealed []byte) ([]byte, error) { |
| + return crypto.OpenSym(s.member(id), sealed) |
| +} |
diff --git a/internal/store/equipo.go b/internal/store/equipo.go| new file mode 100644 |
| index 0000000..86b8ac5 |
| --- /dev/null |
| +++ b/internal/store/equipo.go |
| @@ -0,0 +1,91 @@ |
| +package store |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "time" |
| +) |
| + |
| +// Equipo link states. Pending waits for the member to approve the sign-in |
| +// code in Equipo; connected holds a bearer; lost is a bearer Equipo refused |
| +// (revoked, or the member's Equipo session ended), which needs reconnecting. |
| +const ( |
| + EquipoPending = "pending" |
| + EquipoConnected = "connected" |
| + EquipoLost = "lost" |
| +) |
| + |
| +// EquipoLink is a member's connection to the Equipo at Origin. Sealed is |
| +// opaque here: the web package seals and opens it. Revision is the |
| +// device's revision in Equipo, which revoking it names. |
| +type EquipoLink struct { |
| + MemberID, Origin, State string |
| + DeviceID string |
| + UserCode, VerificationURI string |
| + Sealed []byte |
| + ExpiresAt time.Time |
| + Revision int64 |
| + PolledAt *time.Time |
| +} |
| + |
| +const equipoCols = `member_id, origin, state, device_id, user_code, |
| + verification_uri, sealed, expires_at, revision, polled_at` |
| + |
| +// EquipoLinkFor is the member's link; ok is false when there is none. |
| +func EquipoLinkFor(ctx context.Context, db *sql.DB, memberID string) (l EquipoLink, ok bool, err error) { |
| + var polled sql.NullTime |
| + err = db.QueryRowContext(ctx, `SELECT `+equipoCols+` FROM equipo_links WHERE member_id = ?`, memberID). |
| + Scan(&l.MemberID, &l.Origin, &l.State, &l.DeviceID, &l.UserCode, |
| + &l.VerificationURI, &l.Sealed, &l.ExpiresAt, &l.Revision, &polled) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return EquipoLink{}, false, nil |
| + } |
| + if err != nil { |
| + return EquipoLink{}, false, err |
| + } |
| + if polled.Valid { |
| + t := polled.Time |
| + l.PolledAt = &t |
| + } |
| + return l, true, nil |
| +} |
| + |
| +// SaveEquipoLink stores l as the member's only link, replacing any other. |
| +func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| + var polled any |
| + if l.PolledAt != nil { |
| + polled = l.PolledAt.UTC() |
| + } |
| + _, err := db.ExecContext(ctx, `INSERT INTO equipo_links (`+equipoCols+`, updated_at) |
| + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| + ON CONFLICT (member_id) DO UPDATE SET origin = excluded.origin, state = excluded.state, |
| + device_id = excluded.device_id, user_code = excluded.user_code, |
| + verification_uri = excluded.verification_uri, sealed = excluded.sealed, |
| + expires_at = excluded.expires_at, revision = excluded.revision, |
| + polled_at = excluded.polled_at, updated_at = excluded.updated_at`, |
| + l.MemberID, l.Origin, l.State, l.DeviceID, l.UserCode, l.VerificationURI, |
| + l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, time.Now().UTC()) |
| + 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 |
| +} |
| + |
| +// 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) |
| + 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) |
| + return err |
| +} |
diff --git a/internal/store/equipo_test.go b/internal/store/equipo_test.go| new file mode 100644 |
| index 0000000..cf681f6 |
| --- /dev/null |
| +++ b/internal/store/equipo_test.go |
| @@ -0,0 +1,74 @@ |
| +package store |
| + |
| +import ( |
| + "context" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestEquipoLinkRoundTrip(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + ana, _, err := Invite(ctx, db, "ana@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok, err := EquipoLinkFor(ctx, db, ana.ID); ok || err != nil { |
| + t.Fatalf("fresh member has a link: %v %v", ok, err) |
| + } |
| + exp := time.Now().Add(10 * time.Minute).UTC().Truncate(time.Second) |
| + in := EquipoLink{MemberID: ana.ID, Origin: "https://equipo.test", State: EquipoPending, |
| + DeviceID: "DEV1", UserCode: "ABCD1234", VerificationURI: "https://equipo.test/auth/devices/DEV1", |
| + Sealed: []byte("sealed"), ExpiresAt: exp} |
| + if err := SaveEquipoLink(ctx, db, in); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, ok, err := EquipoLinkFor(ctx, db, ana.ID) |
| + if !ok || err != nil || got.DeviceID != "DEV1" || got.State != EquipoPending || !got.ExpiresAt.Equal(exp) || |
| + 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) |
| + } |
| + got, _, _ = EquipoLinkFor(ctx, db, ana.ID) |
| + 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 { |
| + 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 { |
| + t.Fatal(err) |
| + } |
| + if _, ok, _ := EquipoLinkFor(ctx, db, ana.ID); ok { |
| + t.Fatal("link survived delete") |
| + } |
| +} |
| + |
| +// A member's Equipo link goes with the member. |
| +func TestRemoveMemberDeletesEquipoLink(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + ana, _, err := Invite(ctx, db, "ana@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := SaveEquipoLink(ctx, db, EquipoLink{MemberID: ana.ID, Origin: "https://equipo.test", |
| + State: EquipoConnected, DeviceID: "D", Sealed: []byte("x"), ExpiresAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := RemoveMember(ctx, db, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + var n int |
| + if err := db.QueryRow(`SELECT count(*) FROM equipo_links`).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("links left: %d %v", n, err) |
| + } |
| +} |
diff --git a/internal/store/migrations/0005_equipo_links.sql b/internal/store/migrations/0005_equipo_links.sql| new file mode 100644 |
| index 0000000..d7b60c5 |
| --- /dev/null |
| +++ b/internal/store/migrations/0005_equipo_links.sql |
| @@ -0,0 +1,18 @@ |
| +-- A member's connection to Equipo: the device Base signed in on their |
| +-- behalf. sealed holds the device's private key, its secret and, once |
| +-- connected, the bearer, encrypted under a key derived from |
| +-- BASE_INSTANCE_KEY for this member alone. expires_at is when the sign-in |
| +-- code expires while pending, and when the bearer expires once connected. |
| +CREATE TABLE equipo_links ( |
| + member_id text NOT NULL PRIMARY KEY REFERENCES members (id) ON DELETE CASCADE, |
| + origin text NOT NULL, |
| + state text NOT NULL, |
| + device_id text NOT NULL, |
| + user_code text NOT NULL DEFAULT '', |
| + verification_uri text NOT NULL DEFAULT '', |
| + sealed blob NOT NULL, |
| + expires_at datetime NOT NULL, |
| + revision integer NOT NULL DEFAULT 0, |
| + polled_at datetime, |
| + updated_at datetime NOT NULL |
| +); |