// Package thintest runs a real Equipo instance on 127.0.0.1 for the thin v1 // contract and headless suites, and provides the person API v1 client the // suites drive it with. The client works the same against staging. package thintest import ( "bytes" "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "errors" "fmt" "io" "log/slog" "net" "net/http" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/assist" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/dbtest" "amadan.net/rastrillo/rastrillo/mail" "amadan.net/rastrillo/rastrillo/sessions" ) // Owner is the instance owner in local runs. const Owner = "owner@example.com" var schema = dbtest.FromSet(equipo.BootSchema) // RemoveSchema deletes the migrated template; call it from TestMain. func RemoveSchema() { schema.Remove() } // Instance is one local instance process: a store, a router and an HTTP // server bound to 127.0.0.1. Restart replaces the process and keeps the // database and address, like a deploy. type Instance struct { URL string Path string TeamID string DB *db.DB Store *equipo.Store // NoExecution leaves EQUIPO_EXECUTION_ENABLED off after a Restart. NoExecution bool // MacEngineering is EQUIPO_MAC_ENGINEERING from the next start. MacEngineering bool // AssistantHosts is EQUIPO_ASSISTANT_HOSTS. Providers are served // after the base and team providers (an in-process write that takes // a client key, which Base's contract cannot offer yet). Both apply // from the next start (StartInstanceWith, Restart). AssistantHosts []string Providers []assist.Provider // OficinaConnect and OficinaClientID are // EQUIPO_OFICINA_CONNECT_ORIGIN and EQUIPO_OFICINA_CONNECT_CLIENT_ID. OficinaConnect, OficinaClientID string addr string server *http.Server cookie *http.Cookie logger *slog.Logger logs *logBuffer // calls stops the remote-call worker and waits for it. calls func() } // logBuffer keeps every line the instance logged, so a test can show a // secret never reached one. type logBuffer struct { mu sync.Mutex buf bytes.Buffer } func (l *logBuffer) Write(p []byte) (int, error) { l.mu.Lock() defer l.mu.Unlock() return l.buf.Write(p) } // Logs is everything the instance has logged so far, every level. func (i *Instance) Logs() string { i.logs.mu.Lock() defer i.logs.mu.Unlock() return i.logs.buf.String() } // StartInstance migrates a fresh database and serves it. func StartInstance(t testing.TB) *Instance { return StartInstanceWith(t, nil) } // StartInstanceWith is StartInstance with configure applied before the // first start (AssistantHosts, Providers). func StartInstanceWith(t testing.TB, configure func(*Instance)) *Instance { t.Helper() l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } logs := &logBuffer{} i := &Instance{addr: l.Addr().String(), Path: schema.Path(t), logs: logs, logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))} i.URL = "http://" + i.addr if configure != nil { configure(i) } i.serve(t, l) t.Cleanup(func() { i.Stop() }) if err = i.DB.Writer().QueryRow("SELECT id FROM teams").Scan(&i.TeamID); err != nil { t.Fatal(err) } token := rand.Text() now := time.Now().UTC() 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 { t.Fatal(err) } i.cookie = &http.Cookie{Name: "rastrillo_session", Value: token, Path: "/"} return i } func (i *Instance) serve(t testing.TB, l net.Listener) { t.Helper() d, err := db.Open(i.Path, i.logger) if err != nil { t.Fatal(err) } s := equipo.NewStore(d) 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) if err != nil { t.Fatal(err) } if len(i.Providers) > 0 { c := s.Chat() c.SetOperations(assist.NewRegistry(append([]assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider()}, i.Providers...)...)) } i.DB, i.Store = d, s i.server = &http.Server{Handler: productionHeaders(equipo.Mux(router)), ReadHeaderTimeout: 5 * time.Second} go i.server.Serve(l) // The remote-call worker, as the app's background starts it. ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { defer close(done) s.Chat().ServeRemoteCalls(ctx) }() i.calls = func() { cancel(); <-done } } // Stop drains streams and runners, then closes the server and database. func (i *Instance) Stop() { if i.server == nil { return } i.Store.DrainStreams() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() _ = i.server.Shutdown(ctx) i.calls() // Give hijacked runner sockets a moment to send drain and close. time.Sleep(100 * time.Millisecond) _ = i.DB.Close() i.server = nil } // Restart stops this process and starts a new one on the same address // and database, as a deploy does. func (i *Instance) Restart(t testing.TB) { t.Helper() i.Stop() var l net.Listener var err error for range 50 { if l, err = net.Listen("tcp", i.addr); err == nil { break } time.Sleep(20 * time.Millisecond) } if err != nil { t.Fatal(err) } i.serve(t, l) } // DeviceToken signs a device in with the person API device flow: begin, // approval by the owner's session, exchange. It returns the bearer. func (i *Instance) DeviceToken(t testing.TB) string { t.Helper() return i.DeviceTokenFor(t, Owner) } // SessionFor is a browser session cookie for any member. func (i *Instance) SessionFor(t testing.TB, address string) *http.Cookie { t.Helper() if address == Owner { return i.cookie } token := rand.Text() now := time.Now().UTC() 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 { t.Fatal(err) } return &http.Cookie{Name: "rastrillo_session", Value: token, Path: "/"} } // DeviceTokenFor signs a device in for a member, approved in their own // browser session. func (i *Instance) DeviceTokenFor(t testing.TB, address string) string { t.Helper() cookie := i.SessionFor(t, address) pub, key, err := ed25519.GenerateKey(rand.Reader) if err != nil { t.Fatal(err) } var c personapi.PersonDeviceChallenge i.json(t, "POST", "/api/v1/auth/devices", fmt.Sprintf(`{"public_key":%q,"label":"Headless suite"}`, base64.RawURLEncoding.EncodeToString(pub)), nil, "", 200, &c) i.json(t, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), cookie, `"1"`, 200, nil) p := personapi.PersonDeviceProof{ID: c.ID, DeviceSecret: c.DeviceSecret, Challenge: c.Challenge, Nonce: rand.Text()} p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, personapi.DeviceProofMessage(i.TeamID, p))) raw, _ := json.Marshal(p) var cred personapi.PersonCredential i.json(t, "POST", "/api/v1/auth/devices/exchange", string(raw), nil, "", 200, &cred) if cred.Token == "" { t.Fatal("no device token") } return cred.Token } func (i *Instance) json(t testing.TB, method, path, body string, cookie *http.Cookie, ifMatch string, want int, out any) { t.Helper() r, _ := http.NewRequest(method, i.URL+path, strings.NewReader(body)) r.Header.Set("Content-Type", "application/json") r.Header.Set("Idempotency-Key", rand.Text()) if cookie != nil { r.AddCookie(cookie) r.Header.Set("Origin", i.URL) } if ifMatch != "" { r.Header.Set("If-Match", ifMatch) } res, err := http.DefaultClient.Do(r) if err != nil { t.Fatal(err) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) if res.StatusCode != want { t.Fatalf("%s %s: HTTP %d: %s", method, path, res.StatusCode, raw) } if out != nil { if err := json.Unmarshal(raw, out); err != nil { t.Fatal(err) } } } // Cookie is the owner's browser session. func (i *Instance) Cookie() *http.Cookie { return i.cookie } // EnrolRunner enrols a runner for the owner and returns its credential. func (i *Instance) EnrolRunner(t testing.TB) runnerproto.RunnerCredential { t.Helper() return i.EnrolRunnerFor(t, Owner) } // EnrolRunnerFor enrols a runner approved by person. func (i *Instance) EnrolRunnerFor(t testing.TB, person string) runnerproto.RunnerCredential { t.Helper() pub, key, err := ed25519.GenerateKey(rand.Reader) if err != nil { t.Fatal(err) } ctx := context.Background() code, err := i.Store.BeginEnrolment(ctx, base64.RawURLEncoding.EncodeToString(pub), "Headless runner") if err != nil { t.Fatal(err) } if err = i.Store.ApproveEnrolment(ctx, equipo.Actor{Address: person}, code.UserCode); err != nil { t.Fatal(err) } nonce := make([]byte, 32) _, _ = rand.Read(nonce) proof := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(nonce)} proof.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(code.InstanceID, proof))) cred, err := i.Store.ExchangeEnrolment(ctx, code.DeviceSecret, proof) if err != nil { t.Fatal(err) } return cred } // WriteRunnerCredential stores a credential where the runner reads it. func WriteRunnerCredential(stateDir string, cred runnerproto.RunnerCredential) error { raw, err := json.Marshal(runnerproto.CredentialRotation{Bearer: cred, CleanupTokens: map[string]string{}}) if err != nil { return err } if err = os.MkdirAll(stateDir, 0700); err != nil { return err } if err := os.WriteFile(filepath.Join(stateDir, "credentials.json"), raw, 0600); err != nil { return err } // As enrolment keeps it, beside the credential: no role is a // primary's credential. role := `"primary"` if cred.Role == "worker" { role = `"worker"` } return os.WriteFile(filepath.Join(stateDir, "role"), []byte(role), 0600) } // ErrStatus is an unexpected HTTP status from the person API. type ErrStatus struct { Status int Body []byte } func (e *ErrStatus) Error() string { return fmt.Sprintf("HTTP %d: %s", e.Status, bytes.TrimSpace(e.Body)) } // Status returns the HTTP status carried by err, or 0. func Status(err error) int { var s *ErrStatus if errors.As(err, &s) { return s.Status } return 0 } // Get reads a page as the owner's browser session, which must answer 200. func (i *Instance) Get(t testing.TB, path string) string { t.Helper() req, _ := http.NewRequest("GET", i.URL+path, nil) req.AddCookie(i.Cookie()) res, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) if res.StatusCode != 200 { t.Fatalf("GET %s: %d %s", path, res.StatusCode, raw) } return string(raw) } // productionCSP is Rastrillo v0.30.1's default Content-Security-Policy, // which every production response carries (rastrillo.Handler sets it; the // constant is unexported). Pages here carry it too, so browser tests meet // what Safari met on staging: a chip preview from a blob: URL is blocked. const productionCSP = "default-src 'self'; " + "style-src 'self' 'unsafe-hashes' 'sha256-yJxAE4rjdcckohdlnvecSporPcqS9xOaA4hJxi87LMc='; " + "img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" // productionHeaders sets the policy before the app runs; a handler that // sets its own (an attachment's) replaces it, as in production. func productionHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Security-Policy", productionCSP) w.Header().Set("X-Content-Type-Options", "nosniff") next.ServeHTTP(w, r) }) }