| 1 | package calendar |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/home/connect/linkstore" |
| 17 | "amadan.net/oficina/home/handoff" |
| 18 | "amadan.net/oficina/home/roster" |
| 19 | "amadan.net/oficina/home/teammode" |
| 20 | assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| 21 | "amadan.net/rastrillo/rastrillo/db" |
| 22 | "amadan.net/rastrillo/rastrillo/migrate" |
| 23 | ) |
| 24 | |
| 25 | // markerFor reports whether dbPath holds an activation marker, opening |
| 26 | // it read-only of the app. |
| 27 | func markerFor(t *testing.T, dbPath string) bool { |
| 28 | t.Helper() |
| 29 | d, err := db.Open(dbPath, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 30 | if err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | defer d.Close() |
| 34 | _, activated, err := teamState.Required(context.Background(), d.Writer()) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | return activated |
| 39 | } |
| 40 | |
| 41 | func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { |
| 42 | key, err := assertioncrypto.Generate() |
| 43 | if err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | for name, mutate := range map[string]func(*roster.Bindings){ |
| 47 | "issuer": func(b *roster.Bindings) { b.Issuer = "https://id.elsewhere.test" }, |
| 48 | "consumer": func(b *roster.Bindings) { b.Consumer = "someone-else" }, |
| 49 | "app": func(b *roster.Bindings) { b.App = "slides" }, |
| 50 | "origin": func(b *roster.Bindings) { b.Audience = "https://calendar.elsewhere.test" }, |
| 51 | "team": func(b *roster.Bindings) { b.Team = "TeamB" }, |
| 52 | "directory": func(b *roster.Bindings) { b.Directory = "https://home.elsewhere.test" }, |
| 53 | } { |
| 54 | t.Run(name, func(t *testing.T) { |
| 55 | b := teamTestBindings() |
| 56 | mutate(&b) |
| 57 | dbPath := filepath.Join(t.TempDir(), "calendar.db") |
| 58 | cfg, _, _ := teamConfigFor(t, b, key, dbPath, "") |
| 59 | if name == "team" || name == "directory" { |
| 60 | // The record names the team and directory; the instance's |
| 61 | // own configuration must name the same ones. |
| 62 | good, _, _ := teamConfigFor(t, teamTestBindings(), key, dbPath, "") |
| 63 | good.Team.ProvisioningBase64 = cfg.Team.ProvisioningBase64 |
| 64 | good.Team.OperatorKeysBase64 = cfg.Team.OperatorKeysBase64 |
| 65 | cfg = good |
| 66 | } |
| 67 | a, err := New(cfg) |
| 68 | if err == nil { |
| 69 | a.Close() |
| 70 | t.Fatalf("a record signed for another %s was accepted", name) |
| 71 | } |
| 72 | if markerFor(t, dbPath) { |
| 73 | t.Fatalf("a refused %s wrote the marker", name) |
| 74 | } |
| 75 | }) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | func TestTeamEnvIsAllOrNoneAndNeedsHome(t *testing.T) { |
| 80 | for _, name := range teammode.EnvNames("CALENDAR") { |
| 81 | env := map[string]string{} |
| 82 | for _, n := range teammode.EnvNames("CALENDAR") { |
| 83 | env[n] = "x" |
| 84 | } |
| 85 | delete(env, name) |
| 86 | if c := teammode.ConfigFromLookup("CALENDAR", func(k string) string { return env[k] }); c == nil { |
| 87 | t.Fatalf("four of five (%s missing) read as team mode off", name) |
| 88 | } else { |
| 89 | key, _ := assertioncrypto.Generate() |
| 90 | cfg, _, _ := teamConfigFor(t, teamTestBindings(), key, filepath.Join(t.TempDir(), "calendar.db"), "") |
| 91 | cfg.Team = c |
| 92 | if a, err := New(cfg); err == nil { |
| 93 | a.Close() |
| 94 | t.Fatalf("four of five (%s missing) booted", name) |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | key, _ := assertioncrypto.Generate() |
| 99 | cfg, _, _ := teamConfigFor(t, teamTestBindings(), key, filepath.Join(t.TempDir(), "calendar.db"), "") |
| 100 | cfg.Home = nil |
| 101 | if a, err := New(cfg); err == nil { |
| 102 | a.Close() |
| 103 | t.Fatal("team mode booted without Home") |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | func TestTeamTheAllowlistBecomesOptionalAndAdmitsOnlyLocally(t *testing.T) { |
| 108 | team := &teammode.Config{TeamID: "TeamA"} |
| 109 | for _, env := range []string{"production", "development"} { |
| 110 | list, err := resolveAllowlist(Config{Env: env, Team: team}) |
| 111 | if err != nil { |
| 112 | t.Fatalf("%s team mode with no allowlist: %v", env, err) |
| 113 | } |
| 114 | // Never the development default that admits everyone. |
| 115 | if list.addrs == nil || list.allows("anyone@example.test") { |
| 116 | t.Fatalf("an empty %s team allowlist admits somebody locally", env) |
| 117 | } |
| 118 | list, err = resolveAllowlist(Config{Env: env, Team: team, AllowedAddresses: "alice@example.test"}) |
| 119 | if err != nil || !list.allows("alice@example.test") || list.allows("bob@example.test") { |
| 120 | t.Fatalf("a %s team allowlist is not the local door: %v", env, err) |
| 121 | } |
| 122 | } |
| 123 | // Off team mode the old refusal stands. |
| 124 | if _, err := resolveAllowlist(Config{Env: "production"}); err == nil { |
| 125 | t.Fatal("production without team mode accepted no allowlist") |
| 126 | } |
| 127 | // The fixture's app: an empty list admits nobody. |
| 128 | f := newTeamFixture(t, "") |
| 129 | if f.app.home.admitted.allows("anyone@example.test") { |
| 130 | t.Fatal("an empty team allowlist admits everyone") |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| 135 | f := newTeamFixture(t) |
| 136 | f.app.Close() |
| 137 | if !markerFor(t, f.dbPath) { |
| 138 | t.Fatal("team mode wrote no marker") |
| 139 | } |
| 140 | // Without team configuration: refused, before anything migrates. |
| 141 | off := f.cfg |
| 142 | off.Team = nil |
| 143 | if a, err := New(off); err == nil { |
| 144 | a.Close() |
| 145 | t.Fatal("an activated database booted without team mode") |
| 146 | } |
| 147 | // With another binding: refused. |
| 148 | key, _ := assertioncrypto.Generate() |
| 149 | b := teamTestBindings() |
| 150 | b.Team = "TeamB" |
| 151 | other, _, _ := teamConfigFor(t, b, key, f.dbPath, "") |
| 152 | other.Home = f.cfg.Home |
| 153 | if a, err := New(other); err == nil { |
| 154 | a.Close() |
| 155 | t.Fatal("an activated database booted on another team") |
| 156 | } |
| 157 | // The same configuration boots again. |
| 158 | again, err := New(f.cfg) |
| 159 | if err != nil { |
| 160 | t.Fatalf("the same binding refused: %v", err) |
| 161 | } |
| 162 | defer again.Close() |
| 163 | w := again.DBForTest() |
| 164 | if _, err := w.Exec("DELETE FROM calendar_team_required"); err == nil { |
| 165 | t.Fatal("the marker was deleted") |
| 166 | } |
| 167 | if _, err := w.Exec("UPDATE calendar_team_required SET bindings = 'x'"); err == nil { |
| 168 | t.Fatal("the marker was rewritten") |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| 173 | // Named here, not read from teamIssuerTables: a list that lost a table |
| 174 | // would otherwise lose its test with it. |
| 175 | for _, table := range []string{"home_identity_links", "calendar_team_home_people"} { |
| 176 | t.Run(table, func(t *testing.T) { |
| 177 | f := newTeamFixture(t) |
| 178 | f.app.Close() |
| 179 | // A fresh database, migrated in team mode's shape but not yet |
| 180 | // activated, holding one row from another issuer. |
| 181 | dbPath := filepath.Join(t.TempDir(), "calendar.db") |
| 182 | cfg := f.cfg |
| 183 | cfg.DBPath = dbPath |
| 184 | d := teamMigratedNotActivated(t, dbPath) |
| 185 | w := d.Writer() |
| 186 | var person int64 |
| 187 | if table == "calendar_team_home_people" { |
| 188 | res, err := w.Exec(`INSERT INTO people(address,zone,created_at,updated_at,week_start,default_reminder_min,default_all_day_min) VALUES('home-only:x','UTC',0,0,1,0,0)`) |
| 189 | if err != nil { |
| 190 | t.Fatal(err) |
| 191 | } |
| 192 | person, _ = res.LastInsertId() |
| 193 | } else { |
| 194 | person = 99 |
| 195 | } |
| 196 | if _, err := w.Exec("INSERT INTO "+table+"(issuer,subject,person_id) VALUES('https://id.elsewhere.test',?,?)", teamSubject('q'), person); err != nil { |
| 197 | t.Fatal(err) |
| 198 | } |
| 199 | d.Close() |
| 200 | if a, err := New(cfg); err == nil { |
| 201 | a.Close() |
| 202 | t.Fatalf("a foreign issuer in %s was accepted", table) |
| 203 | } else if !errors.Is(err, teammode.ErrConfig) { |
| 204 | t.Fatalf("refused for another reason: %v", err) |
| 205 | } |
| 206 | if markerFor(t, dbPath) { |
| 207 | t.Fatal("a refused census wrote the marker") |
| 208 | } |
| 209 | }) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | func TestTeamProbeOffSaysOnlyThat(t *testing.T) { |
| 214 | a := NewForTest(t, t.TempDir()) |
| 215 | w := httptest.NewRecorder() |
| 216 | a.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/api/team", nil)) |
| 217 | if w.Code != http.StatusOK || strings.TrimSpace(w.Body.String()) != `{"team_mode":false}` || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| 218 | t.Fatalf("probe off = %d %q %q", w.Code, w.Body.String(), w.Header().Get("Cache-Control")) |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | func TestTeamProbeStatesAndNoAccountData(t *testing.T) { |
| 223 | f := newTeamFixture(t) |
| 224 | probe := func() map[string]any { |
| 225 | t.Helper() |
| 226 | w := httptest.NewRecorder() |
| 227 | f.app.Handler().ServeHTTP(w, httptest.NewRequest("GET", homeTestOrigin+"/api/team", nil)) |
| 228 | if w.Code != http.StatusOK || !strings.Contains(w.Header().Get("Cache-Control"), "no-store") { |
| 229 | t.Fatalf("probe = %d", w.Code) |
| 230 | } |
| 231 | var out map[string]any |
| 232 | if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { |
| 233 | t.Fatal(err) |
| 234 | } |
| 235 | for k := range out { |
| 236 | if k != "team_mode" && k != "consumer" && k != "roster" { |
| 237 | t.Fatalf("probe carries %q", k) |
| 238 | } |
| 239 | } |
| 240 | if strings.Contains(w.Body.String(), teamSubject('p')) || strings.Contains(w.Body.String(), "TeamA") { |
| 241 | t.Fatal("probe names a member or the team") |
| 242 | } |
| 243 | return out |
| 244 | } |
| 245 | f.dir.SetDown(true) |
| 246 | if got := probe(); got["team_mode"] != true || got["consumer"] != teamTestConsumer || got["roster"] != "unknown" { |
| 247 | t.Fatalf("probe before any roster = %v", got) |
| 248 | } |
| 249 | f.dir.SetDown(false) |
| 250 | f.clock.Step(10 * time.Second) |
| 251 | if got := probe(); got["roster"] != "ok" { |
| 252 | t.Fatalf("probe with a roster = %v", got) |
| 253 | } |
| 254 | f.member(teamSubject('p'), "owner") |
| 255 | if got := probe(); got["roster"] != "ok" { |
| 256 | t.Fatalf("probe after a member's request = %v", got) |
| 257 | } |
| 258 | f.expired() |
| 259 | if got := probe(); got["roster"] != "stale" { |
| 260 | t.Fatalf("probe past the lease = %v", got) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // teamMigratedNotActivated opens a fresh database at dbPath with every |
| 265 | // set team mode applies — Calendar's, Home's, teammode's marker and the |
| 266 | // Home-only people — and no marker written. |
| 267 | func teamMigratedNotActivated(t *testing.T, dbPath string) *db.DB { |
| 268 | t.Helper() |
| 269 | d, err := db.Open(dbPath, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 270 | if err != nil { |
| 271 | t.Fatal(err) |
| 272 | } |
| 273 | base := migrate.Merge(BootSchema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| 274 | if _, err := migrate.Apply(context.Background(), d, teamBoot(base)); err != nil { |
| 275 | t.Fatal(err) |
| 276 | } |
| 277 | return d |
| 278 | } |
| 279 | |