package calls import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "path/filepath" "strings" "testing" "amadan.net/oficina/home/roster" "amadan.net/oficina/home/teammode" assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/rastrillo/rastrillo/migrate" ) // tableExists reports whether path's database has table, read without the // app. func tableExists(t *testing.T, path, table string) bool { t.Helper() d := openTeamDB(t, path) var n int if err := d.Writer().QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", table).Scan(&n); err != nil { t.Fatal(err) } return n == 1 } // markerFor reports whether path holds an activation marker. func markerFor(t *testing.T, path string) bool { t.Helper() d := openTeamDB(t, path) _, activated, err := teamState.Required(context.Background(), d.Writer()) if err != nil { t.Fatal(err) } return activated } // bootAt builds the app over path with cfg, returning the error. func bootAt(t *testing.T, path string, cfg Config) error { t.Helper() d := openTeamDB(t, path) _, _, err := buildForTest(t, d, cfg) return err } func TestTeamEnvNamesAreTheFive(t *testing.T) { want := [5]string{"CALLS_TEAM_ID", "CALLS_TEAM_DIRECTORY_ORIGIN", "CALLS_TEAM_PROVISIONING_BASE64", "CALLS_TEAM_OPERATOR_KEYS_BASE64", "CALLS_TEAM_ROSTER_TOKEN"} if got := teammode.EnvNames("CALLS"); got != want { t.Fatalf("CALLS team variables %v", got) } if teammode.ConfigFromLookup("CALLS", func(string) string { return "" }) != nil { t.Fatal("no team variables read as team mode") } } // Every binding the provisioning record names is pinned: one signed for // another issuer, consumer, app, origin, team or directory refuses boot // before anything migrates, and writes no marker. func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { key, err := assertioncrypto.Generate() if err != nil { t.Fatal(err) } for name, mutate := range map[string]func(*roster.Bindings){ "issuer": func(b *roster.Bindings) { b.Issuer = "https://id.elsewhere.test" }, "consumer": func(b *roster.Bindings) { b.Consumer = "someone-else" }, "app": func(b *roster.Bindings) { b.App = "calendar" }, "origin": func(b *roster.Bindings) { b.Audience = "https://calls.elsewhere.test" }, "team": func(b *roster.Bindings) { b.Team = "TeamB" }, "directory": func(b *roster.Bindings) { b.Directory = "https://home.elsewhere.test" }, } { t.Run(name, func(t *testing.T) { b := teamTestBindings() mutate(&b) cfg, _, _ := teamConfigFor(t, b, key) if name == "team" || name == "directory" { // The record names the team and directory; the // instance's own configuration must name the same ones. good, _, _ := teamConfigFor(t, teamTestBindings(), key) good.Team.ProvisioningBase64 = cfg.Team.ProvisioningBase64 good.Team.OperatorKeysBase64 = cfg.Team.OperatorKeysBase64 cfg = good } path := filepath.Join(t.TempDir(), "calls.db") if err := bootAt(t, path, cfg); !errors.Is(err, teammode.ErrConfig) { t.Fatalf("a record signed for another %s: %v", name, err) } if tableExists(t, path, "persons") || markerFor(t, path) { t.Fatalf("a refused %s migrated or wrote the marker", name) } }) } } func TestTeamEnvIsAllOrNoneAndNeedsHome(t *testing.T) { key, _ := assertioncrypto.Generate() for _, name := range teammode.EnvNames("CALLS") { env := map[string]string{} for _, n := range teammode.EnvNames("CALLS") { env[n] = "x" } delete(env, name) c := teammode.ConfigFromLookup("CALLS", func(k string) string { return env[k] }) if c == nil { t.Fatalf("four of five (%s missing) read as team mode off", name) } cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) cfg.Team = c path := filepath.Join(t.TempDir(), "calls.db") if err := bootAt(t, path, cfg); err == nil { t.Fatalf("four of five (%s missing) booted", name) } if tableExists(t, path, "persons") { t.Fatalf("four of five (%s missing) migrated", name) } } cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) cfg.Home = nil if err := bootAt(t, filepath.Join(t.TempDir(), "calls.db"), cfg); err == nil { t.Fatal("team mode booted without Home") } } func TestTeamTheAllowlistBecomesOptionalAndAdmitsOnlyLocally(t *testing.T) { team := &teammode.Config{TeamID: "TeamA"} for _, env := range []string{"production", EnvDevelopment} { list, err := resolveAllowlist(Config{Env: env, Team: team}) if err != nil { t.Fatalf("%s team mode with no allowlist: %v", env, err) } // Never the development default that admits everyone. if list.addrs == nil || list.allows("anyone@example.test") { t.Fatalf("an empty %s team allowlist admits somebody locally", env) } list, err = resolveAllowlist(Config{Env: env, Team: team, AllowedAddresses: []string{"alice@example.test"}}) if err != nil || !list.allows("alice@example.test") || list.allows("bob@example.test") { t.Fatalf("a %s team allowlist is not the local door: %v", env, err) } } if _, err := resolveAllowlist(Config{Env: "production"}); err == nil { t.Fatal("production without team mode accepted no allowlist") } // Alta's shape: no allowlist at all, in production. It boots, and // the local door admits nobody. key, _ := assertioncrypto.Generate() cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) cfg.AllowedAddresses = nil _, a, err := buildForTest(t, openTeamDB(t, filepath.Join(t.TempDir(), "calls.db")), cfg) if err != nil { t.Fatalf("team mode with no allowlist: %v", err) } if a.authorize("anyone@example.test") { t.Fatal("an empty team allowlist admits an address at the local door") } } // Once activated, a database refuses to boot without team configuration // or with another binding, before anything migrates; the marker's // triggers refuse a rewrite. func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { f := newTeamFixture(t) if !markerFor(t, f.dbPath) { t.Fatal("team mode wrote no marker") } off := f.cfg off.Team = nil if err := bootAt(t, f.dbPath, off); err == nil { t.Fatal("an activated database booted without team mode") } key, _ := assertioncrypto.Generate() b := teamTestBindings() b.Team = "TeamB" other, _, _ := teamConfigFor(t, b, key) other.Team.TeamID = "TeamB" if err := bootAt(t, f.dbPath, other); err == nil { t.Fatal("an activated database booted with another team's binding") } if err := bootAt(t, f.dbPath, f.cfg); err != nil { t.Fatalf("the same binding refused: %v", err) } for _, stmt := range []string{"UPDATE calls_team_required SET fingerprint='x'", "DELETE FROM calls_team_required"} { if _, err := f.app.db.Writer().Exec(stmt); err == nil { t.Fatalf("%s: allowed", stmt) } } } // The census: a Home identity from another issuer in either table refuses // activation, and no marker is written. The tables are named here, not // read from teamIssuerTables: a list that lost a table would otherwise // lose its test with it. func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { for _, table := range []string{"home_identity_links", "calls_team_home_persons"} { t.Run(table, func(t *testing.T) { key, _ := assertioncrypto.Generate() cfg, _, _ := teamConfigFor(t, teamTestBindings(), key) // A database migrated in team mode's shape but not yet // activated, holding one row from another issuer. path := filepath.Join(t.TempDir(), "calls.db") d := openTeamDB(t, path) if _, err := migrate.Apply(context.Background(), d, teamBoot(BootSchema)); err != nil { t.Fatal(err) } w := d.Writer() res, err := w.Exec("INSERT INTO persons(email,name,created_at,anonymous) VALUES('home-only:00','n',0,0)") if err != nil { t.Fatal(err) } person, _ := res.LastInsertId() if _, err := w.Exec("INSERT INTO "+table+"(issuer,subject,person_id) VALUES('https://id.elsewhere.test',?,?)", teamSubject('q'), person); err != nil { t.Fatal(err) } if _, _, err := buildForTest(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { t.Fatalf("a foreign issuer in %s: %v", table, err) } if markerFor(t, path) { t.Fatalf("a refused census in %s wrote the marker", table) } }) } } // GET /api/team: {"team_mode":false} off; on, only {team_mode, consumer, // roster} with the roster's three states, no-store, whoever asks. func TestTeamProbeSaysOnlyItsState(t *testing.T) { probe := func(h http.Handler) (map[string]any, *httptest.ResponseRecorder) { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest("GET", homeTestOrigin+"/api/team", nil)) var body map[string]any if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { t.Fatalf("probe body %q", w.Body.String()) } if w.Code != http.StatusOK || w.Header().Get("Cache-Control") != "no-store" { t.Fatalf("probe = %d %q", w.Code, w.Header().Get("Cache-Control")) } return body, w } off := newHomeRouterFixture(t) if body, w := probe(off.handler); len(body) != 1 || body["team_mode"] != false { t.Fatalf("team mode off: %s", w.Body.String()) } f := newTeamFixture(t) f.dir.SetDown(true) if body, _ := probe(f.handler); body["roster"] != "unknown" { t.Fatalf("before any roster: %v", body) } f.refreshed() body, w := probe(f.handler) if len(body) != 3 || body["team_mode"] != true || body["consumer"] != teamTestConsumer || body["roster"] != "ok" { t.Fatalf("roster held: %s", w.Body.String()) } for _, leak := range []string{"TeamA", homeTestIssuer, "pr_", "@"} { if strings.Contains(w.Body.String(), leak) { t.Fatalf("the probe says %q: %s", leak, w.Body.String()) } } f.expired() if body, _ := probe(f.handler); body["roster"] != "stale" { t.Fatalf("aged out: %v", body) } }