// Package equipotest is a fake Equipo for Base's tests: the person API's // device sign-in and the Assistant's chat routes (/api/v1/assistant), in // the shapes Equipo's handlers write (amadan.net/oficina/equipo, // internal/wire, internal/equipo/personapi and // internal/equipo/chat/assistant_http.go). 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 // 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. type Fake struct { URL string Instance string // Reply is what the Assistant answers to a message. Hold keeps every // new turn running until Answer, so a test can cancel one. Reply func(text string) string Hold bool // LookupsRegardless sends lookups to every read, whatever // Base-Capabilities says, so a test can see what Base itself does // with them. LookupsRegardless bool srv *httptest.Server closing chan struct{} mu sync.Mutex calls []Call devices map[string]*device // hold, when set, stops the next exchange until it is closed. hold chan struct{} entered chan struct{} failSend bool // failBegin makes the next device sign-in start answer 503. failBegin bool // beginHold and revokeHold do for the next sign-in start and the next // revocation what hold does for the next exchange. beginHold, beginEntered, revokeHold, revokeEntered chan struct{} // failSnapshot makes every snapshot answer 503. failSnapshot bool // snapHold and snapEntered do for the next snapshot what hold and // entered do for the next exchange. snapHold, snapEntered chan struct{} chat nativeState fileState } // HoldNextExchange makes the next exchange wait, once it has arrived and // before it answers, until release is called: a test can act in between. // entered is closed when it arrives. func (f *Fake) HoldNextExchange() (entered <-chan struct{}, release func()) { f.mu.Lock() defer f.mu.Unlock() f.hold, f.entered = make(chan struct{}), make(chan struct{}) hold := f.hold return f.entered, func() { close(hold) } } // HoldNextSnapshot makes the next snapshot wait, once its bearer has // passed and before it answers, until release is called. entered is // closed when it arrives. func (f *Fake) HoldNextSnapshot() (entered <-chan struct{}, release func()) { f.mu.Lock() defer f.mu.Unlock() f.snapHold, f.snapEntered = make(chan struct{}), make(chan struct{}) hold := f.snapHold return f.snapEntered, func() { close(hold) } } // HoldNextBegin makes the next device sign-in start (POST // /api/v1/auth/devices) wait, once it has arrived and before it answers, // until release is called. entered is closed when it arrives. func (f *Fake) HoldNextBegin() (entered <-chan struct{}, release func()) { f.mu.Lock() defer f.mu.Unlock() f.beginHold, f.beginEntered = make(chan struct{}), make(chan struct{}) hold := f.beginHold return f.beginEntered, func() { close(hold) } } // HoldNextRevoke does the same for the next device revocation (DELETE // /api/v1/auth/devices/{id}). func (f *Fake) HoldNextRevoke() (entered <-chan struct{}, release func()) { f.mu.Lock() defer f.mu.Unlock() f.revokeHold, f.revokeEntered = make(chan struct{}), make(chan struct{}) hold := f.revokeHold return f.revokeEntered, func() { close(hold) } } // waitHeld waits at a hold taken from f, if there is one. func (f *Fake) waitHeld(hold, entered chan struct{}) { if hold == nil { return } close(entered) select { case <-hold: case <-f.closing: } } // FailNextBegin makes the next device sign-in start (POST // /api/v1/auth/devices) answer 503, as when Equipo is down. func (f *Fake) FailNextBegin() { f.mu.Lock() defer f.mu.Unlock() f.failBegin = true } // FailSnapshots makes every snapshot answer 503 while on, as when Equipo // is down for a member who is already connected. func (f *Fake) FailSnapshots(on bool) { f.mu.Lock() defer f.mu.Unlock() f.failSnapshot = on } // FailNextSend makes the next new message's answer a 503 after Equipo has // recorded it, as when the answer is lost on the way back. func (f *Fake) FailNextSend() { f.mu.Lock() defer f.mu.Unlock() f.failSend = true } // New starts a fake Equipo, stopped when the test ends. func New(t testing.TB) *Fake { f := &Fake{Instance: "TEAM1", closing: make(chan struct{}), devices: map[string]*device{}, Reply: func(string) string { return "Hello. What shall we work on?" }} f.chat.init() f.nativeState.init() f.fileState.initFiles() 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) { // An upload is read whole, as Equipo's ReadUpload does, unless it says // it is over the limit; a call keeps its first 64 KiB. limit := int64(64 << 10) if r.Method == http.MethodPost && r.URL.Path == attachments { limit = maxUpload + 1 if r.ContentLength > maxUpload { limit = 0 } } body, _ := io.ReadAll(io.LimitReader(r.Body, limit)) r.Body = io.NopCloser(bytes.NewReader(body)) kept := body[:min(len(body), 64<<10)] f.mu.Lock() f.calls = append(f.calls, Call{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(kept)}) 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") != "" { 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) { f.mu.Lock() fail := f.failBegin f.failBegin = false hold, entered := f.beginHold, f.beginEntered f.beginHold, f.beginEntered = nil, nil f.mu.Unlock() f.waitHeld(hold, entered) if fail { writeError(w, r, 503, "unavailable") 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 } 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() hold, entered := f.hold, f.entered f.hold, f.entered = nil, nil f.mu.Unlock() if hold != nil { close(entered) <-hold } f.mu.Lock() defer f.mu.Unlock() d, ok := f.devices[p.ID] if !ok { 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) { f.mu.Lock() hold, entered := f.revokeHold, f.revokeEntered f.revokeHold, f.revokeEntered = nil, nil f.mu.Unlock() f.waitHeld(hold, entered) 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}) }