| 1 | // Package equipotest is a fake Equipo for Base's tests: the person API's |
| 2 | // device sign-in and the Assistant's chat routes (/api/v1/assistant), in |
| 3 | // the shapes Equipo's handlers write (amadan.net/oficina/equipo, |
| 4 | // internal/wire, internal/equipo/personapi and |
| 5 | // internal/equipo/chat/assistant_http.go). It runs on 127.0.0.1 only. |
| 6 | package equipotest |
| 7 | |
| 8 | import ( |
| 9 | "bytes" |
| 10 | "crypto/ed25519" |
| 11 | "crypto/rand" |
| 12 | "encoding/base64" |
| 13 | "encoding/json" |
| 14 | "fmt" |
| 15 | "io" |
| 16 | "net/http" |
| 17 | "net/http/httptest" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "testing" |
| 21 | "time" |
| 22 | ) |
| 23 | |
| 24 | const ( |
| 25 | personAudience = "equipo.person.v1" |
| 26 | deviceAudience = "equipo.person.device.v1" |
| 27 | ) |
| 28 | |
| 29 | // Call is one request the fake received, as it arrived. |
| 30 | type Call struct { |
| 31 | Method, Path, Query string |
| 32 | Header http.Header |
| 33 | Body string |
| 34 | } |
| 35 | |
| 36 | type device struct { |
| 37 | id, publicKey, label, secret, code, challenge string |
| 38 | approved, revoked bool |
| 39 | nonce, token string |
| 40 | revision int64 |
| 41 | expires time.Time |
| 42 | // session is the native session cookie a device registered with |
| 43 | // Oficina ID ends with; "" for one from the code flow. |
| 44 | session string |
| 45 | } |
| 46 | |
| 47 | // Fake is a running fake Equipo. URL is its origin. |
| 48 | type Fake struct { |
| 49 | URL string |
| 50 | Instance string |
| 51 | // Reply is what the Assistant answers to a message. Hold keeps every |
| 52 | // new turn running until Answer, so a test can cancel one. |
| 53 | Reply func(text string) string |
| 54 | Hold bool |
| 55 | // LookupsRegardless sends lookups to every read, whatever |
| 56 | // Base-Capabilities says, so a test can see what Base itself does |
| 57 | // with them. |
| 58 | LookupsRegardless bool |
| 59 | |
| 60 | srv *httptest.Server |
| 61 | closing chan struct{} |
| 62 | mu sync.Mutex |
| 63 | calls []Call |
| 64 | devices map[string]*device |
| 65 | // hold, when set, stops the next exchange until it is closed. |
| 66 | hold chan struct{} |
| 67 | entered chan struct{} |
| 68 | failSend bool |
| 69 | // failBegin makes the next device sign-in start answer 503. |
| 70 | failBegin bool |
| 71 | // beginHold and revokeHold do for the next sign-in start and the next |
| 72 | // revocation what hold does for the next exchange. |
| 73 | beginHold, beginEntered, revokeHold, revokeEntered chan struct{} |
| 74 | // failSnapshot makes every snapshot answer 503. |
| 75 | failSnapshot bool |
| 76 | // snapHold and snapEntered do for the next snapshot what hold and |
| 77 | // entered do for the next exchange. |
| 78 | snapHold, snapEntered chan struct{} |
| 79 | chat |
| 80 | nativeState |
| 81 | fileState |
| 82 | } |
| 83 | |
| 84 | // HoldNextExchange makes the next exchange wait, once it has arrived and |
| 85 | // before it answers, until release is called: a test can act in between. |
| 86 | // entered is closed when it arrives. |
| 87 | func (f *Fake) HoldNextExchange() (entered <-chan struct{}, release func()) { |
| 88 | f.mu.Lock() |
| 89 | defer f.mu.Unlock() |
| 90 | f.hold, f.entered = make(chan struct{}), make(chan struct{}) |
| 91 | hold := f.hold |
| 92 | return f.entered, func() { close(hold) } |
| 93 | } |
| 94 | |
| 95 | // HoldNextSnapshot makes the next snapshot wait, once its bearer has |
| 96 | // passed and before it answers, until release is called. entered is |
| 97 | // closed when it arrives. |
| 98 | func (f *Fake) HoldNextSnapshot() (entered <-chan struct{}, release func()) { |
| 99 | f.mu.Lock() |
| 100 | defer f.mu.Unlock() |
| 101 | f.snapHold, f.snapEntered = make(chan struct{}), make(chan struct{}) |
| 102 | hold := f.snapHold |
| 103 | return f.snapEntered, func() { close(hold) } |
| 104 | } |
| 105 | |
| 106 | // HoldNextBegin makes the next device sign-in start (POST |
| 107 | // /api/v1/auth/devices) wait, once it has arrived and before it answers, |
| 108 | // until release is called. entered is closed when it arrives. |
| 109 | func (f *Fake) HoldNextBegin() (entered <-chan struct{}, release func()) { |
| 110 | f.mu.Lock() |
| 111 | defer f.mu.Unlock() |
| 112 | f.beginHold, f.beginEntered = make(chan struct{}), make(chan struct{}) |
| 113 | hold := f.beginHold |
| 114 | return f.beginEntered, func() { close(hold) } |
| 115 | } |
| 116 | |
| 117 | // HoldNextRevoke does the same for the next device revocation (DELETE |
| 118 | // /api/v1/auth/devices/{id}). |
| 119 | func (f *Fake) HoldNextRevoke() (entered <-chan struct{}, release func()) { |
| 120 | f.mu.Lock() |
| 121 | defer f.mu.Unlock() |
| 122 | f.revokeHold, f.revokeEntered = make(chan struct{}), make(chan struct{}) |
| 123 | hold := f.revokeHold |
| 124 | return f.revokeEntered, func() { close(hold) } |
| 125 | } |
| 126 | |
| 127 | // waitHeld waits at a hold taken from f, if there is one. |
| 128 | func (f *Fake) waitHeld(hold, entered chan struct{}) { |
| 129 | if hold == nil { |
| 130 | return |
| 131 | } |
| 132 | close(entered) |
| 133 | select { |
| 134 | case <-hold: |
| 135 | case <-f.closing: |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // FailNextBegin makes the next device sign-in start (POST |
| 140 | // /api/v1/auth/devices) answer 503, as when Equipo is down. |
| 141 | func (f *Fake) FailNextBegin() { |
| 142 | f.mu.Lock() |
| 143 | defer f.mu.Unlock() |
| 144 | f.failBegin = true |
| 145 | } |
| 146 | |
| 147 | // FailSnapshots makes every snapshot answer 503 while on, as when Equipo |
| 148 | // is down for a member who is already connected. |
| 149 | func (f *Fake) FailSnapshots(on bool) { |
| 150 | f.mu.Lock() |
| 151 | defer f.mu.Unlock() |
| 152 | f.failSnapshot = on |
| 153 | } |
| 154 | |
| 155 | // FailNextSend makes the next new message's answer a 503 after Equipo has |
| 156 | // recorded it, as when the answer is lost on the way back. |
| 157 | func (f *Fake) FailNextSend() { |
| 158 | f.mu.Lock() |
| 159 | defer f.mu.Unlock() |
| 160 | f.failSend = true |
| 161 | } |
| 162 | |
| 163 | // New starts a fake Equipo, stopped when the test ends. |
| 164 | func New(t testing.TB) *Fake { |
| 165 | f := &Fake{Instance: "TEAM1", closing: make(chan struct{}), devices: map[string]*device{}, |
| 166 | Reply: func(string) string { return "Hello. What shall we work on?" }} |
| 167 | f.chat.init() |
| 168 | f.nativeState.init() |
| 169 | f.fileState.initFiles() |
| 170 | f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) |
| 171 | f.URL = f.srv.URL |
| 172 | t.Cleanup(func() { |
| 173 | close(f.closing) |
| 174 | f.srv.CloseClientConnections() |
| 175 | f.srv.Close() |
| 176 | }) |
| 177 | return f |
| 178 | } |
| 179 | |
| 180 | // Calls are the requests to path (every request when path is ""), oldest |
| 181 | // first. |
| 182 | func (f *Fake) Calls(path string) []Call { |
| 183 | f.mu.Lock() |
| 184 | defer f.mu.Unlock() |
| 185 | var out []Call |
| 186 | for _, c := range f.calls { |
| 187 | if path == "" || c.Path == path { |
| 188 | out = append(out, c) |
| 189 | } |
| 190 | } |
| 191 | return out |
| 192 | } |
| 193 | |
| 194 | // Approve approves the device waiting with userCode, as its person would in |
| 195 | // Equipo's browser page. |
| 196 | func (f *Fake) Approve(userCode string) error { |
| 197 | f.mu.Lock() |
| 198 | defer f.mu.Unlock() |
| 199 | for _, d := range f.devices { |
| 200 | if d.code == userCode { |
| 201 | d.approved = true |
| 202 | d.revision = 2 |
| 203 | return nil |
| 204 | } |
| 205 | } |
| 206 | return fmt.Errorf("equipotest: no device waiting with code %q", userCode) |
| 207 | } |
| 208 | |
| 209 | // Tokens are the bearers the fake has issued. |
| 210 | func (f *Fake) Tokens() []string { |
| 211 | f.mu.Lock() |
| 212 | defer f.mu.Unlock() |
| 213 | var out []string |
| 214 | for _, d := range f.devices { |
| 215 | if d.token != "" { |
| 216 | out = append(out, d.token) |
| 217 | } |
| 218 | } |
| 219 | return out |
| 220 | } |
| 221 | |
| 222 | // RevokeAll revokes every device, as removing the person from the roster |
| 223 | // would: their bearers get 401 from then on. |
| 224 | func (f *Fake) RevokeAll() { |
| 225 | f.mu.Lock() |
| 226 | defer f.mu.Unlock() |
| 227 | for _, d := range f.devices { |
| 228 | d.revoked = true |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // Revoked reports whether the device with id is revoked. |
| 233 | func (f *Fake) Revoked(id string) bool { |
| 234 | f.mu.Lock() |
| 235 | defer f.mu.Unlock() |
| 236 | d, ok := f.devices[id] |
| 237 | return ok && d.revoked |
| 238 | } |
| 239 | |
| 240 | func (f *Fake) serve(w http.ResponseWriter, r *http.Request) { |
| 241 | // An upload is read whole, as Equipo's ReadUpload does, unless it says |
| 242 | // it is over the limit; a call keeps its first 64 KiB. |
| 243 | limit := int64(64 << 10) |
| 244 | if r.Method == http.MethodPost && r.URL.Path == attachments { |
| 245 | limit = maxUpload + 1 |
| 246 | if r.ContentLength > maxUpload { |
| 247 | limit = 0 |
| 248 | } |
| 249 | } |
| 250 | body, _ := io.ReadAll(io.LimitReader(r.Body, limit)) |
| 251 | r.Body = io.NopCloser(bytes.NewReader(body)) |
| 252 | kept := body[:min(len(body), 64<<10)] |
| 253 | f.mu.Lock() |
| 254 | f.calls = append(f.calls, Call{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(kept)}) |
| 255 | f.mu.Unlock() |
| 256 | w.Header().Set("Cache-Control", "no-store") |
| 257 | // Equipo's native sign-in has rules of its own (native.go). |
| 258 | if f.serveNative(w, r) { |
| 259 | return |
| 260 | } |
| 261 | // Equipo refuses a request from another site, and any cookie on a |
| 262 | // device route; a server-to-server request carries neither. |
| 263 | if r.Header.Get("Origin") != "" || r.Header.Get("Cookie") != "" { |
| 264 | writeError(w, r, http.StatusForbidden, "forbidden") |
| 265 | return |
| 266 | } |
| 267 | if r.Method != http.MethodGet && len(r.Header.Values("Idempotency-Key")) != 1 && |
| 268 | strings.HasPrefix(r.URL.Path, "/api/v1/auth/") { |
| 269 | writeError(w, r, http.StatusUnprocessableEntity, "invalid_input") |
| 270 | return |
| 271 | } |
| 272 | switch p := r.URL.Path; { |
| 273 | case r.Method == http.MethodPost && p == "/api/v1/auth/devices": |
| 274 | f.begin(w, r) |
| 275 | case r.Method == http.MethodPost && p == "/api/v1/auth/devices/exchange": |
| 276 | f.exchange(w, r) |
| 277 | case r.Method == http.MethodDelete && strings.HasPrefix(p, "/api/v1/auth/devices/"): |
| 278 | f.revoke(w, r, strings.TrimPrefix(p, "/api/v1/auth/devices/")) |
| 279 | default: |
| 280 | f.serveChat(w, r) |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | func (f *Fake) begin(w http.ResponseWriter, r *http.Request) { |
| 285 | f.mu.Lock() |
| 286 | fail := f.failBegin |
| 287 | f.failBegin = false |
| 288 | hold, entered := f.beginHold, f.beginEntered |
| 289 | f.beginHold, f.beginEntered = nil, nil |
| 290 | f.mu.Unlock() |
| 291 | f.waitHeld(hold, entered) |
| 292 | if fail { |
| 293 | writeError(w, r, 503, "unavailable") |
| 294 | return |
| 295 | } |
| 296 | var in struct { |
| 297 | PublicKey string `json:"public_key"` |
| 298 | Label string `json:"label"` |
| 299 | } |
| 300 | if strict(r, &in) != nil { |
| 301 | writeError(w, r, 422, "invalid_input") |
| 302 | return |
| 303 | } |
| 304 | if pub, err := base64.RawURLEncoding.DecodeString(in.PublicKey); err != nil || |
| 305 | len(pub) != ed25519.PublicKeySize || in.Label == "" || len(in.Label) > 128 { |
| 306 | writeError(w, r, 422, "invalid_input") |
| 307 | return |
| 308 | } |
| 309 | id := rand.Text() |
| 310 | data, _ := json.Marshal([]string{f.Instance, rand.Text()}) |
| 311 | d := &device{id: id, publicKey: in.PublicKey, label: in.Label, secret: deviceAudience + "." + rand.Text(), |
| 312 | code: strings.ToUpper(rand.Text()[:8]), challenge: base64.RawURLEncoding.EncodeToString(data), |
| 313 | revision: 1, expires: time.Now().Add(10 * time.Minute)} |
| 314 | f.mu.Lock() |
| 315 | f.devices[id] = d |
| 316 | f.mu.Unlock() |
| 317 | w.Header().Set("ETag", `"1"`) |
| 318 | writeJSON(w, 200, map[string]any{"id": id, "device_secret": d.secret, "user_code": d.code, |
| 319 | "challenge": d.challenge, "verification_uri": f.URL + "/auth/devices/" + id, |
| 320 | "expires_at": d.expires.UTC(), "poll_interval_seconds": 5}) |
| 321 | } |
| 322 | |
| 323 | // Label is the label the device with userCode asked to be approved under. |
| 324 | func (f *Fake) Label(userCode string) string { |
| 325 | f.mu.Lock() |
| 326 | defer f.mu.Unlock() |
| 327 | for _, d := range f.devices { |
| 328 | if d.code == userCode { |
| 329 | return d.label |
| 330 | } |
| 331 | } |
| 332 | return "" |
| 333 | } |
| 334 | |
| 335 | func (f *Fake) exchange(w http.ResponseWriter, r *http.Request) { |
| 336 | var p struct { |
| 337 | ID string `json:"id"` |
| 338 | DeviceSecret string `json:"device_secret"` |
| 339 | Challenge string `json:"challenge"` |
| 340 | Nonce string `json:"nonce"` |
| 341 | Signature string `json:"signature"` |
| 342 | } |
| 343 | if strict(r, &p) != nil || len(p.Nonce) < 16 { |
| 344 | writeError(w, r, 422, "invalid_input") |
| 345 | return |
| 346 | } |
| 347 | f.mu.Lock() |
| 348 | hold, entered := f.hold, f.entered |
| 349 | f.hold, f.entered = nil, nil |
| 350 | f.mu.Unlock() |
| 351 | if hold != nil { |
| 352 | close(entered) |
| 353 | <-hold |
| 354 | } |
| 355 | f.mu.Lock() |
| 356 | defer f.mu.Unlock() |
| 357 | d, ok := f.devices[p.ID] |
| 358 | if !ok { |
| 359 | writeError(w, r, 403, "forbidden") |
| 360 | return |
| 361 | } |
| 362 | pub, _ := base64.RawURLEncoding.DecodeString(d.publicKey) |
| 363 | sig, _ := base64.RawURLEncoding.DecodeString(p.Signature) |
| 364 | msg, _ := json.Marshal([]string{deviceAudience, f.Instance, p.ID, p.Challenge, p.Nonce}) |
| 365 | switch { |
| 366 | case p.DeviceSecret != d.secret || p.Challenge != d.challenge || !ed25519.Verify(pub, msg, sig): |
| 367 | writeError(w, r, 403, "forbidden") |
| 368 | return |
| 369 | case d.revoked: |
| 370 | writeError(w, r, 403, "forbidden") |
| 371 | return |
| 372 | case d.token != "" && p.Nonce != d.nonce: |
| 373 | writeError(w, r, 403, "forbidden") |
| 374 | return |
| 375 | case d.token == "" && time.Now().After(d.expires): |
| 376 | writeError(w, r, 410, "device_expired") |
| 377 | return |
| 378 | case !d.approved: |
| 379 | writeError(w, r, 409, "authorization_pending") |
| 380 | return |
| 381 | } |
| 382 | if d.token == "" { |
| 383 | d.token, d.nonce, d.revision = personAudience+"."+rand.Text(), p.Nonce, 3 |
| 384 | } |
| 385 | w.Header().Set("ETag", fmt.Sprintf(`"%d"`, d.revision)) |
| 386 | writeJSON(w, 200, map[string]any{"id": d.id, "token": d.token, "audience": personAudience, |
| 387 | "instance_id": f.Instance, "expires_at": time.Now().Add(30 * 24 * time.Hour).UTC()}) |
| 388 | } |
| 389 | |
| 390 | // Expire makes every pending sign-in code expire. |
| 391 | func (f *Fake) Expire() { |
| 392 | f.mu.Lock() |
| 393 | defer f.mu.Unlock() |
| 394 | for _, d := range f.devices { |
| 395 | d.expires = time.Now().Add(-time.Second) |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | func (f *Fake) revoke(w http.ResponseWriter, r *http.Request, id string) { |
| 400 | f.mu.Lock() |
| 401 | hold, entered := f.revokeHold, f.revokeEntered |
| 402 | f.revokeHold, f.revokeEntered = nil, nil |
| 403 | f.mu.Unlock() |
| 404 | f.waitHeld(hold, entered) |
| 405 | d, ok := f.bearer(r) |
| 406 | if !ok { |
| 407 | writeError(w, r, 401, "unauthenticated") |
| 408 | return |
| 409 | } |
| 410 | var empty struct{} |
| 411 | if strict(r, &empty) != nil { |
| 412 | writeError(w, r, 422, "invalid_input") |
| 413 | return |
| 414 | } |
| 415 | f.mu.Lock() |
| 416 | defer f.mu.Unlock() |
| 417 | if d.id != id { |
| 418 | writeError(w, r, 404, "not_found") |
| 419 | return |
| 420 | } |
| 421 | if r.Header.Get("If-Match") != fmt.Sprintf(`"%d"`, d.revision) { |
| 422 | writeError(w, r, 409, "revision_conflict") |
| 423 | return |
| 424 | } |
| 425 | d.revoked = true |
| 426 | d.revision++ |
| 427 | w.Header().Set("ETag", fmt.Sprintf(`"%d"`, d.revision)) |
| 428 | writeJSON(w, 200, map[string]any{"revision": d.revision}) |
| 429 | } |
| 430 | |
| 431 | // bearer is the live device behind the request's bearer. |
| 432 | func (f *Fake) bearer(r *http.Request) (*device, bool) { |
| 433 | h := r.Header.Values("Authorization") |
| 434 | if len(h) != 1 || !strings.HasPrefix(h[0], "Bearer ") { |
| 435 | return nil, false |
| 436 | } |
| 437 | token := strings.TrimPrefix(h[0], "Bearer ") |
| 438 | f.mu.Lock() |
| 439 | defer f.mu.Unlock() |
| 440 | for _, d := range f.devices { |
| 441 | if d.token != "" && d.token == token && !d.revoked { |
| 442 | return d, true |
| 443 | } |
| 444 | } |
| 445 | return nil, false |
| 446 | } |
| 447 | |
| 448 | // strict decodes exactly one JSON object with no unknown fields, as |
| 449 | // Equipo's wire.Strict does, from a body declared as JSON. |
| 450 | func strict(r *http.Request, v any) error { |
| 451 | if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { |
| 452 | return fmt.Errorf("content type %q", ct) |
| 453 | } |
| 454 | d := json.NewDecoder(r.Body) |
| 455 | d.DisallowUnknownFields() |
| 456 | if err := d.Decode(v); err != nil { |
| 457 | return err |
| 458 | } |
| 459 | if d.Decode(new(json.RawMessage)) != io.EOF { |
| 460 | return fmt.Errorf("trailing JSON") |
| 461 | } |
| 462 | return nil |
| 463 | } |
| 464 | |
| 465 | func writeJSON(w http.ResponseWriter, status int, v any) { |
| 466 | w.Header().Set("Content-Type", "application/json") |
| 467 | w.WriteHeader(status) |
| 468 | _ = json.NewEncoder(w).Encode(v) |
| 469 | } |
| 470 | |
| 471 | // writeError writes Equipo's error body: {code, copy_key, request_id}. |
| 472 | func writeError(w http.ResponseWriter, r *http.Request, status int, code string) { |
| 473 | request := r.Header.Get("Idempotency-Key") |
| 474 | if request == "" { |
| 475 | request = rand.Text() |
| 476 | } |
| 477 | writeJSON(w, status, map[string]any{"code": code, "copy_key": "api." + code, "request_id": request}) |
| 478 | } |
| 479 | |