oficina / home Public

Operator confirm pages on both roles, behind fresh sign-in

team-provisioning-amendment.md §4 steps 2 and 3.

- oficina.works/operator/confirm (directory, inside its CSRF group): no
  query, the role's one pending plan. Signed out, stale (auth_time older
  than 300 s) or future auth_time: through the fresh-only consumer
  (/auth/fresh/start?return_to=/operator/confirm). Subject other than
  operator_subject: 404. Renders Home's copy: plan id prefix, kind, label,
  display name, each app as <label>.<app>.oficina.works, expiry. The POST
  re-checks subject and freshness inside the write and opens the window.
- id.oficina.works/operator/confirm (credential, inside its CSRF group,
  joined to credentialReturn's closed list): GET and POST require the
  operator subject (else 404), sessions.Fresh(300), no future auth_time,
  not Keymail without a gesture, and no recovery method. A stale session
  gets a sealed fresh intent (MaxAge 300, Subject operator_subject, random
  nonce, reserved consumer ':operator-confirm') before /signin, so the
  forced sign-in takes a real gesture; the page consumes and clears it.
  handleAssertion refuses the reserved consumer. Renders no account-authored
  string: plan id and owner_index prefixes, compiled app names, fixed kind
  text, expiry. The POST opens the window only if the typed address
  blind-indexes to the stored owner_index, re-checked inside the write.

Tests (amendment §10.4, gates 1, 5, 9, 10): Home's copy rendered; other
plan id refused; stale/future directory sessions; non-operator 404 on both;
mistyped owner; stale credential session -> intent -> email link for a
Keymail identity -> back to the page, intent cleared; reserved consumer
never mints; Keymail-without-gesture and recovery sessions refused; invalid
nonce ignored with no loop; intent cleared after confirm; plan expiry;
end-to-end provisioning (initialize, owner-seed, seed-team, provision,
register, retire) with the registry and handoff CSP; fence refuses a
pre-existing team; additive migrations; no-store on every new route; gate 1
and gate 9 over the whole sequence with hostile refusals.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5f9958b1f70e580ac19e7b0694b67682c3b588c3 parent 0690812
9 files changed, +786 −2
  • internal/home/app.go +4 −0
  • internal/home/calma.go +1 −0
  • internal/home/directory.go +4 −0
  • internal/home/exchange.go +3 −1
  • internal/home/operator_ceremony_test.go +438 −0
  • internal/home/operator_confirm.go +277 −0
  • internal/home/signin_return.go +1 −1
  • internal/home/templates/operator_confirm.html +27 −0
  • internal/home/templates/operator_confirm_id.html +31 −0
diff --git a/internal/home/app.go b/internal/home/app.go
index e874001..4373aac 100644
--- a/internal/home/app.go
+++ b/internal/home/app.go
@@ -204,6 +204,10 @@ func (a *App) Router() http.Handler {
r.Get("/dashboard/authorize", a.beginDashboard)
r.With(a.sessions.Require).Get("/dashboard/resume", a.authorizeDashboard)
r.With(a.sessions.Require).Get("/authorize/resume", a.handleAssertion)
+ if a.op != nil {
+ r.Get(operatorConfirm, a.handleCredentialConfirm)
+ r.Post(operatorConfirm, a.handleCredentialConfirmPost)
+ }
versionAsset("/static/assertion.js", staticAsset("assertion.js"))
r.Get("/static/assertion.js", serveAsset(staticAsset("assertion.js"), "text/javascript; charset=utf-8"))
}
diff --git a/internal/home/calma.go b/internal/home/calma.go
index 34eb125..729fa48 100644
--- a/internal/home/calma.go
+++ b/internal/home/calma.go
@@ -83,6 +83,7 @@ var doorPages = map[string]bool{
"handoff_failed.html": true,
"signout_confirm.html": true,
"directory_signed_out.html": true,
+ "operator_confirm_id.html": true,
}
// hopPages move on by themselves (an auto-submit, a 0 s refresh). They
diff --git a/internal/home/directory.go b/internal/home/directory.go
index 5621501..25bf907 100644
--- a/internal/home/directory.go
+++ b/internal/home/directory.go
@@ -114,6 +114,10 @@ func (a *App) directoryRouter() http.Handler {
r.Get("/signin", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, handoff.StartPath, http.StatusSeeOther)
})
+ if a.op != nil {
+ r.Get(operatorConfirm, a.handleDirectoryConfirm)
+ r.Post(operatorConfirm, a.handleDirectoryConfirmPost)
+ }
// One URL, two audiences. A visitor with no session gets the front
// page — what Oficina is, the apps, and the way in. A signed-in
// person gets their directory. Gating this behind sessions.Require
diff --git a/internal/home/exchange.go b/internal/home/exchange.go
index 26e604e..849b692 100644
--- a/internal/home/exchange.go
+++ b/internal/home/exchange.go
@@ -75,8 +75,10 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) {
a.failAssertion(w, r, assertionIntentInvalid)
return
}
+ // The operator confirm page's fresh intent carries a reserved consumer
+ // value that is never a consumer name; it can never mint an assertion.
target, ok := a.consumers()[intent.Consumer]
- if !ok {
+ if !ok || intent.Consumer == operatorConfirmConsumer {
a.failAssertion(w, r, assertionConsumer)
return
}
diff --git a/internal/home/operator_ceremony_test.go b/internal/home/operator_ceremony_test.go
new file mode 100644
index 0000000..665a792
--- /dev/null
+++ b/internal/home/operator_ceremony_test.go
@@ -0,0 +1,438 @@
+package home
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ "amadan.net/oficina/home/internal/home/sealtest"
+ "amadan.net/oficina/home/internal/operator"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ json "github.com/go-json-experiment/json"
+ "github.com/keymaildev/signin"
+)
+
+func backdate(t *testing.T, a *App, column string, at time.Time) {
+ t.Helper()
+ if _, err := a.db.Writer().Exec("UPDATE sessions SET "+column+"=?", at.UTC().Format(time.RFC3339)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (f *operatorFixture) submit(t *testing.T, role, kind string, apps []string) {
+ t.Helper()
+ if rec := f.post(role, operatorPlanPath, f.plan(t, role, kind, apps, nil), nil); rec.Code != 200 {
+ t.Fatal(role, "plan", rec.Code, rec.Body.String())
+ }
+}
+
+func TestOperatorDirectoryConfirmCeremony(t *testing.T) {
+ f := newOperatorFixture(t)
+ f.submit(t, "directory", "create-team", []string{"docs", "sheets"})
+ // Signed out: the fresh-only start, back to this page.
+ anon := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil)
+ if anon.Code != 303 || anon.Header().Get("Location") != freshStartPath+"?return_to=%2Foperator%2Fconfirm" {
+ t.Fatal("anonymous confirm", anon.Code, anon.Header().Get("Location"))
+ }
+ cred := f.paulCredential(t)
+ session := f.paulDirectory(t, cred)
+ page := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, session)
+ body := page.Body.String()
+ 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") {
+ t.Fatal("directory page does not show Home's copy", page.Code)
+ }
+ // A plan id other than the pending one is refused at confirm.
+ wrong := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(91)}}, session)
+ if wrong.Code != 403 || f.openCount(t, f.directory) != 0 {
+ t.Fatal("other plan id opened", wrong.Code)
+ }
+ // Stale and future auth_time: back through the fresh exchange.
+ for _, at := range []time.Time{time.Now().Add(-301 * time.Second), time.Now().Add(time.Hour)} {
+ backdate(t, f.directory, "auth_time", at)
+ r := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, session)
+ if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), freshStartPath) {
+ t.Fatal("stale/future directory session admitted", r.Code)
+ }
+ post := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(90)}}, session)
+ if post.Code != 303 || f.openCount(t, f.directory) != 0 {
+ t.Fatal("stale POST opened", post.Code)
+ }
+ }
+ session = f.paulDirectory(t, f.paulCredential(t))
+ if rec := f.confirm(t, "directory", session, ""); rec.Code != 200 || f.openCount(t, f.directory) != 1 {
+ t.Fatal("confirm", rec.Code)
+ }
+ // After plan expiry nothing opens.
+ f.expireWindows(t)
+ f.submit(t, "directory", "add-apps", []string{"docs"})
+ f.directory.op.now = func() time.Time { return time.Now().Add(601 * time.Second) }
+ post := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(90)}}, session)
+ if post.Code != 403 || f.openCount(t, f.directory) != 0 || f.countRows(t, f.directory, "operator_plans") != 0 {
+ t.Fatal("expired plan opened or lingered", post.Code)
+ }
+}
+
+func (f *operatorFixture) openCount(t *testing.T, a *App) int {
+ t.Helper()
+ var n int
+ if err := a.db.Writer().QueryRow("SELECT count(*) FROM operator_plans WHERE state='open'").Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func TestOperatorConfirmRefusesAnotherSubjectWith404(t *testing.T) {
+ f := newOperatorFixture(t)
+ f.submit(t, "directory", "add-apps", []string{"docs"})
+ f.submit(t, "credential", "add-apps", []string{"docs"})
+ stranger := signInFully(t, f.credential, "stranger@example.invalid")
+ if r := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, stranger); r.Code != 404 {
+ t.Fatal("credential confirm for a non-operator", r.Code)
+ }
+ if r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {fixtureToken(90)}}, stranger); r.Code != 404 {
+ t.Fatal("credential confirm POST for a non-operator", r.Code)
+ }
+ session := f.paulDirectory(t, stranger)
+ if r := exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, session); r.Code != 404 {
+ t.Fatal("directory confirm for a non-operator", r.Code)
+ }
+ if f.openCount(t, f.directory)+f.openCount(t, f.credential.App) != 0 {
+ t.Fatal("window opened")
+ }
+}
+
+func TestOperatorCredentialConfirmCeremony(t *testing.T) {
+ f := newOperatorFixture(t)
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ f.submit(t, "credential", "create-team", []string{"docs"})
+ paul := f.paulCredential(t)
+ page := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul)
+ 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") {
+ t.Fatal("credential page", page.Code)
+ }
+ // A mistyped owner opens nothing.
+ m := planIDField.FindStringSubmatch(page.Body.String())
+ for _, typed := range []string{"", "someone-else@example.invalid", "canary-8f3a@example.invalid.x"} {
+ r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}, "owner": {typed}}, paul)
+ if r.Code != 403 || f.openCount(t, f.credential.App) != 0 || (typed != "" && strings.Contains(r.Body.String(), typed)) {
+ t.Fatal("mistyped owner", typed, r.Code)
+ }
+ }
+ // Case and surrounding space are the blind index's own normalisation.
+ 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 {
+ t.Fatal("typed owner refused", r.Code)
+ }
+}
+
+func TestOperatorCredentialConfirmStaleSessionGetsAFreshIntentAndNoLoop(t *testing.T) {
+ f := newOperatorFixture(t)
+ f.submit(t, "credential", "add-apps", []string{"docs"})
+ paul := f.paulCredential(t)
+ backdate(t, f.credential.App, "created_at", time.Now().Add(-time.Hour))
+ stale := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul)
+ if stale.Code != 303 || stale.Header().Get("Location") != "/signin?return_to=%2Foperator%2Fconfirm" {
+ t.Fatal("stale session", stale.Code, stale.Header().Get("Location"))
+ }
+ intent := namedCookie(t, stale, assertionIntentCookie)
+ read, ok := f.credential.readAssertionIntent(&http.Request{Header: http.Header{"Cookie": {intent.String()}}}, time.Now())
+ if !ok || read.Consumer != operatorConfirmConsumer || read.MaxAge != 300 || read.Subject != f.paul {
+ t.Fatal("fresh intent shape", read)
+ }
+ // The reserved consumer can never reach an assertion.
+ 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"`) {
+ t.Fatal("reserved consumer minted an assertion", r.Code)
+ }
+ // A Keymail identity is sent to the email link, not a no-gesture loop.
+ form := exchangeRequest(f.credential.App, "GET", Origin+stale.Header().Get("Location"), "", nil, intent, paul)
+ navigation := namedCookie(t, form, returnCookie)
+ f.credential.flow.Classifier = &signin.Classifier{HTTP: &http.Client{Timeout: classifierTimeout}}
+ newKeymailStub(t, f.credential, f.paulAddress)
+ begin := exchangeRequest(f.credential.App, "POST", Origin+"/signin", Origin, url.Values{"address": {f.paulAddress}}, intent, paul, navigation)
+ if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" {
+ t.Fatal("forced sign-in did not take the email link", begin.Code, begin.Header().Get("Location"))
+ }
+ verified := exchangeRequest(f.credential.App, "POST", Origin+linkPath, Origin, url.Values{"token": {capturedLink(t, f.credential)}}, intent, paul, navigation)
+ if verified.Code != 303 || verified.Header().Get("Location") != operatorConfirm {
+ t.Fatal("sign-in lost the confirm page", verified.Code, verified.Header().Get("Location"))
+ }
+ fresh := sessionCookie(verified)
+ back := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, intent, fresh)
+ if back.Code != 200 {
+ t.Fatal("returned fresh session refused", back.Code)
+ }
+ if c := back.Result().Cookies(); len(c) != 1 || c[0].Name != assertionIntentCookie || c[0].MaxAge >= 0 {
+ t.Fatal("intent not consumed", c)
+ }
+ m := planIDField.FindStringSubmatch(back.Body.String())
+ opened := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}}, intent, fresh)
+ if opened.Code != 200 || f.openCount(t, f.credential.App) != 1 {
+ t.Fatal("confirm", opened.Code)
+ }
+ if c := opened.Result().Cookies(); len(c) != 1 || c[0].Name != assertionIntentCookie || c[0].MaxAge >= 0 {
+ t.Fatal("intent cookie not cleared after confirm", c)
+ }
+}
+
+func TestOperatorCredentialConfirmRefusesKeymailWithoutGestureAndRecovery(t *testing.T) {
+ f := newOperatorFixture(t)
+ f.submit(t, "credential", "add-apps", []string{"docs"})
+ for _, method := range []string{string(signin.MethodKeymail), "magiclink+recovery", "keymail+recovery"} {
+ token, err := f.credential.sessions.Mint(sessionWith(f.paul, method))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cookie := &http.Cookie{Name: f.credential.sessions.CookieName(), Value: token}
+ if r := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, cookie); r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin") {
+ t.Fatal(method, "admitted", r.Code)
+ }
+ 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 {
+ t.Fatal(method, "opened", r.Code)
+ }
+ }
+}
+
+func TestOperatorFreshIntentWithInvalidNonceIsIgnored(t *testing.T) {
+ f := newOperatorFixture(t)
+ b, _ := json.Marshal(assertionIntent{Consumer: operatorConfirmConsumer, Nonce: "not-a-nonce", Expires: time.Now().Unix() + 600, MaxAge: 300, Subject: f.paul})
+ sealed, _ := f.credential.secrets.Sealer.Seal("assertion.intent", b)
+ bad := &http.Cookie{Name: assertionIntentCookie, Value: base64.RawURLEncoding.EncodeToString(sealed)}
+ if _, ok := f.credential.readAssertionIntent(&http.Request{Header: http.Header{"Cookie": {bad.String()}}}, time.Now()); ok {
+ t.Fatal("invalid nonce read as an intent")
+ }
+ // A plain sign-in, then the page: no loop.
+ f.submit(t, "credential", "add-apps", []string{"docs"})
+ signIn(t, f.credential, f.paulAddress)
+ verified := redeem(t, f.credential, capturedLink(t, f.credential))
+ if r := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, bad, sessionCookie(verified)); r.Code != 200 {
+ t.Fatal("fresh session with a junk intent refused", r.Code)
+ }
+}
+
+// Gate 5: the credential origin renders no account-authored string. The
+// plan's label and team name live only on the directory; the owner's
+// address is never echoed, typed or not.
+func TestOperatorCredentialConfirmRendersNoAccountAuthoredString(t *testing.T) {
+ f := newOperatorFixture(t)
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ f.provisionTeam(t)
+ f.expireWindows(t)
+ f.submit(t, "directory", "create-team", []string{"docs"})
+ f.submit(t, "credential", "create-team", []string{"docs", "sheets"})
+ paul := f.paulCredential(t)
+ page := exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul)
+ m := planIDField.FindStringSubmatch(page.Body.String())
+ wrong := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}, "owner": {"typed-canary@example.invalid"}}, paul)
+ right := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {m[1]}, "owner": {sealtest.CanaryAddress}}, paul)
+ for _, r := range []string{page.Body.String(), wrong.Body.String(), right.Body.String()} {
+ for _, canary := range []string{operatorLabel, operatorName, sealtest.CanaryAddress, "typed-canary", "blue.docs"} {
+ if strings.Contains(strings.ToLower(r), strings.ToLower(canary)) {
+ t.Fatalf("credential confirm rendered %q", canary)
+ }
+ }
+ }
+}
+
+func sessionWith(subject, method string) sessions.Session {
+ return sessions.Session{Subject: subject, Method: method, At: time.Now()}
+}
+
+func TestOperatorEndToEndProvisioningAndRegistry(t *testing.T) {
+ f := newOperatorFixture(t)
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ f.provisionTeam(t)
+ // The registered consumer is in the union at once: /authorize admits it.
+ nonce, _ := assertion.RandomID()
+ consumer := operatorLabel + "-docs"
+ authorize := exchangeRequest(f.credential.App, "GET", Origin+"/authorize?consumer="+consumer+"&nonce="+nonce, "", nil)
+ if authorize.Code != 303 {
+ t.Fatal("registered consumer refused at /authorize", authorize.Code)
+ }
+ intent := namedCookie(t, authorize, assertionIntentCookie)
+ session := signInFully(t, f.credential, sealtest.CanaryAddress)
+ handoff := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session)
+ target := "https://" + operatorLabel + ".docs.oficina.works"
+ csp := handoff.Header().Get("Content-Security-Policy")
+ if handoff.Code != 200 || !strings.Contains(csp, "form-action 'self' "+target+" "+directoryOrigin+";") && !strings.HasSuffix(csp, "form-action 'self' "+target+" "+directoryOrigin) {
+ t.Fatal("handoff CSP does not name exactly its consumer", handoff.Code, csp)
+ }
+ if strings.Contains(csp, "blue.docs") || strings.Contains(csp, "preview.example") {
+ t.Fatal("handoff CSP names other consumers")
+ }
+ // The fence: a record for a pre-existing (not stream-seeded) team is
+ // unobtainable.
+ if _, err := f.directory.db.Writer().Exec("INSERT INTO teams(sqid,label,sealed_name,created_at) VALUES('gb','acme',zeroblob(40),1)"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.directory.db.Writer().Exec("INSERT INTO memberships(team_id,person_ref,role) VALUES(2,?,'owner')", f.paul); err != nil {
+ t.Fatal(err)
+ }
+ f.expireWindows(t)
+ f.submit(t, "directory", "add-apps", []string{"sheets"})
+ if rec := f.confirm(t, "directory", f.paulDirectory(t, f.paulCredential(t)), ""); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ if rec, _ := f.run(t, "directory", "directory.provision-consumer", func(b operator.InputBase) any {
+ return operator.ProvisionInput{InputBase: b, Generation: generationToken(), TeamSQID: "gb", App: "sheets", Consumer: "acme-sheets", Audience: "https://acme.sheets.oficina.works"}
+ }); rec.Code != 403 {
+ t.Fatal("record for a pre-existing team", rec.Code)
+ }
+ // Retire: refused at /authorize and at sign-out afterwards.
+ f.expireWindows(t)
+ f.submit(t, "credential", "retire-apps", []string{"docs"})
+ paul := f.paulCredential(t)
+ if rec := f.confirm(t, "credential", paul, ""); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ if rec, _ := f.run(t, "credential", "credential.retire-consumer", func(b operator.InputBase) any {
+ return operator.RetireInput{InputBase: b, Consumer: consumer}
+ }); rec.Code != 200 {
+ t.Fatal("retire", rec.Code, rec.Body.String())
+ }
+ if r := exchangeRequest(f.credential.App, "GET", Origin+"/authorize?consumer="+consumer+"&nonce="+nonce, "", nil); r.Code != 400 {
+ t.Fatal("retired consumer admitted at /authorize", r.Code)
+ }
+ signout := exchangeRequest(f.credential.App, "POST", Origin+signoutPath, target, url.Values{}, session)
+ if signout.Code != 403 {
+ t.Fatal("retired consumer admitted at sign-out", signout.Code)
+ }
+}
+
+func TestOperatorSignoutConfirmCSPNamesOneConsumer(t *testing.T) {
+ f := newOperatorFixture(t)
+ r := exchangeRequest(f.credential.App, "POST", Origin+signoutPath, "https://preview.example.test", url.Values{})
+ csp := r.Header().Get("Content-Security-Policy")
+ if r.Code != 200 || csp != f.credential.securityPolicy("https://preview.example.test") || strings.Contains(csp, "blue.docs") {
+ t.Fatal("signoutConfirm CSP", r.Code, csp)
+ }
+}
+
+// Additive migrations: sessions, keys and team ciphertexts written before
+// them survive, and the previous binary's schema still applies after them.
+func TestOperatorHTTPMigrationsAreAdditive(t *testing.T) {
+ p := newExchangePair(t)
+ session := signInFully(t, p.credential, sealtest.CanaryAddress)
+ if _, err := migrate.Apply(context.Background(), p.credential.db, (Runtime{role: "credential"}).ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := migrate.Apply(context.Background(), p.credential.db, migrate.Merge(BootSchema, operator.CredentialSchema)); err != nil {
+ t.Fatal("old credential schema refused the new database", err)
+ }
+ if r := exchangeRequest(p.credential.App, "GET", Origin+"/passkey/enrol", "", nil, session); r.Code != 200 {
+ t.Fatal("session lost across the migration", r.Code)
+ }
+ 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 {
+ t.Fatal(err)
+ }
+ if _, err := migrate.Apply(context.Background(), p.directory.db, (Runtime{role: "directory"}).ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := migrate.Apply(context.Background(), p.directory.db, migrate.Merge(directorySchema, directorydata.OperatorSchema, operator.DirectorySchema)); err != nil {
+ t.Fatal("old directory schema refused the new database", err)
+ }
+ var sealed []byte
+ if err := p.directory.db.Writer().QueryRow("SELECT sealed_name FROM teams").Scan(&sealed); err != nil {
+ t.Fatal(err)
+ }
+ if name, err := p.directory.secrets.Sealer.Open("directory.team-name/1", sealed); err != nil || string(name) != "Alpha" {
+ t.Fatal("team ciphertext lost", err)
+ }
+}
+
+func mustSealName(t *testing.T, a *App, id int64, name string) []byte {
+ t.Helper()
+ b, err := a.secrets.Sealer.Seal("directory.team-name/1", []byte(name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// Gate 1 and gate 9 over the whole sequence: plan, both confirms, every
+// verb, hostile refusals. No canary address, team name, label, plan bytes,
+// bearer or prefilter in either database (file, WAL, SHM) or any log line.
+func TestOperatorPrivacyGatesOverTheWholeSequence(t *testing.T) {
+ f := newOperatorFixture(t)
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ records := f.provisionTeam(t)
+ plan := f.plan(t, "credential", "create-team", []string{"docs"}, nil)
+ // Hostile refusals carrying the canaries in their bodies.
+ f.post("credential", operatorPlanPath, plan, func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+fixtureToken(9)) })
+ f.post("credential", operatorPlanPath, plan, func(r *http.Request) { r.Header.Set("Origin", "https://"+operatorLabel+".docs.oficina.works") })
+ f.post("directory", operatorPath, []byte(`{"label":"`+operatorLabel+`","name":"`+operatorName+`","owner":"`+sealtest.CanaryAddress+`"}`), nil)
+ f.post("credential", operatorPath, []byte(`{"owner":"`+sealtest.CanaryAddress+`"}`), nil)
+ f.post("credential", operatorPlanPath, plan, nil)
+ f.post("credential", operatorPlanPath, plan, nil)
+ for _, path := range []string{f.credential.dbPath, f.directoryPath} {
+ sealtest.AssertNoPlaintext(t, path)
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ b, _ := os.ReadFile(path + suffix)
+ for _, secret := range [][]byte{plan[10:60], records["docs"][10:60], []byte(f.prefilter)} {
+ if bytes.Contains(b, secret) {
+ t.Fatal("private operator bytes at rest in", path+suffix)
+ }
+ }
+ }
+ }
+ logs := f.logs.String()
+ if !strings.Contains(logs, "operator http") {
+ t.Fatal("captured no operator log lines; the gate would pass by not looking")
+ }
+ for _, canary := range []string{sealtest.CanaryAddress, operatorName, operatorLabel, f.prefilter, fixtureToken(90), string(plan[10:40])} {
+ if strings.Contains(strings.ToLower(logs), strings.ToLower(canary)) {
+ t.Fatalf("log line carries %q", canary)
+ }
+ }
+ for _, line := range strings.Split(strings.TrimSpace(logs), "\n") {
+ if strings.Contains(line, "operator") && !regexp.MustCompile(`msg="operator (http|confirm)"`).MatchString(line) {
+ continue
+ }
+ if m := regexp.MustCompile(` op=(\S*)`).FindStringSubmatch(line); m != nil && len(m[1]) > 8 {
+ t.Fatal("operation id logged past its prefix", line)
+ }
+ }
+}
+
+// Gate 10: every new route answers no-store, on both origins, whatever the
+// outcome.
+func TestOperatorRoutesAreNoStore(t *testing.T) {
+ f := newOperatorFixture(t)
+ f.submit(t, "directory", "add-apps", []string{"docs"})
+ f.submit(t, "credential", "add-apps", []string{"docs"})
+ paul := f.paulCredential(t)
+ dir := f.paulDirectory(t, paul)
+ stranger := signInFully(t, f.credential, "stranger@example.invalid")
+ var recs []*httptest.ResponseRecorder
+ for _, role := range []string{"credential", "directory"} {
+ recs = append(recs,
+ f.post(role, operatorPath, []byte("{}"), nil),
+ f.post(role, operatorPlanPath, []byte("{}"), nil),
+ f.post(role, operatorPlanPath, []byte("{}"), func(r *http.Request) { r.Header.Del("Authorization") }),
+ f.post(role, operatorPath, []byte("{}"), func(r *http.Request) { r.Method = "GET" }),
+ )
+ }
+ recs = append(recs,
+ exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil),
+ exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, paul),
+ exchangeRequest(f.credential.App, "GET", Origin+operatorConfirm, "", nil, stranger),
+ exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {"x"}}, paul),
+ exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil),
+ exchangeRequest(f.directory, "GET", directoryOrigin+operatorConfirm, "", nil, dir),
+ exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {"x"}}, dir),
+ )
+ for i, r := range recs {
+ if r.Header().Get("Cache-Control") != "no-store" {
+ t.Errorf("response %d (%d) is cacheable", i, r.Code)
+ }
+ }
+}
diff --git a/internal/home/operator_confirm.go b/internal/home/operator_confirm.go
new file mode 100644
index 0000000..cae5896
--- /dev/null
+++ b/internal/home/operator_confirm.go
@@ -0,0 +1,277 @@
+package home
+
+import (
+ "context"
+ "crypto/hmac"
+ "encoding/base64"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/home/internal/operator"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ json "github.com/go-json-experiment/json"
+)
+
+// The confirm ceremony (team-provisioning-amendment.md §4, steps 2 and 3):
+// Paul opens each role's window on Home's own page, after a fresh sign-in,
+// against Home's own copy of the plan. One pending plan per role, so no
+// query; both pages show the same plan id prefix.
+
+const operatorFreshness = 300 * time.Second
+
+var operatorKinds = map[string]string{
+ "initialize": "Initialize the directory",
+ "create-team": "Create a team",
+ "add-apps": "Add apps to a team",
+ "retire-apps": "Retire apps from a team",
+}
+
+// appName is the compiled registry name for a slug, or "" — never the slug
+// as stored, so the credential page draws only compiled constants.
+func appName(slug string) string {
+ for _, a := range directoryApps() {
+ if a.slug == slug {
+ return a.name
+ }
+ }
+ return ""
+}
+
+func operatorTime(unix int64) string {
+ return time.Unix(unix, 0).UTC().Format("15:04 UTC, 2 Jan 2006")
+}
+
+// ---- directory: oficina.works/operator/confirm ----
+
+// directoryFresh is the directory's view of freshness: the assertion's
+// auth_time, within 300 s and not in the future. The directory cannot see
+// the sign-in method, so a recovery-code or no-gesture Keymail session
+// passes here as it passes the Team page (the amendment's inherited gap);
+// the credential page is where the method is visible and refused.
+func directoryFresh(s sessions.Session, now time.Time) bool {
+ return !s.AuthTime.IsZero() && !s.AuthTime.After(now) && now.Sub(s.AuthTime) <= operatorFreshness
+}
+
+type directoryPlanView struct {
+ ID, Prefix, Kind, Label, Name, Expires string
+ Hosts []string
+}
+
+func (a *App) directoryView(v operator.PlanView) directoryPlanView {
+ out := directoryPlanView{ID: v.ID, Prefix: v.Prefix(), Kind: operatorKinds[v.Kind], Label: v.Label, Name: v.DisplayName, Expires: operatorTime(v.Expires)}
+ for _, app := range v.Apps {
+ out.Hosts = append(out.Hosts, v.Label+"."+app+".oficina.works")
+ }
+ return out
+}
+
+// directoryOperatorSession answers the request itself unless it carries the
+// operator's fresh session.
+func (a *App) directoryOperatorSession(w http.ResponseWriter, r *http.Request) (sessions.Session, bool) {
+ w.Header().Set("Cache-Control", "no-store")
+ s, ok := sessions.Current(r)
+ if ok && s.Subject != a.op.subject {
+ a.notFound(w, r)
+ return s, false
+ }
+ if !ok || !directoryFresh(s, time.Now()) {
+ if r.Method != http.MethodGet {
+ http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
+ return s, false
+ }
+ http.Redirect(w, r, a.fresh.StartPath()+"?return_to=%2Foperator%2Fconfirm", http.StatusSeeOther)
+ return s, false
+ }
+ return s, true
+}
+
+func (a *App) handleDirectoryConfirm(w http.ResponseWriter, r *http.Request) {
+ if _, ok := a.directoryOperatorSession(w, r); !ok {
+ return
+ }
+ data := map[string]any{}
+ v, err := a.op.plans.Pending(r.Context(), a.op.now())
+ switch {
+ case err == nil:
+ data["Plan"] = a.directoryView(v)
+ case !errors.Is(err, operator.ErrRefused):
+ a.serverError(w, r)
+ return
+ }
+ a.render(w, r, http.StatusOK, "operator_confirm.html", data)
+}
+
+func (a *App) handleDirectoryConfirmPost(w http.ResponseWriter, r *http.Request) {
+ s, ok := a.directoryOperatorSession(w, r)
+ if !ok {
+ return
+ }
+ if err := r.ParseForm(); err != nil {
+ a.renderOperatorRefusal(w, r, "operator_confirm.html", http.StatusBadRequest, "Nothing was opened.")
+ return
+ }
+ v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(operator.PlanView) bool {
+ // Subject and freshness again, inside the write.
+ return s.Subject == a.op.subject && directoryFresh(s, time.Now())
+ })
+ a.afterOpen(w, r, "operator_confirm.html", v, err, func(view operator.PlanView) map[string]any {
+ return map[string]any{"Opened": operatorTime(view.WindowExpires), "Prefix": view.Prefix()}
+ })
+}
+
+// ---- credential: id.oficina.works/operator/confirm ----
+
+// credentialFresh: sessions.Fresh(300), no future auth_time, not a Keymail
+// approval without a gesture, and not a recovery-code session (recovery
+// mints AuthTime now, so it would satisfy any freshness window).
+func credentialFresh(s sessions.Session, now time.Time) bool {
+ authTime := s.AuthTime
+ if authTime.IsZero() {
+ authTime = s.At
+ }
+ return sessions.Fresh(s, operatorFreshness, now) && !authTime.After(now) && !keymailWithoutGesture(s) && !strings.Contains(s.Method, "recovery")
+}
+
+// writeOperatorIntent seals the fresh intent handleSigninBegin and the
+// Keymail callback already honour, so the forced sign-in takes a real
+// gesture instead of looping. Its consumer is reserved; its nonce random.
+func (a *App) writeOperatorIntent(w http.ResponseWriter) error {
+ nonce, err := assertion.RandomID()
+ if err != nil {
+ return err
+ }
+ b, err := json.Marshal(assertionIntent{Consumer: operatorConfirmConsumer, Nonce: nonce, Expires: time.Now().Unix() + 600, MaxAge: 300, Subject: a.op.subject})
+ if err != nil {
+ return err
+ }
+ sealed, err := a.secrets.Sealer.Seal("assertion.intent", b)
+ if err != nil {
+ return err
+ }
+ http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: base64.RawURLEncoding.EncodeToString(sealed), Path: "/", MaxAge: 600, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
+ return nil
+}
+
+// clearOperatorIntent consumes this page's own intent, and no other.
+func (a *App) clearOperatorIntent(w http.ResponseWriter, r *http.Request) {
+ if intent, ok := a.readAssertionIntent(r, time.Now()); ok && intent.Consumer == operatorConfirmConsumer {
+ http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
+ }
+}
+
+func (a *App) credentialOperatorSession(w http.ResponseWriter, r *http.Request) (sessions.Session, bool) {
+ w.Header().Set("Cache-Control", "no-store")
+ s, ok := a.sessions.From(r)
+ if ok && s.Subject != a.op.subject {
+ a.notFound(w, r)
+ return s, false
+ }
+ if !ok || !credentialFresh(s, time.Now()) {
+ if r.Method != http.MethodGet {
+ http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
+ return s, false
+ }
+ if err := a.writeOperatorIntent(w); err != nil {
+ a.serverError(w, r)
+ return s, false
+ }
+ http.Redirect(w, r, "/signin?return_to=%2Foperator%2Fconfirm", http.StatusSeeOther)
+ return s, false
+ }
+ return s, true
+}
+
+type credentialPlanView struct {
+ ID, Prefix, Kind, Owner, Expires string
+ Apps []string
+}
+
+func credentialView(v operator.PlanView) credentialPlanView {
+ out := credentialPlanView{ID: v.ID, Prefix: v.Prefix(), Kind: operatorKinds[v.Kind], Expires: operatorTime(v.Expires)}
+ if len(v.OwnerIndex) >= 8 {
+ out.Owner = v.OwnerIndex[:8]
+ }
+ for _, app := range v.Apps {
+ out.Apps = append(out.Apps, appName(app))
+ }
+ return out
+}
+
+func (a *App) handleCredentialConfirm(w http.ResponseWriter, r *http.Request) {
+ if _, ok := a.credentialOperatorSession(w, r); !ok {
+ return
+ }
+ a.clearOperatorIntent(w, r)
+ data := map[string]any{}
+ v, err := a.op.plans.Pending(r.Context(), a.op.now())
+ switch {
+ case err == nil:
+ data["Plan"] = credentialView(v)
+ case !errors.Is(err, operator.ErrRefused):
+ a.serverError(w, r)
+ return
+ }
+ a.render(w, r, http.StatusOK, "operator_confirm_id.html", data)
+}
+
+func (a *App) handleCredentialConfirmPost(w http.ResponseWriter, r *http.Request) {
+ s, ok := a.credentialOperatorSession(w, r)
+ if !ok {
+ return
+ }
+ if err := r.ParseForm(); err != nil {
+ a.renderOperatorRefusal(w, r, "operator_confirm_id.html", http.StatusBadRequest, "Nothing was opened.")
+ return
+ }
+ typed := strings.TrimSpace(r.PostFormValue("owner"))
+ pepper := a.secrets.Pepper
+ v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(v operator.PlanView) bool {
+ // Subject, freshness and method again, inside the write; then the
+ // typed owner must blind-index to Home's stored owner_index.
+ if s.Subject != a.op.subject || !credentialFresh(s, time.Now()) {
+ return false
+ }
+ if v.OwnerIndex == "" {
+ return true
+ }
+ return typed != "" && hmac.Equal([]byte(blindIndex(pepper, typed)), []byte(v.OwnerIndex))
+ })
+ if err == nil {
+ a.clearOperatorIntent(w, r)
+ }
+ a.afterOpen(w, r, "operator_confirm_id.html", v, err, func(view operator.PlanView) map[string]any {
+ return map[string]any{"Opened": operatorTime(view.WindowExpires)}
+ })
+}
+
+// ---- shared ----
+
+func (a *App) afterOpen(w http.ResponseWriter, r *http.Request, page string, v operator.PlanView, err error, opened func(operator.PlanView) map[string]any) {
+ switch {
+ case err == nil:
+ a.logger.Info("operator confirm", "role", a.op.role, "outcome", "opened")
+ a.render(w, r, http.StatusOK, page, opened(v))
+ case errors.Is(err, operator.ErrBusy):
+ a.renderOperatorRefusal(w, r, page, http.StatusConflict, "Another window is already open. Wait for it to close.")
+ case errors.Is(err, operator.ErrRefused):
+ a.renderOperatorRefusal(w, r, page, http.StatusForbidden, "Nothing was opened. Check the plan and what you typed, then try again.")
+ default:
+ a.serverError(w, r)
+ }
+}
+
+func (a *App) renderOperatorRefusal(w http.ResponseWriter, r *http.Request, page string, status int, msg string) {
+ a.logger.Info("operator confirm", "role", a.op.role, "outcome", "refused")
+ data := map[string]any{"Error": msg}
+ if v, err := a.op.plans.Pending(context.Background(), a.op.now()); err == nil {
+ if page == "operator_confirm.html" {
+ data["Plan"] = a.directoryView(v)
+ } else {
+ data["Plan"] = credentialView(v)
+ }
+ }
+ a.render(w, r, status, page, data)
+}
diff --git a/internal/home/signin_return.go b/internal/home/signin_return.go
index 05e08fc..25b9105 100644
--- a/internal/home/signin_return.go
+++ b/internal/home/signin_return.go
@@ -11,7 +11,7 @@ const returnTTL = 10 * time.Minute
func credentialReturn(value string) string {
switch value {
- case "/passkey/enrol", "/passkey/codes", "/authorize/resume", "/dashboard/resume":
+ case "/passkey/enrol", "/passkey/codes", "/authorize/resume", "/dashboard/resume", operatorConfirm:
return value
}
return "/"
diff --git a/internal/home/templates/operator_confirm.html b/internal/home/templates/operator_confirm.html
new file mode 100644
index 0000000..d469c9b
--- /dev/null
+++ b/internal/home/templates/operator_confirm.html
@@ -0,0 +1,27 @@
+{{define "title"}}Confirm a provisioning plan · Oficina{{end}}
+{{define "content"}}
+<h1>Confirm a provisioning plan</h1>
+{{if .Data.Error}}<p role="alert" rst-callout rst-tone="negative"><span rst-callout-body>{{.Data.Error}}</span></p>{{end}}
+{{if .Data.Opened}}
+<p rst-callout rst-tone="positive"><span rst-callout-body>Window open on oficina.works until {{.Data.Opened}}.</span></p>
+<p>Now confirm the same plan, <code>{{.Data.Prefix}}</code>, on id.oficina.works.</p>
+{{else if .Data.Plan}}{{with .Data.Plan}}
+<p>This is Home’s own copy of the plan the provisioner submitted. Check every line before you open the window.</p>
+<dl>
+ <dt>Plan</dt><dd><code>{{.Prefix}}</code></dd>
+ <dt>Kind</dt><dd>{{.Kind}}</dd>
+ {{if .Label}}<dt>Label</dt><dd><code>{{.Label}}</code></dd>{{end}}
+ {{if .Name}}<dt>Name</dt><dd>{{.Name}}</dd>{{end}}
+ {{if .Hosts}}<dt>Apps</dt><dd><ul>{{range .Hosts}}<li><code>{{.}}</code></li>{{end}}</ul></dd>{{end}}
+ <dt>Expires</dt><dd>{{.Expires}}</dd>
+</dl>
+<form method="post" action="/operator/confirm" rst-form>
+ <input type="hidden" name="plan" value="{{.ID}}">
+ <div rst-form-foot>
+ <button type="submit" rst-btn="primary">Open window</button>
+ </div>
+</form>
+{{end}}{{else}}
+<p>No plan is waiting for confirmation.</p>
+{{end}}
+{{end}}
diff --git a/internal/home/templates/operator_confirm_id.html b/internal/home/templates/operator_confirm_id.html
new file mode 100644
index 0000000..f4918bc
--- /dev/null
+++ b/internal/home/templates/operator_confirm_id.html
@@ -0,0 +1,31 @@
+{{define "title"}}Confirm a provisioning plan · Oficina{{end}}
+{{define "content"}}
+{{/* The credential origin never renders an account-authored string (gate
+ 5): only the plan id and owner index prefixes, compiled names, and
+ fixed text. The typed address is never echoed. */}}
+<h1>Confirm a provisioning plan</h1>
+{{if .Data.Error}}<p role="alert" rst-callout rst-tone="negative"><span rst-callout-body>{{.Data.Error}}</span></p>{{end}}
+{{if .Data.Opened}}
+<p rst-callout rst-tone="positive"><span rst-callout-body>Window open on id.oficina.works until {{.Data.Opened}}.</span></p>
+{{else if .Data.Plan}}{{with .Data.Plan}}
+<dl>
+ <dt>Plan</dt><dd><code>{{.Prefix}}</code></dd>
+ <dt>Kind</dt><dd>{{.Kind}}</dd>
+ <dt>Apps</dt><dd>{{range $i, $a := .Apps}}{{if $i}}, {{end}}{{$a}}{{end}}</dd>
+ {{if .Owner}}<dt>Owner</dt><dd><code>{{.Owner}}</code></dd>{{end}}
+ <dt>Expires</dt><dd>{{.Expires}}</dd>
+</dl>
+<form method="post" action="/operator/confirm" rst-form>
+ <input type="hidden" name="plan" value="{{.ID}}">
+ {{if .Owner}}<div rst-field>
+ <label rst-field-label for="owner">Type the owner’s email to confirm</label>
+ <input id="owner" name="owner" type="email" autocomplete="off" required rst-input>
+ </div>{{end}}
+ <div rst-form-foot>
+ <button type="submit" rst-btn="primary">Open window</button>
+ </div>
+</form>
+{{end}}{{else}}
+<p>No plan is waiting for confirmation.</p>
+{{end}}
+{{end}}