| 1 | package calls |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "html" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "net/url" |
| 13 | "path/filepath" |
| 14 | "regexp" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/home/connect" |
| 20 | "amadan.net/oficina/home/roster" |
| 21 | "amadan.net/oficina/home/teammode" |
| 22 | "amadan.net/oficina/home/teammode/teammodetest" |
| 23 | assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| 24 | "amadan.net/rastrillo/rastrillo/db" |
| 25 | "amadan.net/rastrillo/rastrillo/sessions" |
| 26 | ) |
| 27 | |
| 28 | // Team mode's fixture: Home configured exactly as homeRouterFixture does |
| 29 | // (same issuer, origin, consumer and assertion key, so its local and |
| 30 | // exchange helpers drive this app too), and home/teammode's test |
| 31 | // directory (teammodetest) answering the roster in memory from a member |
| 32 | // list a test can change or take down, with a roster clock a test can |
| 33 | // step past the lease. |
| 34 | |
| 35 | const teamTestConsumer = "calls-test" |
| 36 | |
| 37 | // teamSubject is a well-formed person ref: "pr_" and 26 copies of c. |
| 38 | func teamSubject(c byte) string { return teammodetest.Subject(c) } |
| 39 | |
| 40 | // teamTestBindings are this instance's: Home's issuer and consumer ID as |
| 41 | // homeRouterFixture configures them, the test directory and team, Calls, |
| 42 | // and the test origin. |
| 43 | func teamTestBindings() roster.Bindings { |
| 44 | b := teammodetest.Bindings("calls", teamTestConsumer, homeTestOrigin) |
| 45 | b.Issuer = homeTestIssuer |
| 46 | return b |
| 47 | } |
| 48 | |
| 49 | type teamFixture struct { |
| 50 | *homeRouterFixture |
| 51 | t *testing.T |
| 52 | dir *teammodetest.Directory |
| 53 | clock *teammodetest.Clock |
| 54 | cfg Config |
| 55 | d *db.DB |
| 56 | dbPath string |
| 57 | } |
| 58 | |
| 59 | // teamConfigFor is a team-mode Config on bindings b: Home as |
| 60 | // homeRouterFixture has it, the record signed for b, and the test |
| 61 | // directory and clock. allowed is CALLS_ALLOWED_ADDRESSES, which in team |
| 62 | // mode only admits local sign-in; none is Alta's shape. |
| 63 | func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, allowed ...string) (Config, *teammodetest.Directory, *teammodetest.Clock) { |
| 64 | t.Helper() |
| 65 | tcfg, dir := teammodetest.Provision(t, b) |
| 66 | clock := teammodetest.NewClock() |
| 67 | cfg := Config{Origin: homeTestOrigin, InstanceKey: "test-only-instance", DEK: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)), |
| 68 | AllowedAddresses: allowed, Mailer: &homeTestMail{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| 69 | Home: &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: teamTestConsumer, KeysBase64: homeKeysBase64(key), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))}, |
| 70 | Team: tcfg, teamTransport: dir, teamClock: clock} |
| 71 | return cfg, dir, clock |
| 72 | } |
| 73 | |
| 74 | func openTeamDB(t *testing.T, path string) *db.DB { |
| 75 | t.Helper() |
| 76 | d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 77 | if err != nil { |
| 78 | t.Fatal(err) |
| 79 | } |
| 80 | t.Cleanup(func() { d.Close() }) |
| 81 | return d |
| 82 | } |
| 83 | |
| 84 | // newTeamFixture is a team-mode Calls with alice@example.test (or |
| 85 | // allowed) admitted to the local door. |
| 86 | func newTeamFixture(t *testing.T, allowed ...string) *teamFixture { |
| 87 | t.Helper() |
| 88 | key, err := assertioncrypto.Generate() |
| 89 | if err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | if len(allowed) == 0 { |
| 93 | allowed = []string{"alice@example.test"} |
| 94 | } |
| 95 | dbPath := filepath.Join(t.TempDir(), "calls.db") |
| 96 | d := openTeamDB(t, dbPath) |
| 97 | cfg, dir, clock := teamConfigFor(t, teamTestBindings(), key, allowed...) |
| 98 | mux, a, err := buildForTest(t, d, cfg) |
| 99 | if err != nil { |
| 100 | t.Fatalf("build in team mode: %v", err) |
| 101 | } |
| 102 | hf := &homeRouterFixture{app: a, handler: mux, key: key, mail: cfg.Mailer.(*homeTestMail), cookies: map[string]*http.Cookie{}} |
| 103 | return &teamFixture{homeRouterFixture: hf, t: t, dir: dir, clock: clock, cfg: cfg, d: d, dbPath: dbPath} |
| 104 | } |
| 105 | |
| 106 | func (f *teamFixture) get(path string) *httptest.ResponseRecorder { return f.do("GET", path, "") } |
| 107 | func (f *teamFixture) post(path, body string) *httptest.ResponseRecorder { |
| 108 | return f.do("POST", path, body) |
| 109 | } |
| 110 | |
| 111 | // page is a GET that asks for a page, as a browser navigation does. |
| 112 | func (f *teamFixture) page(path string) *httptest.ResponseRecorder { |
| 113 | return f.doWith("GET", path, "", http.Header{"Accept": {"text/html"}}) |
| 114 | } |
| 115 | |
| 116 | // json is a POST with a JSON body, as the native app and the share |
| 117 | // button send. |
| 118 | func (f *teamFixture) json(path, body string) *httptest.ResponseRecorder { |
| 119 | return f.doWith("POST", path, body, http.Header{"Content-Type": {"application/json"}}) |
| 120 | } |
| 121 | |
| 122 | // signInHome runs a full Home exchange for subject from an empty jar and |
| 123 | // returns the finish response. |
| 124 | // |
| 125 | // A roster Member with no account here yet is asked to choose (Home spec |
| 126 | // 2026-11-14-oficina-id-native.md §8); signInHome answers "I'm new here", |
| 127 | // as a new member would, and returns that answer. signInHomeChoosing |
| 128 | // stops at the choice. |
| 129 | func (f *teamFixture) signInHome(subject string) *httptest.ResponseRecorder { |
| 130 | f.t.Helper() |
| 131 | fin := f.signInHomeChoosing(subject) |
| 132 | if fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath { |
| 133 | return fin |
| 134 | } |
| 135 | return f.choose("new") |
| 136 | } |
| 137 | |
| 138 | // signInHomeChoosing is signInHome, stopping at the member choice. |
| 139 | func (f *teamFixture) signInHomeChoosing(subject string) *httptest.ResponseRecorder { |
| 140 | f.t.Helper() |
| 141 | f.cookies = map[string]*http.Cookie{} |
| 142 | start := homeRedirect(f.t, f.do("GET", "/signin/oficina", "")) |
| 143 | return f.exchange(f.t, start, subject) |
| 144 | } |
| 145 | |
| 146 | // choose reads the choice page's form token and posts choice with it. |
| 147 | func (f *teamFixture) choose(choice string) *httptest.ResponseRecorder { |
| 148 | f.t.Helper() |
| 149 | page := f.get(connect.ChoosePath) |
| 150 | if page.Code != http.StatusOK { |
| 151 | f.t.Fatalf("choose page = %d %s", page.Code, page.Body.String()) |
| 152 | } |
| 153 | m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(page.Body.String()) |
| 154 | if m == nil { |
| 155 | f.t.Fatalf("choose page has no form token: %s", page.Body.String()) |
| 156 | } |
| 157 | return f.post(connect.ChoosePath, url.Values{"choice": {choice}, "token": {html.UnescapeString(m[1])}}.Encode()) |
| 158 | } |
| 159 | |
| 160 | // member puts subject on the roster with role, refreshes, and signs them |
| 161 | // in with Home from an empty jar, failing unless they reach the meeting |
| 162 | // list; it returns their person. |
| 163 | func (f *teamFixture) member(subject, role string) Person { |
| 164 | f.t.Helper() |
| 165 | f.dir.Set(subject, role) |
| 166 | f.refreshed() |
| 167 | finish := f.signInHome(subject) |
| 168 | if finish.Code != http.StatusSeeOther { |
| 169 | f.t.Fatalf("sign-in of %s = %d %s", subject, finish.Code, finish.Body.String()) |
| 170 | } |
| 171 | if w := f.get("/"); w.Code != http.StatusOK { |
| 172 | f.t.Fatalf("meeting list of %s = %d %s", subject, w.Code, w.Header().Get("Location")) |
| 173 | } |
| 174 | return f.personFor(subject) |
| 175 | } |
| 176 | |
| 177 | // jar is the cookie jar now, to switch between people. |
| 178 | func (f *teamFixture) jar() map[string]*http.Cookie { |
| 179 | out := make(map[string]*http.Cookie, len(f.cookies)) |
| 180 | for k, v := range f.cookies { |
| 181 | out[k] = v |
| 182 | } |
| 183 | return out |
| 184 | } |
| 185 | |
| 186 | // personFor is the person a Home subject signs in as. |
| 187 | func (f *teamFixture) personFor(subject string) Person { |
| 188 | f.t.Helper() |
| 189 | ref, err := f.app.home.bridge.Resolve(context.Background(), subject) |
| 190 | if err != nil { |
| 191 | f.t.Fatalf("resolve %s: %v", subject, err) |
| 192 | } |
| 193 | p, ok, err := f.app.store.personByID(context.Background(), ref.ID) |
| 194 | if err != nil || !ok { |
| 195 | f.t.Fatalf("person %d: %v %v", ref.ID, ok, err) |
| 196 | } |
| 197 | return p |
| 198 | } |
| 199 | |
| 200 | // refreshed steps the roster clock past the refresh point and waits for |
| 201 | // the refresh, so the next request sees the directory's current list. |
| 202 | func (f *teamFixture) refreshed() { |
| 203 | f.t.Helper() |
| 204 | f.dir.SetDown(false) |
| 205 | f.clock.Step(roster.RefreshAfter + time.Second) |
| 206 | // A refresh a request started while the directory was down may still |
| 207 | // be in flight, and Refresh joins it: past it, ask again. |
| 208 | var err error |
| 209 | for range 5 { |
| 210 | if err = f.app.team.Refresh(context.Background()); err == nil { |
| 211 | return |
| 212 | } |
| 213 | f.clock.Step(roster.RetryAfter + time.Second) |
| 214 | } |
| 215 | f.t.Fatalf("roster refresh: %v", err) |
| 216 | } |
| 217 | |
| 218 | // expired takes the directory down and steps past the lease: Unknown. |
| 219 | func (f *teamFixture) expired() { |
| 220 | f.dir.SetDown(true) |
| 221 | f.clock.Step(roster.MaximumAge + time.Second) |
| 222 | } |
| 223 | |
| 224 | // removed takes subject off the roster and refreshes: NotMember. |
| 225 | func (f *teamFixture) removed(subject string) { |
| 226 | f.t.Helper() |
| 227 | f.dir.Set(subject, "") |
| 228 | f.refreshed() |
| 229 | } |
| 230 | |
| 231 | // withAccess is ctx carrying subject's standing now, for store calls a |
| 232 | // test makes directly as that person. |
| 233 | func (f *teamFixture) withAccess(subject string) context.Context { |
| 234 | return teammode.WithAccess(context.Background(), f.app.team.Access(context.Background(), subject)) |
| 235 | } |
| 236 | |
| 237 | // localSession puts a local (magic link) session for address in the jar, |
| 238 | // as a sign-in the local door admitted would. |
| 239 | func (f *teamFixture) localSession(address string) { |
| 240 | f.t.Helper() |
| 241 | w := httptest.NewRecorder() |
| 242 | r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| 243 | if err := f.app.home.sessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil { |
| 244 | f.t.Fatal(err) |
| 245 | } |
| 246 | f.cookies = map[string]*http.Cookie{} |
| 247 | for _, c := range w.Result().Cookies() { |
| 248 | f.cookies[c.Name] = c |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | var ( |
| 253 | reTeamToken = regexp.MustCompile(`/j/([A-Za-z0-9_-]{43})`) |
| 254 | reTeamSqid = regexp.MustCompile(`/m/([23456789a-z]{10})/join`) |
| 255 | ) |
| 256 | |
| 257 | // meeting makes a meeting as whoever is signed in and returns its sqid |
| 258 | // and its link's token. |
| 259 | func (f *teamFixture) meeting(title string) (sqid, token string) { |
| 260 | f.t.Helper() |
| 261 | w := f.post("/meetings", "title="+strings.ReplaceAll(title, " ", "+")) |
| 262 | if w.Code != http.StatusOK { |
| 263 | f.t.Fatalf("create %q = %d %s", title, w.Code, w.Body.String()) |
| 264 | } |
| 265 | tok, sq := reTeamToken.FindStringSubmatch(w.Body.String()), reTeamSqid.FindStringSubmatch(w.Body.String()) |
| 266 | if tok == nil || sq == nil { |
| 267 | f.t.Fatalf("no link on the link page:\n%s", w.Body.String()) |
| 268 | } |
| 269 | return sq[1], tok[1] |
| 270 | } |
| 271 | |
| 272 | // meetingRow reads a meeting back. |
| 273 | func (f *teamFixture) meetingRow(sqid string) Meeting { |
| 274 | f.t.Helper() |
| 275 | m, ok, err := f.app.store.meetingBySqid(context.Background(), sqid) |
| 276 | if err != nil || !ok { |
| 277 | f.t.Fatalf("meeting %s: %v %v", sqid, ok, err) |
| 278 | } |
| 279 | return m |
| 280 | } |
| 281 | |
| 282 | // count is a table's row count. |
| 283 | func (f *teamFixture) count(table string) int { |
| 284 | f.t.Helper() |
| 285 | var n int |
| 286 | if err := f.app.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil { |
| 287 | f.t.Fatal(err) |
| 288 | } |
| 289 | return n |
| 290 | } |
| 291 | |
| 292 | // retryable fails unless w is the team-mode retryable 503. |
| 293 | func retryable(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| 294 | t.Helper() |
| 295 | if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| 296 | 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()) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | // signedOutRemoved fails unless w ended the session and said why. |
| 301 | func signedOutRemoved(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| 302 | t.Helper() |
| 303 | switch w.Code { |
| 304 | case http.StatusOK: |
| 305 | // The door itself (GET /signin), with the removal in its |
| 306 | // app-problem slot. |
| 307 | if !strings.Contains(w.Body.String(), signinRemoved) { |
| 308 | t.Fatalf("%s: the door does not say why", what) |
| 309 | } |
| 310 | case http.StatusSeeOther: |
| 311 | if !strings.Contains(w.Header().Get("Location"), "err=removed") { |
| 312 | t.Fatalf("%s: redirected to %q, want the removed notice", what, w.Header().Get("Location")) |
| 313 | } |
| 314 | case http.StatusForbidden: |
| 315 | default: |
| 316 | t.Fatalf("%s = %d, want the removed member signed out", what, w.Code) |
| 317 | } |
| 318 | ended := false |
| 319 | for _, c := range w.Result().Cookies() { |
| 320 | if c.MaxAge < 0 { |
| 321 | ended = true |
| 322 | } |
| 323 | } |
| 324 | if !ended { |
| 325 | t.Fatalf("%s: the session cookie was not cleared", what) |
| 326 | } |
| 327 | } |
| 328 | |