| 1 | // Package thintest runs a real Equipo instance on 127.0.0.1 for the thin v1 |
| 2 | // contract and headless suites, and provides the person API v1 client the |
| 3 | // suites drive it with. The client works the same against staging. |
| 4 | package thintest |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "crypto/ed25519" |
| 10 | "crypto/rand" |
| 11 | "encoding/base64" |
| 12 | "encoding/json" |
| 13 | "errors" |
| 14 | "fmt" |
| 15 | "io" |
| 16 | "log/slog" |
| 17 | "net" |
| 18 | "net/http" |
| 19 | "os" |
| 20 | "path/filepath" |
| 21 | "strings" |
| 22 | "sync" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "amadan.net/oficina/equipo/internal/equipo" |
| 27 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 28 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 29 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 30 | "amadan.net/rastrillo/rastrillo/db" |
| 31 | "amadan.net/rastrillo/rastrillo/dbtest" |
| 32 | "amadan.net/rastrillo/rastrillo/mail" |
| 33 | "amadan.net/rastrillo/rastrillo/sessions" |
| 34 | ) |
| 35 | |
| 36 | // Owner is the instance owner in local runs. |
| 37 | const Owner = "owner@example.com" |
| 38 | |
| 39 | var schema = dbtest.FromSet(equipo.BootSchema) |
| 40 | |
| 41 | // RemoveSchema deletes the migrated template; call it from TestMain. |
| 42 | func RemoveSchema() { schema.Remove() } |
| 43 | |
| 44 | // Instance is one local instance process: a store, a router and an HTTP |
| 45 | // server bound to 127.0.0.1. Restart replaces the process and keeps the |
| 46 | // database and address, like a deploy. |
| 47 | type Instance struct { |
| 48 | URL string |
| 49 | Path string |
| 50 | TeamID string |
| 51 | DB *db.DB |
| 52 | Store *equipo.Store |
| 53 | // NoExecution leaves EQUIPO_EXECUTION_ENABLED off after a Restart. |
| 54 | NoExecution bool |
| 55 | // MacEngineering is EQUIPO_MAC_ENGINEERING from the next start. |
| 56 | MacEngineering bool |
| 57 | // AssistantHosts is EQUIPO_ASSISTANT_HOSTS. Providers are served |
| 58 | // after the base and team providers (an in-process write that takes |
| 59 | // a client key, which Base's contract cannot offer yet). Both apply |
| 60 | // from the next start (StartInstanceWith, Restart). |
| 61 | AssistantHosts []string |
| 62 | Providers []assist.Provider |
| 63 | // OficinaConnect and OficinaClientID are |
| 64 | // EQUIPO_OFICINA_CONNECT_ORIGIN and EQUIPO_OFICINA_CONNECT_CLIENT_ID. |
| 65 | OficinaConnect, OficinaClientID string |
| 66 | |
| 67 | addr string |
| 68 | server *http.Server |
| 69 | cookie *http.Cookie |
| 70 | logger *slog.Logger |
| 71 | logs *logBuffer |
| 72 | // calls stops the remote-call worker and waits for it. |
| 73 | calls func() |
| 74 | } |
| 75 | |
| 76 | // logBuffer keeps every line the instance logged, so a test can show a |
| 77 | // secret never reached one. |
| 78 | type logBuffer struct { |
| 79 | mu sync.Mutex |
| 80 | buf bytes.Buffer |
| 81 | } |
| 82 | |
| 83 | func (l *logBuffer) Write(p []byte) (int, error) { |
| 84 | l.mu.Lock() |
| 85 | defer l.mu.Unlock() |
| 86 | return l.buf.Write(p) |
| 87 | } |
| 88 | |
| 89 | // Logs is everything the instance has logged so far, every level. |
| 90 | func (i *Instance) Logs() string { |
| 91 | i.logs.mu.Lock() |
| 92 | defer i.logs.mu.Unlock() |
| 93 | return i.logs.buf.String() |
| 94 | } |
| 95 | |
| 96 | // StartInstance migrates a fresh database and serves it. |
| 97 | func StartInstance(t testing.TB) *Instance { return StartInstanceWith(t, nil) } |
| 98 | |
| 99 | // StartInstanceWith is StartInstance with configure applied before the |
| 100 | // first start (AssistantHosts, Providers). |
| 101 | func StartInstanceWith(t testing.TB, configure func(*Instance)) *Instance { |
| 102 | t.Helper() |
| 103 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 104 | if err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | logs := &logBuffer{} |
| 108 | i := &Instance{addr: l.Addr().String(), Path: schema.Path(t), logs: logs, logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))} |
| 109 | i.URL = "http://" + i.addr |
| 110 | if configure != nil { |
| 111 | configure(i) |
| 112 | } |
| 113 | i.serve(t, l) |
| 114 | t.Cleanup(func() { i.Stop() }) |
| 115 | if err = i.DB.Writer().QueryRow("SELECT id FROM teams").Scan(&i.TeamID); err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | token := rand.Text() |
| 119 | now := time.Now().UTC() |
| 120 | if _, err = i.DB.Writer().Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", sessions.HashToken(token), Owner, "fixture", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Add(24*time.Hour).Format(time.RFC3339Nano)); err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | i.cookie = &http.Cookie{Name: "rastrillo_session", Value: token, Path: "/"} |
| 124 | return i |
| 125 | } |
| 126 | |
| 127 | func (i *Instance) serve(t testing.TB, l net.Listener) { |
| 128 | t.Helper() |
| 129 | d, err := db.Open(i.Path, i.logger) |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | s := equipo.NewStore(d) |
| 134 | router, err := equipo.RouterWithStore(d, equipo.Config{Origin: i.URL, InstanceKey: "thin-v1-test", AllowLoggedMail: true, ExecutionEnabled: !i.NoExecution, MacEngineering: i.MacEngineering, Owners: []string{Owner}, TestPeople: []string{".invalid"}, AssistantHosts: i.AssistantHosts, OficinaConnectOrigin: i.OficinaConnect, OficinaConnectClientID: i.OficinaClientID}, mail.Logged(i.logger), i.logger, s) |
| 135 | if err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | if len(i.Providers) > 0 { |
| 139 | c := s.Chat() |
| 140 | c.SetOperations(assist.NewRegistry(append([]assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider()}, i.Providers...)...)) |
| 141 | } |
| 142 | i.DB, i.Store = d, s |
| 143 | i.server = &http.Server{Handler: productionHeaders(equipo.Mux(router)), ReadHeaderTimeout: 5 * time.Second} |
| 144 | go i.server.Serve(l) |
| 145 | // The remote-call worker, as the app's background starts it. |
| 146 | ctx, cancel := context.WithCancel(context.Background()) |
| 147 | done := make(chan struct{}) |
| 148 | go func() { |
| 149 | defer close(done) |
| 150 | s.Chat().ServeRemoteCalls(ctx) |
| 151 | }() |
| 152 | i.calls = func() { cancel(); <-done } |
| 153 | } |
| 154 | |
| 155 | // Stop drains streams and runners, then closes the server and database. |
| 156 | func (i *Instance) Stop() { |
| 157 | if i.server == nil { |
| 158 | return |
| 159 | } |
| 160 | i.Store.DrainStreams() |
| 161 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 162 | defer cancel() |
| 163 | _ = i.server.Shutdown(ctx) |
| 164 | i.calls() |
| 165 | // Give hijacked runner sockets a moment to send drain and close. |
| 166 | time.Sleep(100 * time.Millisecond) |
| 167 | _ = i.DB.Close() |
| 168 | i.server = nil |
| 169 | } |
| 170 | |
| 171 | // Restart stops this process and starts a new one on the same address |
| 172 | // and database, as a deploy does. |
| 173 | func (i *Instance) Restart(t testing.TB) { |
| 174 | t.Helper() |
| 175 | i.Stop() |
| 176 | var l net.Listener |
| 177 | var err error |
| 178 | for range 50 { |
| 179 | if l, err = net.Listen("tcp", i.addr); err == nil { |
| 180 | break |
| 181 | } |
| 182 | time.Sleep(20 * time.Millisecond) |
| 183 | } |
| 184 | if err != nil { |
| 185 | t.Fatal(err) |
| 186 | } |
| 187 | i.serve(t, l) |
| 188 | } |
| 189 | |
| 190 | // DeviceToken signs a device in with the person API device flow: begin, |
| 191 | // approval by the owner's session, exchange. It returns the bearer. |
| 192 | func (i *Instance) DeviceToken(t testing.TB) string { |
| 193 | t.Helper() |
| 194 | return i.DeviceTokenFor(t, Owner) |
| 195 | } |
| 196 | |
| 197 | // SessionFor is a browser session cookie for any member. |
| 198 | func (i *Instance) SessionFor(t testing.TB, address string) *http.Cookie { |
| 199 | t.Helper() |
| 200 | if address == Owner { |
| 201 | return i.cookie |
| 202 | } |
| 203 | token := rand.Text() |
| 204 | now := time.Now().UTC() |
| 205 | if _, err := i.DB.Writer().Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", sessions.HashToken(token), address, "fixture", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Add(24*time.Hour).Format(time.RFC3339Nano)); err != nil { |
| 206 | t.Fatal(err) |
| 207 | } |
| 208 | return &http.Cookie{Name: "rastrillo_session", Value: token, Path: "/"} |
| 209 | } |
| 210 | |
| 211 | // DeviceTokenFor signs a device in for a member, approved in their own |
| 212 | // browser session. |
| 213 | func (i *Instance) DeviceTokenFor(t testing.TB, address string) string { |
| 214 | t.Helper() |
| 215 | cookie := i.SessionFor(t, address) |
| 216 | pub, key, err := ed25519.GenerateKey(rand.Reader) |
| 217 | if err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | var c personapi.PersonDeviceChallenge |
| 221 | i.json(t, "POST", "/api/v1/auth/devices", fmt.Sprintf(`{"public_key":%q,"label":"Headless suite"}`, base64.RawURLEncoding.EncodeToString(pub)), nil, "", 200, &c) |
| 222 | i.json(t, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), cookie, `"1"`, 200, nil) |
| 223 | p := personapi.PersonDeviceProof{ID: c.ID, DeviceSecret: c.DeviceSecret, Challenge: c.Challenge, Nonce: rand.Text()} |
| 224 | p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, personapi.DeviceProofMessage(i.TeamID, p))) |
| 225 | raw, _ := json.Marshal(p) |
| 226 | var cred personapi.PersonCredential |
| 227 | i.json(t, "POST", "/api/v1/auth/devices/exchange", string(raw), nil, "", 200, &cred) |
| 228 | if cred.Token == "" { |
| 229 | t.Fatal("no device token") |
| 230 | } |
| 231 | return cred.Token |
| 232 | } |
| 233 | |
| 234 | func (i *Instance) json(t testing.TB, method, path, body string, cookie *http.Cookie, ifMatch string, want int, out any) { |
| 235 | t.Helper() |
| 236 | r, _ := http.NewRequest(method, i.URL+path, strings.NewReader(body)) |
| 237 | r.Header.Set("Content-Type", "application/json") |
| 238 | r.Header.Set("Idempotency-Key", rand.Text()) |
| 239 | if cookie != nil { |
| 240 | r.AddCookie(cookie) |
| 241 | r.Header.Set("Origin", i.URL) |
| 242 | } |
| 243 | if ifMatch != "" { |
| 244 | r.Header.Set("If-Match", ifMatch) |
| 245 | } |
| 246 | res, err := http.DefaultClient.Do(r) |
| 247 | if err != nil { |
| 248 | t.Fatal(err) |
| 249 | } |
| 250 | defer res.Body.Close() |
| 251 | raw, _ := io.ReadAll(res.Body) |
| 252 | if res.StatusCode != want { |
| 253 | t.Fatalf("%s %s: HTTP %d: %s", method, path, res.StatusCode, raw) |
| 254 | } |
| 255 | if out != nil { |
| 256 | if err := json.Unmarshal(raw, out); err != nil { |
| 257 | t.Fatal(err) |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | // Cookie is the owner's browser session. |
| 263 | func (i *Instance) Cookie() *http.Cookie { return i.cookie } |
| 264 | |
| 265 | // EnrolRunner enrols a runner for the owner and returns its credential. |
| 266 | func (i *Instance) EnrolRunner(t testing.TB) runnerproto.RunnerCredential { |
| 267 | t.Helper() |
| 268 | return i.EnrolRunnerFor(t, Owner) |
| 269 | } |
| 270 | |
| 271 | // EnrolRunnerFor enrols a runner approved by person. |
| 272 | func (i *Instance) EnrolRunnerFor(t testing.TB, person string) runnerproto.RunnerCredential { |
| 273 | t.Helper() |
| 274 | pub, key, err := ed25519.GenerateKey(rand.Reader) |
| 275 | if err != nil { |
| 276 | t.Fatal(err) |
| 277 | } |
| 278 | ctx := context.Background() |
| 279 | code, err := i.Store.BeginEnrolment(ctx, base64.RawURLEncoding.EncodeToString(pub), "Headless runner") |
| 280 | if err != nil { |
| 281 | t.Fatal(err) |
| 282 | } |
| 283 | if err = i.Store.ApproveEnrolment(ctx, equipo.Actor{Address: person}, code.UserCode); err != nil { |
| 284 | t.Fatal(err) |
| 285 | } |
| 286 | nonce := make([]byte, 32) |
| 287 | _, _ = rand.Read(nonce) |
| 288 | proof := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(nonce)} |
| 289 | proof.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(code.InstanceID, proof))) |
| 290 | cred, err := i.Store.ExchangeEnrolment(ctx, code.DeviceSecret, proof) |
| 291 | if err != nil { |
| 292 | t.Fatal(err) |
| 293 | } |
| 294 | return cred |
| 295 | } |
| 296 | |
| 297 | // WriteRunnerCredential stores a credential where the runner reads it. |
| 298 | func WriteRunnerCredential(stateDir string, cred runnerproto.RunnerCredential) error { |
| 299 | raw, err := json.Marshal(runnerproto.CredentialRotation{Bearer: cred, CleanupTokens: map[string]string{}}) |
| 300 | if err != nil { |
| 301 | return err |
| 302 | } |
| 303 | if err = os.MkdirAll(stateDir, 0700); err != nil { |
| 304 | return err |
| 305 | } |
| 306 | if err := os.WriteFile(filepath.Join(stateDir, "credentials.json"), raw, 0600); err != nil { |
| 307 | return err |
| 308 | } |
| 309 | // As enrolment keeps it, beside the credential: no role is a |
| 310 | // primary's credential. |
| 311 | role := `"primary"` |
| 312 | if cred.Role == "worker" { |
| 313 | role = `"worker"` |
| 314 | } |
| 315 | return os.WriteFile(filepath.Join(stateDir, "role"), []byte(role), 0600) |
| 316 | } |
| 317 | |
| 318 | // ErrStatus is an unexpected HTTP status from the person API. |
| 319 | type ErrStatus struct { |
| 320 | Status int |
| 321 | Body []byte |
| 322 | } |
| 323 | |
| 324 | func (e *ErrStatus) Error() string { |
| 325 | return fmt.Sprintf("HTTP %d: %s", e.Status, bytes.TrimSpace(e.Body)) |
| 326 | } |
| 327 | |
| 328 | // Status returns the HTTP status carried by err, or 0. |
| 329 | func Status(err error) int { |
| 330 | var s *ErrStatus |
| 331 | if errors.As(err, &s) { |
| 332 | return s.Status |
| 333 | } |
| 334 | return 0 |
| 335 | } |
| 336 | |
| 337 | // Get reads a page as the owner's browser session, which must answer 200. |
| 338 | func (i *Instance) Get(t testing.TB, path string) string { |
| 339 | t.Helper() |
| 340 | req, _ := http.NewRequest("GET", i.URL+path, nil) |
| 341 | req.AddCookie(i.Cookie()) |
| 342 | res, err := http.DefaultClient.Do(req) |
| 343 | if err != nil { |
| 344 | t.Fatal(err) |
| 345 | } |
| 346 | defer res.Body.Close() |
| 347 | raw, _ := io.ReadAll(res.Body) |
| 348 | if res.StatusCode != 200 { |
| 349 | t.Fatalf("GET %s: %d %s", path, res.StatusCode, raw) |
| 350 | } |
| 351 | return string(raw) |
| 352 | } |
| 353 | |
| 354 | // productionCSP is Rastrillo v0.30.1's default Content-Security-Policy, |
| 355 | // which every production response carries (rastrillo.Handler sets it; the |
| 356 | // constant is unexported). Pages here carry it too, so browser tests meet |
| 357 | // what Safari met on staging: a chip preview from a blob: URL is blocked. |
| 358 | const productionCSP = "default-src 'self'; " + |
| 359 | "style-src 'self' 'unsafe-hashes' 'sha256-yJxAE4rjdcckohdlnvecSporPcqS9xOaA4hJxi87LMc='; " + |
| 360 | "img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" |
| 361 | |
| 362 | // productionHeaders sets the policy before the app runs; a handler that |
| 363 | // sets its own (an attachment's) replaces it, as in production. |
| 364 | func productionHeaders(next http.Handler) http.Handler { |
| 365 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 366 | w.Header().Set("Content-Security-Policy", productionCSP) |
| 367 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 368 | next.ServeHTTP(w, r) |
| 369 | }) |
| 370 | } |
| 371 | |