| 1 | package teammode_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/home/roster" |
| 11 | "amadan.net/oficina/home/teammode" |
| 12 | "amadan.net/oficina/home/teammode/teammodetest" |
| 13 | ) |
| 14 | |
| 15 | func TestOpenRefusesAForeignIssuerAndWritesNoMarker(t *testing.T) { |
| 16 | ctx := context.Background() |
| 17 | for _, table := range issuerTables { |
| 18 | t.Run(table, func(t *testing.T) { |
| 19 | f := provisioned(t) |
| 20 | if _, err := migrateTeam(f); err != nil { |
| 21 | t.Fatal(err) |
| 22 | } |
| 23 | if _, err := f.db.Writer().Exec("INSERT INTO " + table + "(issuer,subject,person_id) VALUES('https://other.example.com','pr_x',1)"); err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | if _, err := f.open(); !errors.Is(err, teammode.ErrConfig) { |
| 27 | t.Fatalf("foreign issuer in %s: %v", table, err) |
| 28 | } |
| 29 | if _, ok, _ := testState.Required(ctx, f.db.Writer()); ok { |
| 30 | t.Fatal("refused activation wrote the marker") |
| 31 | } |
| 32 | }) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | func TestOpenRefusesIncompleteConfigurationAndBadTables(t *testing.T) { |
| 37 | f := provisioned(t) |
| 38 | if _, err := migrateTeam(f); err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | for name, mutate := range map[string]func(*teammode.RuntimeConfig){ |
| 42 | "no settings": func(c *teammode.RuntimeConfig) { c.Settings = nil }, |
| 43 | "zero state": func(c *teammode.RuntimeConfig) { c.State = teammode.State{} }, |
| 44 | "no db": func(c *teammode.RuntimeConfig) { c.DB = nil }, |
| 45 | "no sealer": func(c *teammode.RuntimeConfig) { c.Sealer = nil }, |
| 46 | "no census": func(c *teammode.RuntimeConfig) { c.IssuerTables = nil }, |
| 47 | "injected table": func(c *teammode.RuntimeConfig) { c.IssuerTables = []string{"people; DROP TABLE people"} }, |
| 48 | } { |
| 49 | c := f.runtimeConfig() |
| 50 | mutate(&c) |
| 51 | if _, err := teammode.Open(context.Background(), c); !errors.Is(err, teammode.ErrConfig) { |
| 52 | t.Errorf("%s: %v", name, err) |
| 53 | } |
| 54 | } |
| 55 | if _, ok, _ := testState.Required(context.Background(), f.db.Writer()); ok { |
| 56 | t.Fatal("a refused Open wrote the marker") |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // Open activates: the marker is written before the runtime exists, and from |
| 61 | // then on the database will not boot without this binding. |
| 62 | func TestOpenActivates(t *testing.T) { |
| 63 | f := newFixture(t) |
| 64 | ctx := context.Background() |
| 65 | if fp, ok, err := testState.Required(ctx, f.db.Writer()); err != nil || !ok || fp != f.settings.Fingerprint() { |
| 66 | t.Fatal("Open did not write the marker") |
| 67 | } |
| 68 | if _, err := testState.BootSchema(ctx, f.db.Writer(), nil, baseSchema, teamSchema); !errors.Is(err, teammode.ErrConfig) { |
| 69 | t.Fatal("activated database boots without team configuration") |
| 70 | } |
| 71 | if _, err := f.open(); err != nil { |
| 72 | t.Fatalf("reopen with the same binding: %v", err) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // A second deployment with another binding cannot take over an activated |
| 77 | // database, even past BootSchema. |
| 78 | func TestOpenRefusesADifferentBinding(t *testing.T) { |
| 79 | f := newFixture(t) |
| 80 | b := f.bindings |
| 81 | b.Team = "TeamB" |
| 82 | cfg, _ := teammodetest.Provision(t, b) |
| 83 | s, err := teammode.Verify(cfg, teammodetest.Home(b), testApp, testOrigin) |
| 84 | if err != nil { |
| 85 | t.Fatal(err) |
| 86 | } |
| 87 | c := f.runtimeConfig() |
| 88 | c.Settings = s |
| 89 | if _, err := teammode.Open(context.Background(), c); !errors.Is(err, teammode.ErrConfig) { |
| 90 | t.Fatalf("rebinding Open: %v", err) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | func TestAccessFollowsTheRostersRole(t *testing.T) { |
| 95 | f := newFixture(t) |
| 96 | f.dir.Set(alice, "owner") |
| 97 | f.dir.Set(bob, "member") |
| 98 | f.refreshed() |
| 99 | ctx := context.Background() |
| 100 | a := f.rt.Access(ctx, alice) |
| 101 | if a.State() != roster.Member || a.Role() != "owner" || a.Subject() != alice || a.Partial() { |
| 102 | t.Fatalf("owner: %d %q", a.State(), a.Role()) |
| 103 | } |
| 104 | b := f.rt.Access(ctx, bob) |
| 105 | if b.State() != roster.Member || b.Role() != "member" { |
| 106 | t.Fatalf("member: %d %q", b.State(), b.Role()) |
| 107 | } |
| 108 | c := f.rt.Access(ctx, carol) |
| 109 | if c.State() != roster.NotMember || c.Role() != "" || c.Remaining() != 0 || c.Partial() { |
| 110 | t.Fatal("stranger has standing") |
| 111 | } |
| 112 | fetches := f.dir.Fetches() |
| 113 | none := f.rt.Access(ctx, "") |
| 114 | if none.State() != roster.NotMember || none.Role() != "" || f.dir.Fetches() != fetches { |
| 115 | t.Fatal("no Home identity asked the roster or had standing") |
| 116 | } |
| 117 | var nilAccess *teammode.Access |
| 118 | if nilAccess.State() != roster.Unknown || nilAccess.Role() != "" || !nilAccess.Partial() || nilAccess.Remaining() != 0 { |
| 119 | t.Fatal("a nil Access has standing") |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // Removal reaches a held decision within the 60 s lease, under a failing |
| 124 | // refresh, and the request never sees Member again once it has seen Unknown. |
| 125 | func TestHeldDecisionEndsAtTheLeaseAndLatches(t *testing.T) { |
| 126 | f := newFixture(t) |
| 127 | f.dir.Set(alice, "member") |
| 128 | f.refreshed() |
| 129 | a := f.rt.Access(context.Background(), alice) |
| 130 | if a.Remaining() != roster.MaximumAge { |
| 131 | t.Fatalf("remaining %v", a.Remaining()) |
| 132 | } |
| 133 | f.dir.SetDown(true) |
| 134 | f.clock.Step(59 * time.Second) |
| 135 | if a.State() != roster.Member || a.Role() != "member" || a.Remaining() != time.Second { |
| 136 | t.Fatal("early expiry") |
| 137 | } |
| 138 | f.clock.Step(2 * time.Second) |
| 139 | if a.State() != roster.Unknown || a.Role() != "" || !a.Partial() || a.Remaining() != 0 { |
| 140 | t.Fatal("standing survived the lease") |
| 141 | } |
| 142 | // The directory is back and a refresh lands: this request's Access |
| 143 | // stays Unknown; the next request's is Member. |
| 144 | f.dir.SetDown(false) |
| 145 | f.clock.Step(roster.RetryAfter) |
| 146 | if err := f.rt.Refresh(context.Background()); err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | if a.State() != roster.Unknown { |
| 150 | t.Fatal("Unknown did not latch") |
| 151 | } |
| 152 | if f.rt.Access(context.Background(), alice).State() != roster.Member { |
| 153 | t.Fatal("next request not decided afresh") |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | // Remaining latches too: a stream that finds its lease gone must not then |
| 158 | // read Member from State. |
| 159 | func TestRemainingLatches(t *testing.T) { |
| 160 | f := newFixture(t) |
| 161 | f.dir.Set(alice, "member") |
| 162 | f.refreshed() |
| 163 | a := f.rt.Access(context.Background(), alice) |
| 164 | f.dir.SetDown(true) |
| 165 | f.clock.Step(roster.MaximumAge) |
| 166 | if a.Remaining() != 0 { |
| 167 | t.Fatal("lapsed lease has time left") |
| 168 | } |
| 169 | if a.State() != roster.Unknown { |
| 170 | t.Fatal("Remaining did not latch") |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // #97 at the package level: a refresh that still lists the person with the |
| 175 | // same role keeps a held decision; a removal or a role change ends it at |
| 176 | // the refresh, not at the lease's end. |
| 177 | func TestHeldDecisionAcrossARefresh(t *testing.T) { |
| 178 | f := newFixture(t) |
| 179 | f.dir.Set(alice, "member") |
| 180 | f.dir.Set(bob, "member") |
| 181 | f.dir.Set(carol, "member") |
| 182 | f.refreshed() |
| 183 | ctx := context.Background() |
| 184 | a, b, c := f.rt.Access(ctx, alice), f.rt.Access(ctx, bob), f.rt.Access(ctx, carol) |
| 185 | f.dir.Set(bob, "") |
| 186 | f.dir.Set(carol, "owner") |
| 187 | f.refreshed() |
| 188 | if a.State() != roster.Member { |
| 189 | t.Fatal("an unchanged member's held decision ended at a refresh") |
| 190 | } |
| 191 | if left := a.Remaining(); left != roster.MaximumAge-roster.RefreshAfter-time.Second { |
| 192 | t.Fatalf("the refresh moved the deadline: %v left", left) |
| 193 | } |
| 194 | if b.State() != roster.Unknown { |
| 195 | t.Fatal("removal did not end the held decision") |
| 196 | } |
| 197 | if c.State() != roster.Unknown { |
| 198 | t.Fatal("a role change did not end the held decision") |
| 199 | } |
| 200 | if f.rt.Access(ctx, bob).State() != roster.NotMember || f.rt.Access(ctx, carol).Role() != "owner" { |
| 201 | t.Fatal("the refresh was not decided") |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | func TestUnknownWhenNoRosterCanBeHeld(t *testing.T) { |
| 206 | f := provisioned(t) |
| 207 | f.dir.SetDown(true) |
| 208 | f.boot() |
| 209 | a := f.rt.Access(context.Background(), alice) |
| 210 | if a.State() != roster.Unknown || !a.Partial() || a.Role() != "" { |
| 211 | t.Fatal("no roster, but standing") |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func TestAdmitUnlinkedOnlyACurrentMember(t *testing.T) { |
| 216 | f := newFixture(t) |
| 217 | ctx := context.Background() |
| 218 | f.dir.Set(alice, "member") |
| 219 | f.refreshed() |
| 220 | iss := f.bindings.Issuer |
| 221 | if err := f.rt.AdmitUnlinked(ctx, iss, alice); err != nil { |
| 222 | t.Fatalf("member refused: %v", err) |
| 223 | } |
| 224 | if err := f.rt.AdmitUnlinked(ctx, iss, bob); !errors.Is(err, teammode.ErrNotMember) { |
| 225 | t.Fatalf("stranger: %v", err) |
| 226 | } |
| 227 | fetches := f.dir.Fetches() |
| 228 | for _, tc := range []struct{ issuer, subject string }{{"https://other.example.com", alice}, {iss, "someone@example.com"}, {iss, "pr_short"}} { |
| 229 | if err := f.rt.AdmitUnlinked(ctx, tc.issuer, tc.subject); !errors.Is(err, teammode.ErrNotMember) { |
| 230 | t.Fatalf("%+v: %v", tc, err) |
| 231 | } |
| 232 | } |
| 233 | if f.dir.Fetches() != fetches { |
| 234 | t.Fatal("an impossible subject asked the directory") |
| 235 | } |
| 236 | f.expired() |
| 237 | if err := f.rt.AdmitUnlinked(ctx, iss, alice); !errors.Is(err, teammode.ErrUnavailable) { |
| 238 | t.Fatalf("Unknown: %v", err) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | // The lease is checked again after the decision: a Member answer whose lease |
| 243 | // lapses before allocation allocates nothing. |
| 244 | func TestAdmitUnlinkedRechecksTheLease(t *testing.T) { |
| 245 | f := newFixture(t) |
| 246 | f.dir.Set(alice, "member") |
| 247 | f.refreshed() |
| 248 | f.dir.SetDown(true) |
| 249 | // The cache's answer is still usable at this reading (59.5 s into a 60 |
| 250 | // s lease) but every reading moves the clock on 0.6 s, so the lease the |
| 251 | // decision carries has lapsed by the time it is checked. |
| 252 | f.clock.Step(roster.MaximumAge - 500*time.Millisecond) |
| 253 | f.clock.SetTick(600 * time.Millisecond) |
| 254 | err := f.rt.AdmitUnlinked(context.Background(), f.bindings.Issuer, alice) |
| 255 | if !errors.Is(err, teammode.ErrUnavailable) { |
| 256 | t.Fatalf("an expired lease admitted: %v", err) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | // Guard reads the carried standing on both sides of the write, and the app's |
| 261 | // rule decides: here a member-only write. |
| 262 | func TestGuardChecksBeforeAndAfterTheWrite(t *testing.T) { |
| 263 | f := newFixture(t) |
| 264 | f.dir.Set(alice, "member") |
| 265 | f.refreshed() |
| 266 | ctx := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), alice)) |
| 267 | wrote := 0 |
| 268 | if err := teammode.Guard(ctx, teammode.RequireMember, func() error { wrote++; return nil }); err != nil || wrote != 1 { |
| 269 | t.Fatalf("member write: %v", err) |
| 270 | } |
| 271 | // The lease lapses during the write: the commit is refused. |
| 272 | f.dir.SetDown(true) |
| 273 | err := teammode.Guard(ctx, teammode.RequireMember, func() error { f.clock.Step(roster.MaximumAge); return nil }) |
| 274 | if !errors.Is(err, teammode.ErrUnavailable) { |
| 275 | t.Fatalf("lapse mid-write committed: %v", err) |
| 276 | } |
| 277 | wrote = 0 |
| 278 | if err := teammode.Guard(ctx, teammode.RequireMember, func() error { wrote++; return nil }); !errors.Is(err, teammode.ErrUnavailable) || wrote != 0 { |
| 279 | t.Fatal("wrote under Unknown") |
| 280 | } |
| 281 | stranger := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), "")) |
| 282 | if err := teammode.Guard(stranger, teammode.RequireMember, func() error { wrote++; return nil }); !errors.Is(err, teammode.ErrNotMember) || wrote != 0 { |
| 283 | t.Fatal("a guest wrote a member-only write") |
| 284 | } |
| 285 | if err := teammode.Guard(context.Background(), teammode.RequireMember, func() error { wrote++; return nil }); !errors.Is(err, teammode.ErrUnavailable) || wrote != 0 { |
| 286 | t.Fatal("no carried standing wrote") |
| 287 | } |
| 288 | writeErr := errors.New("write failed") |
| 289 | ok := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), "")) |
| 290 | if err := teammode.Guard(ok, func(roster.State) error { return nil }, func() error { return writeErr }); err != writeErr { |
| 291 | t.Fatal("write error not returned") |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // The lease check is safe inside the writer transaction: with a refresh's |
| 296 | // publication waiting on the one SQLite writer this transaction holds, Guard |
| 297 | // answers at once instead of deadlocking. The roster answers a contended lease |
| 298 | // from its last published state (oficina/home #158), so the standing that |
| 299 | // admitted the write still holds and nothing latches Unknown. |
| 300 | func TestGuardUnderTheWriterNeverWaitsOnAPublication(t *testing.T) { |
| 301 | f := newFixture(t) |
| 302 | f.dir.Set(alice, "member") |
| 303 | f.refreshed() |
| 304 | w := f.db.Writer() |
| 305 | w.SetMaxOpenConns(1) |
| 306 | ctx := teammode.WithAccess(context.Background(), f.rt.Access(context.Background(), alice)) |
| 307 | tx, err := w.BeginTx(context.Background(), nil) |
| 308 | if err != nil { |
| 309 | t.Fatal(err) |
| 310 | } |
| 311 | defer tx.Rollback() |
| 312 | if _, err := tx.Exec("INSERT INTO items(owner,title) VALUES(1,'x')"); err != nil { |
| 313 | t.Fatal(err) |
| 314 | } |
| 315 | // Two more of this person's requests: one asks for a stream's time |
| 316 | // left during the contention, one is not asked at all. |
| 317 | streamed := f.rt.Access(context.Background(), alice) |
| 318 | untouched := f.rt.Access(context.Background(), alice) |
| 319 | f.dir.Set(bob, "member") // a new epoch, so the refresh must publish |
| 320 | f.clock.Step(roster.RefreshAfter + time.Second) |
| 321 | refreshed := make(chan error, 1) |
| 322 | go func() { refreshed <- f.rt.Refresh(context.Background()) }() |
| 323 | // Wait until the publication is queued on the writer. |
| 324 | deadline := time.Now().Add(2 * time.Second) |
| 325 | for w.Stats().WaitCount == 0 && time.Now().Before(deadline) { |
| 326 | time.Sleep(time.Millisecond) |
| 327 | } |
| 328 | if w.Stats().WaitCount == 0 { |
| 329 | t.Fatal("publication never waited for the writer") |
| 330 | } |
| 331 | done := make(chan error, 1) |
| 332 | go func() { |
| 333 | done <- teammode.Guard(ctx, teammode.RequireMember, func() error { |
| 334 | _, err := tx.Exec("UPDATE items SET title='y'") |
| 335 | return err |
| 336 | }) |
| 337 | }() |
| 338 | select { |
| 339 | case err = <-done: |
| 340 | case <-time.After(time.Second): |
| 341 | _ = tx.Rollback() |
| 342 | t.Fatal("Guard waited on the publication") |
| 343 | } |
| 344 | // 31 s into the lease's 60, during the publication. |
| 345 | if left := streamed.Remaining(); left != roster.MaximumAge-roster.RefreshAfter-time.Second { |
| 346 | t.Fatalf("contended lease has %v left", left) |
| 347 | } |
| 348 | _ = tx.Rollback() |
| 349 | if err != nil { |
| 350 | t.Fatalf("contended lease refused a live standing: %v", err) |
| 351 | } |
| 352 | if e := <-refreshed; e != nil { |
| 353 | t.Fatal(e) |
| 354 | } |
| 355 | // The publication listed alice unchanged, so her lease survived it |
| 356 | // (#97), and the two requests that were asked during the contention |
| 357 | // latched nothing: all three are still Member. |
| 358 | if untouched.State() != roster.Member { |
| 359 | t.Fatal("an unchanged publication ended an uncontended request's lease") |
| 360 | } |
| 361 | if a, _ := teammode.FromContext(ctx); a.State() != roster.Member { |
| 362 | t.Fatal("State latched Unknown on contention") |
| 363 | } |
| 364 | if streamed.State() != roster.Member { |
| 365 | t.Fatal("Remaining latched Unknown on contention") |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | func migrateTeam(f *fixture) (*sql.DB, error) { |
| 370 | schema, err := testState.BootSchema(context.Background(), f.db.Writer(), f.settings, baseSchema, teamSchema) |
| 371 | if err != nil { |
| 372 | return nil, err |
| 373 | } |
| 374 | _, err = migrateApply(f, schema) |
| 375 | return f.db.Writer(), err |
| 376 | } |
| 377 | |