package calls import ( "bytes" "context" "encoding/base64" "html" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strings" "testing" "time" "amadan.net/oficina/home/connect" "amadan.net/oficina/home/roster" "amadan.net/oficina/home/teammode" "amadan.net/oficina/home/teammode/teammodetest" assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/sessions" ) // Team mode's fixture: Home configured exactly as homeRouterFixture does // (same issuer, origin, consumer and assertion key, so its local and // exchange helpers drive this app too), and home/teammode's test // directory (teammodetest) answering the roster in memory from a member // list a test can change or take down, with a roster clock a test can // step past the lease. const teamTestConsumer = "calls-test" // teamSubject is a well-formed person ref: "pr_" and 26 copies of c. func teamSubject(c byte) string { return teammodetest.Subject(c) } // teamTestBindings are this instance's: Home's issuer and consumer ID as // homeRouterFixture configures them, the test directory and team, Calls, // and the test origin. func teamTestBindings() roster.Bindings { b := teammodetest.Bindings("calls", teamTestConsumer, homeTestOrigin) b.Issuer = homeTestIssuer return b } type teamFixture struct { *homeRouterFixture t *testing.T dir *teammodetest.Directory clock *teammodetest.Clock cfg Config d *db.DB dbPath string } // teamConfigFor is a team-mode Config on bindings b: Home as // homeRouterFixture has it, the record signed for b, and the test // directory and clock. allowed is CALLS_ALLOWED_ADDRESSES, which in team // mode only admits local sign-in; none is Alta's shape. func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, allowed ...string) (Config, *teammodetest.Directory, *teammodetest.Clock) { t.Helper() tcfg, dir := teammodetest.Provision(t, b) clock := teammodetest.NewClock() cfg := Config{Origin: homeTestOrigin, InstanceKey: "test-only-instance", DEK: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)), AllowedAddresses: allowed, Mailer: &homeTestMail{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Home: &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: teamTestConsumer, KeysBase64: homeKeysBase64(key), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))}, Team: tcfg, teamTransport: dir, teamClock: clock} return cfg, dir, clock } func openTeamDB(t *testing.T, path string) *db.DB { t.Helper() d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) return d } // newTeamFixture is a team-mode Calls with alice@example.test (or // allowed) admitted to the local door. func newTeamFixture(t *testing.T, allowed ...string) *teamFixture { t.Helper() key, err := assertioncrypto.Generate() if err != nil { t.Fatal(err) } if len(allowed) == 0 { allowed = []string{"alice@example.test"} } dbPath := filepath.Join(t.TempDir(), "calls.db") d := openTeamDB(t, dbPath) cfg, dir, clock := teamConfigFor(t, teamTestBindings(), key, allowed...) mux, a, err := buildForTest(t, d, cfg) if err != nil { t.Fatalf("build in team mode: %v", err) } hf := &homeRouterFixture{app: a, handler: mux, key: key, mail: cfg.Mailer.(*homeTestMail), cookies: map[string]*http.Cookie{}} return &teamFixture{homeRouterFixture: hf, t: t, dir: dir, clock: clock, cfg: cfg, d: d, dbPath: dbPath} } func (f *teamFixture) get(path string) *httptest.ResponseRecorder { return f.do("GET", path, "") } func (f *teamFixture) post(path, body string) *httptest.ResponseRecorder { return f.do("POST", path, body) } // page is a GET that asks for a page, as a browser navigation does. func (f *teamFixture) page(path string) *httptest.ResponseRecorder { return f.doWith("GET", path, "", http.Header{"Accept": {"text/html"}}) } // json is a POST with a JSON body, as the native app and the share // button send. func (f *teamFixture) json(path, body string) *httptest.ResponseRecorder { return f.doWith("POST", path, body, http.Header{"Content-Type": {"application/json"}}) } // signInHome runs a full Home exchange for subject from an empty jar and // returns the finish response. // // A roster Member with no account here yet is asked to choose (Home spec // 2026-11-14-oficina-id-native.md ยง8); signInHome answers "I'm new here", // as a new member would, and returns that answer. signInHomeChoosing // stops at the choice. func (f *teamFixture) signInHome(subject string) *httptest.ResponseRecorder { f.t.Helper() fin := f.signInHomeChoosing(subject) if fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath { return fin } return f.choose("new") } // signInHomeChoosing is signInHome, stopping at the member choice. func (f *teamFixture) signInHomeChoosing(subject string) *httptest.ResponseRecorder { f.t.Helper() f.cookies = map[string]*http.Cookie{} start := homeRedirect(f.t, f.do("GET", "/signin/oficina", "")) return f.exchange(f.t, start, subject) } // choose reads the choice page's form token and posts choice with it. func (f *teamFixture) choose(choice string) *httptest.ResponseRecorder { f.t.Helper() page := f.get(connect.ChoosePath) if page.Code != http.StatusOK { f.t.Fatalf("choose page = %d %s", page.Code, page.Body.String()) } m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(page.Body.String()) if m == nil { f.t.Fatalf("choose page has no form token: %s", page.Body.String()) } return f.post(connect.ChoosePath, url.Values{"choice": {choice}, "token": {html.UnescapeString(m[1])}}.Encode()) } // member puts subject on the roster with role, refreshes, and signs them // in with Home from an empty jar, failing unless they reach the meeting // list; it returns their person. func (f *teamFixture) member(subject, role string) Person { f.t.Helper() f.dir.Set(subject, role) f.refreshed() finish := f.signInHome(subject) if finish.Code != http.StatusSeeOther { f.t.Fatalf("sign-in of %s = %d %s", subject, finish.Code, finish.Body.String()) } if w := f.get("/"); w.Code != http.StatusOK { f.t.Fatalf("meeting list of %s = %d %s", subject, w.Code, w.Header().Get("Location")) } return f.personFor(subject) } // jar is the cookie jar now, to switch between people. func (f *teamFixture) jar() map[string]*http.Cookie { out := make(map[string]*http.Cookie, len(f.cookies)) for k, v := range f.cookies { out[k] = v } return out } // personFor is the person a Home subject signs in as. func (f *teamFixture) personFor(subject string) Person { f.t.Helper() ref, err := f.app.home.bridge.Resolve(context.Background(), subject) if err != nil { f.t.Fatalf("resolve %s: %v", subject, err) } p, ok, err := f.app.store.personByID(context.Background(), ref.ID) if err != nil || !ok { f.t.Fatalf("person %d: %v %v", ref.ID, ok, err) } return p } // refreshed steps the roster clock past the refresh point and waits for // the refresh, so the next request sees the directory's current list. func (f *teamFixture) refreshed() { f.t.Helper() f.dir.SetDown(false) f.clock.Step(roster.RefreshAfter + time.Second) // A refresh a request started while the directory was down may still // be in flight, and Refresh joins it: past it, ask again. var err error for range 5 { if err = f.app.team.Refresh(context.Background()); err == nil { return } f.clock.Step(roster.RetryAfter + time.Second) } f.t.Fatalf("roster refresh: %v", err) } // expired takes the directory down and steps past the lease: Unknown. func (f *teamFixture) expired() { f.dir.SetDown(true) f.clock.Step(roster.MaximumAge + time.Second) } // removed takes subject off the roster and refreshes: NotMember. func (f *teamFixture) removed(subject string) { f.t.Helper() f.dir.Set(subject, "") f.refreshed() } // withAccess is ctx carrying subject's standing now, for store calls a // test makes directly as that person. func (f *teamFixture) withAccess(subject string) context.Context { return teammode.WithAccess(context.Background(), f.app.team.Access(context.Background(), subject)) } // localSession puts a local (magic link) session for address in the jar, // as a sign-in the local door admitted would. func (f *teamFixture) localSession(address string) { f.t.Helper() w := httptest.NewRecorder() r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) if err := f.app.home.sessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil { f.t.Fatal(err) } f.cookies = map[string]*http.Cookie{} for _, c := range w.Result().Cookies() { f.cookies[c.Name] = c } } var ( reTeamToken = regexp.MustCompile(`/j/([A-Za-z0-9_-]{43})`) reTeamSqid = regexp.MustCompile(`/m/([23456789a-z]{10})/join`) ) // meeting makes a meeting as whoever is signed in and returns its sqid // and its link's token. func (f *teamFixture) meeting(title string) (sqid, token string) { f.t.Helper() w := f.post("/meetings", "title="+strings.ReplaceAll(title, " ", "+")) if w.Code != http.StatusOK { f.t.Fatalf("create %q = %d %s", title, w.Code, w.Body.String()) } tok, sq := reTeamToken.FindStringSubmatch(w.Body.String()), reTeamSqid.FindStringSubmatch(w.Body.String()) if tok == nil || sq == nil { f.t.Fatalf("no link on the link page:\n%s", w.Body.String()) } return sq[1], tok[1] } // meetingRow reads a meeting back. func (f *teamFixture) meetingRow(sqid string) Meeting { f.t.Helper() m, ok, err := f.app.store.meetingBySqid(context.Background(), sqid) if err != nil || !ok { f.t.Fatalf("meeting %s: %v %v", sqid, ok, err) } return m } // count is a table's row count. func (f *teamFixture) count(table string) int { f.t.Helper() var n int if err := f.app.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil { f.t.Fatal(err) } return n } // retryable fails unless w is the team-mode retryable 503. func retryable(t *testing.T, what string, w *httptest.ResponseRecorder) { t.Helper() if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { t.Fatalf("%s = %d (Retry-After %q, Cache-Control %q), want a retryable no-store 503: %s", what, w.Code, w.Header().Get("Retry-After"), w.Header().Get("Cache-Control"), w.Body.String()) } } // signedOutRemoved fails unless w ended the session and said why. func signedOutRemoved(t *testing.T, what string, w *httptest.ResponseRecorder) { t.Helper() switch w.Code { case http.StatusOK: // The door itself (GET /signin), with the removal in its // app-problem slot. if !strings.Contains(w.Body.String(), signinRemoved) { t.Fatalf("%s: the door does not say why", what) } case http.StatusSeeOther: if !strings.Contains(w.Header().Get("Location"), "err=removed") { t.Fatalf("%s: redirected to %q, want the removed notice", what, w.Header().Get("Location")) } case http.StatusForbidden: default: t.Fatalf("%s = %d, want the removed member signed out", what, w.Code) } ended := false for _, c := range w.Result().Cookies() { if c.MaxAge < 0 { ended = true } } if !ended { t.Fatalf("%s: the session cookie was not cleared", what) } }