| 1 | package calendar |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "html" |
| 9 | "io" |
| 10 | "log/slog" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "net/url" |
| 14 | "path/filepath" |
| 15 | "regexp" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/home/connect" |
| 21 | "amadan.net/oficina/home/handoff" |
| 22 | "amadan.net/oficina/home/roster" |
| 23 | "amadan.net/oficina/home/teammode" |
| 24 | "amadan.net/oficina/home/teammode/teammodetest" |
| 25 | assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| 26 | "amadan.net/rastrillo/rastrillo/sessions" |
| 27 | ) |
| 28 | |
| 29 | // Team mode's fixture: Home configured exactly as homeRouterFixture does |
| 30 | // (same issuer, origin and assertion key id, so its local and exchange |
| 31 | // helpers drive this app too), and home/teammode's test directory |
| 32 | // (teammodetest) answering the roster in memory from a member list a test |
| 33 | // can change or take down, with a roster clock a test can step past the |
| 34 | // lease. |
| 35 | |
| 36 | const teamTestConsumer = "calendar-test" |
| 37 | |
| 38 | // teamSubject is a well-formed person ref: "pr_" and 26 copies of c. |
| 39 | func teamSubject(c byte) string { return teammodetest.Subject(c) } |
| 40 | |
| 41 | // teamTestBindings are this instance's: Home's issuer and consumer ID as |
| 42 | // homeRouterFixture configures them, the test directory and team, |
| 43 | // Calendar, and the test origin. |
| 44 | func teamTestBindings() roster.Bindings { |
| 45 | b := teammodetest.Bindings("calendar", teamTestConsumer, homeTestOrigin) |
| 46 | b.Issuer = homeTestIssuer |
| 47 | return b |
| 48 | } |
| 49 | |
| 50 | type teamFixture struct { |
| 51 | *homeRouterFixture |
| 52 | t *testing.T |
| 53 | dir *teammodetest.Directory |
| 54 | clock *teammodetest.Clock |
| 55 | cfg Config |
| 56 | dbPath string |
| 57 | } |
| 58 | |
| 59 | // teamConfigFor is a team-mode Config on bindings b over dbPath: Home as |
| 60 | // homeRouterFixture has it, the record signed for b, and the test |
| 61 | // directory and clock. allowed is CALENDAR_ALLOWED_ADDRESSES, which in team |
| 62 | // mode only admits local sign-in; "" is Alta's shape. |
| 63 | func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, dbPath, allowed string) (Config, *teammodetest.Directory, *teammodetest.Clock) { |
| 64 | t.Helper() |
| 65 | tcfg, dir := teammodetest.Provision(t, b) |
| 66 | clock := teammodetest.NewClock() |
| 67 | manifest, _ := json.Marshal(map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}) |
| 68 | cfg := Config{DBPath: dbPath, Env: "development", Origin: homeTestOrigin, AllowedAddresses: allowed, |
| 69 | Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| 70 | Home: &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: teamTestConsumer, KeysBase64: base64.StdEncoding.EncodeToString(manifest), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))}, |
| 71 | Team: tcfg, teamTransport: dir, teamClock: clock} |
| 72 | return cfg, dir, clock |
| 73 | } |
| 74 | |
| 75 | func newTeamFixture(t *testing.T, allowed ...string) *teamFixture { |
| 76 | t.Helper() |
| 77 | key, err := assertioncrypto.Generate() |
| 78 | if err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | list := "alice@example.test" |
| 82 | if len(allowed) == 1 { |
| 83 | list = allowed[0] |
| 84 | } |
| 85 | dbPath := filepath.Join(t.TempDir(), "calendar.db") |
| 86 | cfg, dir, clock := teamConfigFor(t, teamTestBindings(), key, dbPath, list) |
| 87 | hf := &homeRouterFixture{key: key, cookies: map[string]*http.Cookie{}} |
| 88 | cfg.homeNow = hf.now |
| 89 | a, err := New(cfg) |
| 90 | if err != nil { |
| 91 | t.Fatalf("New in team mode: %v", err) |
| 92 | } |
| 93 | t.Cleanup(func() { a.Close() }) |
| 94 | hf.app = a |
| 95 | return &teamFixture{homeRouterFixture: hf, t: t, dir: dir, clock: clock, cfg: cfg, dbPath: dbPath} |
| 96 | } |
| 97 | |
| 98 | // get and post are do with the fixture's cookie jar. |
| 99 | func (f *teamFixture) get(path string) *httptest.ResponseRecorder { return f.do("GET", path, "") } |
| 100 | func (f *teamFixture) post(path, body string) *httptest.ResponseRecorder { |
| 101 | return f.do("POST", path, body) |
| 102 | } |
| 103 | |
| 104 | // signInHome runs a full Home exchange for subject from an empty jar and |
| 105 | // returns the finish response. |
| 106 | // |
| 107 | // A roster Member with no account here yet is asked to choose (Home spec |
| 108 | // 2026-11-14-oficina-id-native.md §8); signInHome answers "I'm new here", |
| 109 | // as a new member would, and returns that answer. signInHomeChoosing |
| 110 | // stops at the choice. |
| 111 | func (f *teamFixture) signInHome(subject string) *httptest.ResponseRecorder { |
| 112 | f.t.Helper() |
| 113 | fin := f.signInHomeChoosing(subject) |
| 114 | if fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath { |
| 115 | return fin |
| 116 | } |
| 117 | return f.choose("new") |
| 118 | } |
| 119 | |
| 120 | // signInHomeChoosing is signInHome, stopping at the member choice. |
| 121 | func (f *teamFixture) signInHomeChoosing(subject string) *httptest.ResponseRecorder { |
| 122 | f.t.Helper() |
| 123 | f.cookies = map[string]*http.Cookie{} |
| 124 | return f.exchange(f.t, handoff.StartPath, subject) |
| 125 | } |
| 126 | |
| 127 | // choose reads the choice page's form token and posts choice with it. |
| 128 | func (f *teamFixture) choose(choice string) *httptest.ResponseRecorder { |
| 129 | f.t.Helper() |
| 130 | page := f.get(connect.ChoosePath) |
| 131 | if page.Code != http.StatusOK { |
| 132 | f.t.Fatalf("choose page = %d %s", page.Code, page.Body.String()) |
| 133 | } |
| 134 | m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(page.Body.String()) |
| 135 | if m == nil { |
| 136 | f.t.Fatalf("choose page has no form token: %s", page.Body.String()) |
| 137 | } |
| 138 | return f.post(connect.ChoosePath, url.Values{"choice": {choice}, "token": {html.UnescapeString(m[1])}}.Encode()) |
| 139 | } |
| 140 | |
| 141 | // member adds subject to the roster with role, refreshes, and signs them |
| 142 | // in with Home from an empty jar, failing unless they got a session; it |
| 143 | // returns their person. |
| 144 | func (f *teamFixture) member(subject, role string) Person { |
| 145 | f.t.Helper() |
| 146 | f.dir.Set(subject, role) |
| 147 | f.refreshed() |
| 148 | finish := f.signInHome(subject) |
| 149 | if finish.Code != http.StatusSeeOther { |
| 150 | f.t.Fatalf("sign-in of %s = %d %s", subject, finish.Code, finish.Body.String()) |
| 151 | } |
| 152 | if f.cookies[f.app.home.sessions.CookieName()] == nil { |
| 153 | f.t.Fatalf("sign-in of %s minted no session", subject) |
| 154 | } |
| 155 | // The first page makes their calendars, as a local person's first |
| 156 | // page does. |
| 157 | if w := f.get("/calendars"); w.Code != http.StatusOK { |
| 158 | f.t.Fatalf("first page of %s = %d", subject, w.Code) |
| 159 | } |
| 160 | return f.personFor(subject) |
| 161 | } |
| 162 | |
| 163 | // personFor is the person a Home subject signs in as. |
| 164 | func (f *teamFixture) personFor(subject string) Person { |
| 165 | f.t.Helper() |
| 166 | ref, err := f.app.home.bridge.Resolve(context.Background(), subject) |
| 167 | if err != nil { |
| 168 | f.t.Fatalf("resolve %s: %v", subject, err) |
| 169 | } |
| 170 | var p Person |
| 171 | if err := f.app.db.G.First(&p, ref.ID).Error; err != nil { |
| 172 | f.t.Fatal(err) |
| 173 | } |
| 174 | return p |
| 175 | } |
| 176 | |
| 177 | // linkedAlice signs alice@example.test in locally, links her to subject |
| 178 | // through the real link flow, and leaves her signed in locally. subject |
| 179 | // is put on the roster as role first, so the link is to a member. |
| 180 | func (f *teamFixture) linkedAlice(subject, role string) Person { |
| 181 | f.t.Helper() |
| 182 | f.dir.Set(subject, role) |
| 183 | f.refreshed() |
| 184 | f.cookies = map[string]*http.Cookie{} |
| 185 | f.local(f.t) |
| 186 | if w := f.get("/account/home"); w.Code != http.StatusOK { |
| 187 | f.t.Fatalf("link page %d %s", w.Code, w.Body.String()) |
| 188 | } |
| 189 | start := homeRedirect(f.t, f.post("/account/home", "")) |
| 190 | if got := homeRedirect(f.t, f.exchange(f.t, start, subject)); got != "/account/home/confirm" { |
| 191 | f.t.Fatalf("link exchange landed on %s", got) |
| 192 | } |
| 193 | homeRedirect(f.t, f.post("/account/home/confirm", "")) |
| 194 | p, ok, err := f.app.store.PersonByAddress(context.Background(), "alice@example.test") |
| 195 | if err != nil || !ok { |
| 196 | f.t.Fatalf("alice: %v %v", ok, err) |
| 197 | } |
| 198 | if subj, err := f.app.homeSubjectOf(context.Background(), p.ID); err != nil || subj != subject { |
| 199 | f.t.Fatalf("alice is linked to %q (%v), want %q", subj, err, subject) |
| 200 | } |
| 201 | return p |
| 202 | } |
| 203 | |
| 204 | // refreshed steps the roster clock past the refresh point and waits for |
| 205 | // the refresh, so the next request sees the directory's current list. |
| 206 | func (f *teamFixture) refreshed() { |
| 207 | f.t.Helper() |
| 208 | f.dir.SetDown(false) |
| 209 | f.clock.Step(roster.RefreshAfter + time.Second) |
| 210 | if err := f.app.team.Refresh(context.Background()); err != nil { |
| 211 | f.t.Fatalf("roster refresh: %v", err) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // expired takes the directory down and steps past the lease: Unknown. |
| 216 | func (f *teamFixture) expired() { |
| 217 | f.dir.SetDown(true) |
| 218 | f.clock.Step(roster.MaximumAge + time.Second) |
| 219 | } |
| 220 | |
| 221 | // withAccess is ctx carrying subject's standing now, for store calls a |
| 222 | // test makes directly as that person. |
| 223 | func (f *teamFixture) withAccess(subject string) context.Context { |
| 224 | return teammode.WithAccess(context.Background(), f.app.team.Access(context.Background(), subject)) |
| 225 | } |
| 226 | |
| 227 | // calendarsOf are p's team and personal calendar ids. |
| 228 | func (f *teamFixture) calendarsOf(p Person) (team, personal int64) { |
| 229 | f.t.Helper() |
| 230 | var cals []Calendar |
| 231 | if err := f.app.db.G.Joins("JOIN grants ON grants.calendar_id = calendars.id AND grants.person_id = ?", p.ID).Find(&cals).Error; err != nil { |
| 232 | f.t.Fatal(err) |
| 233 | } |
| 234 | for _, c := range cals { |
| 235 | switch c.Kind { |
| 236 | case "team": |
| 237 | team = c.ID |
| 238 | case "personal": |
| 239 | personal = c.ID |
| 240 | } |
| 241 | } |
| 242 | if team == 0 || personal == 0 { |
| 243 | f.t.Fatalf("person %d has calendars %+v", p.ID, cals) |
| 244 | } |
| 245 | return team, personal |
| 246 | } |
| 247 | |
| 248 | // event makes an event on calendar as p, directly, standing on subject. |
| 249 | func (f *teamFixture) event(p Person, subject string, calendar int64, title, start, end string) Event { |
| 250 | f.t.Helper() |
| 251 | e, err := f.app.store.CreateEvent(f.withAccess(subject), p.ID, EventInput{CalendarID: calendar, Title: title, StartLocal: start, EndLocal: end, TZ: "UTC", Kind: KindMeeting, Status: StatusConfirmed}) |
| 252 | if err != nil { |
| 253 | f.t.Fatalf("event %q: %v", title, err) |
| 254 | } |
| 255 | return e |
| 256 | } |
| 257 | |
| 258 | // localSession puts a local (magic link) session for address in the jar, |
| 259 | // as a sign-in the allowlist admitted would. |
| 260 | func (f *teamFixture) localSession(address string) { |
| 261 | f.t.Helper() |
| 262 | w := httptest.NewRecorder() |
| 263 | r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| 264 | if err := f.app.home.sessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil { |
| 265 | f.t.Fatal(err) |
| 266 | } |
| 267 | f.cookies = map[string]*http.Cookie{} |
| 268 | for _, c := range w.Result().Cookies() { |
| 269 | f.cookies[c.Name] = c |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // retryable fails unless w is the team-mode retryable 503. |
| 274 | func retryable(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| 275 | t.Helper() |
| 276 | if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| 277 | t.Fatalf("%s = %d (Retry-After %q, Cache-Control %q), want a retryable no-store 503", what, w.Code, w.Header().Get("Retry-After"), w.Header().Get("Cache-Control")) |
| 278 | } |
| 279 | } |
| 280 | |