| 1 | package operator |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/hmac" |
| 7 | "crypto/sha256" |
| 8 | "database/sql" |
| 9 | "encoding/base64" |
| 10 | "encoding/hex" |
| 11 | "errors" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | sharedseal "amadan.net/oficina/home/handoff/seal" |
| 19 | "amadan.net/oficina/home/internal/home/directorydata" |
| 20 | "amadan.net/oficina/home/roster" |
| 21 | "amadan.net/rastrillo/rastrillo/assertion" |
| 22 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 23 | rdb "amadan.net/rastrillo/rastrillo/db" |
| 24 | "amadan.net/rastrillo/rastrillo/migrate" |
| 25 | "github.com/go-json-experiment/json" |
| 26 | ) |
| 27 | |
| 28 | var httpApps = []string{"docs", "sheets"} |
| 29 | |
| 30 | // ---- directory ---- |
| 31 | |
| 32 | type httpDirectory struct { |
| 33 | *directoryFixture |
| 34 | plans *PlanStore |
| 35 | plan byte |
| 36 | } |
| 37 | |
| 38 | func newHTTPDirectory(t *testing.T) *httpDirectory { |
| 39 | t.Helper() |
| 40 | f := newDirectoryFixture(t) |
| 41 | p := f.engine.verifier.pins |
| 42 | p.Actions = []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"} |
| 43 | v, e := NewVerifier(p) |
| 44 | if e != nil { |
| 45 | t.Fatal(e) |
| 46 | } |
| 47 | f.engine.verifier = v |
| 48 | plans, e := NewPlanStore(f.db, "directory", f.engine.sealer) |
| 49 | if e != nil { |
| 50 | t.Fatal(e) |
| 51 | } |
| 52 | return &httpDirectory{f, plans, 200} |
| 53 | } |
| 54 | |
| 55 | func (f *httpDirectory) signPlan(t *testing.T, mutate func(*Plan)) (Plan, []byte) { |
| 56 | t.Helper() |
| 57 | pins := f.engine.verifier.pins |
| 58 | p := Plan{Version: 1, Purpose: "operator-plan", Role: pins.Role, Origin: pins.Origin, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device, PlanID: token(f.plan), Kind: "create-team", Apps: []string{"docs"}, Label: "alpha", DisplayName: "PRIVATE-TEAM-NAME-CANARY", Issued: f.now.Unix(), Expires: f.now.Unix() + PlanLifetime} |
| 59 | f.plan++ |
| 60 | if mutate != nil { |
| 61 | mutate(&p) |
| 62 | } |
| 63 | raw, e := SignPlan(f.key, p, httpApps) |
| 64 | if e != nil { |
| 65 | t.Fatal(e) |
| 66 | } |
| 67 | return p, raw |
| 68 | } |
| 69 | |
| 70 | // openPlan submits and confirms a plan, as Alta then Paul would. |
| 71 | func (f *httpDirectory) openPlan(t *testing.T, mutate func(*Plan)) Plan { |
| 72 | t.Helper() |
| 73 | _, raw := f.signPlan(t, mutate) |
| 74 | p, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now) |
| 75 | if e != nil { |
| 76 | t.Fatal(e) |
| 77 | } |
| 78 | if e = f.plans.Submit(context.Background(), p, "", *f.now); e != nil { |
| 79 | t.Fatal(e) |
| 80 | } |
| 81 | if _, e = f.plans.Open(context.Background(), p.PlanID, *f.now, func(PlanView) bool { return true }); e != nil { |
| 82 | t.Fatal(e) |
| 83 | } |
| 84 | return p |
| 85 | } |
| 86 | |
| 87 | func (f *httpDirectory) run(t *testing.T, action string, build func(InputBase) any) ([]byte, error) { |
| 88 | t.Helper() |
| 89 | return f.directory.ExecuteHTTP(context.Background(), f.input(t, action, build)) |
| 90 | } |
| 91 | func (f *httpDirectory) seedHTTP(t *testing.T, id int64, label, name string) ([]byte, error) { |
| 92 | t.Helper() |
| 93 | sqid, _ := TeamSQID(id) |
| 94 | proof := f.receipt(t, id) |
| 95 | return f.run(t, "directory.seed-team", func(b InputBase) any { |
| 96 | return SeedInput{b, token(10), id, sqid, label, name, proof} |
| 97 | }) |
| 98 | } |
| 99 | |
| 100 | // initialized brings the stream to: generation present, a create-team window |
| 101 | // for alpha/docs open. |
| 102 | func initializedHTTP(t *testing.T) *httpDirectory { |
| 103 | t.Helper() |
| 104 | f := newHTTPDirectory(t) |
| 105 | f.openPlan(t, func(p *Plan) { p.Kind, p.Apps, p.Label, p.DisplayName = "initialize", nil, "", "" }) |
| 106 | if _, e := f.run(t, "directory.initialize", func(b InputBase) any { |
| 107 | return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"} |
| 108 | }); e != nil { |
| 109 | t.Fatal(e) |
| 110 | } |
| 111 | // The initialize window stays open until it expires; one open per role. |
| 112 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 113 | f.openPlan(t, nil) |
| 114 | return f |
| 115 | } |
| 116 | |
| 117 | func TestOperatorPlanVerifyRefusesWrongKeyContextPinsAndClock(t *testing.T) { |
| 118 | f := newHTTPDirectory(t) |
| 119 | _, good := f.signPlan(t, nil) |
| 120 | if _, e := f.engine.verifier.VerifyPlan(good, httpApps, *f.now); e != nil { |
| 121 | t.Fatal(e) |
| 122 | } |
| 123 | other, _ := family.Generate() |
| 124 | pins := f.engine.verifier.pins |
| 125 | base := Plan{Version: 1, Purpose: "operator-plan", Role: pins.Role, Origin: pins.Origin, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device, PlanID: token(99), Kind: "create-team", Apps: []string{"docs"}, Label: "alpha", DisplayName: "Alpha", Issued: f.now.Unix(), Expires: f.now.Unix() + 600} |
| 126 | wrongKey, _ := SignPlan(other, base, httpApps) |
| 127 | payload, _ := encode(base) |
| 128 | sig, _ := family.Sign(f.key, InputContext, payload) |
| 129 | wrongContext, _ := encode(envelope{1, keyID(f.key.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) |
| 130 | cases := map[string][]byte{"key": wrongKey, "context": wrongContext} |
| 131 | for name, mutate := range map[string]func(*Plan){ |
| 132 | "role": func(p *Plan) { p.Role = "credential"; p.Label, p.DisplayName, p.Owner = "", "", "a@example.test" }, |
| 133 | "origin": func(p *Plan) { p.Origin = "https://other.oficina.works" }, |
| 134 | "device": func(p *Plan) { p.Device = token(77) }, |
| 135 | "app": func(p *Plan) { p.Apps = []string{"calendar"} }, |
| 136 | "duplicate": func(p *Plan) { p.Apps = []string{"docs", "docs"} }, |
| 137 | "long": func(p *Plan) { p.Expires = p.Issued + PlanLifetime + 1 }, |
| 138 | "future": func(p *Plan) { p.Issued, p.Expires = p.Issued+1, p.Issued+600 }, |
| 139 | "name-on-add": func(p *Plan) { p.Kind = "add-apps" }, |
| 140 | "no-name": func(p *Plan) { p.DisplayName = "" }, |
| 141 | "owner": func(p *Plan) { p.Owner = "a@example.test" }, |
| 142 | "label": func(p *Plan) { p.Label = "Alpha" }, |
| 143 | "init-label": func(p *Plan) { p.Kind, p.Apps, p.DisplayName = "initialize", nil, "" }, |
| 144 | "unknown-kind": func(p *Plan) { p.Kind = "rename" }, |
| 145 | } { |
| 146 | p := base |
| 147 | mutate(&p) |
| 148 | payload, _ := encode(p) |
| 149 | sig, _ := family.Sign(f.key, PlanContext, payload) |
| 150 | cases[name], _ = encode(envelope{1, keyID(f.key.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) |
| 151 | } |
| 152 | for name, raw := range cases { |
| 153 | if _, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now); e != ErrRefused { |
| 154 | t.Error(name, "accepted", e) |
| 155 | } |
| 156 | } |
| 157 | if _, e := f.engine.verifier.VerifyPlan(good, httpApps, f.now.Add(PlanLifetime*time.Second)); e != ErrRefused { |
| 158 | t.Fatal("expired plan accepted", e) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | func TestOperatorPlanStoreOnePendingOneOpenAndExpiredRowsDeleted(t *testing.T) { |
| 163 | f := newHTTPDirectory(t) |
| 164 | ctx := context.Background() |
| 165 | _, raw := f.signPlan(t, nil) |
| 166 | p, _ := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now) |
| 167 | if e := f.plans.Submit(ctx, p, "", *f.now); e != nil { |
| 168 | t.Fatal(e) |
| 169 | } |
| 170 | _, raw2 := f.signPlan(t, func(p *Plan) { p.Label = "beta" }) |
| 171 | p2, _ := f.engine.verifier.VerifyPlan(raw2, httpApps, *f.now) |
| 172 | if e := f.plans.Submit(ctx, p2, "", *f.now); e != ErrBusy { |
| 173 | t.Fatal("second pending plan accepted", e) |
| 174 | } |
| 175 | if e := f.plans.Submit(ctx, p, "", *f.now); e != ErrBusy { |
| 176 | t.Fatal("same plan twice", e) |
| 177 | } |
| 178 | view, e := f.plans.Pending(ctx, *f.now) |
| 179 | if e != nil || view.ID != p.PlanID || view.DisplayName != p.DisplayName || view.Label != "alpha" || view.Prefix() != hex.EncodeToString(bytes.Repeat([]byte{200}, 4)) { |
| 180 | t.Fatal("pending copy", e, view) |
| 181 | } |
| 182 | if _, e = f.plans.Open(ctx, p2.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrRefused { |
| 183 | t.Fatal("opened a plan that is not the pending one", e) |
| 184 | } |
| 185 | if _, e = f.plans.Open(ctx, p.PlanID, *f.now, func(PlanView) bool { return false }); e != ErrRefused { |
| 186 | t.Fatal("admit refusal ignored", e) |
| 187 | } |
| 188 | // Expiry: the row is deleted, not left behind, and the role is free. |
| 189 | *f.now = time.Unix(p.Expires, 0) |
| 190 | if _, e = f.plans.Open(ctx, p.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrRefused { |
| 191 | t.Fatal("expired plan opened", e) |
| 192 | } |
| 193 | if countRows(t, f.db, "operator_plans") != 0 { |
| 194 | t.Fatal("expired plan row left at rest") |
| 195 | } |
| 196 | // One open window blocks opening another until it expires. |
| 197 | f.openPlan(t, nil) |
| 198 | _, raw3 := f.signPlan(t, func(p *Plan) { p.Label = "gamma" }) |
| 199 | p3, _ := f.engine.verifier.VerifyPlan(raw3, httpApps, *f.now) |
| 200 | if e = f.plans.Submit(ctx, p3, "", *f.now); e != nil { |
| 201 | t.Fatal("pending beside an open window", e) |
| 202 | } |
| 203 | if _, e = f.plans.Open(ctx, p3.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrBusy { |
| 204 | t.Fatal("second open window", e) |
| 205 | } |
| 206 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 207 | if e = f.plans.Sweep(ctx, *f.now); e != nil || countRows(t, f.db, "operator_plans") != 0 { |
| 208 | t.Fatal("expired window row left", e) |
| 209 | } |
| 210 | // The display name is sealed at rest, and no plan bytes are stored. |
| 211 | for _, suffix := range []string{"", "-wal"} { |
| 212 | disk, e := os.ReadFile(f.path + suffix) |
| 213 | if e != nil && !errors.Is(e, os.ErrNotExist) { |
| 214 | t.Fatal(e) |
| 215 | } |
| 216 | secrets := [][]byte{[]byte("PRIVATE-TEAM-NAME-CANARY"), []byte(`"display_name":"PRIVATE-TEAM-NAME-CANARY"`)} |
| 217 | for _, signed := range [][]byte{raw, raw2, raw3} { |
| 218 | secrets = append(secrets, signedPlanParts(t, signed)...) |
| 219 | } |
| 220 | for _, secret := range secrets { |
| 221 | if bytes.Contains(disk, secret) { |
| 222 | t.Fatalf("plan bytes or name at rest: %.40q", secret) |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | func TestOperatorHTTPDirectoryNeedsAnOpenWindowOfTheRightKind(t *testing.T) { |
| 229 | f := newHTTPDirectory(t) |
| 230 | init := func(b InputBase) any { return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"} } |
| 231 | if _, e := f.run(t, "directory.initialize", init); e != ErrRefused { |
| 232 | t.Fatal("no window: initialize accepted", e) |
| 233 | } |
| 234 | f.openPlan(t, nil) // create-team, not initialize |
| 235 | if _, e := f.run(t, "directory.initialize", init); e != ErrRefused { |
| 236 | t.Fatal("verb outside kind accepted", e) |
| 237 | } |
| 238 | if countRows(t, f.db, "roster_generation") != 0 || countRows(t, f.db, "directory_operator_state") != 0 { |
| 239 | t.Fatal("refusal mutated") |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | func TestOperatorHTTPSeedTeamBindsLabelAndExactSealedName(t *testing.T) { |
| 244 | f := initializedHTTP(t) |
| 245 | if _, e := f.seedHTTP(t, 1, "beta", "PRIVATE-TEAM-NAME-CANARY"); e != ErrRefused { |
| 246 | t.Fatal("other label accepted", e) |
| 247 | } |
| 248 | for _, name := range []string{"PRIVATE-TEAM-NAME-CANARY ", "private-team-name-canary", "Other"} { |
| 249 | if _, e := f.seedHTTP(t, 1, "alpha", name); e != ErrRefused { |
| 250 | t.Fatalf("name %q accepted", name) |
| 251 | } |
| 252 | } |
| 253 | if countRows(t, f.db, "teams") != 0 { |
| 254 | t.Fatal("refused seed mutated") |
| 255 | } |
| 256 | if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil { |
| 257 | t.Fatal(e) |
| 258 | } |
| 259 | var team int64 |
| 260 | if e := f.db.QueryRow("SELECT team_id FROM operator_http_teams").Scan(&team); e != nil || team != 1 { |
| 261 | t.Fatal("seed not fenced in", e) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | func TestOperatorHTTPProvenanceFenceAndScope(t *testing.T) { |
| 266 | f := initializedHTTP(t) |
| 267 | if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil { |
| 268 | t.Fatal(e) |
| 269 | } |
| 270 | provision := func(sqid, app, consumer, audience string) error { |
| 271 | _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { |
| 272 | return ProvisionInput{b, token(10), sqid, app, consumer, audience, 0} |
| 273 | }) |
| 274 | return e |
| 275 | } |
| 276 | if e := provision("Uk", "sheets", "alpha-sheets", "https://alpha.sheets.oficina.works"); e != ErrRefused { |
| 277 | t.Fatal("app outside the window's apps", e) |
| 278 | } |
| 279 | // A team the native path seeded (not this stream) is outside the fence, |
| 280 | // even for a window naming its label. |
| 281 | if _, e := f.db.Exec("INSERT INTO teams(sqid,label,sealed_name,created_at) VALUES('gb','beta',zeroblob(40),1)"); e != nil { |
| 282 | t.Fatal(e) |
| 283 | } |
| 284 | if _, e := f.db.Exec("INSERT INTO memberships(team_id,person_ref,role) VALUES(2,'pr_aaaaaaaaaaaaaaaaaaaaaaaaaa','owner')"); e != nil { |
| 285 | t.Fatal(e) |
| 286 | } |
| 287 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 288 | f.openPlan(t, func(p *Plan) { p.Kind, p.Label, p.DisplayName = "add-apps", "beta", "" }) |
| 289 | if e := provision("gb", "docs", "beta-docs", "https://beta.docs.oficina.works"); e != ErrRefused { |
| 290 | t.Fatal("fence: unfenced team reached", e) |
| 291 | } |
| 292 | if e := provision("Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works"); e != ErrRefused { |
| 293 | t.Fatal("window for beta reached alpha", e) |
| 294 | } |
| 295 | if countRows(t, f.db, "team_instances") != 0 { |
| 296 | t.Fatal("refusal mutated") |
| 297 | } |
| 298 | // Window expiring mid-run: the next operation refuses. |
| 299 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 300 | f.openPlan(t, func(p *Plan) { p.Kind, p.DisplayName = "add-apps", "" }) |
| 301 | if e := provision("Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works"); e != nil { |
| 302 | t.Fatal(e) |
| 303 | } |
| 304 | *f.now = f.now.Add((WindowLifetime - 1) * time.Second) |
| 305 | in := VerificationInput{Consumer: "alpha-docs", TeamSQID: "Uk", App: "docs", Audience: "https://alpha.docs.oficina.works", Generation: token(10), RecordSequence: 1, Epoch: 2, Owner: "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", Issued: f.now.Unix(), Expires: f.now.Unix() + 600} |
| 306 | var digest []byte |
| 307 | if e := f.db.QueryRow("SELECT record_digest FROM directory_operator_consumer_records").Scan(&digest); e != nil { |
| 308 | t.Fatal(e) |
| 309 | } |
| 310 | in.RecordDigest = base64.RawURLEncoding.EncodeToString(digest) |
| 311 | if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != nil { |
| 312 | t.Fatal("inside window", e) |
| 313 | } |
| 314 | *f.now = f.now.Add(time.Second) |
| 315 | if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != ErrRefused { |
| 316 | t.Fatal("window expired mid-run but admitted", e) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | func TestOperatorHTTPDisableConsumerUnderRetireApps(t *testing.T) { |
| 321 | f := initializedHTTP(t) |
| 322 | if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil { |
| 323 | t.Fatal(e) |
| 324 | } |
| 325 | if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { |
| 326 | return ProvisionInput{b, token(10), "Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works", 0} |
| 327 | }); e != nil { |
| 328 | t.Fatal(e) |
| 329 | } |
| 330 | disable := func(b InputBase) any { return DisableInput{b, token(10), "Uk", "docs", "alpha-docs"} } |
| 331 | if _, e := f.run(t, "directory.disable-consumer", disable); e != ErrRefused { |
| 332 | t.Fatal("disable under create-team", e) |
| 333 | } |
| 334 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 335 | f.openPlan(t, func(p *Plan) { p.Kind, p.DisplayName = "retire-apps", "" }) |
| 336 | if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any { |
| 337 | return ProvisionInput{b, token(10), "Uk", "sheets", "alpha-sheets", "https://alpha.sheets.oficina.works", 0} |
| 338 | }); e != ErrRefused { |
| 339 | t.Fatal("provision under retire-apps", e) |
| 340 | } |
| 341 | if _, e := f.run(t, "directory.disable-consumer", disable); e != nil { |
| 342 | t.Fatal(e) |
| 343 | } |
| 344 | var state string |
| 345 | var enabled int |
| 346 | if e := f.db.QueryRow("SELECT i.state,c.enabled FROM team_instances i JOIN roster_consumers c USING(consumer_id)").Scan(&state, &enabled); e != nil || state != "disabled" || enabled != 0 { |
| 347 | t.Fatal("not disabled", e) |
| 348 | } |
| 349 | var kind string |
| 350 | if e := f.db.QueryRow("SELECT operation FROM roster_operator_receipts WHERE consumer_id='alpha-docs' ORDER BY rowid DESC LIMIT 1").Scan(&kind); e != nil || kind != "disable" { |
| 351 | t.Fatal("no disable receipt", e) |
| 352 | } |
| 353 | if _, e := f.run(t, "directory.disable-consumer", disable); e != ErrRefused { |
| 354 | t.Fatal("disabled twice", e) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | func TestOperatorHTTPReplayAfterWindowExpiryReturnsStoredResult(t *testing.T) { |
| 359 | f := initializedHTTP(t) |
| 360 | sqid, _ := TeamSQID(1) |
| 361 | proof := f.receipt(t, 1) |
| 362 | raw := f.input(t, "directory.seed-team", func(b InputBase) any { |
| 363 | return SeedInput{b, token(10), 1, sqid, "alpha", "PRIVATE-TEAM-NAME-CANARY", proof} |
| 364 | }) |
| 365 | out, e := f.directory.ExecuteHTTP(context.Background(), raw) |
| 366 | if e != nil { |
| 367 | t.Fatal(e) |
| 368 | } |
| 369 | *f.now = f.now.Add(2 * WindowLifetime * time.Second) |
| 370 | again, e := f.directory.ExecuteHTTP(context.Background(), raw) |
| 371 | if e != nil || !bytes.Equal(again, out) || countRows(t, f.db, "teams") != 1 { |
| 372 | t.Fatal("exact replay after expiry", e) |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | func TestOperatorHTTPDirectoryInspectReportsStreamAndPlansOnly(t *testing.T) { |
| 377 | f := initializedHTTP(t) |
| 378 | pins := f.engine.verifier.pins |
| 379 | raw, e := SignInspect(f.key, InspectChallenge{1, "operator-inspect", pins.Role, pins.Origin, pins.Installation, pins.Registry, pins.Device, token(66), f.now.Unix(), f.now.Unix() + 60}) |
| 380 | if e != nil { |
| 381 | t.Fatal(e) |
| 382 | } |
| 383 | out, e := f.directory.InspectHTTP(context.Background(), raw) |
| 384 | if e != nil { |
| 385 | t.Fatal(e) |
| 386 | } |
| 387 | var got HTTPInspection |
| 388 | var head string |
| 389 | if e = f.db.QueryRow("SELECT head FROM directory_operator_state").Scan(&head); e != nil { |
| 390 | t.Fatal(e) |
| 391 | } |
| 392 | if json.Unmarshal(out, &got) != nil || got.Sequence != 1 || got.Head != head || got.Generation == nil || got.TeamSQID != "Uk" || got.OpenPlan == "" || got.WindowExpires == 0 { |
| 393 | t.Fatal("inspection", string(out)) |
| 394 | } |
| 395 | if strings.Contains(string(out), "alpha") || strings.Contains(string(out), "CANARY") { |
| 396 | t.Fatal("inspection carried plan contents") |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | // ---- credential ---- |
| 401 | |
| 402 | type httpCredential struct { |
| 403 | db *sql.DB |
| 404 | path string |
| 405 | now *time.Time |
| 406 | key *family.Keypair |
| 407 | auth Authorization |
| 408 | http *CredentialHTTP |
| 409 | plans *PlanStore |
| 410 | dirKey *family.Keypair |
| 411 | attempt byte |
| 412 | pepper []byte |
| 413 | resolved int |
| 414 | } |
| 415 | |
| 416 | const ownerCanary = "owner-canary@example.test" |
| 417 | |
| 418 | func credentialIndex(pepper []byte, address string) string { |
| 419 | m := hmac.New(sha256.New, pepper) |
| 420 | m.Write([]byte(strings.ToLower(address))) |
| 421 | return hex.EncodeToString(m.Sum(nil)) |
| 422 | } |
| 423 | |
| 424 | func newHTTPCredential(t *testing.T) *httpCredential { |
| 425 | t.Helper() |
| 426 | path := filepath.Join(t.TempDir(), "credential.db") |
| 427 | handle, e := rdb.Open(path, nil) |
| 428 | if e != nil { |
| 429 | t.Fatal(e) |
| 430 | } |
| 431 | t.Cleanup(func() { handle.Close() }) |
| 432 | if _, e = migrate.Apply(context.Background(), handle, migrate.Merge(CredentialSchema, CredentialHTTPSchema)); e != nil { |
| 433 | t.Fatal(e) |
| 434 | } |
| 435 | db := handle.Writer() |
| 436 | if _, e = db.Exec("CREATE TABLE people(person_ref TEXT PRIMARY KEY, blind_index TEXT UNIQUE)"); e != nil { |
| 437 | t.Fatal(e) |
| 438 | } |
| 439 | f := &httpCredential{db: db, path: path, attempt: 30, pepper: bytes.Repeat([]byte{9}, 32)} |
| 440 | if _, e = db.Exec("INSERT INTO people VALUES('pr_aaaaaaaaaaaaaaaaaaaaaaaaaa',?)", credentialIndex(f.pepper, ownerCanary)); e != nil { |
| 441 | t.Fatal(e) |
| 442 | } |
| 443 | f.key, _ = family.Generate() |
| 444 | f.dirKey, _ = family.Generate() |
| 445 | owner, _ := family.Generate() |
| 446 | browser, _ := family.Generate() |
| 447 | f.auth = Authorization{Version: 1, Purpose: "operator-input", Role: "credential", Origin: "https://id.oficina.works", Installation: token(1), Registry: token(2), Device: token(3), JournalSequence: 1, Issued: 2000000000, Expires: 2000000300} |
| 448 | v, e := NewVerifier(Pins{"credential", f.auth.Origin, token(1), token(2), token(3), base64.RawURLEncoding.EncodeToString(f.key.SignPub()), []string{"credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect"}}) |
| 449 | if e != nil { |
| 450 | t.Fatal(e) |
| 451 | } |
| 452 | now := time.Unix(f.auth.Issued, 0) |
| 453 | f.now = &now |
| 454 | sealer, _ := sharedseal.New(bytes.Repeat([]byte{6}, 32), "oficina/operator") |
| 455 | engine, e := NewEngine(db, v, sealer, bytes.Repeat([]byte{7}, 32), func() time.Time { return *f.now }) |
| 456 | if e != nil { |
| 457 | t.Fatal(e) |
| 458 | } |
| 459 | resolve := func(ctx context.Context, c *sql.Conn, address string, existing bool, _ time.Time) (string, bool, error) { |
| 460 | f.resolved++ |
| 461 | var ref string |
| 462 | e := c.QueryRowContext(ctx, "SELECT person_ref FROM people WHERE blind_index=?", credentialIndex(f.pepper, address)).Scan(&ref) |
| 463 | if errors.Is(e, sql.ErrNoRows) { |
| 464 | return "", false, nil |
| 465 | } |
| 466 | return ref, e == nil, e |
| 467 | } |
| 468 | c, e := NewCredential(engine, "https://oficina.works", owner, [][]byte{browser.SignPub()}, resolve) |
| 469 | if e != nil { |
| 470 | t.Fatal(e) |
| 471 | } |
| 472 | env := map[string]string{"directory": "https://oficina.works", "docs": "https://docs.oficina.works"} |
| 473 | // The registry reload's own admission (internal/home registryAdmits): |
| 474 | // a consumer-name ID and an audience the assertion verifier accepts. |
| 475 | assertionKeys := map[string][]byte{keyID(browser.SignPub()): browser.SignPub()} |
| 476 | admit := func(id, origin string) bool { |
| 477 | _, err := assertion.NewVerifier(f.auth.Origin, origin, assertionKeys) |
| 478 | return atom(id, 64) && err == nil |
| 479 | } |
| 480 | f.http, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.dirKey.SignPub()), env, httpApps, func(a string) string { return credentialIndex(f.pepper, a) }, admit) |
| 481 | if e != nil { |
| 482 | t.Fatal(e) |
| 483 | } |
| 484 | if _, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.key.SignPub()), env, httpApps, func(string) string { return "" }, admit); e != ErrRefused { |
| 485 | t.Fatal("Alta's key accepted as the directory provisioning pin") |
| 486 | } |
| 487 | f.plans, _ = NewPlanStore(db, "credential", sealer) |
| 488 | return f |
| 489 | } |
| 490 | |
| 491 | func (f *httpCredential) openPlan(t *testing.T, kind string, apps ...string) { |
| 492 | t.Helper() |
| 493 | p := Plan{Version: 1, Purpose: "operator-plan", Role: "credential", Origin: f.auth.Origin, Installation: token(1), Registry: token(2), Device: token(3), PlanID: token(f.attempt + 100), Kind: kind, Apps: apps, Issued: f.now.Unix(), Expires: f.now.Unix() + 600} |
| 494 | index := "" |
| 495 | if kind == "create-team" { |
| 496 | p.Owner = ownerCanary |
| 497 | index = credentialIndex(f.pepper, ownerCanary) |
| 498 | } |
| 499 | raw, e := SignPlan(f.key, p, httpApps) |
| 500 | if e != nil { |
| 501 | t.Fatal(e) |
| 502 | } |
| 503 | if p, e = f.http.c.engine.verifier.VerifyPlan(raw, httpApps, *f.now); e != nil { |
| 504 | t.Fatal(e) |
| 505 | } |
| 506 | if e = f.plans.Submit(context.Background(), p, index, *f.now); e != nil { |
| 507 | t.Fatal(e) |
| 508 | } |
| 509 | if _, e = f.plans.Open(context.Background(), p.PlanID, *f.now, func(PlanView) bool { return true }); e != nil { |
| 510 | t.Fatal(e) |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | func (f *httpCredential) run(t *testing.T, action string, input func(InputBase) any) ([]byte, error) { |
| 515 | t.Helper() |
| 516 | a := f.auth |
| 517 | var sequence int64 |
| 518 | var head string |
| 519 | if e := f.db.QueryRow("SELECT sequence,head FROM credential_operator_state").Scan(&sequence, &head); e != nil && !errors.Is(e, sql.ErrNoRows) { |
| 520 | t.Fatal(e) |
| 521 | } |
| 522 | a.Sequence, a.Previous, a.Initial = sequence+1, head, sequence == 0 |
| 523 | a.Action, a.OperationID = action, token(f.attempt) |
| 524 | f.attempt++ |
| 525 | a.Issued, a.Expires = f.now.Unix(), f.now.Unix()+300 |
| 526 | raw, e := SignRequest(f.key, a, input(InputBase{1, action, a.OperationID})) |
| 527 | if e != nil { |
| 528 | t.Fatal(e) |
| 529 | } |
| 530 | return f.http.ExecuteHTTP(context.Background(), raw) |
| 531 | } |
| 532 | |
| 533 | func (f *httpCredential) record(t *testing.T, key *family.Keypair, consumer, app, audience string) []byte { |
| 534 | t.Helper() |
| 535 | page, _ := family.Generate() |
| 536 | b := roster.Bindings{Issuer: f.auth.Origin, Directory: "https://oficina.works", Consumer: consumer, App: app, Team: "Uk", Audience: audience} |
| 537 | raw, e := roster.SignProvisioning(key, keyID(key.SignPub()), roster.Provisioning{Version: 1, Operation: token(70), Sequence: 1, Bindings: b, Generation: token(10), MinEpoch: 2, Keys: []roster.Key{{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(page.SignPub())}}}) |
| 538 | if e != nil { |
| 539 | t.Fatal(e) |
| 540 | } |
| 541 | return raw |
| 542 | } |
| 543 | |
| 544 | func ownerSeedInput(address string, existing bool) func(InputBase) any { |
| 545 | return func(b InputBase) any { return OwnerInput{b, "https://oficina.works", 1, "Uk", address, existing} } |
| 546 | } |
| 547 | |
| 548 | func TestOperatorHTTPOwnerSeedIsExistingOnlyAndTheTypedOwner(t *testing.T) { |
| 549 | f := newHTTPCredential(t) |
| 550 | if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != ErrRefused { |
| 551 | t.Fatal("no window", e) |
| 552 | } |
| 553 | f.openPlan(t, "create-team", "docs") |
| 554 | if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, false)); e != ErrRefused { |
| 555 | t.Fatal("minting owner-seed admitted", e) |
| 556 | } |
| 557 | if _, e := f.db.Exec("INSERT INTO people VALUES('pr_bbbbbbbbbbbbbbbbbbbbbbbbbb',?)", credentialIndex(f.pepper, "other@example.test")); e != nil { |
| 558 | t.Fatal(e) |
| 559 | } |
| 560 | if _, e := f.run(t, "credential.owner-seed", ownerSeedInput("other@example.test", true)); e != ErrRefused { |
| 561 | t.Fatal("owner other than the confirmed one", e) |
| 562 | } |
| 563 | if f.resolved != 0 { |
| 564 | t.Fatal("refused owner reached resolution") |
| 565 | } |
| 566 | out, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)) |
| 567 | if e != nil { |
| 568 | t.Fatal(e) |
| 569 | } |
| 570 | var result Result |
| 571 | if json.Unmarshal(out, &result) != nil || len(result.Receipt) == 0 { |
| 572 | t.Fatal("no receipt") |
| 573 | } |
| 574 | // An expired receipt needs a new owner-seed operation under a live window. |
| 575 | *f.now = f.now.Add(301 * time.Second) |
| 576 | if _, e = f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { |
| 577 | t.Fatal("fresh owner-seed in a live window", e) |
| 578 | } |
| 579 | disk, _ := os.ReadFile(f.path) |
| 580 | wal, _ := os.ReadFile(f.path + "-wal") |
| 581 | if bytes.Contains(append(disk, wal...), []byte(ownerCanary)) { |
| 582 | t.Fatal("owner address at rest") |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | func TestOperatorHTTPRegisterConsumerOnlyFromTheDirectoryRecord(t *testing.T) { |
| 587 | f := newHTTPCredential(t) |
| 588 | // The credential stream opens with owner-seed (sequence 1, initial |
| 589 | // authority); every other verb refuses Initial. |
| 590 | f.openPlan(t, "create-team", "docs") |
| 591 | if _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { |
| 592 | return RegisterInput{b, f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works")} |
| 593 | }); e != ErrRefused { |
| 594 | t.Fatal("register as the stream's first operation", e) |
| 595 | } |
| 596 | if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { |
| 597 | t.Fatal(e) |
| 598 | } |
| 599 | register := func(record []byte) error { |
| 600 | _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, record} }) |
| 601 | return e |
| 602 | } |
| 603 | other, _ := family.Generate() |
| 604 | for name, record := range map[string][]byte{ |
| 605 | "none": []byte(`{}`), |
| 606 | "other-key": f.record(t, other, "alpha-docs", "docs", "https://alpha.docs.oficina.works"), |
| 607 | "alta-key": f.record(t, f.key, "alpha-docs", "docs", "https://alpha.docs.oficina.works"), |
| 608 | "app": f.record(t, f.dirKey, "alpha-sheets", "sheets", "https://alpha.sheets.oficina.works"), |
| 609 | "env-origin": f.record(t, f.dirKey, "team-docs", "docs", "https://docs.oficina.works"), |
| 610 | "env-id": f.record(t, f.dirKey, "docs", "docs", "https://alpha.docs.oficina.works"), |
| 611 | "directory": f.record(t, f.dirKey, "directory", "docs", "https://alpha.docs.oficina.works"), |
| 612 | // Blocker 1, #94: an audience the registry reload refuses (the |
| 613 | // credential origin itself) must never be committed. |
| 614 | "credential-origin": f.record(t, f.dirKey, "alpha-docs", "docs", f.auth.Origin), |
| 615 | "issuer-swap": nil, |
| 616 | } { |
| 617 | if record == nil { |
| 618 | page, _ := family.Generate() |
| 619 | b := roster.Bindings{Issuer: "https://id.other.works", Directory: "https://oficina.works", Consumer: "alpha-docs", App: "docs", Team: "Uk", Audience: "https://alpha.docs.oficina.works"} |
| 620 | record, _ = roster.SignProvisioning(f.dirKey, keyID(f.dirKey.SignPub()), roster.Provisioning{Version: 1, Operation: token(70), Sequence: 1, Bindings: b, Generation: token(10), MinEpoch: 2, Keys: []roster.Key{{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(page.SignPub())}}}) |
| 621 | } |
| 622 | if e := register(record); e != ErrRefused { |
| 623 | t.Error(name, "registered", e) |
| 624 | } |
| 625 | } |
| 626 | if countRows(t, f.db, "consumers") != 0 { |
| 627 | t.Fatal("refused registration wrote") |
| 628 | } |
| 629 | good := f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works") |
| 630 | if e := register(good); e != nil { |
| 631 | t.Fatal(e) |
| 632 | } |
| 633 | if e := register(good); e != ErrRefused { |
| 634 | t.Fatal("same consumer twice", e) |
| 635 | } |
| 636 | var id, origin, app, state string |
| 637 | if e := f.db.QueryRow("SELECT consumer_id,origin,app,state FROM consumers").Scan(&id, &origin, &app, &state); e != nil || id != "alpha-docs" || origin != "https://alpha.docs.oficina.works" || app != "docs" || state != "active" { |
| 638 | t.Fatal("registered row", e) |
| 639 | } |
| 640 | // Retire needs a retire-apps window, and a retired origin is dead for good. |
| 641 | retire := func() error { |
| 642 | _, e := f.run(t, "credential.retire-consumer", func(b InputBase) any { return RetireInput{b, "alpha-docs"} }) |
| 643 | return e |
| 644 | } |
| 645 | if e := retire(); e != ErrRefused { |
| 646 | t.Fatal("retire under add-apps", e) |
| 647 | } |
| 648 | // A retire-apps window for another app does not reach this one. |
| 649 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 650 | f.openPlan(t, "retire-apps", "sheets") |
| 651 | if e := retire(); e != ErrRefused { |
| 652 | t.Fatal("retired an app outside the window's apps", e) |
| 653 | } |
| 654 | var still string |
| 655 | if e := f.db.QueryRow("SELECT state FROM consumers WHERE consumer_id='alpha-docs'").Scan(&still); e != nil || still != "active" { |
| 656 | t.Fatal("refused retire changed the row", still, e) |
| 657 | } |
| 658 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 659 | f.openPlan(t, "retire-apps", "docs") |
| 660 | out, e := f.run(t, "credential.retire-consumer", func(b InputBase) any { return RetireInput{b, "alpha-docs"} }) |
| 661 | if e != nil { |
| 662 | t.Fatal(e) |
| 663 | } |
| 664 | var result Result |
| 665 | want, _ := ManifestDigest(map[string]string{"directory": "https://oficina.works", "docs": "https://docs.oficina.works"}) |
| 666 | if json.Unmarshal(out, &result) != nil || result.Manifest != want { |
| 667 | t.Fatal("manifest digest after retire", result.Manifest) |
| 668 | } |
| 669 | if _, e = f.db.Exec("UPDATE consumers SET state='active'"); e == nil { |
| 670 | t.Fatal("retired consumer reactivated") |
| 671 | } |
| 672 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 673 | f.openPlan(t, "add-apps", "docs") |
| 674 | if e := register(good); e != ErrRefused { |
| 675 | t.Fatal("retired hostname reused", e) |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | func TestOperatorHTTPConsumerTableCap(t *testing.T) { |
| 680 | f := newHTTPCredential(t) |
| 681 | tx, _ := f.db.Begin() |
| 682 | for i := 0; i < 4096; i++ { |
| 683 | if _, e := tx.Exec("INSERT INTO consumers VALUES(?,?,'docs','active','2026-10-27',?)", "c"+strings.Repeat("x", 1)+itoa(i), "https://t"+itoa(i)+".docs.oficina.works", token(1)); e != nil { |
| 684 | t.Fatal(i, e) |
| 685 | } |
| 686 | } |
| 687 | if e := tx.Commit(); e != nil { |
| 688 | t.Fatal(e) |
| 689 | } |
| 690 | f.openPlan(t, "create-team", "docs") |
| 691 | if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { |
| 692 | t.Fatal(e) |
| 693 | } |
| 694 | _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { |
| 695 | return RegisterInput{b, f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works")} |
| 696 | }) |
| 697 | if e != ErrRefused || countRows(t, f.db, "consumers") != 4096 { |
| 698 | t.Fatal("4,097th consumer", e) |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | func itoa(i int) string { |
| 703 | if i == 0 { |
| 704 | return "0" |
| 705 | } |
| 706 | s := "" |
| 707 | for ; i > 0; i /= 10 { |
| 708 | s = string(rune('0'+i%10)) + s |
| 709 | } |
| 710 | return s |
| 711 | } |
| 712 | |
| 713 | func TestOperatorHTTPCredentialInspect(t *testing.T) { |
| 714 | f := newHTTPCredential(t) |
| 715 | f.openPlan(t, "create-team", "docs") |
| 716 | if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil { |
| 717 | t.Fatal(e) |
| 718 | } |
| 719 | raw, e := SignInspect(f.key, InspectChallenge{1, "operator-inspect", "credential", f.auth.Origin, token(1), token(2), token(3), token(66), f.now.Unix(), f.now.Unix() + 60}) |
| 720 | if e != nil { |
| 721 | t.Fatal(e) |
| 722 | } |
| 723 | out, e := f.http.InspectHTTP(context.Background(), raw) |
| 724 | var got HTTPInspection |
| 725 | if e != nil || json.Unmarshal(out, &got) != nil || got.Role != "credential" || got.Sequence != 1 || !CanonicalToken(got.Head) || got.OpenPlan == "" || got.Generation != nil { |
| 726 | t.Fatal("credential inspect", e, string(out)) |
| 727 | } |
| 728 | other, _ := family.Generate() |
| 729 | raw, _ = SignInspect(other, InspectChallenge{1, "operator-inspect", "credential", f.auth.Origin, token(1), token(2), token(3), token(66), f.now.Unix(), f.now.Unix() + 60}) |
| 730 | if _, e = f.http.InspectHTTP(context.Background(), raw); e != ErrRefused { |
| 731 | t.Fatal("foreign inspect key", e) |
| 732 | } |
| 733 | _ = directorydata.ValidLabel |
| 734 | } |
| 735 | |
| 736 | // signedPlanParts is what "the signed plan bytes" means at rest: the payload |
| 737 | // and the signature, raw and as their base64url text. |
| 738 | func signedPlanParts(t *testing.T, raw []byte) [][]byte { |
| 739 | t.Helper() |
| 740 | var env envelope |
| 741 | if e := json.Unmarshal(raw, &env); e != nil { |
| 742 | t.Fatal(e) |
| 743 | } |
| 744 | payload, ok := canonical(env.Payload, -1) |
| 745 | sig, ok2 := canonical(env.Signature, 64) |
| 746 | if !ok || !ok2 { |
| 747 | t.Fatal("plan envelope") |
| 748 | } |
| 749 | return [][]byte{payload, sig, []byte(env.Payload), []byte(env.Signature)} |
| 750 | } |
| 751 | |
| 752 | // An open window's row is gone once it expires, swept before the next |
| 753 | // operation even though that operation is refused (its rollback must not |
| 754 | // bring the row back). |
| 755 | func TestOperatorHTTPExpiredWindowRowSweptBeforeARefusedOperation(t *testing.T) { |
| 756 | f := newHTTPDirectory(t) |
| 757 | f.openPlan(t, nil) |
| 758 | *f.now = f.now.Add(WindowLifetime * time.Second) |
| 759 | if _, e := f.run(t, "directory.initialize", func(b InputBase) any { |
| 760 | return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"} |
| 761 | }); e != ErrRefused { |
| 762 | t.Fatal("operation after the window", e) |
| 763 | } |
| 764 | if countRows(t, f.db, "operator_plans") != 0 { |
| 765 | t.Fatal("expired window row left at rest") |
| 766 | } |
| 767 | } |
| 768 | |