| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "net/url" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | |
| 16 | "amadan.net/oficina/home/roster" |
| 17 | "amadan.net/oficina/home/teammode" |
| 18 | "amadan.net/rastrillo/rastrillo/migrate" |
| 19 | ) |
| 20 | |
| 21 | // The record is verified against bindings built only from configuration: |
| 22 | // Home's issuer and consumer ID, the app, the team, the directory and |
| 23 | // this instance's origin. A record signed for any other value of any one |
| 24 | // of them refuses boot, before anything migrates. |
| 25 | func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { |
| 26 | key := teamKey(t) |
| 27 | cases := map[string]func(*roster.Bindings, *teammode.Config){ |
| 28 | "issuer": func(b *roster.Bindings, _ *teammode.Config) { b.Issuer = "https://id.other.example" }, |
| 29 | "consumer": func(b *roster.Bindings, _ *teammode.Config) { b.Consumer = "another-consumer" }, |
| 30 | "app": func(b *roster.Bindings, _ *teammode.Config) { b.App = "sheets" }, |
| 31 | "origin": func(b *roster.Bindings, _ *teammode.Config) { b.Audience = "https://other.example.com" }, |
| 32 | "team": func(_ *roster.Bindings, c *teammode.Config) { c.TeamID = "TeamB" }, |
| 33 | "directory": func(_ *roster.Bindings, c *teammode.Config) { c.DirectoryOrigin = "https://dir.other.example" }, |
| 34 | } |
| 35 | for name, change := range cases { |
| 36 | t.Run(name, func(t *testing.T) { |
| 37 | b := teamTestBindings(homeTestOrigin) |
| 38 | change(&b, &teammode.Config{}) |
| 39 | cfg, _, _ := teamConfigFor(t, b, key) |
| 40 | // The instance's own configuration, whatever the record says. |
| 41 | cfg.Origin = homeTestOrigin |
| 42 | change(&roster.Bindings{}, cfg.Team) |
| 43 | d := teamDB(t) |
| 44 | if _, _, _, err := bootTeam(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { |
| 45 | t.Fatalf("a record for another %s = %v, want ErrConfig", name, err) |
| 46 | } |
| 47 | if _, activated, _ := teamState.Required(context.Background(), d.Writer()); activated { |
| 48 | t.Fatal("a refused record left a marker") |
| 49 | } |
| 50 | var tables int |
| 51 | d.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='documents'").Scan(&tables) |
| 52 | if tables != 0 { |
| 53 | t.Fatal("a refused record migrated the database") |
| 54 | } |
| 55 | }) |
| 56 | } |
| 57 | // And the right record boots. |
| 58 | cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| 59 | if _, _, _, err := bootTeam(t, teamDB(t), cfg); err != nil { |
| 60 | t.Fatalf("the instance's own record: %v", err) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | // teamEnv is an environment LoadConfig accepts, with team configuration |
| 65 | // for bindings b when team is true. |
| 66 | func teamEnv(t *testing.T, team bool, owners string) map[string]string { |
| 67 | t.Helper() |
| 68 | key := teamKey(t) |
| 69 | cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| 70 | keys, _ := json.Marshal(map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}) |
| 71 | env := map[string]string{ |
| 72 | "MEMORIA_DEK": base64.StdEncoding.EncodeToString(make([]byte, 32)), |
| 73 | "MEMORIA_INSTANCE_KEY": "k", |
| 74 | "MEMORIA_ALLOW_LOGGED_MAIL": "1", |
| 75 | "MEMORIA_ORIGIN": homeTestOrigin, |
| 76 | "MEMORIA_OWNERS": owners, |
| 77 | "MEMORIA_HOME_ISSUER": homeTestIssuer, |
| 78 | "MEMORIA_HOME_CONSUMER_ID": teamTestConsumer, |
| 79 | "MEMORIA_HOME_KEYS_BASE64": base64.StdEncoding.EncodeToString(keys), |
| 80 | "MEMORIA_HOME_DEK_BASE64": base64.StdEncoding.EncodeToString(make([]byte, 32)), |
| 81 | } |
| 82 | if team { |
| 83 | names := teammode.EnvNames("MEMORIA") |
| 84 | for i, v := range []string{cfg.Team.TeamID, cfg.Team.DirectoryOrigin, cfg.Team.ProvisioningBase64, cfg.Team.OperatorKeysBase64, cfg.Team.RosterToken} { |
| 85 | env[names[i]] = v |
| 86 | } |
| 87 | } |
| 88 | return env |
| 89 | } |
| 90 | |
| 91 | // Five variables, all or none, and only beside Home. One present is a |
| 92 | // configuration, and an invalid one: there is no falling back to the |
| 93 | // owners list. In team mode MEMORIA_OWNERS is optional, and empty admits |
| 94 | // nobody locally; outside it, it is still required. MEMORIA_AI stays off |
| 95 | // unless asked for, team mode or not (Paul's ruling for team instances). |
| 96 | // |
| 97 | // MUTATION-TESTED 2026-10-30, each seen red and reverted: the owners |
| 98 | // check made unconditional ("owners optional"); the Home requirement |
| 99 | // dropped ("team without Home"). |
| 100 | func TestTeamEnvIsAllOrNoneAndTheOwnersListBecomesOptional(t *testing.T) { |
| 101 | names := teammode.EnvNames("MEMORIA") |
| 102 | if names != [5]string{"MEMORIA_TEAM_ID", "MEMORIA_TEAM_DIRECTORY_ORIGIN", "MEMORIA_TEAM_PROVISIONING_BASE64", "MEMORIA_TEAM_OPERATOR_KEYS_BASE64", "MEMORIA_TEAM_ROSTER_TOKEN"} { |
| 103 | t.Fatalf("env names = %v", names) |
| 104 | } |
| 105 | key := teamKey(t) |
| 106 | for _, only := range names { |
| 107 | env := teamEnv(t, false, "owner@example.test") |
| 108 | env[only] = "x" |
| 109 | c, err := LoadConfig(func(n string) string { return env[n] }) |
| 110 | if err != nil { |
| 111 | t.Fatalf("%s alone: LoadConfig = %v", only, err) |
| 112 | } |
| 113 | if c.Team == nil { |
| 114 | t.Fatalf("%s alone read as team mode off", only) |
| 115 | } |
| 116 | cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| 117 | cfg.Team = c.Team |
| 118 | if _, _, _, err := bootTeam(t, teamDB(t), cfg); !errors.Is(err, teammode.ErrConfig) { |
| 119 | t.Fatalf("%s alone = %v, want ErrConfig", only, err) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // Team mode, no owners list: loads, and AI is off. |
| 124 | env := teamEnv(t, true, "") |
| 125 | c, err := LoadConfig(func(n string) string { return env[n] }) |
| 126 | if err != nil || c.Team == nil { |
| 127 | t.Fatalf("team mode with no owners list: %+v, %v", c.Team, err) |
| 128 | } |
| 129 | if c.AI || c.TensorXKey != "" { |
| 130 | t.Fatal("team mode switched AI on") |
| 131 | } |
| 132 | // The same without team mode is still a refusal. |
| 133 | env = teamEnv(t, false, "") |
| 134 | if _, err := LoadConfig(func(n string) string { return env[n] }); !errors.Is(err, ErrMissing) { |
| 135 | t.Fatalf("no owners list outside team mode = %v, want ErrMissing", err) |
| 136 | } |
| 137 | // Team mode requires Home. |
| 138 | env = teamEnv(t, true, "") |
| 139 | for _, n := range []string{"MEMORIA_HOME_ISSUER", "MEMORIA_HOME_CONSUMER_ID", "MEMORIA_HOME_KEYS_BASE64", "MEMORIA_HOME_DEK_BASE64"} { |
| 140 | delete(env, n) |
| 141 | } |
| 142 | if _, err := LoadConfig(func(n string) string { return env[n] }); err == nil { |
| 143 | t.Fatal("team mode without Home loaded") |
| 144 | } |
| 145 | cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| 146 | cfg.Home = nil |
| 147 | if _, _, _, err := bootTeam(t, teamDB(t), cfg); !errors.Is(err, teammode.ErrConfig) { |
| 148 | t.Fatalf("team mode without Home at boot = %v, want ErrConfig", err) |
| 149 | } |
| 150 | |
| 151 | // Booted with no owners list, the local sign-in admits nobody, and |
| 152 | // the guard answers a stranger's "sent" rather than failing closed |
| 153 | // as a misconfiguration. |
| 154 | f := newTeamFixture(t) |
| 155 | if f.app.Admit("anyone@example.test") { |
| 156 | t.Fatal("an empty team-mode owners list admits an address") |
| 157 | } |
| 158 | w := f.do("POST", "/auth/begin", "address=anyone%40example.test") |
| 159 | if loc, _ := url.Parse(w.Header().Get("Location")); w.Code != http.StatusSeeOther || loc == nil || loc.Path != "/signin" || |
| 160 | loc.Query().Get("sent") != "1" || loc.Query().Get("attempt") == "" { |
| 161 | t.Fatalf("local sign-in with no owners list = %d %q, want the stranger's Sent (rastrillo's AnswerAsSent)", w.Code, w.Header().Get("Location")) |
| 162 | } |
| 163 | if f.mail.body != "" { |
| 164 | t.Fatal("a sign-in link was sent") |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // The marker locks a database into team mode: once activated it refuses |
| 169 | // to boot without team configuration, or with another binding, before |
| 170 | // anything migrates; the same binding boots again. Its namespace is |
| 171 | // memoria_team. |
| 172 | func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| 173 | key := teamKey(t) |
| 174 | d := teamDB(t) |
| 175 | cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| 176 | if _, _, _, err := bootTeam(t, d, cfg); err != nil { |
| 177 | t.Fatal(err) |
| 178 | } |
| 179 | fp, activated, err := teamState.Required(context.Background(), d.Writer()) |
| 180 | if err != nil || !activated || fp != teammode.Fingerprint(teamTestBindings(homeTestOrigin)) { |
| 181 | t.Fatalf("marker = %q %v %v", fp, activated, err) |
| 182 | } |
| 183 | var set int |
| 184 | d.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='memoria_team_required'").Scan(&set) |
| 185 | if set != 1 { |
| 186 | t.Fatal("the marker is not in the memoria_team namespace") |
| 187 | } |
| 188 | |
| 189 | off := cfg |
| 190 | off.Team = nil |
| 191 | if _, _, _, err := bootTeam(t, d, off); !errors.Is(err, teammode.ErrConfig) { |
| 192 | t.Fatalf("activated database without team configuration = %v, want ErrConfig", err) |
| 193 | } |
| 194 | // Refused before anything migrated: App's plain path too. |
| 195 | if _, _, err := App(d, homeTestOrigin, teamSealer(t), slogDiscard()); !errors.Is(err, teammode.ErrConfig) { |
| 196 | t.Fatalf("activated database through App = %v, want ErrConfig", err) |
| 197 | } |
| 198 | other := teamTestBindings(homeTestOrigin) |
| 199 | other.Team = "TeamB" |
| 200 | rebound, _, _ := teamConfigFor(t, other, key) |
| 201 | if _, _, _, err := bootTeam(t, d, rebound); !errors.Is(err, teammode.ErrConfig) { |
| 202 | t.Fatalf("activated database with another binding = %v, want ErrConfig", err) |
| 203 | } |
| 204 | if _, _, _, err := bootTeam(t, d, cfg); err != nil { |
| 205 | t.Fatalf("the same binding again: %v", err) |
| 206 | } |
| 207 | if _, err := d.Writer().Exec("UPDATE memoria_team_required SET bindings='x'"); err == nil { |
| 208 | t.Fatal("the marker was rewritten") |
| 209 | } |
| 210 | if _, err := d.Writer().Exec("DELETE FROM memoria_team_required"); err == nil { |
| 211 | t.Fatal("the marker was deleted") |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // The census: a Home identity from another issuer, in either table that |
| 216 | // holds one, refuses activation, and no marker is written. |
| 217 | func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| 218 | key := teamKey(t) |
| 219 | for _, table := range []string{"home_identity_links", "memoria_team_home_members"} { |
| 220 | t.Run(table, func(t *testing.T) { |
| 221 | d := teamDB(t) |
| 222 | cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| 223 | // The team schema applied and never activated: what a boot |
| 224 | // refused after migrating leaves behind. |
| 225 | if _, err := migrate.Apply(context.Background(), d, teamBoot(BootSchema)); err != nil { |
| 226 | t.Fatal(err) |
| 227 | } |
| 228 | if _, err := d.Writer().Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('home-only:x',X'')"); err != nil { |
| 229 | t.Fatal(err) |
| 230 | } |
| 231 | if _, err := d.Writer().Exec("INSERT INTO "+table+"(issuer,subject,person_id) VALUES('https://id.other.example',?,1)", teamSubject('f')); err != nil { |
| 232 | t.Fatal(err) |
| 233 | } |
| 234 | if _, _, _, err := bootTeam(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { |
| 235 | t.Fatalf("a %s row from another issuer = %v, want ErrConfig", table, err) |
| 236 | } |
| 237 | if _, activated, _ := teamState.Required(context.Background(), d.Writer()); activated { |
| 238 | t.Fatal("a refused census left a marker") |
| 239 | } |
| 240 | }) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | // Team mode off: GET /api/team says only that, no-store, and nothing |
| 245 | // team mode adds is in the database. Paul's own instance is this. |
| 246 | func TestTeamProbeOffSaysOnlyThat(t *testing.T) { |
| 247 | f := newHomeRouterFixture(t) |
| 248 | w := f.do("GET", "/api/team", "") |
| 249 | if w.Code != 200 || strings.TrimSpace(w.Body.String()) != `{"team_mode":false}` || w.Header().Get("Cache-Control") != "no-store" { |
| 250 | t.Fatalf("probe off = %d %q %v", w.Code, w.Body.String(), w.Header()) |
| 251 | } |
| 252 | var n int |
| 253 | f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE name LIKE 'memoria_team%'").Scan(&n) |
| 254 | if n != 0 { |
| 255 | t.Fatalf("team mode off created %d team tables or triggers", n) |
| 256 | } |
| 257 | if f.app.teamMode() || f.app.store.team { |
| 258 | t.Fatal("team mode off reads as on") |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | // The probe in team mode: unauthenticated, no-store, the same body |
| 263 | // whoever asks, {team_mode, consumer, roster} and nothing else, through |
| 264 | // its three states. |
| 265 | func TestTeamProbeStatesAndNoAccountData(t *testing.T) { |
| 266 | f := newTeamFixture(t) |
| 267 | probe := func() map[string]any { |
| 268 | t.Helper() |
| 269 | r := httptest.NewRequest("GET", homeTestOrigin+"/api/team", nil) |
| 270 | w := httptest.NewRecorder() |
| 271 | f.handler.ServeHTTP(w, r) |
| 272 | if w.Code != 200 || w.Header().Get("Cache-Control") != "no-store" { |
| 273 | t.Fatalf("probe = %d %v", w.Code, w.Header()) |
| 274 | } |
| 275 | raw, _ := io.ReadAll(w.Body) |
| 276 | var out map[string]any |
| 277 | if err := json.Unmarshal(raw, &out); err != nil { |
| 278 | t.Fatal(err) |
| 279 | } |
| 280 | for k := range out { |
| 281 | if k != "team_mode" && k != "consumer" && k != "roster" { |
| 282 | t.Fatalf("probe carries %q", k) |
| 283 | } |
| 284 | } |
| 285 | if strings.Contains(string(raw), teamSubject('a')) || strings.Contains(string(raw), "TeamA") { |
| 286 | t.Fatalf("probe leaks the team or a member: %s", raw) |
| 287 | } |
| 288 | return out |
| 289 | } |
| 290 | f.member(teamSubject('a'), "owner") |
| 291 | if got := probe(); got["team_mode"] != true || got["consumer"] != teamTestConsumer || got["roster"] != "ok" { |
| 292 | t.Fatalf("probe = %v", got) |
| 293 | } |
| 294 | f.expired() |
| 295 | if got := probe()["roster"]; got == "ok" { |
| 296 | t.Fatalf("probe roster after the lease = %v", got) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | func slogDiscard() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } |
| 301 | |