oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "crypto/sha256"
8 "database/sql"
9 "encoding/base64"
10 "encoding/hex"
11 "errors"
12 "html"
13 "log/slog"
14 "net/http"
15 "net/http/httptest"
16 "net/url"
17 "os"
18 "path/filepath"
19 "regexp"
20 "strings"
21 "testing"
22 "time"
23
24 "amadan.net/oficina/home/handoff"
25 "amadan.net/oficina/home/internal/home/seal"
26 "amadan.net/oficina/home/internal/home/sealtest"
27 "amadan.net/oficina/home/internal/operator"
28 "amadan.net/oficina/home/roster"
29 family "amadan.net/rastrillo/rastrillo/crypto"
30 "amadan.net/rastrillo/rastrillo/db"
31 "amadan.net/rastrillo/rastrillo/migrate"
32 json "github.com/go-json-experiment/json"
33)
34
35// operatorFixture is both Home roles with HOME_OPERATOR_HTTP configured,
36// built through loadOperatorHTTP from the environment, as at boot.
37type operatorFixture struct {
38 credential *testApp
39 directory *App
40 directoryPath string
41 logs *bytes.Buffer
42 alta *family.Keypair
43 prefilter string
44 paul string // Paul's person ref, operator_subject on both roles
45 paulAddress string
46 ownerSeed *family.Keypair
47 provisioning *family.Keypair
48 resolve *family.Keypair // HOME_RESOLVE_KEY; the directory pins its public half
49 journal int64
50 opByte byte
51}
52
53const (
54 operatorPaul = "paul-operator@example.invalid"
55 operatorLabel = "canarylabel"
56 operatorName = "CANARY-TEAM-NAME-2b71"
57)
58
59func encodedKeypair(t *testing.T, k *family.Keypair) string {
60 t.Helper()
61 b, err := family.MarshalKeypair(k)
62 if err != nil {
63 t.Fatal(err)
64 }
65 return base64.StdEncoding.EncodeToString(b)
66}
67func rawURLPub(k *family.Keypair) string { return base64.RawURLEncoding.EncodeToString(k.SignPub()) }
68
69func operatorHTTPJSON(t *testing.T, role, origin string, alta *family.Keypair, subject, prefilterSum string, actions []string, provisioning string) string {
70 t.Helper()
71 c := operatorHTTPConfig{Version: 1, Role: role, Origin: origin, Installation: fixtureToken(1), Registry: fixtureToken(2), Device: fixtureToken(3), PublicKey: rawURLPub(alta), KeyID: hexID(alta), Actions: actions, OperatorSubject: subject, PrefilterSHA256: prefilterSum, DirectoryProvisioningPublicKey: provisioning}
72 b, err := json.Marshal(c)
73 if err != nil {
74 t.Fatal(err)
75 }
76 return string(b)
77}
78
79var credentialActions = []string{"credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect"}
80var directoryActions = []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"}
81
82func newOperatorFixture(t *testing.T) *operatorFixture {
83 return newOperatorFixtureConsumers(t, nil)
84}
85
86func newOperatorFixtureConsumers(t *testing.T, consumers map[string]string) *operatorFixture {
87 t.Helper()
88 f := &operatorFixture{paulAddress: operatorPaul, opByte: 40, logs: new(bytes.Buffer)}
89 logger := slog.New(slog.NewTextHandler(f.logs, nil))
90 var err error
91 if f.alta, err = family.Generate(); err != nil {
92 t.Fatal(err)
93 }
94 f.ownerSeed, _ = family.Generate()
95 f.provisioning, _ = family.Generate()
96 f.resolve, _ = family.Generate()
97 rosterKey, _ := family.Generate()
98 prefilter := make([]byte, 32)
99 rand.Read(prefilter)
100 f.prefilter = base64.RawURLEncoding.EncodeToString(prefilter)
101 sum := sha256.Sum256(prefilter)
102 prefilterSum := hex.EncodeToString(sum[:])
103
104 // Credential role.
105 RegisterSecureDelete()
106 credPath := filepath.Join(t.TempDir(), "credential.db")
107 cd, err := db.Open(credPath, quietLogger())
108 if err != nil {
109 t.Fatal(err)
110 }
111 t.Cleanup(func() { cd.Close() })
112 if _, err = migrate.Apply(context.Background(), cd, (Runtime{role: "credential"}).ServingSchema()); err != nil {
113 t.Fatal(err)
114 }
115 secrets, mailer := testSecrets(t)
116 if f.paul, err = findOrMintPersonOn(context.Background(), cd.Writer(), secrets.Pepper, f.paulAddress, time.Now()); err != nil {
117 t.Fatal(err)
118 }
119 key, _ := family.Generate()
120 kid := hexID(key)
121 ccfg := Runtime{role: "credential", origins: Origins{Origin, directoryOrigin}, secrets: secrets, signer: key, keyID: kid, keys: map[string][]byte{kid: key.SignPub()}, consumers: map[string]string{"directory": directoryOrigin, "team_docs": "https://blue.docs.oficina.works", "preview": "https://preview.example.test"}, resolveSigner: f.resolve}
122 for id, origin := range consumers {
123 ccfg.consumers[id] = origin
124 }
125 t.Setenv("HOME_OPERATOR_HTTP", operatorHTTPJSON(t, "credential", Origin, f.alta, f.paul, prefilterSum, credentialActions, rawURLPub(f.provisioning)))
126 t.Setenv("HOME_OPERATOR_MATERIAL", `{"version":1,"role":"credential","mac_key":"`+base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))+`","owner_seed_key":"`+encodedKeypair(t, f.ownerSeed)+`"}`)
127 if err = loadOperatorHTTP(&ccfg); err != nil || ccfg.operator == nil {
128 t.Fatal("credential operator config", err)
129 }
130 capp, err := NewRuntime(ccfg, cd, logger)
131 if err != nil {
132 t.Fatal(err)
133 }
134 capp.flow.Classifier.LookupTXT = func(context.Context, string) ([]string, error) {
135 return nil, errors.New("no resolver in tests")
136 }
137 // This fixture performs many independent operator ceremonies in one window.
138 capp.flow.IPBudget = 200
139 capp.flow.AddressBudget = 100
140 f.credential = &testApp{App: capp, mailer: mailer, db: cd, dbPath: credPath}
141
142 // Directory role.
143 f.directoryPath = filepath.Join(t.TempDir(), "directory.db")
144 dd, err := db.Open(f.directoryPath, quietLogger())
145 if err != nil {
146 t.Fatal(err)
147 }
148 t.Cleanup(func() { dd.Close() })
149 if _, err = migrate.Apply(context.Background(), dd, (Runtime{role: "directory"}).ServingSchema()); err != nil {
150 t.Fatal(err)
151 }
152 dek := make([]byte, 32)
153 rand.Read(dek)
154 sealer, _ := seal.New(dek)
155 dcfg := Runtime{role: "directory", origins: ccfg.origins, secrets: Secrets{Sealer: sealer}, keys: ccfg.keys, roster: rosterRuntime{mode: "disabled"}, resolvePublic: f.resolve.SignPub()}
156 t.Setenv("HOME_OPERATOR_HTTP", operatorHTTPJSON(t, "directory", directoryOrigin, f.alta, f.paul, prefilterSum, directoryActions, ""))
157 material, _ := json.Marshal(directoryOperatorMaterial{Version: 1, Role: "directory", MAC: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{8}, 32)), Owner: rawURLPub(f.ownerSeed), Provisioning: encodedKeypair(t, f.provisioning), Roster: []roster.Key{{ID: hexID(rosterKey), Public: rawURLPub(rosterKey)}}})
158 t.Setenv("HOME_OPERATOR_MATERIAL", string(material))
159 if err = loadOperatorHTTP(&dcfg); err != nil || dcfg.operator == nil {
160 t.Fatal("directory operator config", err)
161 }
162 if f.directory, err = NewRuntime(dcfg, dd, logger); err != nil {
163 t.Fatal(err)
164 }
165 return f
166}
167
168func (f *operatorFixture) app(role string) *App {
169 if role == "credential" {
170 return f.credential.App
171 }
172 return f.directory
173}
174func roleOrigin(role string) string {
175 if role == "credential" {
176 return Origin
177 }
178 return directoryOrigin
179}
180
181// post sends Alta's request exactly as Alta would, then lets each test
182// break one thing about it.
183func (f *operatorFixture) post(role, path string, body []byte, edit func(*http.Request)) *httptest.ResponseRecorder {
184 r := httptest.NewRequest("POST", roleOrigin(role)+path, bytes.NewReader(body))
185 r.Header.Set("Content-Type", "application/json")
186 r.Header.Set("Authorization", "Bearer "+f.prefilter)
187 if edit != nil {
188 edit(r)
189 }
190 rec := httptest.NewRecorder()
191 f.app(role).Router().ServeHTTP(rec, r)
192 return rec
193}
194
195func (f *operatorFixture) plan(t *testing.T, role, kind string, apps []string, mutate func(*operator.Plan)) []byte {
196 t.Helper()
197 now := time.Now()
198 p := operator.Plan{Version: 1, Purpose: "operator-plan", Role: role, Origin: roleOrigin(role), Installation: fixtureToken(1), Registry: fixtureToken(2), Device: fixtureToken(3), PlanID: fixtureToken(90), Kind: kind, Apps: apps, Issued: now.Unix(), Expires: now.Unix() + 600}
199 if role == "directory" && kind != "initialize" {
200 p.Label = operatorLabel
201 if kind == "create-team" {
202 p.DisplayName = operatorName
203 }
204 }
205 if role == "credential" && kind == "create-team" {
206 p.Owner = sealtest.CanaryAddress
207 }
208 if mutate != nil {
209 mutate(&p)
210 }
211 raw, err := operator.SignPlan(f.alta, p, operatorApps())
212 if err != nil {
213 t.Fatal(err)
214 }
215 return raw
216}
217
218func (f *operatorFixture) operation(t *testing.T, role, action string, input func(operator.InputBase) any) []byte {
219 t.Helper()
220 app := f.app(role)
221 var sequence int64
222 var head string
223 if err := app.db.Writer().QueryRow("SELECT sequence,head FROM "+role+"_operator_state").Scan(&sequence, &head); err != nil && !errors.Is(err, sql.ErrNoRows) {
224 t.Fatal(err)
225 }
226 f.journal++
227 op := fixtureToken(f.opByte)
228 f.opByte++
229 now := time.Now().Unix()
230 a := operator.Authorization{Version: 1, Purpose: "operator-input", Role: role, Origin: roleOrigin(role), Installation: fixtureToken(1), Registry: fixtureToken(2), Device: fixtureToken(3), Sequence: sequence + 1, Initial: sequence == 0, Previous: head, JournalSequence: f.journal, OperationID: op, Action: action, Issued: now, Expires: now + 300}
231 raw, err := operator.SignRequest(f.alta, a, input(operator.InputBase{Version: 1, Operation: action, OperationID: op}))
232 if err != nil {
233 t.Fatal(err)
234 }
235 return raw
236}
237
238func (f *operatorFixture) run(t *testing.T, role, action string, input func(operator.InputBase) any) (*httptest.ResponseRecorder, operator.Result) {
239 t.Helper()
240 rec := f.post(role, operatorPath, f.operation(t, role, action, input), nil)
241 var result operator.Result
242 if rec.Code == 200 {
243 if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
244 t.Fatal(err)
245 }
246 }
247 return rec, result
248}
249
250// paulCredential is a fresh credential-origin session for Paul.
251func (f *operatorFixture) paulCredential(t *testing.T) *http.Cookie {
252 t.Helper()
253 return signInFully(t, f.credential, f.paulAddress)
254}
255
256// paulDirectory runs the fresh exchange from /auth/fresh/start, as the
257// directory confirm page sends Paul, and returns his directory session.
258func (f *operatorFixture) paulDirectory(t *testing.T, credentialSession *http.Cookie) *http.Cookie {
259 t.Helper()
260 start := exchangeRequest(f.directory, "GET", directoryOrigin+freshStartPath+"?return_to=%2Foperator%2Fconfirm", "", nil)
261 if start.Code != 303 || !strings.Contains(start.Header().Get("Location"), "max_age=300") {
262 t.Fatal("fresh start", start.Code)
263 }
264 pending := namedCookie(t, start, "__Host-oficina-assertion-pending")
265 authorize := exchangeRequest(f.credential.App, "GET", start.Header().Get("Location"), "", nil, credentialSession)
266 intent := namedCookie(t, authorize, assertionIntentCookie)
267 credentialSession = reauthenticateCredential(t, f.credential, credentialSession)
268 resume := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, credentialSession)
269 m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(resume.Body.String())
270 if resume.Code != 200 || len(m) != 2 {
271 t.Fatal("resume", resume.Code, resume.Header().Get("Location"))
272 }
273 callback := exchangeRequest(f.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, url.Values{"assertion": {html.UnescapeString(m[1])}})
274 inbox := namedCookie(t, callback, "__Host-oficina-assertion-inbox")
275 finish := exchangeRequest(f.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, pending, inbox)
276 if finish.Code != 303 || finish.Header().Get("Location") != operatorConfirm || sessionCookie(finish) == nil {
277 t.Fatal("finish", finish.Code, finish.Header().Get("Location"))
278 }
279 return sessionCookie(finish)
280}
281
282var planIDField = regexp.MustCompile(`name="plan" value="([^"]+)"`)
283
284// confirm opens role's window: GET the page, POST its own plan id.
285func (f *operatorFixture) confirm(t *testing.T, role string, session *http.Cookie, owner string) *httptest.ResponseRecorder {
286 t.Helper()
287 page := exchangeRequest(f.app(role), "GET", roleOrigin(role)+operatorConfirm, "", nil, session)
288 m := planIDField.FindStringSubmatch(page.Body.String())
289 if page.Code != 200 || len(m) != 2 {
290 t.Fatal(role, "confirm page", page.Code, page.Header().Get("Location"))
291 }
292 form := url.Values{"plan": {m[1]}}
293 if owner != "" {
294 form.Set("owner", owner)
295 }
296 return exchangeRequest(f.app(role), "POST", roleOrigin(role)+operatorConfirm, roleOrigin(role), form, session)
297}
298
299func (f *operatorFixture) openWindows(t *testing.T, kind string, apps []string) {
300 t.Helper()
301 for _, role := range []string{"directory", "credential"} {
302 if role == "credential" && kind == "initialize" {
303 continue
304 }
305 if rec := f.post(role, operatorPlanPath, f.plan(t, role, kind, apps, func(p *operator.Plan) { p.PlanID = fixtureToken(f.opByte) }), nil); rec.Code != 200 {
306 t.Fatal(role, "plan", rec.Code, rec.Body.String())
307 }
308 }
309 cred := f.paulCredential(t)
310 if rec := f.confirm(t, "directory", f.paulDirectory(t, cred), ""); rec.Code != 200 {
311 t.Fatal("directory confirm", rec.Code)
312 }
313 if kind != "initialize" {
314 owner := ""
315 if kind == "create-team" {
316 owner = sealtest.CanaryAddress
317 }
318 if rec := f.confirm(t, "credential", cred, owner); rec.Code != 200 {
319 t.Fatal("credential confirm", rec.Code)
320 }
321 }
322}
323
324// expireWindows moves both roles' windows past their end.
325func (f *operatorFixture) expireWindows(t *testing.T) {
326 t.Helper()
327 for _, a := range []*App{f.credential.App, f.directory} {
328 if _, err := a.db.Writer().Exec("DELETE FROM operator_plans"); err != nil {
329 t.Fatal(err)
330 }
331 }
332}
333
334func generationToken() string { return fixtureToken(10) }
335
336// provisionTeam drives Alta's whole create-team sequence for label/apps,
337// returning the directory's provisioning record per app.
338func (f *operatorFixture) provisionTeam(t *testing.T) map[string][]byte {
339 t.Helper()
340 f.openWindows(t, "initialize", nil)
341 if rec, _ := f.run(t, "directory", "directory.initialize", func(b operator.InputBase) any {
342 return operator.InitializeInput{InputBase: b, Generation: generationToken(), Baseline: "operator-attests-never-provisioned"}
343 }); rec.Code != 200 {
344 t.Fatal("initialize", rec.Code, rec.Body.String())
345 }
346 f.expireWindows(t)
347 f.openWindows(t, "create-team", []string{"docs"})
348 sqid, _ := operator.TeamSQID(1)
349 rec, owner := f.run(t, "credential", "credential.owner-seed", func(b operator.InputBase) any {
350 return operator.OwnerInput{InputBase: b, Directory: directoryOrigin, TeamID: 1, TeamSQID: sqid, Address: sealtest.CanaryAddress, ExistingOnly: true}
351 })
352 if rec.Code != 200 {
353 t.Fatal("owner-seed", rec.Code, rec.Body.String())
354 }
355 if rec, _ = f.run(t, "directory", "directory.seed-team", func(b operator.InputBase) any {
356 return operator.SeedInput{InputBase: b, Generation: generationToken(), TeamID: 1, TeamSQID: sqid, Label: operatorLabel, Name: operatorName, Receipt: owner.Receipt}
357 }); rec.Code != 200 {
358 t.Fatal("seed-team", rec.Code, rec.Body.String())
359 }
360 records := map[string][]byte{}
361 rec, provisioned := f.run(t, "directory", "directory.provision-consumer", func(b operator.InputBase) any {
362 return operator.ProvisionInput{InputBase: b, Generation: generationToken(), TeamSQID: sqid, App: "docs", Consumer: operatorLabel + "-docs", Audience: "https://" + operatorLabel + ".docs.oficina.works"}
363 })
364 if rec.Code != 200 {
365 t.Fatal("provision", rec.Code, rec.Body.String())
366 }
367 records["docs"] = provisioned.Record
368 if rec, _ = f.run(t, "credential", "credential.register-consumer", func(b operator.InputBase) any {
369 return operator.RegisterInput{InputBase: b, Record: provisioned.Record}
370 }); rec.Code != 200 {
371 t.Fatal("register", rec.Code, rec.Body.String())
372 }
373 return records
374}
375
376func TestOperatorEndpointIsOffWithoutConfiguration(t *testing.T) {
377 p := newExchangePair(t)
378 for _, a := range []*App{p.credential.App, p.directory} {
379 for _, path := range []string{operatorPath, operatorPlanPath, operatorConfirm} {
380 for _, host := range []string{Origin, directoryOrigin} {
381 for _, method := range []string{"GET", "POST"} {
382 r := httptest.NewRequest(method, host+path, strings.NewReader("{}"))
383 r.Header.Set("Content-Type", "application/json")
384 rec := httptest.NewRecorder()
385 a.Router().ServeHTTP(rec, r)
386 if rec.Code != 404 && rec.Code != 403 {
387 t.Fatal("unconfigured operator route answered", method, host+path, rec.Code)
388 }
389 if strings.Contains(rec.Body.String(), "outcome") {
390 t.Fatal("operator handler reached without configuration")
391 }
392 }
393 }
394 }
395 }
396}
397
398func TestOperatorHTTPConfigurationIsClosedAndKeysDistinct(t *testing.T) {
399 f := newOperatorFixture(t)
400 cfg := *f.credential.runtime
401 cfg.operator = nil
402 sum := sha256.Sum256([]byte("x"))
403 prefilter := hex.EncodeToString(sum[:])
404 base := operatorHTTPConfig{Version: 1, Role: "credential", Origin: Origin, Installation: fixtureToken(1), Registry: fixtureToken(2), Device: fixtureToken(3), PublicKey: rawURLPub(f.alta), KeyID: hexID(f.alta), Actions: credentialActions, OperatorSubject: f.paul, PrefilterSHA256: prefilter, DirectoryProvisioningPublicKey: rawURLPub(f.provisioning)}
405 material := `{"version":1,"role":"credential","mac_key":"` + base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) + `","owner_seed_key":"` + encodedKeypair(t, f.ownerSeed) + `"}`
406 t.Setenv("HOME_OPERATOR_MATERIAL", material)
407 try := func(c operatorHTTPConfig, extra string) error {
408 b, _ := json.Marshal(c)
409 raw := string(b)
410 if extra != "" {
411 raw = strings.TrimSuffix(raw, "}") + extra + "}"
412 }
413 t.Setenv("HOME_OPERATOR_HTTP", raw)
414 probe := cfg
415 return loadOperatorHTTP(&probe)
416 }
417 if err := try(base, ""); err != nil {
418 t.Fatal("valid config refused", err)
419 }
420 for name, mutate := range map[string]func(*operatorHTTPConfig){
421 "role": func(c *operatorHTTPConfig) { c.Role = "directory" },
422 "origin": func(c *operatorHTTPConfig) { c.Origin = directoryOrigin },
423 "kid": func(c *operatorHTTPConfig) { c.KeyID = strings.Repeat("0", 64) },
424 "subject": func(c *operatorHTTPConfig) { c.OperatorSubject = "paul" },
425 "prefilter": func(c *operatorHTTPConfig) { c.PrefilterSHA256 = "abc" },
426 "no-inspect": func(c *operatorHTTPConfig) { c.Actions = []string{"credential.owner-seed"} },
427 "wrong-action": func(c *operatorHTTPConfig) { c.Actions = []string{"directory.seed-team", "credential.inspect"} },
428 "no-dir-key": func(c *operatorHTTPConfig) { c.DirectoryProvisioningPublicKey = "" },
429 "alta-is-owner-seed": func(c *operatorHTTPConfig) {
430 c.PublicKey, c.KeyID = rawURLPub(f.ownerSeed), hexID(f.ownerSeed)
431 },
432 "alta-is-provisioning": func(c *operatorHTTPConfig) {
433 c.DirectoryProvisioningPublicKey = rawURLPub(f.alta)
434 },
435 "alta-is-assertion": func(c *operatorHTTPConfig) {
436 c.PublicKey, c.KeyID = rawURLPub(cfg.signer), hexID(cfg.signer)
437 },
438 } {
439 c := base
440 mutate(&c)
441 if err := try(c, ""); err == nil {
442 t.Error(name, "accepted")
443 }
444 }
445 if err := try(base, `,"extra":1`); err == nil {
446 t.Error("unknown field accepted")
447 }
448 t.Setenv("HOME_OPERATOR_HTTP", "")
449 probe := cfg
450 if err := loadOperatorHTTP(&probe); err != nil || probe.operator != nil {
451 t.Fatal("absent config is not off", err)
452 }
453}
454
455func TestOperatorTransportRefusesBrowsersAndChecksPrefilterFirst(t *testing.T) {
456 f := newOperatorFixture(t)
457 body := f.plan(t, "credential", "add-apps", []string{"docs"}, nil)
458 for name, c := range map[string]struct {
459 edit func(*http.Request)
460 status int
461 }{
462 "cookie": {func(r *http.Request) { r.AddCookie(&http.Cookie{Name: "x", Value: "y"}) }, 403},
463 "origin": {func(r *http.Request) { r.Header.Set("Origin", Origin) }, 403},
464 "sec-fetch": {func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") }, 403},
465 "sec-fetch-mode": {func(r *http.Request) { r.Header.Set("Sec-Fetch-Mode", "cors") }, 403},
466 "query": {func(r *http.Request) { r.URL.RawQuery = "x=1" }, 403},
467 "media": {func(r *http.Request) { r.Header.Set("Content-Type", "text/plain") }, 415},
468 "media-params": {func(r *http.Request) { r.Header.Set("Content-Type", "application/json; charset=utf-8") }, 415},
469 "no-bearer": {func(r *http.Request) { r.Header.Del("Authorization") }, 401},
470 "wrong-bearer": {func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+fixtureToken(5)) }, 401},
471 "bearer-form": {func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+f.prefilter+"=") }, 401},
472 "method": {func(r *http.Request) { r.Method = "PUT" }, 405},
473 "host-spoof": {func(r *http.Request) { r.Host = "evil.oficina.works" }, 404},
474 "other-role": {func(r *http.Request) { r.Host = "oficina.works" }, 404},
475 } {
476 rec := f.post("credential", operatorPlanPath, body, c.edit)
477 if rec.Code != c.status {
478 t.Error(name, rec.Code, rec.Body.String())
479 }
480 if rec.Code == 401 && rec.Body.String() != `{"outcome":"prefilter"}` {
481 t.Error("prefilter refusal is not fixed", rec.Body.String())
482 }
483 if len(rec.Result().Cookies()) != 0 {
484 t.Error(name, "set a cookie")
485 }
486 }
487 big := bytes.Repeat([]byte(" "), operator.BodyLimit+1)
488 if rec := f.post("credential", operatorPath, big, nil); rec.Code != 413 {
489 t.Fatal("oversized body", rec.Code)
490 }
491 if n := f.countRows(t, f.credential.App, "operator_plans"); n != 0 {
492 t.Fatal("refused transport stored a plan")
493 }
494 // Role separation: the directory's routes answer only on its host.
495 if rec := f.post("directory", operatorPlanPath, f.plan(t, "directory", "add-apps", []string{"docs"}, nil), func(r *http.Request) { r.Host = "id.oficina.works" }); rec.Code != 404 {
496 t.Fatal("directory endpoint answered on the credential host", rec.Code)
497 }
498}
499
500func (f *operatorFixture) countRows(t *testing.T, a *App, table string) int {
501 t.Helper()
502 var n int
503 if err := a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil {
504 t.Fatal(err)
505 }
506 return n
507}
508
509func TestOperatorPlanSubmitStoresClosedFieldsOnly(t *testing.T) {
510 f := newOperatorFixture(t)
511 // The owner must already exist: an unknown address refuses and stores
512 // nothing.
513 if rec := f.post("credential", operatorPlanPath, f.plan(t, "credential", "create-team", []string{"docs"}, nil), nil); rec.Code != 403 {
514 t.Fatal("plan for an owner who never signed in", rec.Code)
515 }
516 signInFully(t, f.credential, sealtest.CanaryAddress)
517 other, _ := family.Generate()
518 foreign, _ := operator.SignPlan(other, operator.Plan{Version: 1, Purpose: "operator-plan", Role: "credential", Origin: Origin, Installation: fixtureToken(1), Registry: fixtureToken(2), Device: fixtureToken(3), PlanID: fixtureToken(91), Kind: "add-apps", Apps: []string{"docs"}, Issued: time.Now().Unix(), Expires: time.Now().Unix() + 600}, operatorApps())
519 if rec := f.post("credential", operatorPlanPath, foreign, nil); rec.Code != 403 {
520 t.Fatal("plan signed by another key", rec.Code)
521 }
522 credPlan := f.plan(t, "credential", "create-team", []string{"docs"}, nil)
523 if rec := f.post("credential", operatorPlanPath, credPlan, nil); rec.Code != 200 {
524 t.Fatal("plan", rec.Code, rec.Body.String())
525 }
526 if rec := f.post("credential", operatorPlanPath, f.plan(t, "credential", "add-apps", []string{"docs"}, func(p *operator.Plan) { p.PlanID = fixtureToken(92) }), nil); rec.Code != 409 {
527 t.Fatal("second pending plan", rec.Code)
528 }
529 dirPlan := f.plan(t, "directory", "create-team", []string{"docs"}, nil)
530 if rec := f.post("directory", operatorPlanPath, dirPlan, nil); rec.Code != 200 {
531 t.Fatal("directory plan", rec.Code)
532 }
533 // Gate 2, plan-submit path: neither the signed plan bytes nor the
534 // canary address (nor the sealed team name) are in file, WAL or SHM.
535 for path, plan := range map[string][]byte{f.credential.dbPath: credPlan, f.directoryPath: dirPlan} {
536 sealtest.AssertNoPlaintext(t, path)
537 for _, suffix := range []string{"", "-wal", "-shm"} {
538 b, _ := os.ReadFile(path + suffix)
539 for _, secret := range signedPlanParts(t, plan) {
540 if bytes.Contains(b, secret) {
541 t.Fatalf("signed plan bytes at rest in %s: %.40q", filepath.Base(path+suffix), secret)
542 }
543 }
544 }
545 }
546 // An expired plan's row is gone.
547 f.credential.op.now = func() time.Time { return time.Now().Add(601 * time.Second) }
548 if err := f.credential.op.plans.Sweep(context.Background(), f.credential.op.now()); err != nil {
549 t.Fatal(err)
550 }
551 if f.countRows(t, f.credential.App, "operator_plans") != 0 {
552 t.Fatal("expired plan row left")
553 }
554 sealtest.AssertNoPlaintext(t, f.credential.dbPath)
555}
556
557// signedPlanParts is what "the signed plan bytes" means at rest: the payload
558// and the signature, raw and as their base64url text, plus the plan's own
559// spelling of its account-authored fields.
560func signedPlanParts(t *testing.T, raw []byte) [][]byte {
561 t.Helper()
562 var env struct {
563 V int `json:"v"`
564 KID string `json:"kid"`
565 Payload string `json:"payload"`
566 Signature string `json:"signature"`
567 }
568 if err := json.Unmarshal(raw, &env); err != nil {
569 t.Fatal(err)
570 }
571 payload, err := base64.RawURLEncoding.DecodeString(env.Payload)
572 sig, err2 := base64.RawURLEncoding.DecodeString(env.Signature)
573 if err != nil || err2 != nil || len(sig) != 64 {
574 t.Fatal("plan envelope")
575 }
576 return [][]byte{payload, sig, []byte(env.Payload), []byte(env.Signature), []byte(`"owner":"` + sealtest.CanaryAddress + `"`), []byte(`"display_name":"` + operatorName + `"`)}
577}
578
579// The expiry sweeps run on their own: a pending plan and an open window
580// are deleted at their end with no further request and no Sweep by hand.
581func TestOperatorExpirySweepsRunUnprompted(t *testing.T) {
582 f := newOperatorFixture(t)
583 var pending []func()
584 var waits []time.Duration
585 clock := time.Now()
586 for _, a := range []*App{f.credential.App, f.directory} {
587 a.op.after = func(d time.Duration, fn func()) { waits = append(waits, d); pending = append(pending, fn) }
588 a.op.now = func() time.Time { return clock }
589 }
590 fire := func(keep bool) {
591 for _, fn := range pending {
592 fn()
593 }
594 if !keep {
595 pending = nil
596 }
597 }
598 // A plan nobody confirms.
599 signInFully(t, f.credential, sealtest.CanaryAddress)
600 if rec := f.post("credential", operatorPlanPath, f.plan(t, "credential", "create-team", []string{"docs"}, nil), nil); rec.Code != 200 {
601 t.Fatal(rec.Code)
602 }
603 if len(pending) != 1 || waits[0] < 600*time.Second || waits[0] > 602*time.Second {
604 t.Fatal("no expiry sweep scheduled for the plan", waits)
605 }
606 clock = clock.Add(601 * time.Second)
607 fire(false)
608 if f.countRows(t, f.credential.App, "operator_plans") != 0 {
609 t.Fatal("unconfirmed plan row left after expiry")
610 }
611 // A window that is opened, then left.
612 clock = time.Now()
613 if rec := f.post("directory", operatorPlanPath, f.plan(t, "directory", "add-apps", []string{"docs"}, nil), nil); rec.Code != 200 {
614 t.Fatal(rec.Code)
615 }
616 if rec := f.confirm(t, "directory", f.paulDirectory(t, f.paulCredential(t)), ""); rec.Code != 200 {
617 t.Fatal(rec.Code)
618 }
619 if len(pending) != 2 || waits[len(waits)-1] < operator.WindowLifetime*time.Second || waits[len(waits)-1] > (operator.WindowLifetime+2)*time.Second {
620 t.Fatal("no expiry sweep scheduled for the window", waits)
621 }
622 clock = clock.Add((operator.WindowLifetime - 2) * time.Second)
623 fire(true)
624 if f.countRows(t, f.directory, "operator_plans") != 1 {
625 t.Fatal("window swept before it expired")
626 }
627 clock = clock.Add(3 * time.Second)
628 fire(false)
629 if f.countRows(t, f.directory, "operator_plans") != 0 {
630 t.Fatal("expired window row left")
631 }
632}
633
634// A plan row that survives a restart is still swept at its end: boot
635// schedules one sweep per surviving row (PlanStore.Ends).
636func TestOperatorBootSchedulesSweepsForSurvivingRows(t *testing.T) {
637 f := newOperatorFixture(t)
638 if rec := f.post("directory", operatorPlanPath, f.plan(t, "directory", "add-apps", []string{"docs"}, nil), nil); rec.Code != 200 {
639 t.Fatal(rec.Code)
640 }
641 var end int64
642 if err := f.directory.db.Writer().QueryRow("SELECT expires_at FROM operator_plans").Scan(&end); err != nil {
643 t.Fatal(err)
644 }
645 // Boot again on the same database, with the scheduler captured.
646 cfg := *f.directory.runtime
647 settings := *cfg.operator
648 clock := time.Now()
649 settings.now = func() time.Time { return clock }
650 var waits []time.Duration
651 var sweeps []func()
652 settings.after = func(d time.Duration, fn func()) { waits = append(waits, d); sweeps = append(sweeps, fn) }
653 cfg.operator = &settings
654 a, err := NewRuntime(cfg, f.directory.db, quietLogger())
655 if err != nil {
656 t.Fatal(err)
657 }
658 want := time.Unix(end, 0).Sub(clock) + time.Second
659 if len(waits) != 1 || waits[0] != want {
660 t.Fatal("boot scheduled", waits, "want", want)
661 }
662 clock = time.Unix(end, 0).Add(time.Second)
663 sweeps[0]()
664 if f.countRows(t, a, "operator_plans") != 0 {
665 t.Fatal("surviving plan row not swept at its end")
666 }
667}
668