| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "regexp" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/home/internal/home/directorydata" |
| 17 | "amadan.net/oficina/home/internal/home/sealtest" |
| 18 | "amadan.net/oficina/home/internal/operator" |
| 19 | "amadan.net/oficina/home/roster" |
| 20 | "amadan.net/rastrillo/rastrillo/assertion" |
| 21 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 22 | "amadan.net/rastrillo/rastrillo/migrate" |
| 23 | "amadan.net/rastrillo/rastrillo/sessions" |
| 24 | json "github.com/go-json-experiment/json" |
| 25 | "github.com/keymaildev/signin" |
| 26 | ) |
| 27 | |
| 28 | func backdate(t *testing.T, a *App, column string, at time.Time) { |
| 29 | t.Helper() |
| 30 | if _, err := a.db.Writer().Exec("UPDATE sessions SET "+column+"=?", at.UTC().Format(time.RFC3339)); err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | func (f *operatorFixture) submit(t *testing.T, role, kind string, apps []string) { |
| 36 | t.Helper() |
| 37 | if rec := f.post(role, operatorPlanPath, f.plan(t, role, kind, apps, nil), nil); rec.Code != 200 { |
| 38 | t.Fatal(role, "plan", rec.Code, rec.Body.String()) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | func TestOperatorDirectoryConfirmCeremony(t *testing.T) { |
| 43 | f := newOperatorFixture(t) |
| 44 | f.submit(t, "directory", "create-team", []string{"docs", "sheets"}) |
| 45 | // Signed out: the fresh-only start, back to this page. |
| 46 | anon := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil) |
| 47 | if anon.Code != 303 || anon.Header().Get("Location") != freshStartPath+"?return_to=%2Foperator%2Fconfirm" { |
| 48 | t.Fatal("anonymous confirm", anon.Code, anon.Header().Get("Location")) |
| 49 | } |
| 50 | cred := f.paulCredential(t) |
| 51 | session := f.paulDirectory(t, cred) |
| 52 | page := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, session) |
| 53 | body := page.Body.String() |
| 54 | if page.Code != 200 || !strings.Contains(body, operatorName) || !strings.Contains(body, operatorLabel+".docs.oficina.works") || !strings.Contains(body, operatorLabel+".sheets.oficina.works") || !strings.Contains(body, "5a5a5a5a") { |
| 55 | t.Fatal("directory page does not show Home's copy", page.Code) |
| 56 | } |
| 57 | // A plan id other than the pending one is refused at confirm. |
| 58 | wrong := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(91)}}, session) |
| 59 | if wrong.Code != 403 || f.openCount(t, f.directory) != 0 { |
| 60 | t.Fatal("other plan id opened", wrong.Code) |
| 61 | } |
| 62 | // Stale and future auth_time: back through the fresh exchange. |
| 63 | for _, at := range []time.Time{time.Now().Add(-301 * time.Second), time.Now().Add(time.Hour)} { |
| 64 | backdate(t, f.directory, "auth_time", at) |
| 65 | r := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, session) |
| 66 | if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), freshStartPath) { |
| 67 | t.Fatal("stale/future directory session admitted", r.Code) |
| 68 | } |
| 69 | post := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(90)}}, session) |
| 70 | if post.Code != 303 || f.openCount(t, f.directory) != 0 { |
| 71 | t.Fatal("stale POST opened", post.Code) |
| 72 | } |
| 73 | // Any other id is a redirect too, never a page drawn to a stale session. |
| 74 | other := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(91)}}, session) |
| 75 | if other.Code != 303 || strings.Contains(other.Body.String(), operatorName) { |
| 76 | t.Fatal("stale POST with another plan id rendered", other.Code) |
| 77 | } |
| 78 | } |
| 79 | session = f.paulDirectory(t, f.paulCredential(t)) |
| 80 | if rec := f.confirm(t, "directory", session, ""); rec.Code != 200 || f.openCount(t, f.directory) != 1 { |
| 81 | t.Fatal("confirm", rec.Code) |
| 82 | } |
| 83 | // After plan expiry nothing opens. |
| 84 | f.expireWindows(t) |
| 85 | f.submit(t, "directory", "add-apps", []string{"docs"}) |
| 86 | f.directory.op.now = func() time.Time { return time.Now().Add(601 * time.Second) } |
| 87 | post := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(90)}}, session) |
| 88 | if post.Code != 403 || f.openCount(t, f.directory) != 0 || f.countRows(t, f.directory, "operator_plans") != 0 { |
| 89 | t.Fatal("expired plan opened or lingered", post.Code) |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | func (f *operatorFixture) openCount(t *testing.T, a *App) int { |
| 94 | t.Helper() |
| 95 | var n int |
| 96 | if err := a.db.Writer().QueryRow("SELECT count(*) FROM operator_plans WHERE state='open'").Scan(&n); err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | return n |
| 100 | } |
| 101 | |
| 102 | func TestOperatorConfirmRefusesAnotherSubjectWith404(t *testing.T) { |
| 103 | f := newOperatorFixture(t) |
| 104 | f.submit(t, "directory", "add-apps", []string{"docs"}) |
| 105 | f.submit(t, "credential", "add-apps", []string{"docs"}) |
| 106 | stranger := signInFully(t, f.credential, "stranger@example.invalid") |
| 107 | if r := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, stranger); r.Code != 404 { |
| 108 | t.Fatal("credential confirm for a non-operator", r.Code) |
| 109 | } |
| 110 | if r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {fixtureToken(90)}}, stranger); r.Code != 404 { |
| 111 | t.Fatal("credential confirm POST for a non-operator", r.Code) |
| 112 | } |
| 113 | session := f.paulDirectory(t, stranger) |
| 114 | if r := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, session); r.Code != 404 { |
| 115 | t.Fatal("directory confirm for a non-operator", r.Code) |
| 116 | } |
| 117 | if f.openCount(t, f.directory)+f.openCount(t, f.credential.App) != 0 { |
| 118 | t.Fatal("window opened") |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | func TestOperatorCredentialConfirmCeremony(t *testing.T) { |
| 123 | f := newOperatorFixture(t) |
| 124 | signInFully(t, f.credential, sealtest.CanaryAddress) |
| 125 | f.submit(t, "credential", "create-team", []string{"docs"}) |
| 126 | paul := f.paulCredential(t) |
| 127 | page := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul) |
| 128 | if page.Code != 200 || !strings.Contains(page.Body.String(), "Type the owner’s email to confirm") || !strings.Contains(page.Body.String(), "5a5a5a5a") || !strings.Contains(page.Body.String(), "Docs") { |
| 129 | t.Fatal("credential page", page.Code) |
| 130 | } |
| 131 | // A mistyped owner opens nothing. |
| 132 | m := planIDField.FindStringSubmatch(page.Body.String()) |
| 133 | for _, typed := range []string{"", "someone-else@example.invalid", "canary-8f3a@example.invalid.x"} { |
| 134 | r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}, "owner": {typed}}, paul) |
| 135 | if r.Code != 403 || f.openCount(t, f.credential.App) != 0 || (typed != "" && strings.Contains(r.Body.String(), typed)) { |
| 136 | t.Fatal("mistyped owner", typed, r.Code) |
| 137 | } |
| 138 | } |
| 139 | // Case and surrounding space are the blind index's own normalisation. |
| 140 | if r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}, "owner": {" " + strings.ToUpper(sealtest.CanaryAddress) + " "}}, paul); r.Code != 200 || f.openCount(t, f.credential.App) != 1 { |
| 141 | t.Fatal("typed owner refused", r.Code) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | func TestOperatorCredentialConfirmStaleSessionGetsAFreshIntentAndNoLoop(t *testing.T) { |
| 146 | f := newOperatorFixture(t) |
| 147 | f.submit(t, "credential", "add-apps", []string{"docs"}) |
| 148 | paul := f.paulCredential(t) |
| 149 | backdate(t, f.credential.App, "auth_time", time.Now().Add(-time.Hour)) |
| 150 | stale := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul) |
| 151 | if stale.Code != 303 || stale.Header().Get("Location") != "/signin?return_to=%2Foperator%2Fconfirm" { |
| 152 | t.Fatal("stale session", stale.Code, stale.Header().Get("Location")) |
| 153 | } |
| 154 | intent := namedCookie(t, stale, assertionIntentCookie) |
| 155 | read, ok := f.credential.readAssertionIntent(&http.Request{Header: http.Header{"Cookie": {intent.String()}}}, time.Now()) |
| 156 | if !ok || read.Consumer != operatorConfirmConsumer || read.MaxAge != 300 || read.Subject != f.paul { |
| 157 | t.Fatal("fresh intent shape", read) |
| 158 | } |
| 159 | // The reserved consumer can never reach an assertion. |
| 160 | if r := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, f.paulCredential(t)); r.Code == 200 || strings.Contains(r.Body.String(), `name="assertion"`) { |
| 161 | t.Fatal("reserved consumer minted an assertion", r.Code) |
| 162 | } |
| 163 | // A Keymail identity is sent to the email link, not a no-gesture loop. |
| 164 | form := exchangeRequest(f.credential.App, "GET", Origin+stale.Header().Get("Location"), "", nil, intent, paul) |
| 165 | navigation := namedCookie(t, form, returnCookie) |
| 166 | f.credential.flow.Classifier = &signin.Classifier{HTTP: &http.Client{Timeout: classifierTimeout}} |
| 167 | newKeymailStub(t, f.credential, f.paulAddress) |
| 168 | begin := exchangeRequest(f.credential.App, "POST", Origin+"/signin", Origin, url.Values{"address": {f.paulAddress}}, intent, paul, navigation) |
| 169 | if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" { |
| 170 | t.Fatal("forced sign-in did not take the email link", begin.Code, begin.Header().Get("Location")) |
| 171 | } |
| 172 | verified := exchangeRequest(f.credential.App, "POST", Origin+linkPath, Origin, url.Values{"token": {capturedLink(t, f.credential)}}, intent, paul, navigation) |
| 173 | if verified.Code != 303 || verified.Header().Get("Location") != operatorConfirm { |
| 174 | t.Fatal("sign-in lost the confirm page", verified.Code, verified.Header().Get("Location")) |
| 175 | } |
| 176 | fresh := sessionCookie(verified) |
| 177 | back := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, intent, fresh) |
| 178 | if back.Code != 200 { |
| 179 | t.Fatal("returned fresh session refused", back.Code) |
| 180 | } |
| 181 | if c := back.Result().Cookies(); len(c) != 1 || c[0].Name != assertionIntentCookie || c[0].MaxAge >= 0 { |
| 182 | t.Fatal("intent not consumed", c) |
| 183 | } |
| 184 | m := planIDField.FindStringSubmatch(back.Body.String()) |
| 185 | opened := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}}, intent, fresh) |
| 186 | if opened.Code != 200 || f.openCount(t, f.credential.App) != 1 { |
| 187 | t.Fatal("confirm", opened.Code) |
| 188 | } |
| 189 | if c := opened.Result().Cookies(); len(c) != 1 || c[0].Name != assertionIntentCookie || c[0].MaxAge >= 0 { |
| 190 | t.Fatal("intent cookie not cleared after confirm", c) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | func TestOperatorCredentialConfirmRefusesKeymailWithoutGestureAndRecovery(t *testing.T) { |
| 195 | f := newOperatorFixture(t) |
| 196 | f.submit(t, "credential", "add-apps", []string{"docs"}) |
| 197 | for _, method := range []string{string(signin.MethodKeymail), "magiclink+recovery", "keymail+recovery"} { |
| 198 | token, err := f.credential.sessions.Mint(sessionWith(f.paul, method)) |
| 199 | if err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | cookie := &http.Cookie{Name: f.credential.sessions.CookieName(), Value: token} |
| 203 | if r := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, cookie); r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin") { |
| 204 | t.Fatal(method, "admitted", r.Code) |
| 205 | } |
| 206 | if r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {fixtureToken(90)}}, cookie); r.Code != 303 || f.openCount(t, f.credential.App) != 0 { |
| 207 | t.Fatal(method, "opened", r.Code) |
| 208 | } |
| 209 | if r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {fixtureToken(91)}}, cookie); r.Code != 303 { |
| 210 | t.Fatal(method, "stale POST with another plan id rendered", r.Code) |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func TestOperatorFreshIntentWithInvalidNonceIsIgnored(t *testing.T) { |
| 216 | f := newOperatorFixture(t) |
| 217 | b, _ := json.Marshal(assertionIntent{Consumer: operatorConfirmConsumer, Nonce: "not-a-nonce", Expires: time.Now().Unix() + 600, MaxAge: 300, Subject: f.paul}) |
| 218 | sealed, _ := f.credential.secrets.Sealer.Seal("assertion.intent", b) |
| 219 | bad := &http.Cookie{Name: assertionIntentCookie, Value: base64.RawURLEncoding.EncodeToString(sealed)} |
| 220 | if _, ok := f.credential.readAssertionIntent(&http.Request{Header: http.Header{"Cookie": {bad.String()}}}, time.Now()); ok { |
| 221 | t.Fatal("invalid nonce read as an intent") |
| 222 | } |
| 223 | // A plain sign-in, then the page: no loop. |
| 224 | f.submit(t, "credential", "add-apps", []string{"docs"}) |
| 225 | signIn(t, f.credential, f.paulAddress) |
| 226 | verified := redeem(t, f.credential, capturedLink(t, f.credential)) |
| 227 | if r := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, bad, sessionCookie(verified)); r.Code != 200 { |
| 228 | t.Fatal("fresh session with a junk intent refused", r.Code) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // Gate 5: the credential origin renders no account-authored string. The |
| 233 | // plan's label and team name live only on the directory; the owner's |
| 234 | // address is never echoed, typed or not. |
| 235 | func TestOperatorCredentialConfirmRendersNoAccountAuthoredString(t *testing.T) { |
| 236 | f := newOperatorFixture(t) |
| 237 | signInFully(t, f.credential, sealtest.CanaryAddress) |
| 238 | f.provisionTeam(t) |
| 239 | f.expireWindows(t) |
| 240 | f.submit(t, "directory", "create-team", []string{"docs"}) |
| 241 | f.submit(t, "credential", "create-team", []string{"docs", "sheets"}) |
| 242 | paul := f.paulCredential(t) |
| 243 | page := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul) |
| 244 | m := planIDField.FindStringSubmatch(page.Body.String()) |
| 245 | wrong := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}, "owner": {"typed-canary@example.invalid"}}, paul) |
| 246 | right := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}, "owner": {sealtest.CanaryAddress}}, paul) |
| 247 | for _, r := range []string{page.Body.String(), wrong.Body.String(), right.Body.String()} { |
| 248 | for _, canary := range []string{operatorLabel, operatorName, sealtest.CanaryAddress, "typed-canary", "blue.docs"} { |
| 249 | if strings.Contains(strings.ToLower(r), strings.ToLower(canary)) { |
| 250 | t.Fatalf("credential confirm rendered %q", canary) |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | func sessionWith(subject, method string) sessions.Session { |
| 257 | return sessions.Session{Subject: subject, Method: method, At: time.Now()} |
| 258 | } |
| 259 | |
| 260 | func TestOperatorEndToEndProvisioningAndRegistry(t *testing.T) { |
| 261 | f := newOperatorFixture(t) |
| 262 | signInFully(t, f.credential, sealtest.CanaryAddress) |
| 263 | f.provisionTeam(t) |
| 264 | // The registered consumer is in the union at once: /authorize admits it. |
| 265 | nonce, _ := assertion.RandomID() |
| 266 | consumer := operatorLabel + "-docs" |
| 267 | authorize := exchangeRequest(f.credential.App, "GET", Origin+"/authorize?consumer="+consumer+"&nonce="+nonce, "", nil) |
| 268 | if authorize.Code != 303 { |
| 269 | t.Fatal("registered consumer refused at /authorize", authorize.Code) |
| 270 | } |
| 271 | intent := namedCookie(t, authorize, assertionIntentCookie) |
| 272 | session := signInFully(t, f.credential, sealtest.CanaryAddress) |
| 273 | handoff := exchangeRequest(f.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, session) |
| 274 | target := "https://" + operatorLabel + ".docs.oficina.works" |
| 275 | csp := handoff.Header().Get("Content-Security-Policy") |
| 276 | if handoff.Code != 200 || !strings.Contains(csp, "form-action 'self' "+target+" "+directoryOrigin+";") && !strings.HasSuffix(csp, "form-action 'self' "+target+" "+directoryOrigin) { |
| 277 | t.Fatal("handoff CSP does not name exactly its consumer", handoff.Code, csp) |
| 278 | } |
| 279 | if strings.Contains(csp, "blue.docs") || strings.Contains(csp, "preview.example") { |
| 280 | t.Fatal("handoff CSP names other consumers") |
| 281 | } |
| 282 | // The fence: a record for a pre-existing (not stream-seeded) team is |
| 283 | // unobtainable. |
| 284 | if _, err := f.directory.db.Writer().Exec("INSERT INTO teams(sqid,label,sealed_name,created_at) VALUES('gb','acme',zeroblob(40),1)"); err != nil { |
| 285 | t.Fatal(err) |
| 286 | } |
| 287 | if _, err := f.directory.db.Writer().Exec("INSERT INTO memberships(team_id,person_ref,role) VALUES(2,?,'owner')", f.paul); err != nil { |
| 288 | t.Fatal(err) |
| 289 | } |
| 290 | f.expireWindows(t) |
| 291 | f.submit(t, "directory", "add-apps", []string{"sheets"}) |
| 292 | if rec := f.confirm(t, "directory", f.paulDirectory(t, f.paulCredential(t)), ""); rec.Code != 200 { |
| 293 | t.Fatal(rec.Code) |
| 294 | } |
| 295 | if rec, _ := f.run(t, "directory", "directory.provision-consumer", func(b operator.InputBase) any { |
| 296 | return operator.ProvisionInput{InputBase: b, Generation: generationToken(), TeamSQID: "gb", App: "sheets", Consumer: "acme-sheets", Audience: "https://acme.sheets.oficina.works"} |
| 297 | }); rec.Code != 403 { |
| 298 | t.Fatal("record for a pre-existing team", rec.Code) |
| 299 | } |
| 300 | // Retire: refused at /authorize and at sign-out afterwards. |
| 301 | f.expireWindows(t) |
| 302 | f.submit(t, "credential", "retire-apps", []string{"docs"}) |
| 303 | paul := f.paulCredential(t) |
| 304 | if rec := f.confirm(t, "credential", paul, ""); rec.Code != 200 { |
| 305 | t.Fatal(rec.Code) |
| 306 | } |
| 307 | if rec, _ := f.run(t, "credential", "credential.retire-consumer", func(b operator.InputBase) any { |
| 308 | return operator.RetireInput{InputBase: b, Consumer: consumer} |
| 309 | }); rec.Code != 200 { |
| 310 | t.Fatal("retire", rec.Code, rec.Body.String()) |
| 311 | } |
| 312 | if r := exchangeRequest(f.credential.App, "GET", Origin+"/authorize?consumer="+consumer+"&nonce="+nonce, "", nil); r.Code != 400 { |
| 313 | t.Fatal("retired consumer admitted at /authorize", r.Code) |
| 314 | } |
| 315 | signout := exchangeRequest(f.credential.App, "POST", Origin+signoutPath, target, url.Values{}, session) |
| 316 | if signout.Code != 403 { |
| 317 | t.Fatal("retired consumer admitted at sign-out", signout.Code) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | func TestOperatorSignoutConfirmCSPNamesOneConsumer(t *testing.T) { |
| 322 | f := newOperatorFixture(t) |
| 323 | r := exchangeRequest(f.credential.App, "POST", Origin+signoutPath, "https://preview.example.test", url.Values{}) |
| 324 | csp := r.Header().Get("Content-Security-Policy") |
| 325 | if r.Code != 200 || csp != f.credential.securityPolicy("https://preview.example.test") || strings.Contains(csp, "blue.docs") { |
| 326 | t.Fatal("signoutConfirm CSP", r.Code, csp) |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | // Additive migrations: sessions, keys and team ciphertexts written before |
| 331 | // them survive, and the previous binary's schema still applies after them. |
| 332 | func TestOperatorHTTPMigrationsAreAdditive(t *testing.T) { |
| 333 | p := newExchangePair(t) |
| 334 | session := signInFully(t, p.credential, sealtest.CanaryAddress) |
| 335 | if _, err := migrate.Apply(context.Background(), p.credential.db, (Runtime{role: "credential"}).ServingSchema()); err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | if _, err := migrate.Apply(context.Background(), p.credential.db, migrate.Merge(BootSchema, operator.CredentialSchema)); err != nil { |
| 339 | t.Fatal("old credential schema refused the new database", err) |
| 340 | } |
| 341 | if r := exchangeRequest(p.credential.App, "GET", Origin+"/passkey/enrol", "", nil, session); r.Code != 200 { |
| 342 | t.Fatal("session lost across the migration", r.Code) |
| 343 | } |
| 344 | if _, err := p.directory.db.Writer().Exec("INSERT INTO teams(sqid,label,sealed_name,created_at) VALUES('Uk','alpha',?,1)", mustSealName(t, p.directory, 1, "Alpha")); err != nil { |
| 345 | t.Fatal(err) |
| 346 | } |
| 347 | if _, err := migrate.Apply(context.Background(), p.directory.db, (Runtime{role: "directory"}).ServingSchema()); err != nil { |
| 348 | t.Fatal(err) |
| 349 | } |
| 350 | if _, err := migrate.Apply(context.Background(), p.directory.db, migrate.Merge(directorySchema, directorydata.OperatorSchema, operator.DirectorySchema)); err != nil { |
| 351 | t.Fatal("old directory schema refused the new database", err) |
| 352 | } |
| 353 | var sealed []byte |
| 354 | if err := p.directory.db.Writer().QueryRow("SELECT sealed_name FROM teams").Scan(&sealed); err != nil { |
| 355 | t.Fatal(err) |
| 356 | } |
| 357 | if name, err := p.directory.secrets.Sealer.Open("directory.team-name/1", sealed); err != nil || string(name) != "Alpha" { |
| 358 | t.Fatal("team ciphertext lost", err) |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | func mustSealName(t *testing.T, a *App, id int64, name string) []byte { |
| 363 | t.Helper() |
| 364 | b, err := a.secrets.Sealer.Seal("directory.team-name/1", []byte(name)) |
| 365 | if err != nil { |
| 366 | t.Fatal(err) |
| 367 | } |
| 368 | return b |
| 369 | } |
| 370 | |
| 371 | // Gate 1 and gate 9 over the whole sequence: plan, both confirms, every |
| 372 | // verb, hostile refusals. No canary address, team name, label, plan bytes, |
| 373 | // bearer or prefilter in either database (file, WAL, SHM) or any log line. |
| 374 | func TestOperatorPrivacyGatesOverTheWholeSequence(t *testing.T) { |
| 375 | f := newOperatorFixture(t) |
| 376 | signInFully(t, f.credential, sealtest.CanaryAddress) |
| 377 | records := f.provisionTeam(t) |
| 378 | plan := f.plan(t, "credential", "create-team", []string{"docs"}, nil) |
| 379 | // Hostile refusals carrying the canaries in their bodies. |
| 380 | f.post("credential", operatorPlanPath, plan, func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+fixtureToken(9)) }) |
| 381 | f.post("credential", operatorPlanPath, plan, func(r *http.Request) { r.Header.Set("Origin", "https://"+operatorLabel+".docs.oficina.works") }) |
| 382 | f.post("directory", operatorPath, []byte(`{"label":"`+operatorLabel+`","name":"`+operatorName+`","owner":"`+sealtest.CanaryAddress+`"}`), nil) |
| 383 | f.post("credential", operatorPath, []byte(`{"owner":"`+sealtest.CanaryAddress+`"}`), nil) |
| 384 | f.post("credential", operatorPlanPath, plan, nil) |
| 385 | f.post("credential", operatorPlanPath, plan, nil) |
| 386 | for _, path := range []string{f.credential.dbPath, f.directoryPath} { |
| 387 | sealtest.AssertNoPlaintext(t, path) |
| 388 | for _, suffix := range []string{"", "-wal", "-shm"} { |
| 389 | b, _ := os.ReadFile(path + suffix) |
| 390 | secrets := append(signedPlanParts(t, plan), []byte(f.prefilter)) |
| 391 | secrets = append(secrets, signedPlanParts(t, records["docs"])[:4]...) |
| 392 | for _, secret := range secrets { |
| 393 | if bytes.Contains(b, secret) { |
| 394 | t.Fatal("private operator bytes at rest in", path+suffix) |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | } |
| 399 | logs := f.logs.String() |
| 400 | if !strings.Contains(logs, "operator http") { |
| 401 | t.Fatal("captured no operator log lines; the gate would pass by not looking") |
| 402 | } |
| 403 | for _, canary := range []string{sealtest.CanaryAddress, operatorName, operatorLabel, f.prefilter, fixtureToken(90), string(signedPlanParts(t, plan)[2][:40])} { |
| 404 | if strings.Contains(strings.ToLower(logs), strings.ToLower(canary)) { |
| 405 | t.Fatalf("log line carries %q", canary) |
| 406 | } |
| 407 | } |
| 408 | for _, line := range strings.Split(strings.TrimSpace(logs), "\n") { |
| 409 | if strings.Contains(line, "operator") && !regexp.MustCompile(`msg="operator (http|confirm)"`).MatchString(line) { |
| 410 | continue |
| 411 | } |
| 412 | if m := regexp.MustCompile(` op=(\S*)`).FindStringSubmatch(line); m != nil && len(m[1]) > 8 { |
| 413 | t.Fatal("operation id logged past its prefix", line) |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // Gate 10: every new route answers no-store, on both origins, whatever the |
| 419 | // outcome. |
| 420 | func TestOperatorRoutesAreNoStore(t *testing.T) { |
| 421 | f := newOperatorFixture(t) |
| 422 | f.submit(t, "directory", "add-apps", []string{"docs"}) |
| 423 | f.submit(t, "credential", "add-apps", []string{"docs"}) |
| 424 | paul := f.paulCredential(t) |
| 425 | dir := f.paulDirectory(t, paul) |
| 426 | stranger := signInFully(t, f.credential, "stranger@example.invalid") |
| 427 | var recs []*httptest.ResponseRecorder |
| 428 | for _, role := range []string{"credential", "directory"} { |
| 429 | recs = append(recs, |
| 430 | f.post(role, operatorPath, []byte("{}"), nil), |
| 431 | f.post(role, operatorPlanPath, []byte("{}"), nil), |
| 432 | f.post(role, operatorPlanPath, []byte("{}"), func(r *http.Request) { r.Header.Del("Authorization") }), |
| 433 | f.post(role, operatorPath, []byte("{}"), func(r *http.Request) { r.Method = "GET" }), |
| 434 | ) |
| 435 | } |
| 436 | recs = append(recs, |
| 437 | exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil), |
| 438 | exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul), |
| 439 | exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, stranger), |
| 440 | exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {"x"}}, paul), |
| 441 | exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil), |
| 442 | exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, dir), |
| 443 | exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {"x"}}, dir), |
| 444 | ) |
| 445 | for i, r := range recs { |
| 446 | if r.Header().Get("Cache-Control") != "no-store" { |
| 447 | t.Errorf("response %d (%d) is cacheable", i, r.Code) |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | // Blocker 1, #94: register-consumer admits exactly what the registry reload |
| 453 | // admits, so every row it commits reloads — and boots — cleanly. |
| 454 | func TestOperatorRegisteredRowsAlwaysReload(t *testing.T) { |
| 455 | f := newOperatorFixture(t) |
| 456 | signInFully(t, f.credential, sealtest.CanaryAddress) |
| 457 | f.provisionTeam(t) |
| 458 | page, _ := family.Generate() |
| 459 | for _, audience := range []string{Origin, "https://id.oficina.works:8443"} { |
| 460 | b := roster.Bindings{Issuer: Origin, Directory: directoryOrigin, Consumer: "self-docs", App: "docs", Team: "Uk", Audience: audience} |
| 461 | record, err := roster.SignProvisioning(f.provisioning, hexID(f.provisioning), roster.Provisioning{Version: 1, Operation: fixtureToken(71), Sequence: 1, Bindings: b, Generation: generationToken(), MinEpoch: 2, Keys: []roster.Key{{ID: hexID(page), Public: rawURLPub(page)}}}) |
| 462 | if err != nil { |
| 463 | t.Fatal(err) |
| 464 | } |
| 465 | if rec, _ := f.run(t, "credential", "credential.register-consumer", func(in operator.InputBase) any { |
| 466 | return operator.RegisterInput{InputBase: in, Record: record} |
| 467 | }); rec.Code != 403 { |
| 468 | t.Fatal("registered an audience the reload refuses", audience, rec.Code) |
| 469 | } |
| 470 | } |
| 471 | if f.countRows(t, f.credential.App, "consumers") != 1 { |
| 472 | t.Fatal("refused registration wrote a row") |
| 473 | } |
| 474 | fresh := newConsumerRegistry(f.credential.runtime.consumers) |
| 475 | if err := fresh.load(context.Background(), f.credential.db.Writer(), Origin, f.credential.runtime.keys); err != nil { |
| 476 | t.Fatal("a committed row fails the reload", err) |
| 477 | } |
| 478 | if _, ok := fresh.snapshot()[operatorLabel+"-docs"]; !ok { |
| 479 | t.Fatal("registered consumer missing from a fresh union") |
| 480 | } |
| 481 | cfg := *f.credential.runtime |
| 482 | cfg.registry, cfg.operator = nil, nil |
| 483 | if _, err := NewRuntime(cfg, f.credential.db, quietLogger()); err != nil { |
| 484 | t.Fatal("the credential role no longer boots", err) |
| 485 | } |
| 486 | } |
| 487 | |