oficina / home Public

Operator HTTP transport, confirm ceremony and consumer registry (team-provisioning-amendment.md slice 1). Adds POST /operator/v1 and /operator/v1/plan on both Home roles, off unless HOME_OPERATOR_HTTP is configured, outside CSRF and sessions, refusing browser markers and gated by a prefilter bearer, Alta's pinned signature and a 15-minute window that Paul opens on Home's own confirm pages after a fresh sign-in (the directory behind the new fresh-only consumer at /auth/fresh/start; the credential origin with a sealed fresh intent, recovery and no-gesture Keymail sessions refused, the owner retyped and compared as a blind index). Plans keep only closed fields (owner blind-indexed, name sealed, never the signed bytes or an address) and expired rows are deleted. The operator engine is unchanged and its verbs are wrapped by the window and, on the directory, a provenance fence; new verbs credential.register-consumer (only from the directory's signed provisioning record, admitted exactly as the registry reload admits), credential.retire-consumer, directory.disable-consumer and <role>.inspect. The credential consumer list becomes HOME_CONSUMERS plus a consumers table behind an atomic pointer, with per-response form-action and boot refused on collision; new tables live in their own migration sets via Runtime.ServingSchema. Tests cover every amendment §10 item except the deployed-preview canary, privacy gates 1, 2, 5, 9 and 10, and hand mutations of each guard. Reviewed by Claude Fable 5.1 (claude-fable-5-1), discussion 94, APPROVED at c880a02; approval notes applied at b4fc99d. Not deployed.

Squashed from operator-http into main.
claude agent, operated by paul@keymail.dev 82d938882ed314174cf769cdca0d702054b14ca0 parent 69ea999
47 files changed, +4,649 −128
  • cmd/home/main.go +1 −1
  • docs/superpowers/specs/2026-08-30-home-design.md +2 −0
  • go.mod +1 −1
  • go.sum +2 −2
  • implementation/directory-runtime.md +2 −0
  • implementation/home-operator-seed.md +2 −0
  • implementation/home-provisioner.md +2 −0
  • implementation/roster-contract.md +2 −0
  • implementation/team-entry.md +2 −0
  • implementation/team-provisioning-amendment.md +67 −10
  • internal/guardstest/noaddress_test.go +21 −0
  • internal/home/app.go +17 −1
  • internal/home/calma.go +1 −0
  • internal/home/consumer_registry.go +107 −0
  • internal/home/consumer_registry_test.go +122 −0
  • internal/home/dashboard_config.go +21 −10
  • internal/home/directory.go +39 −3
  • internal/home/exchange.go +8 −3
  • internal/home/exchange_test.go +29 −2
  • internal/home/fresh_start_test.go +44 −0
  • internal/home/handoff_failure.go +2 −0
  • internal/home/legacy_schema_diagnostic.go +57 −0
  • internal/home/legacy_schema_diagnostic_test.go +30 −0
  • internal/home/noscript_test.go +74 −1
  • internal/home/operator_ceremony_test.go +486 −0
  • internal/home/operator_command_linux.go +0 −46
  • internal/home/operator_confirm.go +313 −0
  • internal/home/operator_http.go +501 −0
  • internal/home/operator_http_test.go +654 −0
  • internal/home/operator_material.go +57 −0
  • internal/home/operator_schema_linux_test.go +16 −0
  • internal/home/runtime.go +41 −1
  • internal/home/schema_inventory.go +2 −2
  • internal/home/security.go +31 −13
  • internal/home/signin_return.go +1 −1
  • internal/home/signout.go +5 −3
  • internal/home/templates/operator_confirm.html +27 −0
  • internal/home/templates/operator_confirm_id.html +31 −0
  • internal/operator/credential.go +29 −25
  • internal/operator/directory.go +1 −0
  • internal/operator/engine_test.go +1 −1
  • internal/operator/http_migrations/credential/migrations/0001_operator_http.sql +29 −0
  • internal/operator/http_migrations/directory/migrations/0001_operator_http.sql +19 −0
  • internal/operator/http_verbs.go +534 −0
  • internal/operator/http_verbs_test.go +767 −0
  • internal/operator/plan.go +444 −0
  • internal/operator/protocol.go +5 −2

CI passed — run details

diff --git a/cmd/home/main.go b/cmd/home/main.go
index ed7948e..5f32a85 100644
--- a/cmd/home/main.go
+++ b/cmd/home/main.go
@@ -96,7 +96,7 @@ func main() {
// Ledgered, once at boot, forward-only. A boot that cannot reconcile
// its schema refuses rather than guessing, same as a failed open.
- if _, err := migrate.Apply(context.Background(), d, runtime.Schema()); err != nil {
+ if _, err := migrate.Apply(context.Background(), d, runtime.ServingSchema()); err != nil {
logger.Error("migrate", "err", err)
os.Exit(1)
}
diff --git a/docs/superpowers/specs/2026-08-30-home-design.md b/docs/superpowers/specs/2026-08-30-home-design.md
index 429edb4..815ad16 100644
--- a/docs/superpowers/specs/2026-08-30-home-design.md
+++ b/docs/superpowers/specs/2026-08-30-home-design.md
@@ -1081,6 +1081,8 @@ origin, where the session was minted by real authentication. It does not
transfer.) The doctrine agrees: §5.4 says "home §14 names it; this is its
trigger".
+*(Widened by `implementation/team-provisioning-amendment.md` §2 item 11: the first owner may also come from an operator-authored plan over the operator endpoint; the signup queue is untouched and still drained by a human.)*
+
**Or seeded by the drain** with the person the sealed queue payload §7
already carries. That bootstrap exists because gating a membership write on an owner
needs an owner to exist first, and the circularity has to break outside the
diff --git a/go.mod b/go.mod
index 73e8581..a377be6 100644
--- a/go.mod
+++ b/go.mod
@@ -7,7 +7,7 @@ toolchain go1.26.5
require (
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816
- amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
+ amadan.net/oficina/home/handoff v0.0.0-20261027235000-69ea999ccbf7
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd
filippo.io/age v1.3.2
diff --git a/go.sum b/go.sum
index 3904a7c..273bb1f 100644
--- a/go.sum
+++ b/go.sum
@@ -4,8 +4,8 @@ amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
-amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
-amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
+amadan.net/oficina/home/handoff v0.0.0-20261027235000-69ea999ccbf7 h1:F0wJpR9hBz5CBfCdw80TuBu0Ufioh+tmpODB9Y7ifH0=
+amadan.net/oficina/home/handoff v0.0.0-20261027235000-69ea999ccbf7/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf h1:SRKjCUgtk42WwR7VSn+V0eLNk20mfiY8dQmzdw13Sbo=
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg=
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc=
diff --git a/implementation/directory-runtime.md b/implementation/directory-runtime.md
index b8638cc..feb3530 100644
--- a/implementation/directory-runtime.md
+++ b/implementation/directory-runtime.md
@@ -1,5 +1,7 @@
# Mount the directory-owned Docs entry
+> **Superseded in part** by `implementation/team-provisioning-amendment.md` §2 item 10 (there is now exactly one exported network writer that can mark an instance live).
+
Status: base9ccdd2b independently APPROVED by configured claude-fable-5 (Home29); the expired-session continuation clarification below requires a follow-up verdict. Base is reviewed, unmounted chooser07043915daebae10512a710915263093ed793b5b and directory store4c0d84811a018c53a47b604a0de5885baec0771e. Home discussion24 approved the parent directory designfa64e28. Docs Home linking is now deployed1e862f8 and merged5fe0447. This plan does not make that existing-account pilot into authoritative team admission.
## Existing source and boundary
diff --git a/implementation/home-operator-seed.md b/implementation/home-operator-seed.md
index f4c49d0..341c271 100644
--- a/implementation/home-operator-seed.md
+++ b/implementation/home-operator-seed.md
@@ -1,5 +1,7 @@
# Local Home operator seed and provisioning
+> **Superseded in part** by `implementation/team-provisioning-amendment.md` §2 items 4, 5 and 6 (platform 117's fence and "no HTTP server", authorization outside the request, and the activation attestation, which is weakened).
+
Status: design approved by configured Claude Fable (`claude-fable-5`, provider
event metadata verified), 2026-09-08, exact reviewed commit
898fe219f4da5092b2cc28210b344ede6a478e50. Home discussion 37 retains the verdict
diff --git a/implementation/home-provisioner.md b/implementation/home-provisioner.md
index ea3a497..be4a551 100644
--- a/implementation/home-provisioner.md
+++ b/implementation/home-provisioner.md
@@ -1,5 +1,7 @@
# Operator registry and first team provisioning
+> **Superseded in part** by `implementation/team-provisioning-amendment.md` §2 items 1, 2, 3 and 8 (the local `oficina provision` command, "normal HTTP startup does not expose it", registry custody and its floor, and the bounded `HOME_CONSUMERS` registration step).
+
Status: design approved by configured Claude Fable (`claude-fable-5`, verified
provider metadata), 2026-09-08, reviewed commit898fe219f4da5092b2cc28210b344ede6a478e50,
Home discussion37. Implementation and live-use gates below remain. This makes
diff --git a/implementation/roster-contract.md b/implementation/roster-contract.md
index acceebc..eeaf759 100644
--- a/implementation/roster-contract.md
+++ b/implementation/roster-contract.md
@@ -1,5 +1,7 @@
# Authenticated roster snapshots and bounded team standing
+> **Superseded in part** by `implementation/team-provisioning-amendment.md` §2 item 7 ("no runtime operator mutation transport": the operator endpoint is that transport, for provisioning only; restore stays gated).
+
Status: proposed implementation design by Codex, 2026-09-08; requires independent Fable design review before code. Source bases: approved team-directoryfa64e286990762aecc6913bb9076a3cb75b088c3, directorydata4c0d84811a018c53a47b604a0de5885baec0771e, chooser07043915daebae10512a710915263093ed793b5b, Home spec call8 and restore ruling23, suite doctrine5.3, Docs1e862f80752004d16db98693c25d4c693dc19510. This is an internal implementation contract, not an operator runbook or a deployed feature.
## Existing boundaries
diff --git a/implementation/team-entry.md b/implementation/team-entry.md
index 5ad3fcb..b0ad6d2 100644
--- a/implementation/team-entry.md
+++ b/implementation/team-entry.md
@@ -1,5 +1,7 @@
# Home and team app entry
+> **Superseded in part** by `implementation/team-provisioning-amendment.md` §2 item 9 (one signed, Paul-approved request type now registers or retires a consumer; no browser request can).
+
Status: bounded Home/directory transport design approved by Claude Fable 5.1 at 36f876c on 2026-09-08; code still requires review. The user has prioritized docs.oficina.works → Home sign-in → team choice → team Docs, and accepted the existing team-subdomain shape. This branch starts with the shared Home/directory exchange; the acceptance target still includes Docs and two teams. Copy review is waived for this round. Fable reviews each implementation stage.
## Deployment and authority
diff --git a/implementation/team-provisioning-amendment.md b/implementation/team-provisioning-amendment.md
index 938c6b6..60bdf77 100644
--- a/implementation/team-provisioning-amendment.md
+++ b/implementation/team-provisioning-amendment.md
@@ -5,6 +5,10 @@ Paul. **Reviewed by Claude Fable 5.1 (claude-fable-5-1), 2026-10-27,
discussion 92, APPROVED (design, round 3)** at `93f8209`, after round 1
(CHANGES REQUIRED, 5 blockers) and round 2 (CHANGES REQUIRED, narrow, 3
blockers); round 3's six non-blocking notes are applied (§13).
+**Implementation slice 1** (operator HTTP transport, confirm ceremony,
+consumer registry, new verbs) **reviewed by Claude Fable 5.1
+(claude-fable-5-1), 2026-10-28, discussion 94, APPROVED** at `c880a02`
+(round 4, §13). Each superseded file below carries a one-line pointer here.
**Not approved by this verdict, and needing its own review before the code
it gates** (Fable, round 3, verbatim):
1. The shared `handoff` change (`ConsumerConfig.StartPath`) — before the
@@ -46,7 +50,7 @@ about its own resources.
## 2. Approved text this supersedes (quoted)
-Each quoted file gains a one-line pointer here when this lands.
+Each quoted file carries a one-line pointer here (added when slice 1 landed).
1. `home-provisioner.md`: *"Implement a separate local Go command,
`oficina provision`, callable directly by a human. … Every maintenance
@@ -136,12 +140,17 @@ credential role only); ruling 19; ruling 23; `home-operator-seed.md`'s
pending plan per role).
- **Off unless configured.** `HOME_OPERATOR_HTTP` (JSON ≤ 8 KiB, closed
fields) per role: `version`, `role`, `origin`, `installation`, `registry`,
- `device`, `public_key`, `key_id`, `actions` (≤ 8), `operator_subject`
- (Paul's person ref), `prefilter_token_sha256`; **credential role also**
+ `device`, `public_key`, `key_id`, `actions` (≤ 8, and **must include
+ `<role>.inspect`**, which Alta resynchronises from — round 4),
+ `operator_subject` (Paul's person ref), `prefilter_token_sha256`; **credential role also**
`directory_provisioning_public_key` (the directory's
`oficina/roster/provisioning/v1` key, which the credential role pins for
the first time — §5). Absent → no route mounted (404 like any unknown
path). Malformed → boot refuses.
+- **The role's own keys** (the MAC key, the owner-seed signer, the
+ directory's provisioning signer and its roster keys) come from the
+ existing reviewed `HOME_OPERATOR_MATERIAL`, the material the native
+ command reads (round 4).
- **Separate keys.** Alta's key differs from the assertion, owner-seed,
directory-provisioning, roster and resolve keys (`NewDirectory` /
`NewCredential` already refuse equality; the HTTP loader extends it).
@@ -186,8 +195,9 @@ review land **before** the directory confirm page and the Team page.
3): `seed-team` opens the seal inside its transaction and compares bytes. Credential blind-indexes `owner` with `findOrMintPersonOn`'s
normalisation (`links.go:156`, existing-only lookup) and writes
`plan_id`, `kind`, `apps`, `owner_index`, `expires_at`. One pending and
- one open plan per role; a further submit refuses until the pending one is
- confirmed or expires (**up to 15 minutes; no cancel verb** — a convenience
+ one open plan per role (`UNIQUE(state)`); a further submit refuses until
+ the pending one is confirmed or expires, and **confirming a pending plan
+ while a window is open answers 409** until that window expires (round 4) (**up to 15 minutes; no cancel verb** — a convenience
we skip). **Expired and refused plan rows are deleted** (`secure_delete`
is on), so a blind index for a never-confirmed plan does not linger.
2. **Paul's browser confirms on the directory**:
@@ -332,14 +342,17 @@ by two pages; that is the cost of not trusting Alta's rendering.
- **`directory.initialize`** keeps its precondition (no generation, no
consumer, no tokens, no bootstrap receipt — `directory.go:160-168`) and its
`baseline_attestation`, which is Paul's typed confirmation in Alta (§12),
- signed in the plan. It must be the directory stream's **first operation**:
+ carried in the `initialize` operation's input under Alta's signature, as
+ the existing verb has it — not repeated in the plan, which for
+ `initialize` carries no label, apps or name (round 4). It must be the directory stream's **first operation**:
the engine requires `initial_authority = true` at sequence 1
(`engine.go:160-163`), and every other directory verb refuses `Initial`.
- **One stream per role.** The engine stores one operator identity per role
and refuses any other once one has acted. Alta will own both streams.
**Restore therefore needs Alta's key material** (or a separately reviewed
- re-enrolment) until such a design exists — the native Linux command can act
- only with Alta's pins and key.
+ re-enrolment) until such a design exists. Restore through the native
+ command needs a reviewed profile regeneration first; until then it refuses
+ a database that has served over HTTP (round 4).
**Refused, permanently or until their own design:** any membership write but
the seed's first owner (Team page — spec §10, `team-members.md`); rename;
@@ -381,7 +394,10 @@ Production `HOME_CONSUMERS` holds 7 entries today (§12); **Alta becomes the
8th env entry** before the table lands. The directory needs nothing new
here: `team_instances` and `roster_consumers` are rows already.
-**New tables (additive):** credential `consumers`, `operator_plans`
+**New tables (additive)**, in their own migration sets
+(`oficina_<role>_operator_http`, applied through `Runtime.ServingSchema()`;
+round 4): credential `consumers` (with an `app` column, a compiled registry
+slug, so `retire-consumer` can check the window's apps), `operator_plans`
(plan_id, pending/open, kind, apps, owner_index, expiry); directory
`operator_plans` (plan_id, pending/open, kind, label, apps, sealed display
name, expiry), `operator_http_teams`; both keep
@@ -453,7 +469,9 @@ credentials.
under a used sequence; exact replay after expiry returns the stored
result and mutates nothing.
4. **Ceremony:** plan signed by another key; a second pending plan
- refused; differing `plan_id`s across roles refused at confirm; confirm by
+ refused; differing `plan_id`s across roles refused at confirm (round 4:
+ unbuildable across two databases; each confirm POST refuses any id but
+ the one its GET showed, and Paul compares the prefix on both pages); confirm by
a non-operator subject → 404; directory confirm with stale or future
`auth_time`; credential confirm with a stale session (a fresh intent is
written and the forced sign-in returns to `/operator/confirm` — no loop
@@ -549,3 +567,42 @@ nonce, cleared on consumption, reserved consumer refused by
`handleAssertion` (§4 step 3, §10.4); §10.4 additions (invalid nonce
ignored, cookie cleared). The `lagged-team` blank keys, PLATFORM timing and
Docs prefix preflight are applied in `team-provisioning-app.md` §6.
+
+**Round 4 (implementation, discussion 94).** Whole-code review of branch
+`operator-http` by Claude Fable 5.1 (claude-fable-5-1) at `2f1cac8`: CHANGES
+REQUIRED (narrow); the three blockers — registration admission equal to the
+registry reload's, a test of `retire-consumer`'s app scope, and this entry —
+are fixed on the same branch. Deviations from the text above, each with the
+review's ruling:
+
+1. The new tables live in their own migration sets, applied by
+ `Runtime.ServingSchema()`; `Runtime.Schema()` and the frozen
+ compatibility, admission and legacy-diagnostic profiles are unchanged, and
+ the native command refuses a database carrying them (§5's restore
+ sentence). **Accepted** — restore stays gated and platform 117 does not
+ exist. The legacy diagnostic skips exactly this set, so a true mismatch is
+ not hidden behind a standing false one.
+2. `consumers.app`, a compiled slug under a `CHECK`. **Accepted** (§7).
+3. §10.4's cross-role `plan_id` refusal is unbuildable; each confirm POST
+ carries the id its GET showed and refuses any other. **Accepted** — the
+ buildable half of round 2's ask, and tested.
+4. `baseline_attestation` stays in `initialize`'s signed input. **Accepted**
+ (§5).
+5. A stale, future, Keymail-without-gesture or recovery session on the
+ credential page is redirected to sign-in with the fresh intent rather than
+ shown a refusal page; no window opens. **Accepted.**
+6. An open window makes a second confirm answer 409 until it expires.
+ **Accepted** (§4).
+7. The role's own keys from `HOME_OPERATOR_MATERIAL`. **Accepted** (§3).
+8. `<role>.inspect` required in `actions`. **Accepted** (§3).
+9. `TestNoHandlerSetsItsOwnCSP` exempts `security.go`, whose
+ `setConsumerPolicy` may only add one registered consumer to form-action.
+ **Accepted.**
+
+**For a later amendment (design note, not a deviation):**
+`credential.retire-consumer` is app-scoped, not team-scoped — the credential
+role sees no labels — so a confirmed `retire-apps` window admits retiring any
+table consumer of those apps for any team, and the credential page cannot
+show Paul which. The mirror of `register-consumer`'s record derivation would
+be a directory-signed `disable` receipt. Weigh it before a second team
+exists.
diff --git a/internal/guardstest/noaddress_test.go b/internal/guardstest/noaddress_test.go
index 220738a..1ca2566 100644
--- a/internal/guardstest/noaddress_test.go
+++ b/internal/guardstest/noaddress_test.go
@@ -1,6 +1,7 @@
package guards
import (
+ "path/filepath"
"regexp"
"strings"
"testing"
@@ -162,3 +163,23 @@ func TestEveryForbiddenWordIsMatched(t *testing.T) {
}
}
}
+
+// Gate 2's static half, extended for the operator endpoint
+// (team-provisioning-amendment.md §9): the walk must reach the HTTP
+// operator migrations on both roles, whose plan and registry tables are the
+// new address-adjacent schema (the owner's blind index, consumer origins).
+func TestNoAddressColumnReachesOperatorHTTPMigrations(t *testing.T) {
+ root := repoRoot(t)
+ seen := map[string]bool{}
+ for _, path := range migrationFiles(t, root) {
+ seen[filepath.ToSlash(relPath(t, root, path))] = true
+ }
+ for _, want := range []string{
+ "internal/operator/http_migrations/credential/migrations/0001_operator_http.sql",
+ "internal/operator/http_migrations/directory/migrations/0001_operator_http.sql",
+ } {
+ if !seen[want] {
+ t.Errorf("gate 2's static half does not read %s", want)
+ }
+ }
+}
diff --git a/internal/home/app.go b/internal/home/app.go
index fe40da7..4373aac 100644
--- a/internal/home/app.go
+++ b/internal/home/app.go
@@ -42,6 +42,8 @@ type App struct {
runtime *Runtime
directory *directoryFeatures
consumer *handoff.Consumer
+ fresh *handoff.Consumer
+ op *operatorEndpoint
origins Origins
credentialHost string
directoryHost string
@@ -202,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"))
}
@@ -257,5 +263,15 @@ func (a *App) Router() http.Handler {
mountCalma(r)
mountSite(r)
- return r
+ if a.op == nil {
+ return r
+ }
+ // The operator transport sits outside csrf.Protect and every session
+ // check (operator_http.go); it refuses any Cookie anyway.
+ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if a.serveOperator(w, req) {
+ return
+ }
+ r.ServeHTTP(w, req)
+ })
}
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/consumer_registry.go b/internal/home/consumer_registry.go
new file mode 100644
index 0000000..e0248d9
--- /dev/null
+++ b/internal/home/consumer_registry.go
@@ -0,0 +1,107 @@
+package home
+
+import (
+ "context"
+ "database/sql"
+ "maps"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "amadan.net/oficina/home/internal/operator"
+ "amadan.net/rastrillo/rastrillo/assertion"
+)
+
+// consumerRegistry is the credential origin's effective consumer list
+// (team-provisioning-amendment.md §7): HOME_CONSUMERS ∪ the active rows of
+// the consumers table, held as one immutable map behind an atomic pointer
+// and swapped whole after each committed registry write. Every reader —
+// /authorize, the assertion handoff, sign-out, the dashboard check, the
+// per-response CSP — reads the union through it.
+type consumerRegistry struct {
+ env map[string]string
+ current atomic.Pointer[map[string]string]
+ reload sync.Mutex
+}
+
+// errConsumerCollision refuses boot: an ID or origin in both HOME_CONSUMERS
+// and the table. That takes suite sign-in down, deliberately; the runbook is
+// to remove the env entry and redeploy.
+var errConsumerCollision = errExchangeConfig
+
+func newConsumerRegistry(env map[string]string) *consumerRegistry {
+ r := &consumerRegistry{env: maps.Clone(env)}
+ union := maps.Clone(env)
+ r.current.Store(&union)
+ return r
+}
+
+// load reads the table and swaps in the union. Any row (retired included)
+// sharing an ID or origin with the env manifest is a collision.
+func (r *consumerRegistry) load(ctx context.Context, db *sql.DB, credential string, keys map[string][]byte) error {
+ r.reload.Lock()
+ defer r.reload.Unlock()
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ envOrigins := map[string]bool{}
+ for _, origin := range r.env {
+ envOrigins[origin] = true
+ }
+ rows, err := db.QueryContext(ctx, "SELECT consumer_id,origin FROM consumers LIMIT 4097")
+ if err != nil {
+ return errExchangeConfig
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id, origin string
+ if rows.Scan(&id, &origin) != nil {
+ return errExchangeConfig
+ }
+ if _, clash := r.env[id]; clash || envOrigins[origin] {
+ return errConsumerCollision
+ }
+ }
+ if rows.Err() != nil {
+ return errExchangeConfig
+ }
+ active, err := operator.ActiveConsumers(ctx, db)
+ if err != nil {
+ return errExchangeConfig
+ }
+ union := maps.Clone(r.env)
+ admits := registryAdmits(credential, keys)
+ for id, origin := range active {
+ if !admits(id, origin) {
+ return errExchangeConfig
+ }
+ union[id] = origin
+ }
+ r.current.Store(&union)
+ return nil
+}
+
+func (r *consumerRegistry) snapshot() map[string]string { return *r.current.Load() }
+
+// consumers is the one reader every credential-origin path uses.
+func (a *App) consumers() map[string]string {
+ if a.runtime == nil {
+ return nil
+ }
+ if a.runtime.registry != nil {
+ return a.runtime.registry.snapshot()
+ }
+ return a.runtime.consumers
+}
+
+// registryAdmits is the one admission rule for a table consumer: the reload
+// applies it to every row, and credential.register-consumer applies it before
+// it writes one, so no committed row can be one the next boot refuses.
+func registryAdmits(credential string, keys map[string][]byte) func(id, origin string) bool {
+ return func(id, origin string) bool {
+ if !consumerName(id) {
+ return false
+ }
+ _, err := assertion.NewVerifier(credential, origin, keys)
+ return err == nil
+ }
+}
diff --git a/internal/home/consumer_registry_test.go b/internal/home/consumer_registry_test.go
new file mode 100644
index 0000000..5daa4d4
--- /dev/null
+++ b/internal/home/consumer_registry_test.go
@@ -0,0 +1,122 @@
+package home
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/assertion"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+func fixtureToken(b byte) string {
+ return base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{b}, 32))
+}
+func hexID(k *family.Keypair) string {
+ sum := sha256.Sum256(k.SignPub())
+ return hex.EncodeToString(sum[:])
+}
+
+// newRegistryCredential boots a credential role through NewRuntime on a
+// serving-schema database, with rows written to the consumers table first.
+func newRegistryCredential(t *testing.T, rows ...[3]string) (*App, Runtime, *db.DB, error) {
+ t.Helper()
+ RegisterSecureDelete()
+ d, err := db.Open(filepath.Join(t.TempDir(), "credential.db"), quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ if _, err = migrate.Apply(context.Background(), d, (Runtime{role: "credential"}).ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ for _, row := range rows {
+ if _, err = d.Writer().Exec("INSERT INTO consumers VALUES(?,?,'docs',?,'2026-10-27',?)", row[0], row[1], row[2], fixtureToken(1)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ secrets, _ := testSecrets(t)
+ key, _ := family.Generate()
+ kid := hexID(key)
+ cfg := 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"}}
+ a, err := NewRuntime(cfg, d, quietLogger())
+ return a, cfg, d, err
+}
+
+func TestConsumerRegistryUnionPastSixteen(t *testing.T) {
+ var rows [][3]string
+ for i := 0; i < 20; i++ {
+ id := "t" + strings.Repeat("x", i%3) + string(rune('a'+i))
+ rows = append(rows, [3]string{id, "https://" + id + ".docs.oficina.works", "active"})
+ }
+ rows = append(rows, [3]string{"gone", "https://gone.docs.oficina.works", "retired"})
+ a, _, d, err := newRegistryCredential(t, rows...)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := len(a.consumers()); n != 22 {
+ t.Fatal("union size", n)
+ }
+ nonce, _ := assertion.RandomID()
+ // The twentieth table consumer, past HOME_CONSUMERS' 16-entry cap.
+ if r := exchangeRequest(a, "GET", Origin+"/authorize?consumer=txt&nonce="+nonce, "", nil); r.Code != 303 {
+ t.Fatal("table consumer past sixteen refused", r.Code)
+ }
+ // Retired: refused at /authorize and at sign-out.
+ if r := exchangeRequest(a, "GET", Origin+"/authorize?consumer=gone&nonce="+nonce, "", nil); r.Code != 400 {
+ t.Fatal("retired consumer admitted at /authorize", r.Code)
+ }
+ if r := exchangeRequest(a, "POST", Origin+signoutPath, "https://gone.docs.oficina.works", nil); r.Code != 403 {
+ t.Fatal("retired consumer admitted at sign-out", r.Code)
+ }
+ if r := exchangeRequest(a, "POST", Origin+signoutPath, "https://txt.docs.oficina.works", nil); r.Code != 303 {
+ t.Fatal("table consumer refused at sign-out", r.Code)
+ }
+ // The standing CSP names no consumer, however many there are.
+ if strings.Contains(a.SecurityPolicy(), "docs.oficina.works") {
+ t.Fatal("standing CSP lists consumers")
+ }
+ // Concurrent reads while the union is swapped (make test-race).
+ var wg sync.WaitGroup
+ stop := make(chan struct{})
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ _ = a.consumers()["txt"]
+ _, _ = a.consumerOrigin("https://txt.docs.oficina.works")
+ }
+ }
+ }()
+ }
+ for i := 0; i < 20; i++ {
+ if err := a.runtime.registry.load(context.Background(), d.Writer(), Origin, a.runtime.keys); err != nil {
+ t.Fatal(err)
+ }
+ }
+ close(stop)
+ wg.Wait()
+}
+
+// An ID or origin in both HOME_CONSUMERS and the table — retired rows
+// included — refuses boot.
+func TestConsumerRegistryCollisionRefusesBoot(t *testing.T) {
+ for _, row := range [][3]string{{"team_docs", "https://other.docs.oficina.works", "active"}, {"other", "https://blue.docs.oficina.works", "retired"}} {
+ if _, _, _, err := newRegistryCredential(t, row); err != errExchangeConfig {
+ t.Fatal("collision booted", row, err)
+ }
+ }
+}
diff --git a/internal/home/dashboard_config.go b/internal/home/dashboard_config.go
index 4b8a220..24b7826 100644
--- a/internal/home/dashboard_config.go
+++ b/internal/home/dashboard_config.go
@@ -67,16 +67,8 @@ func loadDashboardConfig(cfg *Runtime) error {
}
origins[s.Origin] = t.ID
apps[s.App] = true
- if cfg.role == "credential" {
- found := false
- for _, v := range cfg.consumers {
- if v == s.Origin {
- found = true
- }
- }
- if !found {
- return errExchangeConfig
- }
+ if cfg.role == "credential" && !registeredOrigin(cfg.consumerUnion(), s.Origin) {
+ return errExchangeConfig
}
}
launchers := map[string]string{}
@@ -107,3 +99,22 @@ func (a *App) dashboardTeam(id string) (dashboardTeam, bool) {
}
return dashboardTeam{}, false
}
+
+// registeredOrigin reports whether origin is a registered consumer's.
+func registeredOrigin(consumers map[string]string, origin string) bool {
+ for _, v := range consumers {
+ if v == origin {
+ return true
+ }
+ }
+ return false
+}
+
+// consumerUnion is the effective registry once it is loaded (NewRuntime
+// re-checks the dashboard against it), and HOME_CONSUMERS before that.
+func (cfg *Runtime) consumerUnion() map[string]string {
+ if cfg.registry != nil {
+ return cfg.registry.snapshot()
+ }
+ return cfg.consumers
+}
diff --git a/internal/home/directory.go b/internal/home/directory.go
index 8be4069..25bf907 100644
--- a/internal/home/directory.go
+++ b/internal/home/directory.go
@@ -17,6 +17,10 @@ import (
"github.com/go-chi/chi/v5"
)
+// freshStartPath is the directory's fresh-only start (handoff
+// ConsumerConfig.StartPath). It asks the credential origin for max_age=300.
+const freshStartPath = "/auth/fresh/start"
+
func newDirectory(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) {
if !cfg.validAppPreviews() || cfg.role != "directory" || cfg.origins.validate() != nil || cfg.secrets.Sealer == nil || d == nil || cfg.signer != nil || !cfg.roster.valid(cfg.role, cfg.keys) {
return nil, errExchangeConfig
@@ -40,15 +44,34 @@ func newDirectory(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) {
return nil, err
}
a := &App{runtime: &cfg, origins: cfg.origins, credentialHost: strings.TrimPrefix(cfg.origins.Credential, "https://"), directoryHost: strings.TrimPrefix(cfg.origins.Directory, "https://"), secrets: cfg.secrets, db: d, logger: logger, renderer: renderer, sessions: sess}
+ // One completion for both consumers: the directory's one session boundary.
+ complete := func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error {
+ return a.sessions.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "assertion", AuthTime: time.Unix(c.AuthTime, 0)})
+ }
a.consumer, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: "directory", CurrentSubject: func(r *http.Request) string {
s, ok := sessions.Current(r)
if !ok {
return ""
}
return s.Subject
- }, Complete: func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error {
- return a.sessions.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "assertion", AuthTime: time.Unix(c.AuthTime, 0)})
- }, Fail: func(w http.ResponseWriter, r *http.Request, status int) {
+ }, Complete: complete, Fail: func(w http.ResponseWriter, r *http.Request, status int) {
+ a.failDirectoryHandoff(w, r, status)
+ }})
+ if err != nil {
+ return nil, err
+ }
+ // The fresh-only consumer (team-provisioning-amendment.md §4, the
+ // directory confirm page; team-members.md §2): the same Store, consumer ID,
+ // Callback and Finish as the ordinary one, its own start path, and
+ // max_age=300 on every authorize it asks for. Store.Finish enforces the
+ // freshness the pending row was started with, whichever Finish serves it.
+ a.fresh, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: "directory", RequireFreshAuth: true, StartPath: freshStartPath, CurrentSubject: func(r *http.Request) string {
+ s, ok := sessions.Current(r)
+ if !ok {
+ return ""
+ }
+ return s.Subject
+ }, Complete: complete, Fail: func(w http.ResponseWriter, r *http.Request, status int) {
a.failDirectoryHandoff(w, r, status)
}})
if err != nil {
@@ -59,6 +82,9 @@ func newDirectory(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) {
if err != nil {
return nil, err
}
+ if err = a.newOperatorEndpoint(a.runtime); err != nil {
+ return nil, err
+ }
return a, nil
}
func (a *App) directoryRouter() http.Handler {
@@ -83,10 +109,15 @@ func (a *App) directoryRouter() http.Handler {
r.Post(chooser.choicePath, chooser.Select)
}
r.Get(handoff.StartPath, a.consumer.Start)
+ r.Get(a.fresh.StartPath(), a.fresh.Start)
r.Get(handoff.FinishPath, a.consumer.Finish)
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
@@ -140,6 +171,11 @@ func (a *App) directoryRouter() http.Handler {
a.directory.roster.ServeHTTP(w, req)
return
}
+ // Outside csrf.Protect and before the session middleware, as the
+ // handoff callback is outside CSRF; it refuses any Cookie anyway.
+ if a.serveOperator(w, req) {
+ return
+ }
r.ServeHTTP(w, req)
})
}
diff --git a/internal/home/exchange.go b/internal/home/exchange.go
index 32b23a3..849b692 100644
--- a/internal/home/exchange.go
+++ b/internal/home/exchange.go
@@ -38,7 +38,7 @@ func (a *App) handleAuthorize(w http.ResponseWriter, r *http.Request) {
if maxAge != 0 {
wantFields++
}
- if err != nil || len(q) != wantFields || len(q["consumer"]) != 1 || len(q["nonce"]) != 1 || !handoff.ValidNonce(q.Get("nonce")) || a.runtime.consumers[q.Get("consumer")] == "" {
+ if err != nil || len(q) != wantFields || len(q["consumer"]) != 1 || len(q["nonce"]) != 1 || !handoff.ValidNonce(q.Get("nonce")) || a.consumers()[q.Get("consumer")] == "" {
a.failAssertion(w, r, authorizeRequest)
return
}
@@ -75,8 +75,10 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) {
a.failAssertion(w, r, assertionIntentInvalid)
return
}
- target, ok := a.runtime.consumers[intent.Consumer]
- if !ok {
+ // 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 || intent.Consumer == operatorConfirmConsumer {
a.failAssertion(w, r, assertionConsumer)
return
}
@@ -108,6 +110,9 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) {
return
}
http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
+ // This page's form posts to one consumer; its form-action names that one
+ // origin and no other (team-provisioning-amendment.md §7).
+ a.setConsumerPolicy(w, target)
a.render(w, r, http.StatusOK, "assertion.html", map[string]any{"Action": target + handoff.CallbackPath, "Token": token})
}
diff --git a/internal/home/exchange_test.go b/internal/home/exchange_test.go
index 46119f8..7569860 100644
--- a/internal/home/exchange_test.go
+++ b/internal/home/exchange_test.go
@@ -268,12 +268,39 @@ func TestHomeRoleAndMutationIsolation(t *testing.T) {
}
}
}
+
+// The credential origin's standing policy names no consumer: the one page
+// whose form goes to a consumer names that one, per response
+// (team-provisioning-amendment.md §7), so the list can outgrow a header.
func TestHomePolicyMatchesRegisteredConsumers(t *testing.T) {
p := newExchangePair(t)
baseline := (&App{origins: p.credential.origins}).SecurityPolicy()
+ if p.credential.SecurityPolicy() != baseline || strings.Contains(baseline, "blue.docs") {
+ t.Fatal("standing CSP names consumers")
+ }
+ session := signInFully(t, p.credential, sealtest.CanaryAddress)
+ nonce, _ := assertion.RandomID()
+ authorize := exchangeRequest(p.credential.App, "GET", Origin+"/authorize?consumer=team_docs&nonce="+nonce, "", nil)
+ rec := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, namedCookie(t, authorize, assertionIntentCookie), session)
want := strings.Replace(baseline, "form-action 'self' "+directoryOrigin, "form-action 'self' https://blue.docs.oficina.works "+directoryOrigin, 1)
- if p.credential.SecurityPolicy() != want {
- t.Fatal("CSP differs outside exact manifest")
+ if rec.Code != 200 || rec.Header().Get("Content-Security-Policy") != want {
+ t.Fatalf("handoff CSP %d %q, want %q", rec.Code, rec.Header().Get("Content-Security-Policy"), want)
+ }
+}
+
+func TestConsumerPolicyOnlyWidensFormAction(t *testing.T) {
+ p := newExchangePair(t)
+ base := p.credential.SecurityPolicy()
+ rec := httptest.NewRecorder()
+ p.credential.setConsumerPolicy(rec, "https://blue.docs.oficina.works")
+ got := rec.Header().Get("Content-Security-Policy")
+ if got != strings.Replace(base, "form-action 'self' "+directoryOrigin, "form-action 'self' https://blue.docs.oficina.works "+directoryOrigin, 1) || got == base {
+ t.Fatalf("consumer policy changed more than form-action: %q", got)
+ }
+ rec = httptest.NewRecorder()
+ p.credential.setConsumerPolicy(rec, "https://evil.oficina.works")
+ if rec.Header().Get("Content-Security-Policy") != "" {
+ t.Fatal("unregistered origin reached form-action")
}
}
diff --git a/internal/home/fresh_start_test.go b/internal/home/fresh_start_test.go
new file mode 100644
index 0000000..005d3ee
--- /dev/null
+++ b/internal/home/fresh_start_test.go
@@ -0,0 +1,44 @@
+package home
+
+import (
+ "net/url"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/home/handoff"
+)
+
+// The directory mounts two consumers on one Store: the ordinary start asks
+// the credential origin for an assertion with no age bound, and the fresh
+// start (team-provisioning-amendment.md §4) asks for max_age=300.
+func TestDirectoryOrdinaryAndFreshStartPaths(t *testing.T) {
+ p := newExchangePair(t)
+ for _, c := range []struct {
+ path string
+ maxAge bool
+ }{{handoff.StartPath, false}, {freshStartPath, true}} {
+ r := exchangeRequest(p.directory, "GET", directoryOrigin+c.path+"?return_to=%2Foperator%2Fconfirm", "", nil)
+ if r.Code != 303 {
+ t.Fatal(c.path, r.Code)
+ }
+ u, err := url.Parse(r.Header().Get("Location"))
+ if err != nil || u.Scheme+"://"+u.Host != Origin || u.Path != "/authorize" {
+ t.Fatal(c.path, "redirected elsewhere", r.Header().Get("Location"))
+ }
+ q := u.Query()
+ if q.Get("consumer") != "directory" || !handoff.ValidNonce(q.Get("nonce")) {
+ t.Fatal(c.path, "authorize query", u.RawQuery)
+ }
+ if got := q["max_age"]; c.maxAge != (len(got) == 1 && got[0] == "300") || (!c.maxAge && len(got) != 0) {
+ t.Fatal(c.path, "max_age", got)
+ }
+ namedCookie(t, r, "__Host-oficina-assertion-pending")
+ }
+ // The fresh start answers only its own path; a typo is an ordinary 404.
+ if r := exchangeRequest(p.directory, "GET", directoryOrigin+"/auth/fresh/start/", "", nil); r.Code != 404 {
+ t.Fatal("near-miss fresh path served", r.Code)
+ }
+ if !strings.HasPrefix(freshStartPath, "/auth/") || p.directory.fresh.StartPath() != freshStartPath {
+ t.Fatal("fresh consumer mounted at an unexpected path")
+ }
+}
diff --git a/internal/home/handoff_failure.go b/internal/home/handoff_failure.go
index 1aa45da..cb12d38 100644
--- a/internal/home/handoff_failure.go
+++ b/internal/home/handoff_failure.go
@@ -58,6 +58,8 @@ func (a *App) failDirectoryHandoff(w http.ResponseWriter, r *http.Request, statu
switch r.URL.Path {
case handoff.StartPath:
stage = "directory_start"
+ case freshStartPath:
+ stage = "directory_fresh_start"
case handoff.CallbackPath:
stage = "directory_callback"
case handoff.FinishPath:
diff --git a/internal/home/legacy_schema_diagnostic.go b/internal/home/legacy_schema_diagnostic.go
index 08ad742..6250921 100644
--- a/internal/home/legacy_schema_diagnostic.go
+++ b/internal/home/legacy_schema_diagnostic.go
@@ -7,6 +7,7 @@ import (
_ "embed"
"encoding/json"
"log/slog"
+ "sync"
"amadan.net/rastrillo/rastrillo/migrate"
)
@@ -94,6 +95,55 @@ func inspectLegacySchema(ctx context.Context, d *sql.DB) (result legacyDiagnosti
return
}
+// legacyDiagnosticAdditive is the operator endpoint's additive directory
+// set (oficina_directory_operator_http): its ledger rows and exactly the
+// objects it creates are not the historical profile's business, and are
+// skipped so that every directory boot does not read "mismatch" and hide a
+// true one behind it. Only exact matches are skipped; a changed HTTP table is
+// still a mismatch. If the set cannot be replayed, nothing is skipped.
+var legacyDiagnosticAdditive = sync.OnceValues(func() (map[string]string, map[string]legacyDiagnosticObject) {
+ ledger, objects := map[string]string{}, map[string]legacyDiagnosticObject{}
+ // ServingSchema less Schema: the additive set, without reaching into the
+ // operator package (TestLegacyDiagnosticCannotExpandAcceptedProfiles).
+ frozen := map[string]bool{}
+ for _, m := range (Runtime{role: "directory"}).Schema().All() {
+ frozen[m.ID] = true
+ }
+ var all []migrate.Migration
+ for _, m := range (Runtime{role: "directory"}).ServingSchema().All() {
+ if !frozen[m.ID] {
+ all = append(all, m)
+ }
+ }
+ if len(all) == 0 {
+ return nil, nil
+ }
+ d, err := migrate.Replay(context.Background(), all)
+ if err != nil {
+ return nil, nil
+ }
+ defer d.Close()
+ for _, m := range all {
+ ledger[m.ID] = migrate.Checksum(m.SQL)
+ }
+ rows, err := d.Query("SELECT type,name,tbl_name,coalesce(sql,'') FROM sqlite_schema")
+ if err != nil {
+ return nil, nil
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var o legacyDiagnosticObject
+ if rows.Scan(&o.Type, &o.Name, &o.Table, &o.SQL) != nil {
+ return nil, nil
+ }
+ objects[o.Type+"/"+o.Name] = o
+ }
+ if rows.Err() != nil {
+ return nil, nil
+ }
+ return ledger, objects
+})
+
func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResult {
unavailable := legacyDiagnosticResult{status: "unavailable"}
mismatch := legacyDiagnosticResult{status: "mismatch"}
@@ -101,6 +151,7 @@ func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResul
if !ok {
return unavailable
}
+ additiveLedger, additiveObjects := legacyDiagnosticAdditive()
expected := map[string]string{}
for _, m := range migrations {
expected[m.ID] = migrate.Checksum(m.SQL)
@@ -120,6 +171,9 @@ func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResul
rows.Close()
return unavailable
}
+ if sum.Valid && additiveLedger[id.String] == sum.String && id.Valid {
+ continue
+ }
if !id.Valid || !sum.Valid || count > legacyDiagnosticMaxRows || expected[id.String] != sum.String {
matched = false
}
@@ -155,6 +209,9 @@ func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResul
}
object := legacyDiagnosticObject{kind.String, name.String, table.String, statement.String}
key := kind.String + "/" + name.String
+ if extra, ok := additiveObjects[key]; ok && extra == object && kind.Valid && name.Valid && table.Valid && statement.Valid {
+ continue
+ }
prior, exists := objects[key]
if !kind.Valid || !name.Valid || !table.Valid || !statement.Valid || count > legacyDiagnosticMaxRows || !exists || prior != object {
matched = false
diff --git a/internal/home/legacy_schema_diagnostic_test.go b/internal/home/legacy_schema_diagnostic_test.go
index 4e61072..3d7ef08 100644
--- a/internal/home/legacy_schema_diagnostic_test.go
+++ b/internal/home/legacy_schema_diagnostic_test.go
@@ -400,3 +400,33 @@ func TestLegacyDiagnosticBeginFailureEvictsOpenTransaction(t *testing.T) {
}
}
}
+
+// The operator endpoint's additive directory set (ServingSchema) does not
+// turn every directory boot into "mismatch"; a change to one of its own
+// tables still is one.
+func TestLegacyDiagnosticSkipsOnlyTheExactOperatorHTTPSet(t *testing.T) {
+ d := legacyDiagnosticFixture(t, true, true)
+ if _, err := migrate.Apply(t.Context(), d, (Runtime{role: "directory"}).ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ if result := inspectLegacySchema(t.Context(), d.Writer()); result.status != "match" {
+ t.Fatal("serving schema read as a mismatch", result)
+ }
+ for name, statement := range map[string]string{
+ "changed": "ALTER TABLE operator_plans ADD COLUMN foreign_value INTEGER",
+ "ledger": "UPDATE rastrillo_migrations SET checksum='" + strings.Repeat("0", 64) + "' WHERE id LIKE 'oficina_directory_operator_http/%'",
+ } {
+ t.Run(name, func(t *testing.T) {
+ d := legacyDiagnosticFixture(t, true, true)
+ if _, err := migrate.Apply(t.Context(), d, (Runtime{role: "directory"}).ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := d.Writer().Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ if result := inspectLegacySchema(t.Context(), d.Writer()); result.status != "mismatch" {
+ t.Fatal("drift in the HTTP set hidden", result)
+ }
+ })
+ }
+}
diff --git a/internal/home/noscript_test.go b/internal/home/noscript_test.go
index 932ec12..3e0cc40 100644
--- a/internal/home/noscript_test.go
+++ b/internal/home/noscript_test.go
@@ -5,6 +5,7 @@ import (
"io/fs"
"net/http"
"net/http/httptest"
+ "net/url"
"os"
"path"
"path/filepath"
@@ -15,6 +16,7 @@ import (
"testing"
"amadan.net/oficina/estilo.git/theme"
+ "amadan.net/oficina/home/internal/home/sealtest"
"amadan.net/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/ui"
"github.com/go-chi/chi/v5"
@@ -476,7 +478,10 @@ func TestNoHandlerSetsItsOwnCSP(t *testing.T) {
}
var checked int
for _, f := range files {
- if strings.HasSuffix(f, "_test.go") {
+ // security.go's setConsumerPolicy is the one exception: it may only
+ // add one registered consumer to form-action, and
+ // TestConsumerPolicyOnlyWidensFormAction holds it to that.
+ if strings.HasSuffix(f, "_test.go") || f == "security.go" {
continue
}
checked++
@@ -505,3 +510,71 @@ var busyScript = regexp.MustCompile(`<script defer src=["']/static/busy\.js\?v=[
func hasOtherScript(body string) bool {
return strings.Contains(busyScript.ReplaceAllString(body, ""), "<script")
}
+
+// The operator endpoint's pages and routes, which the sweep above cannot
+// reach (its fixture has no HOME_OPERATOR_HTTP): both confirm pages on both
+// outcomes and both transport routes, on both origins, under the served
+// policy. No inline or eval'd script, and no script but estilo's busy rule.
+func TestOperatorPagesUnderTheScriptlessSweep(t *testing.T) {
+ f := newOperatorFixture(t)
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ f.submit(t, "directory", "create-team", []string{"docs"})
+ f.submit(t, "credential", "create-team", []string{"docs"})
+ paul := f.paulCredential(t)
+ directory := f.paulDirectory(t, paul)
+ stranger := signInFully(t, f.credential, "stranger@example.invalid")
+ type probe struct {
+ role, method, path string
+ form url.Values
+ cookie *http.Cookie
+ }
+ probes := []probe{
+ {"credential", "GET", operatorConfirm, nil, paul},
+ {"credential", "GET", operatorConfirm, nil, stranger},
+ {"credential", "GET", operatorConfirm, nil, nil},
+ {"credential", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}, "owner": {"wrong@example.invalid"}}, paul},
+ {"credential", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}, "owner": {sealtest.CanaryAddress}}, paul},
+ {"directory", "GET", operatorConfirm, nil, directory},
+ {"directory", "GET", operatorConfirm, nil, nil},
+ {"directory", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(91)}}, directory},
+ {"directory", "POST", operatorConfirm, url.Values{"plan": {fixtureToken(90)}}, directory},
+ {"credential", "POST", operatorPath, nil, nil},
+ {"directory", "POST", operatorPlanPath, nil, nil},
+ }
+ for i, p := range probes {
+ a := f.app(p.role)
+ mux := http.NewServeMux()
+ mux.Handle("/", a.Router())
+ h, cleanup, err := rastrillo.Handler(rastrillo.Options{Mux: mux, Logger: quietLogger(), CSP: a.SecurityPolicy()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cleanup != nil {
+ t.Cleanup(func() { cleanup() })
+ }
+ body := ""
+ if p.form != nil {
+ body = p.form.Encode()
+ }
+ req := httptest.NewRequest(p.method, roleOrigin(p.role)+p.path, strings.NewReader(body))
+ if p.form != nil {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", roleOrigin(p.role))
+ }
+ if p.cookie != nil {
+ req.AddCookie(p.cookie)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ csp := rec.Header().Get("Content-Security-Policy")
+ if !strings.Contains(csp, "default-src 'self'") || strings.Contains(csp, "'unsafe-eval'") || strings.Contains(strings.Replace(csp, "style-src 'self' 'unsafe-inline'", "", 1), "'unsafe-inline'") {
+ t.Errorf("probe %d (%s %s %s): CSP %q", i, p.role, p.method, p.path, csp)
+ }
+ if hasOtherScript(rec.Body.String()) {
+ t.Errorf("probe %d (%s %s %s, %d) carries a script beyond busy.js", i, p.role, p.method, p.path, rec.Code)
+ }
+ }
+ if f.openCount(t, f.directory) != 1 || f.openCount(t, f.credential.App) != 1 {
+ t.Fatal("the sweep did not reach the confirm pages' success paths")
+ }
+}
diff --git a/internal/home/operator_ceremony_test.go b/internal/home/operator_ceremony_test.go
new file mode 100644
index 0000000..1f25986
--- /dev/null
+++ b/internal/home/operator_ceremony_test.go
@@ -0,0 +1,486 @@
+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/oficina/home/roster"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "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)
+ }
+ // Any other id is a redirect too, never a page drawn to a stale session.
+ other := exchangeRequest(f.directory, "POST", directoryOrigin+operatorConfirm, directoryOrigin, url.Values{"plan": {fixtureToken(91)}}, session)
+ if other.Code != 303 || strings.Contains(other.Body.String(), operatorName) {
+ t.Fatal("stale POST with another plan id rendered", other.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)
+ }
+ if r := exchangeRequest(f.credential.App, "POST", Origin+operatorConfirm, Origin, url.Values{"plan": {fixtureToken(91)}}, cookie); r.Code != 303 {
+ t.Fatal(method, "stale POST with another plan id rendered", 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)
+ secrets := append(signedPlanParts(t, plan), []byte(f.prefilter))
+ secrets = append(secrets, signedPlanParts(t, records["docs"])[:4]...)
+ for _, secret := range secrets {
+ 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(signedPlanParts(t, plan)[2][: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)
+ }
+ }
+}
+
+// Blocker 1, #94: register-consumer admits exactly what the registry reload
+// admits, so every row it commits reloads — and boots — cleanly.
+func TestOperatorRegisteredRowsAlwaysReload(t *testing.T) {
+ f := newOperatorFixture(t)
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ f.provisionTeam(t)
+ page, _ := family.Generate()
+ for _, audience := range []string{Origin, "https://id.oficina.works:8443"} {
+ b := roster.Bindings{Issuer: Origin, Directory: directoryOrigin, Consumer: "self-docs", App: "docs", Team: "Uk", Audience: audience}
+ 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)}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rec, _ := f.run(t, "credential", "credential.register-consumer", func(in operator.InputBase) any {
+ return operator.RegisterInput{InputBase: in, Record: record}
+ }); rec.Code != 403 {
+ t.Fatal("registered an audience the reload refuses", audience, rec.Code)
+ }
+ }
+ if f.countRows(t, f.credential.App, "consumers") != 1 {
+ t.Fatal("refused registration wrote a row")
+ }
+ fresh := newConsumerRegistry(f.credential.runtime.consumers)
+ if err := fresh.load(context.Background(), f.credential.db.Writer(), Origin, f.credential.runtime.keys); err != nil {
+ t.Fatal("a committed row fails the reload", err)
+ }
+ if _, ok := fresh.snapshot()[operatorLabel+"-docs"]; !ok {
+ t.Fatal("registered consumer missing from a fresh union")
+ }
+ cfg := *f.credential.runtime
+ cfg.registry, cfg.operator = nil, nil
+ if _, err := NewRuntime(cfg, f.credential.db, quietLogger()); err != nil {
+ t.Fatal("the credential role no longer boots", err)
+ }
+}
diff --git a/internal/home/operator_command_linux.go b/internal/home/operator_command_linux.go
index 155079b..b2d0052 100644
--- a/internal/home/operator_command_linux.go
+++ b/internal/home/operator_command_linux.go
@@ -5,7 +5,6 @@ package home
import (
"bytes"
"context"
- "crypto/elliptic"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
@@ -16,26 +15,10 @@ import (
"amadan.net/oficina/home/internal/home/directorydata"
"amadan.net/oficina/home/internal/home/seal"
"amadan.net/oficina/home/internal/operator"
- "amadan.net/oficina/home/roster"
"amadan.net/rastrillo/rastrillo/assertion"
json "github.com/go-json-experiment/json"
)
-type credentialOperatorMaterial struct {
- Version int `json:"version"`
- Role string `json:"role"`
- MAC string `json:"mac_key"`
- Owner string `json:"owner_seed_key"`
-}
-type directoryOperatorMaterial struct {
- Version int `json:"version"`
- Role string `json:"role"`
- MAC string `json:"mac_key"`
- Owner string `json:"owner_seed_public"`
- Provisioning string `json:"provisioning_key"`
- Roster []roster.Key `json:"roster_keys"`
-}
-
// RunOperatorCommand has no serving startup, migration, mailer or logger.
func RunOperatorCommand(ctx context.Context, path string) (code int) {
code = 3
@@ -67,35 +50,6 @@ func RunOperatorCommand(ctx context.Context, path string) (code int) {
return 0
}
-func operatorMAC(raw string) ([]byte, error) {
- key, err := base64.StdEncoding.Strict().DecodeString(raw)
- if err != nil || len(key) != 32 || base64.StdEncoding.EncodeToString(key) != raw || bytes.Equal(key, make([]byte, 32)) {
- return nil, operator.ErrRefused
- }
- return key, nil
-}
-func operatorPublic(raw string) ([]byte, error) {
- key, err := base64.RawURLEncoding.Strict().DecodeString(raw)
- if err != nil || len(key) != 65 || base64.RawURLEncoding.EncodeToString(key) != raw {
- return nil, operator.ErrRefused
- }
- x, _ := elliptic.Unmarshal(elliptic.P256(), key)
- if x == nil {
- return nil, operator.ErrRefused
- }
- return key, nil
-}
-func distinctOperatorKeys(keys [][]byte) bool {
- seen := map[string]bool{}
- for _, key := range keys {
- if len(key) == 0 || seen[string(key)] {
- return false
- }
- seen[string(key)] = true
- }
- return true
-}
-
func loadOperatorMaterial() (operator.CommandMaterial, error) {
var material operator.CommandMaterial
role := os.Getenv("HOME_ROLE")
diff --git a/internal/home/operator_confirm.go b/internal/home/operator_confirm.go
new file mode 100644
index 0000000..ae0b90c
--- /dev/null
+++ b/internal/home/operator_confirm.go
@@ -0,0 +1,313 @@
+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
+ }
+ // A POST's freshness is checked inside the write only (the Open admit
+ // closure), so that check is the one that counts.
+ if !ok || (r.Method == http.MethodGet && !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
+ }
+ // Freshness once up front, so no stale session is drawn a page; the
+ // check inside the write below is still the one that counts.
+ fresh := directoryFresh(s, time.Now())
+ if err := r.ParseForm(); err != nil {
+ if !fresh {
+ http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
+ return
+ }
+ a.renderOperatorRefusal(w, r, "operator_confirm.html", http.StatusBadRequest, "Nothing was opened.")
+ return
+ }
+ stale := false
+ v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(operator.PlanView) bool {
+ // Subject and freshness inside the write: the POST's only freshness
+ // check. A stale session goes back through the GET's fresh exchange.
+ if s.Subject != a.op.subject || !directoryFresh(s, time.Now()) {
+ stale = true
+ return false
+ }
+ return true
+ })
+ if !fresh || stale {
+ http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
+ return
+ }
+ 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
+ }
+ // A POST's freshness and method are checked inside the write only (the
+ // Open admit closure), so that check is the one that counts.
+ if !ok || (r.Method == http.MethodGet && !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
+ }
+ // Freshness once up front, so no stale session is drawn a page; the
+ // check inside the write below is still the one that counts.
+ fresh := credentialFresh(s, time.Now())
+ if err := r.ParseForm(); err != nil {
+ if !fresh {
+ http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
+ return
+ }
+ a.renderOperatorRefusal(w, r, "operator_confirm_id.html", http.StatusBadRequest, "Nothing was opened.")
+ return
+ }
+ typed := strings.TrimSpace(r.PostFormValue("owner"))
+ pepper := a.secrets.Pepper
+ stale := false
+ v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(v operator.PlanView) bool {
+ // Subject, freshness and method inside the write — the POST's only
+ // check of them — then the typed owner must blind-index to Home's
+ // stored owner_index.
+ if s.Subject != a.op.subject || !credentialFresh(s, time.Now()) {
+ stale = true
+ return false
+ }
+ if v.OwnerIndex == "" {
+ return true
+ }
+ return typed != "" && hmac.Equal([]byte(blindIndex(pepper, typed)), []byte(v.OwnerIndex))
+ })
+ if !fresh || stale {
+ http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
+ return
+ }
+ 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.op.sweepAt(v.WindowExpires)
+ 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/operator_http.go b/internal/home/operator_http.go
new file mode 100644
index 0000000..279f6e5
--- /dev/null
+++ b/internal/home/operator_http.go
@@ -0,0 +1,501 @@
+package home
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "crypto/subtle"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ "amadan.net/oficina/home/internal/operator"
+ "amadan.net/oficina/home/roster"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ json "github.com/go-json-experiment/json"
+)
+
+// The operator endpoint (implementation/team-provisioning-amendment.md):
+// POST /operator/v1 and POST /operator/v1/plan on each role's own origin,
+// callable only by one pinned external signer (Alta), outside csrf.Protect
+// and before any session middleware, refusing anything a browser sends.
+// Off unless HOME_OPERATOR_HTTP is configured: then neither route exists.
+const (
+ operatorPath = "/operator/v1"
+ operatorPlanPath = "/operator/v1/plan"
+ operatorConfirm = "/operator/confirm"
+ // operatorConfirmConsumer is the reserved consumer value in the
+ // credential confirm page's fresh intent. It is not a valid consumer
+ // name, so no registration can take it, and handleAssertion refuses it.
+ operatorConfirmConsumer = ":operator-confirm"
+)
+
+// operatorHTTPConfig is HOME_OPERATOR_HTTP: closed fields, ≤ 8 KiB.
+type operatorHTTPConfig struct {
+ Version int `json:"version"`
+ Role string `json:"role"`
+ Origin string `json:"origin"`
+ Installation string `json:"installation"`
+ Registry string `json:"registry"`
+ Device string `json:"device"`
+ PublicKey string `json:"public_key"`
+ KeyID string `json:"key_id"`
+ Actions []string `json:"actions"`
+ OperatorSubject string `json:"operator_subject"`
+ PrefilterSHA256 string `json:"prefilter_token_sha256"`
+ DirectoryProvisioningPublicKey string `json:"directory_provisioning_public_key,omitzero"`
+}
+
+// operatorHTTPSettings is what LoadRuntime validated: the pins and the role's
+// own operator material (HOME_OPERATOR_MATERIAL), not yet bound to a DB.
+type operatorHTTPSettings struct {
+ config operatorHTTPConfig
+ verifier *operator.Verifier
+ prefilter []byte
+ mac []byte
+ // credential role
+ owner *family.Keypair
+ // directory role
+ ownerVerifier *operator.OwnerVerifier
+ provisioning *family.Keypair
+ rosterKeys []roster.Key
+ now func() time.Time
+ // after schedules expiry sweeps; nil is time.AfterFunc (tests capture).
+ after func(time.Duration, func())
+}
+
+var errOperatorConfig = errExchangeConfig
+
+func operatorApps() []string {
+ var apps []string
+ for _, app := range directoryApps() {
+ if app.integrated {
+ apps = append(apps, app.slug)
+ }
+ }
+ return apps
+}
+
+// loadOperatorHTTP reads HOME_OPERATOR_HTTP for an explicit role. Absent is
+// off; anything malformed refuses boot.
+func loadOperatorHTTP(cfg *Runtime) error {
+ raw, err := exchangeJSON("HOME_OPERATOR_HTTP", 8192)
+ if err != nil {
+ return err
+ }
+ if raw == "" {
+ return nil
+ }
+ if cfg.role != "credential" && cfg.role != "directory" {
+ return errOperatorConfig
+ }
+ var c operatorHTTPConfig
+ if len(raw) > 8192 || json.Unmarshal([]byte(raw), &c, json.RejectUnknownMembers(true)) != nil || c.Version != 1 || c.Role != cfg.role {
+ return errOperatorConfig
+ }
+ own := cfg.origins.Credential
+ if cfg.role == "directory" {
+ own = cfg.origins.Directory
+ }
+ if c.Origin != own || !ValidPersonRef(c.OperatorSubject) || (cfg.role == "credential") != (c.DirectoryProvisioningPublicKey != "") {
+ return errOperatorConfig
+ }
+ alta, err := operatorPublic(c.PublicKey)
+ if err != nil {
+ return errOperatorConfig
+ }
+ sum := sha256.Sum256(alta)
+ if c.KeyID != hex.EncodeToString(sum[:]) {
+ return errOperatorConfig
+ }
+ prefilter, err := hex.DecodeString(c.PrefilterSHA256)
+ if err != nil || len(prefilter) != 32 || hex.EncodeToString(prefilter) != c.PrefilterSHA256 {
+ return errOperatorConfig
+ }
+ inspect := false
+ for _, a := range c.Actions {
+ inspect = inspect || a == cfg.role+".inspect"
+ }
+ verifier, err := operator.NewVerifier(operator.Pins{Role: c.Role, Origin: c.Origin, Installation: c.Installation, Registry: c.Registry, Device: c.Device, PublicKey: c.PublicKey, Actions: c.Actions})
+ if err != nil || !inspect {
+ return errOperatorConfig
+ }
+ s := &operatorHTTPSettings{config: c, verifier: verifier, prefilter: prefilter, now: time.Now}
+ material, err := exchangeJSON("HOME_OPERATOR_MATERIAL", 16384)
+ if err != nil || material == "" {
+ return errOperatorConfig
+ }
+ // Alta's key is distinct from every key this role holds or pins:
+ // assertion, owner-seed, directory provisioning and roster keys.
+ keys := [][]byte{alta}
+ if cfg.role == "credential" {
+ var m credentialOperatorMaterial
+ if json.Unmarshal([]byte(material), &m, json.RejectUnknownMembers(true)) != nil || m.Version != 1 || m.Role != cfg.role {
+ return errOperatorConfig
+ }
+ if s.mac, err = operatorMAC(m.MAC); err != nil {
+ return errOperatorConfig
+ }
+ if s.owner, err = decodeHomeKeypair(m.Owner); err != nil {
+ return errOperatorConfig
+ }
+ provisioning, err := operatorPublic(c.DirectoryProvisioningPublicKey)
+ if err != nil || cfg.signer == nil {
+ return errOperatorConfig
+ }
+ keys = append(keys, s.owner.SignPub(), provisioning, cfg.signer.SignPub())
+ } else {
+ var m directoryOperatorMaterial
+ if json.Unmarshal([]byte(material), &m, json.RejectUnknownMembers(true)) != nil || m.Version != 1 || m.Role != cfg.role || len(m.Roster) == 0 || len(m.Roster) > 8 {
+ return errOperatorConfig
+ }
+ if s.mac, err = operatorMAC(m.MAC); err != nil {
+ return errOperatorConfig
+ }
+ if s.ownerVerifier, err = operator.NewOwnerVerifier(m.Owner, cfg.origins.Credential, cfg.origins.Directory); err != nil {
+ return errOperatorConfig
+ }
+ ownerPub, err := operatorPublic(m.Owner)
+ if err != nil {
+ return errOperatorConfig
+ }
+ if s.provisioning, err = decodeHomeKeypair(m.Provisioning); err != nil {
+ return errOperatorConfig
+ }
+ keys = append(keys, ownerPub, s.provisioning.SignPub())
+ for _, k := range cfg.keys {
+ keys = append(keys, k)
+ }
+ ids := map[string]bool{}
+ matched := cfg.roster.mode != "serve"
+ for _, k := range m.Roster {
+ pub, err := operatorPublic(k.Public)
+ sum := sha256.Sum256(pub)
+ if err != nil || k.ID != hex.EncodeToString(sum[:]) || ids[k.ID] {
+ return errOperatorConfig
+ }
+ ids[k.ID] = true
+ keys = append(keys, pub)
+ if cfg.roster.mode == "serve" && bytes.Equal(pub, cfg.roster.signer.SignPub()) {
+ matched = true
+ }
+ s.rosterKeys = append(s.rosterKeys, k)
+ }
+ if !matched {
+ return errOperatorConfig
+ }
+ }
+ if !distinctOperatorKeys(keys) {
+ return errOperatorConfig
+ }
+ cfg.operator = s
+ return nil
+}
+
+// operatorEndpoint is one role's mounted endpoint, bound to its database.
+type operatorEndpoint struct {
+ role, host, subject string
+ prefilter []byte
+ verifier *operator.Verifier
+ plans *operator.PlanStore
+ directory *operator.Directory
+ credential *operator.CredentialHTTP
+ apps []string
+ now func() time.Time
+ // after schedules the expiry sweeps; time.AfterFunc outside tests.
+ after func(time.Duration, func())
+}
+
+// sweepAt deletes the role's expired plan rows one second after unix (a
+// plan's expiry, or an open window's), even if nothing else touches the role
+// before then. Boot and every plan access sweep too; this is what keeps an
+// unconfirmed owner blind index from lingering on an idle role.
+func (e *operatorEndpoint) sweepAt(unix int64) {
+ wait := time.Unix(unix, 0).Sub(e.now()) + time.Second
+ if wait < 0 {
+ wait = 0
+ }
+ if wait > (operator.PlanLifetime+operator.WindowLifetime+5)*time.Second {
+ return
+ }
+ plans, clock := e.plans, e.now
+ e.after(wait, func() { _ = plans.Sweep(context.Background(), clock()) })
+}
+
+func (a *App) newOperatorEndpoint(cfg *Runtime) error {
+ s := cfg.operator
+ if s == nil {
+ return nil
+ }
+ sealer := a.secrets.Sealer
+ engine, err := operator.NewEngine(a.db.Writer(), s.verifier, sealer, s.mac, s.now)
+ if err != nil {
+ return errOperatorConfig
+ }
+ plans, err := operator.NewPlanStore(a.db.Writer(), cfg.role, sealer)
+ if err != nil {
+ return errOperatorConfig
+ }
+ e := &operatorEndpoint{role: cfg.role, subject: s.config.OperatorSubject, prefilter: s.prefilter, verifier: s.verifier, plans: plans, apps: operatorApps(), now: s.now, after: s.after}
+ if e.after == nil {
+ e.after = func(d time.Duration, f func()) { time.AfterFunc(d, f) }
+ }
+ if cfg.role == "credential" {
+ e.host = a.credentialHost
+ resolve, err := NewOperatorPersonResolver(a.secrets.Pepper)
+ if err != nil {
+ return errOperatorConfig
+ }
+ c, err := operator.NewCredential(engine, cfg.origins.Directory, s.owner, [][]byte{cfg.signer.SignPub()}, resolve)
+ if err != nil {
+ return errOperatorConfig
+ }
+ pepper := a.secrets.Pepper
+ e.credential, err = operator.NewCredentialHTTP(c, s.config.DirectoryProvisioningPublicKey, cfg.consumers, e.apps, func(address string) string { return blindIndex(pepper, address) }, registryAdmits(cfg.origins.Credential, cfg.keys))
+ if err != nil {
+ return errOperatorConfig
+ }
+ } else {
+ e.host = a.directoryHost
+ e.directory, err = operator.NewDirectory(engine, s.ownerVerifier, s.provisioning, s.rosterKeys, directorydata.Config{Apps: e.apps, ValidateRoute: directoryRouteAllowed})
+ if err != nil {
+ return errOperatorConfig
+ }
+ }
+ if err = plans.Sweep(context.Background(), s.now()); err != nil {
+ return err
+ }
+ // A row that survived a restart is still deleted at its end.
+ ends, err := plans.Ends(context.Background(), s.now())
+ if err != nil {
+ return err
+ }
+ for _, end := range ends {
+ e.sweepAt(end)
+ }
+ a.op = e
+ return nil
+}
+
+// serveOperator answers the two transport routes and reports whether it did.
+// Off (no HOME_OPERATOR_HTTP) it answers nothing, so they 404 like any
+// unknown path.
+func (a *App) serveOperator(w http.ResponseWriter, r *http.Request) bool {
+ if a.op == nil || (r.URL.Path != operatorPath && r.URL.Path != operatorPlanPath) {
+ return false
+ }
+ a.handleOperator(w, r)
+ return true
+}
+
+type operatorOutcome struct {
+ status int
+ code string
+}
+
+var (
+ operatorNotFound = operatorOutcome{http.StatusNotFound, "not_found"}
+ operatorMethod = operatorOutcome{http.StatusMethodNotAllowed, "method"}
+ operatorBrowser = operatorOutcome{http.StatusForbidden, "browser"}
+ operatorMedia = operatorOutcome{http.StatusUnsupportedMediaType, "media"}
+ operatorBearer = operatorOutcome{http.StatusUnauthorized, "prefilter"}
+ operatorTooLarge = operatorOutcome{http.StatusRequestEntityTooLarge, "size"}
+ operatorRefused = operatorOutcome{http.StatusForbidden, "refused"}
+ operatorBusy = operatorOutcome{http.StatusConflict, "busy"}
+ operatorDown = operatorOutcome{http.StatusServiceUnavailable, "unavailable"}
+)
+
+// operatorLog is gate 9's whole vocabulary here: a fixed route label, a verb
+// from the closed allowedAction set (or a fixed placeholder), an outcome code
+// and the operation id's first 8 characters. Nothing from a refused body.
+func (a *App) operatorLog(route, verb string, o operatorOutcome, op string) {
+ if len(op) > 8 {
+ op = op[:8]
+ }
+ a.logger.Info("operator http", "route", route, "verb", verb, "outcome", o.code, "op", op)
+}
+
+func (a *App) operatorAnswer(w http.ResponseWriter, route, verb, op string, o operatorOutcome) {
+ a.operatorLog(route, verb, o, op)
+ w.Header().Set("Content-Type", "application/json")
+ if o == operatorBearer {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ }
+ w.WriteHeader(o.status)
+ _, _ = io.WriteString(w, `{"outcome":"`+o.code+`"}`)
+}
+
+func browserMarked(r *http.Request) bool {
+ if len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Origin")) != 0 {
+ return true
+ }
+ for name := range r.Header {
+ if strings.HasPrefix(http.CanonicalHeaderKey(name), "Sec-Fetch-") {
+ return true
+ }
+ }
+ return false
+}
+
+func (a *App) prefilterPasses(r *http.Request) bool {
+ values := r.Header.Values("Authorization")
+ if len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") {
+ return false
+ }
+ token := strings.TrimPrefix(values[0], "Bearer ")
+ raw, err := base64.RawURLEncoding.Strict().DecodeString(token)
+ if err != nil || len(raw) != 32 || base64.RawURLEncoding.EncodeToString(raw) != token {
+ return false
+ }
+ sum := sha256.Sum256(raw)
+ return subtle.ConstantTimeCompare(sum[:], a.op.prefilter) == 1
+}
+
+func (a *App) handleOperator(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ route := "operation"
+ if r.URL.Path == operatorPlanPath {
+ route = "plan"
+ }
+ // Each role answers on its own origin only.
+ if strings.ToLower(r.Host) != a.op.host {
+ a.operatorAnswer(w, route, "-", "", operatorNotFound)
+ return
+ }
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", http.MethodPost)
+ a.operatorAnswer(w, route, "-", "", operatorMethod)
+ return
+ }
+ // 1. Not a browser: no cookie is read, no session is minted here.
+ if browserMarked(r) || r.URL.RawQuery != "" {
+ a.operatorAnswer(w, route, "-", "", operatorBrowser)
+ return
+ }
+ media, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || media != "application/json" || len(params) != 0 {
+ a.operatorAnswer(w, route, "-", "", operatorMedia)
+ return
+ }
+ // 2. The prefilter bearer: a DoS filter, not authority.
+ if !a.prefilterPasses(r) {
+ a.operatorAnswer(w, route, "-", "", operatorBearer)
+ return
+ }
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, operator.BodyLimit))
+ if err != nil {
+ a.operatorAnswer(w, route, "-", "", operatorTooLarge)
+ return
+ }
+ if route == "plan" {
+ a.submitPlan(w, body)
+ return
+ }
+ // 3 and 4 — Alta's signature, then the window — happen inside the
+ // engine's transaction. Verify here only to name the verb in the log.
+ if req, err := a.op.verifier.Verify(body); err == nil {
+ action, op := req.Authorization().Action, req.Authorization().OperationID
+ var out []byte
+ if a.op.role == "directory" {
+ out, err = a.op.directory.ExecuteHTTP(r.Context(), body)
+ } else {
+ out, err = a.op.credential.ExecuteHTTP(r.Context(), body)
+ // On replay too: a reload that failed after the commit is retried.
+ if err == nil && (action == "credential.register-consumer" || action == "credential.retire-consumer") {
+ // The committed write is visible; swap the union in. If that
+ // fails, answer unavailable: Alta's exact replay returns the
+ // stored result and reloads again, so a retired consumer never
+ // stays admitted behind a 200.
+ // Not the request's context: a client gone after the commit
+ // must not leave the union stale (load bounds itself).
+ if err = a.runtime.registry.load(context.Background(), a.db.Writer(), a.origins.Credential, a.runtime.keys); err != nil {
+ err = operator.ErrUnavailable
+ }
+ }
+ }
+ a.operatorResult(w, route, action, op, out, err)
+ return
+ }
+ var out []byte
+ if a.op.role == "directory" {
+ out, err = a.op.directory.InspectHTTP(r.Context(), body)
+ } else {
+ out, err = a.op.credential.InspectHTTP(r.Context(), body)
+ }
+ // Neither a verified operation nor a verified inspect: the log says
+ // "-", not which of the two it failed to be.
+ verb := a.op.role + ".inspect"
+ if errors.Is(err, operator.ErrRefused) {
+ route, verb = "operation", "-"
+ } else {
+ route = "inspect"
+ }
+ a.operatorResult(w, route, verb, "", out, err)
+}
+
+func (a *App) operatorResult(w http.ResponseWriter, route, verb, op string, out []byte, err error) {
+ switch {
+ case err == nil:
+ a.operatorLog(route, verb, operatorOutcome{http.StatusOK, "ok"}, op)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(out)
+ case errors.Is(err, operator.ErrRefused):
+ a.operatorAnswer(w, route, verb, op, operatorRefused)
+ default:
+ a.operatorAnswer(w, route, verb, op, operatorDown)
+ }
+}
+
+// submitPlan stores a verified plan's closed fields; never the signed bytes,
+// never the address. On the credential role the owner must already exist.
+func (a *App) submitPlan(w http.ResponseWriter, body []byte) {
+ now := a.op.now()
+ plan, err := a.op.verifier.VerifyPlan(body, a.op.apps, now)
+ if err != nil {
+ a.operatorAnswer(w, "plan", "plan", "", operatorRefused)
+ return
+ }
+ index := ""
+ if a.op.role == "credential" && plan.Owner != "" {
+ index = blindIndex(a.secrets.Pepper, plan.Owner)
+ var found int
+ err := a.db.Writer().QueryRow("SELECT 1 FROM people WHERE blind_index=?", index).Scan(&found)
+ if err != nil {
+ o := operatorRefused
+ if !errors.Is(err, sql.ErrNoRows) {
+ o = operatorDown
+ }
+ a.operatorAnswer(w, "plan", "plan", "", o)
+ return
+ }
+ }
+ err = a.op.plans.Submit(context.Background(), plan, index, now)
+ switch {
+ case errors.Is(err, operator.ErrBusy):
+ a.operatorAnswer(w, "plan", "plan", "", operatorBusy)
+ return
+ case errors.Is(err, operator.ErrRefused):
+ a.operatorAnswer(w, "plan", "plan", "", operatorRefused)
+ return
+ case err != nil:
+ a.operatorAnswer(w, "plan", "plan", "", operatorDown)
+ return
+ }
+ a.op.sweepAt(plan.Expires)
+ a.operatorLog("plan", "plan", operatorOutcome{http.StatusOK, "ok"}, "")
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ out, _ := json.Marshal(struct {
+ Outcome string `json:"outcome"`
+ Expires int64 `json:"expires_at"`
+ }{"pending", plan.Expires})
+ _, _ = w.Write(out)
+}
diff --git a/internal/home/operator_http_test.go b/internal/home/operator_http_test.go
new file mode 100644
index 0000000..f144fed
--- /dev/null
+++ b/internal/home/operator_http_test.go
@@ -0,0 +1,654 @@
+package home
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "html"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/oficina/home/internal/home/seal"
+ "amadan.net/oficina/home/internal/home/sealtest"
+ "amadan.net/oficina/home/internal/operator"
+ "amadan.net/oficina/home/roster"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ json "github.com/go-json-experiment/json"
+)
+
+// operatorFixture is both Home roles with HOME_OPERATOR_HTTP configured,
+// built through loadOperatorHTTP from the environment, as at boot.
+type operatorFixture struct {
+ credential *testApp
+ directory *App
+ directoryPath string
+ logs *bytes.Buffer
+ alta *family.Keypair
+ prefilter string
+ paul string // Paul's person ref, operator_subject on both roles
+ paulAddress string
+ ownerSeed *family.Keypair
+ provisioning *family.Keypair
+ journal int64
+ opByte byte
+}
+
+const (
+ operatorPaul = "paul-operator@example.invalid"
+ operatorLabel = "canarylabel"
+ operatorName = "CANARY-TEAM-NAME-2b71"
+)
+
+func encodedKeypair(t *testing.T, k *family.Keypair) string {
+ t.Helper()
+ b, err := family.MarshalKeypair(k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return base64.StdEncoding.EncodeToString(b)
+}
+func rawURLPub(k *family.Keypair) string { return base64.RawURLEncoding.EncodeToString(k.SignPub()) }
+
+func operatorHTTPJSON(t *testing.T, role, origin string, alta *family.Keypair, subject, prefilterSum string, actions []string, provisioning string) string {
+ t.Helper()
+ 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}
+ b, err := json.Marshal(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+var credentialActions = []string{"credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect"}
+var directoryActions = []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"}
+
+func newOperatorFixture(t *testing.T) *operatorFixture {
+ t.Helper()
+ f := &operatorFixture{paulAddress: operatorPaul, opByte: 40, logs: new(bytes.Buffer)}
+ logger := slog.New(slog.NewTextHandler(f.logs, nil))
+ var err error
+ if f.alta, err = family.Generate(); err != nil {
+ t.Fatal(err)
+ }
+ f.ownerSeed, _ = family.Generate()
+ f.provisioning, _ = family.Generate()
+ rosterKey, _ := family.Generate()
+ prefilter := make([]byte, 32)
+ rand.Read(prefilter)
+ f.prefilter = base64.RawURLEncoding.EncodeToString(prefilter)
+ sum := sha256.Sum256(prefilter)
+ prefilterSum := hex.EncodeToString(sum[:])
+
+ // Credential role.
+ RegisterSecureDelete()
+ credPath := filepath.Join(t.TempDir(), "credential.db")
+ cd, err := db.Open(credPath, quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cd.Close() })
+ if _, err = migrate.Apply(context.Background(), cd, (Runtime{role: "credential"}).ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ secrets, mailer := testSecrets(t)
+ if f.paul, err = findOrMintPersonOn(context.Background(), cd.Writer(), secrets.Pepper, f.paulAddress, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ key, _ := family.Generate()
+ kid := hexID(key)
+ 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"}}
+ t.Setenv("HOME_OPERATOR_HTTP", operatorHTTPJSON(t, "credential", Origin, f.alta, f.paul, prefilterSum, credentialActions, rawURLPub(f.provisioning)))
+ 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)+`"}`)
+ if err = loadOperatorHTTP(&ccfg); err != nil || ccfg.operator == nil {
+ t.Fatal("credential operator config", err)
+ }
+ capp, err := NewRuntime(ccfg, cd, logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ capp.flow.Classifier.LookupTXT = func(context.Context, string) ([]string, error) {
+ return nil, errors.New("no resolver in tests")
+ }
+ f.credential = &testApp{App: capp, mailer: mailer, db: cd, dbPath: credPath}
+
+ // Directory role.
+ f.directoryPath = filepath.Join(t.TempDir(), "directory.db")
+ dd, err := db.Open(f.directoryPath, quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { dd.Close() })
+ if _, err = migrate.Apply(context.Background(), dd, (Runtime{role: "directory"}).ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ dek := make([]byte, 32)
+ rand.Read(dek)
+ sealer, _ := seal.New(dek)
+ dcfg := Runtime{role: "directory", origins: ccfg.origins, secrets: Secrets{Sealer: sealer}, keys: ccfg.keys, roster: rosterRuntime{mode: "disabled"}}
+ t.Setenv("HOME_OPERATOR_HTTP", operatorHTTPJSON(t, "directory", directoryOrigin, f.alta, f.paul, prefilterSum, directoryActions, ""))
+ 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)}}})
+ t.Setenv("HOME_OPERATOR_MATERIAL", string(material))
+ if err = loadOperatorHTTP(&dcfg); err != nil || dcfg.operator == nil {
+ t.Fatal("directory operator config", err)
+ }
+ if f.directory, err = NewRuntime(dcfg, dd, logger); err != nil {
+ t.Fatal(err)
+ }
+ return f
+}
+
+func (f *operatorFixture) app(role string) *App {
+ if role == "credential" {
+ return f.credential.App
+ }
+ return f.directory
+}
+func roleOrigin(role string) string {
+ if role == "credential" {
+ return Origin
+ }
+ return directoryOrigin
+}
+
+// post sends Alta's request exactly as Alta would, then lets each test
+// break one thing about it.
+func (f *operatorFixture) post(role, path string, body []byte, edit func(*http.Request)) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("POST", roleOrigin(role)+path, bytes.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Authorization", "Bearer "+f.prefilter)
+ if edit != nil {
+ edit(r)
+ }
+ rec := httptest.NewRecorder()
+ f.app(role).Router().ServeHTTP(rec, r)
+ return rec
+}
+
+func (f *operatorFixture) plan(t *testing.T, role, kind string, apps []string, mutate func(*operator.Plan)) []byte {
+ t.Helper()
+ now := time.Now()
+ 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}
+ if role == "directory" && kind != "initialize" {
+ p.Label = operatorLabel
+ if kind == "create-team" {
+ p.DisplayName = operatorName
+ }
+ }
+ if role == "credential" && kind == "create-team" {
+ p.Owner = sealtest.CanaryAddress
+ }
+ if mutate != nil {
+ mutate(&p)
+ }
+ raw, err := operator.SignPlan(f.alta, p, operatorApps())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func (f *operatorFixture) operation(t *testing.T, role, action string, input func(operator.InputBase) any) []byte {
+ t.Helper()
+ app := f.app(role)
+ var sequence int64
+ var head string
+ if err := app.db.Writer().QueryRow("SELECT sequence,head FROM "+role+"_operator_state").Scan(&sequence, &head); err != nil && !errors.Is(err, sql.ErrNoRows) {
+ t.Fatal(err)
+ }
+ f.journal++
+ op := fixtureToken(f.opByte)
+ f.opByte++
+ now := time.Now().Unix()
+ 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}
+ raw, err := operator.SignRequest(f.alta, a, input(operator.InputBase{Version: 1, Operation: action, OperationID: op}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func (f *operatorFixture) run(t *testing.T, role, action string, input func(operator.InputBase) any) (*httptest.ResponseRecorder, operator.Result) {
+ t.Helper()
+ rec := f.post(role, operatorPath, f.operation(t, role, action, input), nil)
+ var result operator.Result
+ if rec.Code == 200 {
+ if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return rec, result
+}
+
+// paulCredential is a fresh credential-origin session for Paul.
+func (f *operatorFixture) paulCredential(t *testing.T) *http.Cookie {
+ t.Helper()
+ return signInFully(t, f.credential, f.paulAddress)
+}
+
+// paulDirectory runs the fresh exchange from /auth/fresh/start, as the
+// directory confirm page sends Paul, and returns his directory session.
+func (f *operatorFixture) paulDirectory(t *testing.T, credentialSession *http.Cookie) *http.Cookie {
+ t.Helper()
+ start := exchangeRequest(f.directory, "GET", directoryOrigin+freshStartPath+"?return_to=%2Foperator%2Fconfirm", "", nil)
+ if start.Code != 303 || !strings.Contains(start.Header().Get("Location"), "max_age=300") {
+ t.Fatal("fresh start", start.Code)
+ }
+ pending := namedCookie(t, start, "__Host-oficina-assertion-pending")
+ authorize := exchangeRequest(f.credential.App, "GET", start.Header().Get("Location"), "", nil, credentialSession)
+ intent := namedCookie(t, authorize, assertionIntentCookie)
+ resume := exchangeRequest(f.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, credentialSession)
+ m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(resume.Body.String())
+ if resume.Code != 200 || len(m) != 2 {
+ t.Fatal("resume", resume.Code, resume.Header().Get("Location"))
+ }
+ callback := exchangeRequest(f.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, url.Values{"assertion": {html.UnescapeString(m[1])}})
+ inbox := namedCookie(t, callback, "__Host-oficina-assertion-inbox")
+ finish := exchangeRequest(f.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, pending, inbox)
+ if finish.Code != 303 || finish.Header().Get("Location") != operatorConfirm || sessionCookie(finish) == nil {
+ t.Fatal("finish", finish.Code, finish.Header().Get("Location"))
+ }
+ return sessionCookie(finish)
+}
+
+var planIDField = regexp.MustCompile(`name="plan" value="([^"]+)"`)
+
+// confirm opens role's window: GET the page, POST its own plan id.
+func (f *operatorFixture) confirm(t *testing.T, role string, session *http.Cookie, owner string) *httptest.ResponseRecorder {
+ t.Helper()
+ page := exchangeRequest(f.app(role), "GET", roleOrigin(role)+operatorConfirm, "", nil, session)
+ m := planIDField.FindStringSubmatch(page.Body.String())
+ if page.Code != 200 || len(m) != 2 {
+ t.Fatal(role, "confirm page", page.Code, page.Header().Get("Location"))
+ }
+ form := url.Values{"plan": {m[1]}}
+ if owner != "" {
+ form.Set("owner", owner)
+ }
+ return exchangeRequest(f.app(role), "POST", roleOrigin(role)+operatorConfirm, roleOrigin(role), form, session)
+}
+
+func (f *operatorFixture) openWindows(t *testing.T, kind string, apps []string) {
+ t.Helper()
+ for _, role := range []string{"directory", "credential"} {
+ if role == "credential" && kind == "initialize" {
+ continue
+ }
+ 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 {
+ t.Fatal(role, "plan", rec.Code, rec.Body.String())
+ }
+ }
+ cred := f.paulCredential(t)
+ if rec := f.confirm(t, "directory", f.paulDirectory(t, cred), ""); rec.Code != 200 {
+ t.Fatal("directory confirm", rec.Code)
+ }
+ if kind != "initialize" {
+ owner := ""
+ if kind == "create-team" {
+ owner = sealtest.CanaryAddress
+ }
+ if rec := f.confirm(t, "credential", cred, owner); rec.Code != 200 {
+ t.Fatal("credential confirm", rec.Code)
+ }
+ }
+}
+
+// expireWindows moves both roles' windows past their end.
+func (f *operatorFixture) expireWindows(t *testing.T) {
+ t.Helper()
+ for _, a := range []*App{f.credential.App, f.directory} {
+ if _, err := a.db.Writer().Exec("DELETE FROM operator_plans"); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func generationToken() string { return fixtureToken(10) }
+
+// provisionTeam drives Alta's whole create-team sequence for label/apps,
+// returning the directory's provisioning record per app.
+func (f *operatorFixture) provisionTeam(t *testing.T) map[string][]byte {
+ t.Helper()
+ f.openWindows(t, "initialize", nil)
+ if rec, _ := f.run(t, "directory", "directory.initialize", func(b operator.InputBase) any {
+ return operator.InitializeInput{InputBase: b, Generation: generationToken(), Baseline: "operator-attests-never-provisioned"}
+ }); rec.Code != 200 {
+ t.Fatal("initialize", rec.Code, rec.Body.String())
+ }
+ f.expireWindows(t)
+ f.openWindows(t, "create-team", []string{"docs"})
+ sqid, _ := operator.TeamSQID(1)
+ rec, owner := f.run(t, "credential", "credential.owner-seed", func(b operator.InputBase) any {
+ return operator.OwnerInput{InputBase: b, Directory: directoryOrigin, TeamID: 1, TeamSQID: sqid, Address: sealtest.CanaryAddress, ExistingOnly: true}
+ })
+ if rec.Code != 200 {
+ t.Fatal("owner-seed", rec.Code, rec.Body.String())
+ }
+ if rec, _ = f.run(t, "directory", "directory.seed-team", func(b operator.InputBase) any {
+ return operator.SeedInput{InputBase: b, Generation: generationToken(), TeamID: 1, TeamSQID: sqid, Label: operatorLabel, Name: operatorName, Receipt: owner.Receipt}
+ }); rec.Code != 200 {
+ t.Fatal("seed-team", rec.Code, rec.Body.String())
+ }
+ records := map[string][]byte{}
+ rec, provisioned := f.run(t, "directory", "directory.provision-consumer", func(b operator.InputBase) any {
+ return operator.ProvisionInput{InputBase: b, Generation: generationToken(), TeamSQID: sqid, App: "docs", Consumer: operatorLabel + "-docs", Audience: "https://" + operatorLabel + ".docs.oficina.works"}
+ })
+ if rec.Code != 200 {
+ t.Fatal("provision", rec.Code, rec.Body.String())
+ }
+ records["docs"] = provisioned.Record
+ if rec, _ = f.run(t, "credential", "credential.register-consumer", func(b operator.InputBase) any {
+ return operator.RegisterInput{InputBase: b, Record: provisioned.Record}
+ }); rec.Code != 200 {
+ t.Fatal("register", rec.Code, rec.Body.String())
+ }
+ return records
+}
+
+func TestOperatorEndpointIsOffWithoutConfiguration(t *testing.T) {
+ p := newExchangePair(t)
+ for _, a := range []*App{p.credential.App, p.directory} {
+ for _, path := range []string{operatorPath, operatorPlanPath, operatorConfirm} {
+ for _, host := range []string{Origin, directoryOrigin} {
+ for _, method := range []string{"GET", "POST"} {
+ r := httptest.NewRequest(method, host+path, strings.NewReader("{}"))
+ r.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ a.Router().ServeHTTP(rec, r)
+ if rec.Code != 404 && rec.Code != 403 {
+ t.Fatal("unconfigured operator route answered", method, host+path, rec.Code)
+ }
+ if strings.Contains(rec.Body.String(), "outcome") {
+ t.Fatal("operator handler reached without configuration")
+ }
+ }
+ }
+ }
+ }
+}
+
+func TestOperatorHTTPConfigurationIsClosedAndKeysDistinct(t *testing.T) {
+ f := newOperatorFixture(t)
+ cfg := *f.credential.runtime
+ cfg.operator = nil
+ sum := sha256.Sum256([]byte("x"))
+ prefilter := hex.EncodeToString(sum[:])
+ 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)}
+ material := `{"version":1,"role":"credential","mac_key":"` + base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) + `","owner_seed_key":"` + encodedKeypair(t, f.ownerSeed) + `"}`
+ t.Setenv("HOME_OPERATOR_MATERIAL", material)
+ try := func(c operatorHTTPConfig, extra string) error {
+ b, _ := json.Marshal(c)
+ raw := string(b)
+ if extra != "" {
+ raw = strings.TrimSuffix(raw, "}") + extra + "}"
+ }
+ t.Setenv("HOME_OPERATOR_HTTP", raw)
+ probe := cfg
+ return loadOperatorHTTP(&probe)
+ }
+ if err := try(base, ""); err != nil {
+ t.Fatal("valid config refused", err)
+ }
+ for name, mutate := range map[string]func(*operatorHTTPConfig){
+ "role": func(c *operatorHTTPConfig) { c.Role = "directory" },
+ "origin": func(c *operatorHTTPConfig) { c.Origin = directoryOrigin },
+ "kid": func(c *operatorHTTPConfig) { c.KeyID = strings.Repeat("0", 64) },
+ "subject": func(c *operatorHTTPConfig) { c.OperatorSubject = "paul" },
+ "prefilter": func(c *operatorHTTPConfig) { c.PrefilterSHA256 = "abc" },
+ "no-inspect": func(c *operatorHTTPConfig) { c.Actions = []string{"credential.owner-seed"} },
+ "wrong-action": func(c *operatorHTTPConfig) { c.Actions = []string{"directory.seed-team", "credential.inspect"} },
+ "no-dir-key": func(c *operatorHTTPConfig) { c.DirectoryProvisioningPublicKey = "" },
+ "alta-is-owner-seed": func(c *operatorHTTPConfig) {
+ c.PublicKey, c.KeyID = rawURLPub(f.ownerSeed), hexID(f.ownerSeed)
+ },
+ "alta-is-provisioning": func(c *operatorHTTPConfig) {
+ c.DirectoryProvisioningPublicKey = rawURLPub(f.alta)
+ },
+ "alta-is-assertion": func(c *operatorHTTPConfig) {
+ c.PublicKey, c.KeyID = rawURLPub(cfg.signer), hexID(cfg.signer)
+ },
+ } {
+ c := base
+ mutate(&c)
+ if err := try(c, ""); err == nil {
+ t.Error(name, "accepted")
+ }
+ }
+ if err := try(base, `,"extra":1`); err == nil {
+ t.Error("unknown field accepted")
+ }
+ t.Setenv("HOME_OPERATOR_HTTP", "")
+ probe := cfg
+ if err := loadOperatorHTTP(&probe); err != nil || probe.operator != nil {
+ t.Fatal("absent config is not off", err)
+ }
+}
+
+func TestOperatorTransportRefusesBrowsersAndChecksPrefilterFirst(t *testing.T) {
+ f := newOperatorFixture(t)
+ body := f.plan(t, "credential", "add-apps", []string{"docs"}, nil)
+ for name, c := range map[string]struct {
+ edit func(*http.Request)
+ status int
+ }{
+ "cookie": {func(r *http.Request) { r.AddCookie(&http.Cookie{Name: "x", Value: "y"}) }, 403},
+ "origin": {func(r *http.Request) { r.Header.Set("Origin", Origin) }, 403},
+ "sec-fetch": {func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") }, 403},
+ "sec-fetch-mode": {func(r *http.Request) { r.Header.Set("Sec-Fetch-Mode", "cors") }, 403},
+ "query": {func(r *http.Request) { r.URL.RawQuery = "x=1" }, 403},
+ "media": {func(r *http.Request) { r.Header.Set("Content-Type", "text/plain") }, 415},
+ "media-params": {func(r *http.Request) { r.Header.Set("Content-Type", "application/json; charset=utf-8") }, 415},
+ "no-bearer": {func(r *http.Request) { r.Header.Del("Authorization") }, 401},
+ "wrong-bearer": {func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+fixtureToken(5)) }, 401},
+ "bearer-form": {func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+f.prefilter+"=") }, 401},
+ "method": {func(r *http.Request) { r.Method = "PUT" }, 405},
+ "host-spoof": {func(r *http.Request) { r.Host = "evil.oficina.works" }, 404},
+ "other-role": {func(r *http.Request) { r.Host = "oficina.works" }, 404},
+ } {
+ rec := f.post("credential", operatorPlanPath, body, c.edit)
+ if rec.Code != c.status {
+ t.Error(name, rec.Code, rec.Body.String())
+ }
+ if rec.Code == 401 && rec.Body.String() != `{"outcome":"prefilter"}` {
+ t.Error("prefilter refusal is not fixed", rec.Body.String())
+ }
+ if len(rec.Result().Cookies()) != 0 {
+ t.Error(name, "set a cookie")
+ }
+ }
+ big := bytes.Repeat([]byte(" "), operator.BodyLimit+1)
+ if rec := f.post("credential", operatorPath, big, nil); rec.Code != 413 {
+ t.Fatal("oversized body", rec.Code)
+ }
+ if n := f.countRows(t, f.credential.App, "operator_plans"); n != 0 {
+ t.Fatal("refused transport stored a plan")
+ }
+ // Role separation: the directory's routes answer only on its host.
+ 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 {
+ t.Fatal("directory endpoint answered on the credential host", rec.Code)
+ }
+}
+
+func (f *operatorFixture) countRows(t *testing.T, a *App, table string) int {
+ t.Helper()
+ var n int
+ if err := a.db.Writer().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func TestOperatorPlanSubmitStoresClosedFieldsOnly(t *testing.T) {
+ f := newOperatorFixture(t)
+ // The owner must already exist: an unknown address refuses and stores
+ // nothing.
+ if rec := f.post("credential", operatorPlanPath, f.plan(t, "credential", "create-team", []string{"docs"}, nil), nil); rec.Code != 403 {
+ t.Fatal("plan for an owner who never signed in", rec.Code)
+ }
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ other, _ := family.Generate()
+ 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())
+ if rec := f.post("credential", operatorPlanPath, foreign, nil); rec.Code != 403 {
+ t.Fatal("plan signed by another key", rec.Code)
+ }
+ credPlan := f.plan(t, "credential", "create-team", []string{"docs"}, nil)
+ if rec := f.post("credential", operatorPlanPath, credPlan, nil); rec.Code != 200 {
+ t.Fatal("plan", rec.Code, rec.Body.String())
+ }
+ 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 {
+ t.Fatal("second pending plan", rec.Code)
+ }
+ dirPlan := f.plan(t, "directory", "create-team", []string{"docs"}, nil)
+ if rec := f.post("directory", operatorPlanPath, dirPlan, nil); rec.Code != 200 {
+ t.Fatal("directory plan", rec.Code)
+ }
+ // Gate 2, plan-submit path: neither the signed plan bytes nor the
+ // canary address (nor the sealed team name) are in file, WAL or SHM.
+ for path, plan := range map[string][]byte{f.credential.dbPath: credPlan, f.directoryPath: dirPlan} {
+ sealtest.AssertNoPlaintext(t, path)
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ b, _ := os.ReadFile(path + suffix)
+ for _, secret := range signedPlanParts(t, plan) {
+ if bytes.Contains(b, secret) {
+ t.Fatalf("signed plan bytes at rest in %s: %.40q", filepath.Base(path+suffix), secret)
+ }
+ }
+ }
+ }
+ // An expired plan's row is gone.
+ f.credential.op.now = func() time.Time { return time.Now().Add(601 * time.Second) }
+ if err := f.credential.op.plans.Sweep(context.Background(), f.credential.op.now()); err != nil {
+ t.Fatal(err)
+ }
+ if f.countRows(t, f.credential.App, "operator_plans") != 0 {
+ t.Fatal("expired plan row left")
+ }
+ sealtest.AssertNoPlaintext(t, f.credential.dbPath)
+}
+
+// signedPlanParts is what "the signed plan bytes" means at rest: the payload
+// and the signature, raw and as their base64url text, plus the plan's own
+// spelling of its account-authored fields.
+func signedPlanParts(t *testing.T, raw []byte) [][]byte {
+ t.Helper()
+ var env struct {
+ V int `json:"v"`
+ KID string `json:"kid"`
+ Payload string `json:"payload"`
+ Signature string `json:"signature"`
+ }
+ if err := json.Unmarshal(raw, &env); err != nil {
+ t.Fatal(err)
+ }
+ payload, err := base64.RawURLEncoding.DecodeString(env.Payload)
+ sig, err2 := base64.RawURLEncoding.DecodeString(env.Signature)
+ if err != nil || err2 != nil || len(sig) != 64 {
+ t.Fatal("plan envelope")
+ }
+ return [][]byte{payload, sig, []byte(env.Payload), []byte(env.Signature), []byte(`"owner":"` + sealtest.CanaryAddress + `"`), []byte(`"display_name":"` + operatorName + `"`)}
+}
+
+// The expiry sweeps run on their own: a pending plan and an open window
+// are deleted at their end with no further request and no Sweep by hand.
+func TestOperatorExpirySweepsRunUnprompted(t *testing.T) {
+ f := newOperatorFixture(t)
+ var pending []func()
+ var waits []time.Duration
+ clock := time.Now()
+ for _, a := range []*App{f.credential.App, f.directory} {
+ a.op.after = func(d time.Duration, fn func()) { waits = append(waits, d); pending = append(pending, fn) }
+ a.op.now = func() time.Time { return clock }
+ }
+ fire := func(keep bool) {
+ for _, fn := range pending {
+ fn()
+ }
+ if !keep {
+ pending = nil
+ }
+ }
+ // A plan nobody confirms.
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ if rec := f.post("credential", operatorPlanPath, f.plan(t, "credential", "create-team", []string{"docs"}, nil), nil); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ if len(pending) != 1 || waits[0] < 600*time.Second || waits[0] > 602*time.Second {
+ t.Fatal("no expiry sweep scheduled for the plan", waits)
+ }
+ clock = clock.Add(601 * time.Second)
+ fire(false)
+ if f.countRows(t, f.credential.App, "operator_plans") != 0 {
+ t.Fatal("unconfirmed plan row left after expiry")
+ }
+ // A window that is opened, then left.
+ clock = time.Now()
+ if rec := f.post("directory", operatorPlanPath, f.plan(t, "directory", "add-apps", []string{"docs"}, nil), nil); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ if rec := f.confirm(t, "directory", f.paulDirectory(t, f.paulCredential(t)), ""); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ if len(pending) != 2 || waits[len(waits)-1] < operator.WindowLifetime*time.Second || waits[len(waits)-1] > (operator.WindowLifetime+2)*time.Second {
+ t.Fatal("no expiry sweep scheduled for the window", waits)
+ }
+ clock = clock.Add((operator.WindowLifetime - 2) * time.Second)
+ fire(true)
+ if f.countRows(t, f.directory, "operator_plans") != 1 {
+ t.Fatal("window swept before it expired")
+ }
+ clock = clock.Add(3 * time.Second)
+ fire(false)
+ if f.countRows(t, f.directory, "operator_plans") != 0 {
+ t.Fatal("expired window row left")
+ }
+}
+
+// A plan row that survives a restart is still swept at its end: boot
+// schedules one sweep per surviving row (PlanStore.Ends).
+func TestOperatorBootSchedulesSweepsForSurvivingRows(t *testing.T) {
+ f := newOperatorFixture(t)
+ if rec := f.post("directory", operatorPlanPath, f.plan(t, "directory", "add-apps", []string{"docs"}, nil), nil); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ var end int64
+ if err := f.directory.db.Writer().QueryRow("SELECT expires_at FROM operator_plans").Scan(&end); err != nil {
+ t.Fatal(err)
+ }
+ // Boot again on the same database, with the scheduler captured.
+ cfg := *f.directory.runtime
+ settings := *cfg.operator
+ clock := time.Now()
+ settings.now = func() time.Time { return clock }
+ var waits []time.Duration
+ var sweeps []func()
+ settings.after = func(d time.Duration, fn func()) { waits = append(waits, d); sweeps = append(sweeps, fn) }
+ cfg.operator = &settings
+ a, err := NewRuntime(cfg, f.directory.db, quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := time.Unix(end, 0).Sub(clock) + time.Second
+ if len(waits) != 1 || waits[0] != want {
+ t.Fatal("boot scheduled", waits, "want", want)
+ }
+ clock = time.Unix(end, 0).Add(time.Second)
+ sweeps[0]()
+ if f.countRows(t, a, "operator_plans") != 0 {
+ t.Fatal("surviving plan row not swept at its end")
+ }
+}
diff --git a/internal/home/operator_material.go b/internal/home/operator_material.go
new file mode 100644
index 0000000..82391fd
--- /dev/null
+++ b/internal/home/operator_material.go
@@ -0,0 +1,57 @@
+package home
+
+import (
+ "bytes"
+ "crypto/elliptic"
+ "encoding/base64"
+
+ "amadan.net/oficina/home/internal/operator"
+ "amadan.net/oficina/home/roster"
+)
+
+// HOME_OPERATOR_MATERIAL: each role's own operator keys. The native command
+// (operator_command_linux.go) and the HTTP transport (operator_http.go) read
+// the same reviewed material.
+type credentialOperatorMaterial struct {
+ Version int `json:"version"`
+ Role string `json:"role"`
+ MAC string `json:"mac_key"`
+ Owner string `json:"owner_seed_key"`
+}
+type directoryOperatorMaterial struct {
+ Version int `json:"version"`
+ Role string `json:"role"`
+ MAC string `json:"mac_key"`
+ Owner string `json:"owner_seed_public"`
+ Provisioning string `json:"provisioning_key"`
+ Roster []roster.Key `json:"roster_keys"`
+}
+
+func operatorMAC(raw string) ([]byte, error) {
+ key, err := base64.StdEncoding.Strict().DecodeString(raw)
+ if err != nil || len(key) != 32 || base64.StdEncoding.EncodeToString(key) != raw || bytes.Equal(key, make([]byte, 32)) {
+ return nil, operator.ErrRefused
+ }
+ return key, nil
+}
+func operatorPublic(raw string) ([]byte, error) {
+ key, err := base64.RawURLEncoding.Strict().DecodeString(raw)
+ if err != nil || len(key) != 65 || base64.RawURLEncoding.EncodeToString(key) != raw {
+ return nil, operator.ErrRefused
+ }
+ x, _ := elliptic.Unmarshal(elliptic.P256(), key)
+ if x == nil {
+ return nil, operator.ErrRefused
+ }
+ return key, nil
+}
+func distinctOperatorKeys(keys [][]byte) bool {
+ seen := map[string]bool{}
+ for _, key := range keys {
+ if len(key) == 0 || seen[string(key)] {
+ return false
+ }
+ seen[string(key)] = true
+ }
+ return true
+}
diff --git a/internal/home/operator_schema_linux_test.go b/internal/home/operator_schema_linux_test.go
index a9a39a7..80f261d 100644
--- a/internal/home/operator_schema_linux_test.go
+++ b/internal/home/operator_schema_linux_test.go
@@ -95,6 +95,22 @@ func TestRuntimeOperatorSchemasAreAdditiveAndRoleSpecific(t *testing.T) {
if tables["credential_operator_results"] != (role == "credential") || tables["directory_operator_results"] != (role == "directory") || tables["people"] == (role == "directory") || tables["teams"] != (role == "directory") {
t.Fatal("role schema crossed boundary")
}
+ // The operator endpoint's tables stay out of the selected-release
+ // schema and on their own role in the serving one.
+ if tables["consumers"] || tables["operator_plans"] || tables["operator_http_teams"] {
+ t.Fatal("HTTP operator tables entered the frozen role schema")
+ }
+ serving, err := migrate.Replay(t.Context(), cfg.ServingSchema().All())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer serving.Close()
+ for name, want := range map[string]bool{"consumers": role == "credential", "operator_http_teams": role == "directory", "operator_plans": role != ""} {
+ var n int
+ if serving.QueryRow("SELECT count(*) FROM sqlite_schema WHERE type='table' AND name=?", name).Scan(&n) != nil || (n == 1) != want {
+ t.Fatal("serving schema table", name, "for role", role)
+ }
+ }
})
}
}
diff --git a/internal/home/runtime.go b/internal/home/runtime.go
index ecd6f39..1d92e6c 100644
--- a/internal/home/runtime.go
+++ b/internal/home/runtime.go
@@ -1,6 +1,7 @@
package home
import (
+ "context"
"crypto/elliptic"
"crypto/sha256"
"encoding/base64"
@@ -34,7 +35,14 @@ type Runtime struct {
signer *assertioncrypto.Keypair
keyID string
keys map[string][]byte
- consumers map[string]string
+ // consumers is HOME_CONSUMERS as configured; registry, once NewRuntime
+ // has loaded the credential consumers table, is the union every reader
+ // uses (consumer_registry.go).
+ consumers map[string]string
+ registry *consumerRegistry
+ // operator is HOME_OPERATOR_HTTP plus this role's operator material, or
+ // nil: the operator endpoint is off (operator_http.go).
+ operator *operatorHTTPSettings
}
// LoadRuntime keeps existing deployments on the legacy path until a role is
@@ -149,6 +157,9 @@ func LoadRuntime(dbPath string, logger *slog.Logger) (Runtime, error) {
default:
return Runtime{}, errExchangeConfig
}
+ if err := loadOperatorHTTP(&cfg); err != nil {
+ return Runtime{}, err
+ }
if err := loadDashboardConfig(&cfg); err != nil {
return Runtime{}, err
}
@@ -174,6 +185,22 @@ func (cfg Runtime) Schema() *migrate.Set {
}
return BootSchema
}
+
+// ServingSchema is what boot applies: Schema plus the operator endpoint's
+// additive tables (team-provisioning-amendment.md §7). Schema stays the
+// role's selected-release schema, which the frozen compatibility, admission
+// and legacy-diagnostic profiles describe; a database carrying the HTTP
+// tables is refused by the native command's exact ledger check, as any
+// additive foreign ledger is, until those profiles are reviewed afresh.
+func (cfg Runtime) ServingSchema() *migrate.Set {
+ switch cfg.role {
+ case "directory":
+ return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema)
+ case "credential":
+ return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema)
+ }
+ return cfg.Schema()
+}
func NewRuntime(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) {
if !cfg.roster.valid(cfg.role, cfg.keys) || !cfg.validAppPreviews() {
return nil, errExchangeConfig
@@ -192,6 +219,19 @@ func NewRuntime(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) {
return nil, errExchangeConfig
}
a.runtime = &cfg
+ if cfg.role == "credential" {
+ // HOME_CONSUMERS ∪ the consumers table; a collision refuses boot.
+ a.runtime.registry = newConsumerRegistry(cfg.consumers)
+ if err := a.runtime.registry.load(context.Background(), d.Writer(), cfg.origins.Credential, cfg.keys); err != nil {
+ return nil, err
+ }
+ if err := loadDashboardConfig(a.runtime); err != nil {
+ return nil, err
+ }
+ }
+ if err := a.newOperatorEndpoint(a.runtime); err != nil {
+ return nil, err
+ }
return a, nil
}
diff --git a/internal/home/schema_inventory.go b/internal/home/schema_inventory.go
index 8d0dada..cc7b69b 100644
--- a/internal/home/schema_inventory.go
+++ b/internal/home/schema_inventory.go
@@ -21,11 +21,11 @@ func LogSchemaInventory(parent context.Context, d *db.DB, cfg Runtime, logger *s
defer logLegacySchemaDiagnostic(ctx, d.Writer(), cfg.role, logger)
expected := map[string]bool{}
known := map[string]bool{}
- for _, m := range cfg.Schema().All() {
+ for _, m := range cfg.ServingSchema().All() {
expected[m.ID] = true
}
for _, role := range []string{"credential", "directory"} {
- for _, m := range (Runtime{role: role}).Schema().All() {
+ for _, m := range (Runtime{role: role}).ServingSchema().All() {
known[m.ID] = true
}
}
diff --git a/internal/home/security.go b/internal/home/security.go
index 9165dce..20eec76 100644
--- a/internal/home/security.go
+++ b/internal/home/security.go
@@ -1,24 +1,42 @@
package home
import (
+ "net/http"
"sort"
"strings"
)
-// SecurityPolicy preserves framework defaults and names only registered form
-// destinations. The credential origin renders no account-authored markup.
-func (a *App) SecurityPolicy() string {
+// SecurityPolicy is the policy every response starts with. It preserves
+// framework defaults and names, in form-action, the directory and nothing
+// else on the credential origin; the two pages whose form goes to a consumer
+// (the assertion handoff and the "Finish signing out" page for a preview)
+// name that one consumer per response, through securityPolicy. That is
+// what lets the consumer list outgrow the header (team-provisioning-
+// amendment.md §7). The credential origin renders no account-authored
+// markup.
+func (a *App) SecurityPolicy() string { return a.securityPolicy("") }
+
+// setConsumerPolicy is the one place a handler replaces the policy, and it
+// can only add one registered consumer to form-action: the rest is
+// SecurityPolicy's, byte for byte (TestConsumerPolicyOnlyWidensFormAction).
+// The assertion handoff and the preview "Finish signing out" page call it.
+func (a *App) setConsumerPolicy(w http.ResponseWriter, consumer string) {
+ if !registeredOrigin(a.consumers(), consumer) {
+ return
+ }
+ w.Header().Set("Content-Security-Policy", a.securityPolicy(consumer))
+}
+
+func (a *App) securityPolicy(consumer string) string {
origins := map[string]bool{a.origins.Directory: true}
- if a.runtime != nil {
- for _, origin := range a.runtime.consumers {
- origins[origin] = true
- }
- // form-action governs a form's redirects too, so the directory's
- // sign-out, which 307s its POST on to the credential origin, is
- // blocked in the browser without this. See signoutPath.
- if a.runtime.role == "directory" {
- origins[a.origins.Credential] = true
- }
+ if consumer != "" {
+ origins[consumer] = true
+ }
+ // form-action governs a form's redirects too, so the directory's
+ // sign-out, which 307s its POST on to the credential origin, is
+ // blocked in the browser without this. See signoutPath.
+ if a.runtime != nil && a.runtime.role == "directory" {
+ origins[a.origins.Credential] = true
}
list := make([]string, 0, len(origins))
for origin := range origins {
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/signout.go b/internal/home/signout.go
index c7da8e2..5a884fa 100644
--- a/internal/home/signout.go
+++ b/internal/home/signout.go
@@ -57,6 +57,7 @@ func (a *App) handleCredentialSignout(w http.ResponseWriter, r *http.Request) {
a.render(w, r, http.StatusForbidden, "signout_confirm.html", nil)
return
case signoutConfirm:
+ a.setConsumerPolicy(w, back)
// Admitted, but the id.* cookie did not ride this hop, so there is
// no row to revoke yet. Clearing the cookie now would leave the
// row alive behind it; keep it, and let the same-origin button
@@ -164,13 +165,14 @@ func (a *App) signoutReturn(r *http.Request) (string, signoutVerdict) {
}
// consumerOrigin returns the registered consumer origin exactly equal to
-// origin. Registrations are validated at boot (assertion.NewVerifier), so
-// an exact string match is a match on scheme, host and port.
+// origin. Registrations are validated at boot and on every registry reload
+// (assertion.NewVerifier), so an exact string match is a match on scheme,
+// host and port. A retired table consumer is not in the union.
func (a *App) consumerOrigin(origin string) (string, bool) {
if a.runtime == nil {
return "", false
}
- for _, registered := range a.runtime.consumers {
+ for _, registered := range a.consumers() {
if registered == origin {
return registered, true
}
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}}
diff --git a/internal/operator/credential.go b/internal/operator/credential.go
index d76249f..d5843b0 100644
--- a/internal/operator/credential.go
+++ b/internal/operator/credential.go
@@ -46,29 +46,33 @@ func NewCredential(engine *Engine, directory string, signer *family.Keypair, bro
return &Credential{engine, directory, signer, resolve}, nil
}
func (c *Credential) Execute(ctx context.Context, raw []byte) ([]byte, error) {
- return c.engine.Execute(ctx, raw, func(ctx context.Context, conn *sql.Conn, r Request) ([]byte, error) {
- var in OwnerInput
- if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Action != "credential.owner-seed" || in.Directory != c.directory || !validTeam(in.TeamID, in.TeamSQID) || len(in.Address) == 0 || len(in.Address) > 320 || !utf8.ValidString(in.Address) {
- return nil, ErrRefused
- }
- address, e := mail.ParseAddress(in.Address)
- if e != nil || address.Address != in.Address || address.Name != "" {
- return nil, ErrRefused
- }
- now := c.engine.now()
- subject, found, e := c.resolve(ctx, conn, in.Address, in.ExistingOnly, now)
- if e != nil {
- return nil, ErrUnavailable
- }
- if !found || !PersonRef(subject) {
- return nil, ErrRefused
- }
- receipt, e := SignOwner(c.signer, OwnerReceipt{1, "owner-seed", r.authorization.OperationID, r.authorization.Origin, c.directory, in.TeamID, in.TeamSQID, subject, "owner", now.Unix(), now.Unix() + 300})
- if e != nil {
- return nil, e
- }
- result := resultFor(r)
- result.Receipt = receipt
- return encode(result)
- })
+ return c.engine.Execute(ctx, raw, c.ownerSeed)
+}
+
+// ownerSeed is credential.owner-seed's mutation, shared by the native command
+// and the HTTP path (which wraps it in a window check).
+func (c *Credential) ownerSeed(ctx context.Context, conn *sql.Conn, r Request) ([]byte, error) {
+ var in OwnerInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Action != "credential.owner-seed" || in.Directory != c.directory || !validTeam(in.TeamID, in.TeamSQID) || len(in.Address) == 0 || len(in.Address) > 320 || !utf8.ValidString(in.Address) {
+ return nil, ErrRefused
+ }
+ address, e := mail.ParseAddress(in.Address)
+ if e != nil || address.Address != in.Address || address.Name != "" {
+ return nil, ErrRefused
+ }
+ now := c.engine.now()
+ subject, found, e := c.resolve(ctx, conn, in.Address, in.ExistingOnly, now)
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if !found || !PersonRef(subject) {
+ return nil, ErrRefused
+ }
+ receipt, e := SignOwner(c.signer, OwnerReceipt{1, "owner-seed", r.authorization.OperationID, r.authorization.Origin, c.directory, in.TeamID, in.TeamSQID, subject, "owner", now.Unix(), now.Unix() + 300})
+ if e != nil {
+ return nil, e
+ }
+ result := resultFor(r)
+ result.Receipt = receipt
+ return encode(result)
}
diff --git a/internal/operator/directory.go b/internal/operator/directory.go
index c0e629c..55812eb 100644
--- a/internal/operator/directory.go
+++ b/internal/operator/directory.go
@@ -63,6 +63,7 @@ type Result struct {
Record jsontext.Value `json:"record,omitempty"`
Bearer string `json:"bearer,omitempty"`
Receipt jsontext.Value `json:"receipt,omitempty"`
+ Manifest string `json:"credential_manifest_digest,omitempty"`
}
func resultFor(r Request) Result {
diff --git a/internal/operator/engine_test.go b/internal/operator/engine_test.go
index 6ee5aa4..d361ca7 100644
--- a/internal/operator/engine_test.go
+++ b/internal/operator/engine_test.go
@@ -44,7 +44,7 @@ func newEngineFixture(t *testing.T) engineFixture {
if _, e = db.Exec("PRAGMA journal_mode=WAL"); e != nil {
t.Fatal(e)
}
- if _, e = migrate.Apply(context.Background(), handle, migrate.Merge(directorydata.Schema, directorydata.RosterSchema, directorydata.OperatorSchema, DirectorySchema)); e != nil {
+ if _, e = migrate.Apply(context.Background(), handle, migrate.Merge(directorydata.Schema, directorydata.RosterSchema, directorydata.OperatorSchema, DirectorySchema, DirectoryHTTPSchema)); e != nil {
t.Fatal(e)
}
if _, e = db.Exec("CREATE TABLE test_items(id INTEGER PRIMARY KEY)"); e != nil {
diff --git a/internal/operator/http_migrations/credential/migrations/0001_operator_http.sql b/internal/operator/http_migrations/credential/migrations/0001_operator_http.sql
new file mode 100644
index 0000000..eaf6d2b
--- /dev/null
+++ b/internal/operator/http_migrations/credential/migrations/0001_operator_http.sql
@@ -0,0 +1,29 @@
+CREATE TABLE consumers (
+ consumer_id TEXT PRIMARY KEY CHECK(length(consumer_id) BETWEEN 1 AND 64 AND consumer_id NOT GLOB '*[^a-zA-Z0-9_-]*'),
+ origin TEXT NOT NULL UNIQUE CHECK(length(origin) BETWEEN 9 AND 253 AND substr(origin,1,8)='https://'),
+ app TEXT NOT NULL CHECK(length(app) BETWEEN 1 AND 32 AND app NOT GLOB '*[^a-z]*'),
+ state TEXT NOT NULL CHECK(state IN ('active','retired')),
+ created_at TEXT NOT NULL CHECK(length(created_at)=10),
+ operation_id TEXT NOT NULL CHECK(length(operation_id)=43)
+);
+-- The cap is a runaway provisioner's limit, not a scale target.
+CREATE TRIGGER consumers_cap BEFORE INSERT ON consumers
+WHEN (SELECT count(*) FROM consumers) >= 4096
+BEGIN SELECT RAISE(ABORT,'consumer registry full'); END;
+-- A retired hostname is dead at Home for good; nothing but active->retired.
+CREATE TRIGGER consumers_retire_only BEFORE UPDATE ON consumers
+WHEN OLD.state!='active' OR NEW.state!='retired' OR NEW.consumer_id IS NOT OLD.consumer_id OR NEW.origin IS NOT OLD.origin OR NEW.app IS NOT OLD.app OR NEW.created_at IS NOT OLD.created_at OR NEW.operation_id IS NOT OLD.operation_id
+BEGIN SELECT RAISE(ABORT,'consumer registry rows only retire'); END;
+CREATE TRIGGER consumers_no_delete BEFORE DELETE ON consumers
+BEGIN SELECT RAISE(ABORT,'consumer registry rows are never deleted'); END;
+CREATE TABLE operator_plans (
+ plan_id TEXT PRIMARY KEY CHECK(length(plan_id)=43 AND plan_id NOT GLOB '*[^a-zA-Z0-9_-]*'),
+ state TEXT NOT NULL UNIQUE CHECK(state IN ('pending','open')),
+ kind TEXT NOT NULL CHECK(kind IN ('create-team','add-apps','retire-apps')),
+ apps TEXT NOT NULL CHECK(length(apps) BETWEEN 1 AND 256 AND apps NOT GLOB '*[^a-z,]*'),
+ owner_index TEXT CHECK(owner_index IS NULL OR (length(owner_index)=64 AND owner_index NOT GLOB '*[^0-9a-f]*')),
+ expires_at INTEGER NOT NULL CHECK(typeof(expires_at)='integer' AND expires_at>0),
+ window_expires_at INTEGER CHECK(window_expires_at IS NULL OR (typeof(window_expires_at)='integer' AND window_expires_at>0)),
+ CHECK((kind='create-team') = (owner_index IS NOT NULL)),
+ CHECK((state='open') = (window_expires_at IS NOT NULL))
+);
diff --git a/internal/operator/http_migrations/directory/migrations/0001_operator_http.sql b/internal/operator/http_migrations/directory/migrations/0001_operator_http.sql
new file mode 100644
index 0000000..25e0844
--- /dev/null
+++ b/internal/operator/http_migrations/directory/migrations/0001_operator_http.sql
@@ -0,0 +1,19 @@
+CREATE TABLE operator_plans (
+ plan_id TEXT PRIMARY KEY CHECK(length(plan_id)=43 AND plan_id NOT GLOB '*[^a-zA-Z0-9_-]*'),
+ state TEXT NOT NULL UNIQUE CHECK(state IN ('pending','open')),
+ kind TEXT NOT NULL CHECK(kind IN ('initialize','create-team','add-apps','retire-apps')),
+ label TEXT CHECK(label IS NULL OR (length(label) BETWEEN 1 AND 63 AND label NOT GLOB '*[^a-z0-9-]*')),
+ apps TEXT NOT NULL CHECK(length(apps)<=256 AND apps NOT GLOB '*[^a-z,]*'),
+ sealed_name BLOB CHECK(sealed_name IS NULL OR (typeof(sealed_name)='blob' AND length(sealed_name) BETWEEN 29 AND 284)),
+ expires_at INTEGER NOT NULL CHECK(typeof(expires_at)='integer' AND expires_at>0),
+ window_expires_at INTEGER CHECK(window_expires_at IS NULL OR (typeof(window_expires_at)='integer' AND window_expires_at>0)),
+ CHECK((kind='initialize') = (label IS NULL)),
+ CHECK((kind='initialize') = (apps='')),
+ CHECK((kind='create-team') = (sealed_name IS NOT NULL)),
+ CHECK((state='open') = (window_expires_at IS NOT NULL))
+);
+-- The provenance fence: teams whose seed committed through the HTTP stream.
+CREATE TABLE operator_http_teams (
+ team_id INTEGER PRIMARY KEY REFERENCES teams(id),
+ operation_id TEXT NOT NULL UNIQUE REFERENCES directory_operator_results(operation_id) DEFERRABLE INITIALLY DEFERRED
+);
diff --git a/internal/operator/http_verbs.go b/internal/operator/http_verbs.go
new file mode 100644
index 0000000..e792109
--- /dev/null
+++ b/internal/operator/http_verbs.go
@@ -0,0 +1,534 @@
+package operator
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ stdjson "encoding/json"
+ "errors"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/home/roster"
+ "github.com/go-json-experiment/json"
+ "github.com/go-json-experiment/json/jsontext"
+)
+
+// The verbs reachable over POST /operator/v1 (team-provisioning-amendment.md
+// §5). The engine is unchanged; each verb is wrapped by a window check, and on
+// the directory by the provenance fence, inside the operation's own
+// transaction. The native command's Execute methods are untouched.
+
+func contains(list []string, s string) bool { return slices.Contains(list, s) }
+
+// ---- directory ----
+
+type DisableInput struct {
+ InputBase
+ Generation string `json:"expected_generation"`
+ TeamSQID string `json:"team_sqid"`
+ App string `json:"app"`
+ Consumer string `json:"consumer"`
+}
+
+// fence admits only a team whose seed committed through this HTTP stream, and
+// only the window's label. It returns the team id.
+func fence(ctx context.Context, c *sql.Conn, sqid, label string) (int64, error) {
+ var id int64
+ var stored string
+ e := c.QueryRowContext(ctx, "SELECT t.id,t.label FROM teams t JOIN operator_http_teams h ON h.team_id=t.id WHERE t.sqid=?", sqid).Scan(&id, &stored)
+ if errors.Is(e, sql.ErrNoRows) {
+ return 0, ErrRefused
+ }
+ if e != nil {
+ return 0, ErrUnavailable
+ }
+ if stored != label {
+ return 0, ErrRefused
+ }
+ return id, nil
+}
+
+// ExecuteHTTP is the directory's /operator/v1 operation path.
+func (d *Directory) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if d == nil {
+ return nil, ErrRefused
+ }
+ // Expired plan rows go before the operation, in their own statement, so
+ // a refused operation's rollback cannot bring them back.
+ if e := sweepPlans(ctx, d.engine.db, d.engine.now().Unix()); e != nil {
+ return nil, e
+ }
+ return d.engine.Execute(ctx, raw, func(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
+ action := r.authorization.Action
+ now := d.engine.now().Unix()
+ w, sealed, e := window(ctx, c, "directory", now)
+ if e != nil {
+ return nil, e
+ }
+ if !windowAdmits(w.Kind, action) {
+ return nil, ErrRefused
+ }
+ switch action {
+ case "directory.initialize":
+ return d.initialize(ctx, c, r)
+ case "directory.seed-team":
+ var in SeedInput
+ if DecodeInput(r, &in) != nil || in.Label != w.Label || sealed == nil {
+ return nil, ErrRefused
+ }
+ // The display name Paul saw on Home is the one the team gets:
+ // opened inside this transaction and compared byte for byte.
+ name, e := d.engine.sealer.Open(planNamePurpose(w.ID), sealed)
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if !bytes.Equal(name, []byte(in.Name)) {
+ return nil, ErrRefused
+ }
+ out, e := d.seed(ctx, c, r)
+ if e != nil {
+ return nil, e
+ }
+ var result Result
+ if json.Unmarshal(out, &result) != nil || result.TeamID <= 0 {
+ return nil, ErrUnavailable
+ }
+ if _, e = c.ExecContext(ctx, "INSERT INTO operator_http_teams(team_id,operation_id) VALUES(?,?)", result.TeamID, r.authorization.OperationID); e != nil {
+ return nil, ErrUnavailable
+ }
+ return out, nil
+ case "directory.provision-consumer":
+ var in ProvisionInput
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) {
+ return nil, ErrRefused
+ }
+ if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
+ return nil, e
+ }
+ return d.provision(ctx, c, r)
+ case "directory.verify-consumer":
+ var in VerificationInput
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) {
+ return nil, ErrRefused
+ }
+ if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
+ return nil, e
+ }
+ return d.verifyConsumer(ctx, c, r)
+ case "directory.activate-consumer":
+ var in ActivationInput
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.Evidence.App) {
+ return nil, ErrRefused
+ }
+ if _, e := fence(ctx, c, in.Evidence.TeamSQID, w.Label); e != nil {
+ return nil, e
+ }
+ return d.activate(ctx, c, r)
+ case "directory.disable-consumer":
+ return d.disable(ctx, c, r, w)
+ }
+ return nil, ErrRefused
+ })
+}
+
+func (d *Directory) disable(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
+ var in DisableInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !d.apps[in.App] || !contains(w.Apps, in.App) || !atom(in.Consumer, 64) {
+ return nil, ErrRefused
+ }
+ if e := generation(ctx, c, in.Generation); e != nil {
+ return nil, e
+ }
+ team, e := fence(ctx, c, in.TeamSQID, w.Label)
+ if e != nil {
+ return nil, e
+ }
+ var state string
+ e = c.QueryRowContext(ctx, "SELECT state FROM team_instances WHERE team_id=? AND app=? AND consumer_id=?", team, in.App, in.Consumer).Scan(&state)
+ if errors.Is(e, sql.ErrNoRows) {
+ return nil, ErrRefused
+ }
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if state == "disabled" {
+ return nil, ErrRefused
+ }
+ if _, e = c.ExecContext(ctx, "UPDATE team_instances SET state='disabled' WHERE team_id=? AND app=? AND consumer_id=?", team, in.App, in.Consumer); e != nil {
+ return nil, ErrUnavailable
+ }
+ if _, e = c.ExecContext(ctx, "UPDATE roster_consumers SET enabled=0 WHERE consumer_id=? AND team_id=? AND app=?", in.Consumer, team, in.App); e != nil {
+ return nil, ErrUnavailable
+ }
+ result := resultFor(r)
+ result.Generation = in.Generation
+ result.TeamID = team
+ result.TeamSQID = in.TeamSQID
+ out, e := encode(result)
+ if e != nil {
+ return nil, e
+ }
+ h := sha256.Sum256(out)
+ if _, e = c.ExecContext(ctx, "INSERT INTO roster_operator_receipts VALUES(?,1,'disable',?,?,?,?)", r.authorization.OperationID, in.Consumer, in.Generation, h[:], d.engine.now().Unix()); e != nil {
+ return nil, ErrUnavailable
+ }
+ return out, nil
+}
+
+// ---- credential ----
+
+// ConsumerCap is the consumers table's limit (and its trigger's): a runaway
+// provisioner's ceiling, not a scale target.
+const ConsumerCap = 4096
+
+// RegisterInput carries the directory's signed provisioning record and
+// nothing else: the consumer, audience and app come from what verifies.
+type RegisterInput struct {
+ InputBase
+ Record jsontext.Value `json:"record"`
+}
+type RetireInput struct {
+ InputBase
+ Consumer string `json:"consumer"`
+}
+
+// CredentialHTTP is the credential role's /operator/v1 path.
+type CredentialHTTP struct {
+ c *Credential
+ provisioning []roster.Key
+ env map[string]string
+ apps map[string]bool
+ ownerIndex func(string) string
+ admit func(id, origin string) bool
+}
+
+// NewCredentialHTTP pins the directory's provisioning public key (the
+// credential role's first pin of anything the directory signs), the
+// HOME_CONSUMERS manifest it must never collide with, the compiled app
+// registry and the blind index that compares the typed owner. admit is the
+// registry reload's own admission predicate: no row is committed that the
+// reload — and so the next boot — would refuse (discussion 94, blocker 1).
+func NewCredentialHTTP(c *Credential, provisioningPublic string, env map[string]string, apps []string, ownerIndex func(string) string, admit func(id, origin string) bool) (*CredentialHTTP, error) {
+ if c == nil || ownerIndex == nil || admit == nil || len(env) == 0 || len(apps) == 0 {
+ return nil, ErrRefused
+ }
+ k, e := public(provisioningPublic)
+ if e != nil || bytes.Equal(k, c.engine.verifier.key) || bytes.Equal(k, c.signer.SignPub()) {
+ return nil, ErrRefused
+ }
+ h := &CredentialHTTP{c, []roster.Key{{ID: keyID(k), Public: provisioningPublic}}, map[string]string{}, map[string]bool{}, ownerIndex, admit}
+ for id, origin := range env {
+ if !atom(id, 64) || !Origin(origin) {
+ return nil, ErrRefused
+ }
+ h.env[id] = origin
+ }
+ for _, a := range apps {
+ h.apps[a] = true
+ }
+ return h, nil
+}
+
+func (h *CredentialHTTP) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if h == nil {
+ return nil, ErrRefused
+ }
+ c := h.c
+ if e := sweepPlans(ctx, c.engine.db, c.engine.now().Unix()); e != nil {
+ return nil, e
+ }
+ return c.engine.Execute(ctx, raw, func(ctx context.Context, conn *sql.Conn, r Request) ([]byte, error) {
+ action := r.authorization.Action
+ now := c.engine.now().Unix()
+ w, _, e := window(ctx, conn, "credential", now)
+ if e != nil {
+ return nil, e
+ }
+ if !windowAdmits(w.Kind, action) {
+ return nil, ErrRefused
+ }
+ switch action {
+ case "credential.owner-seed":
+ var in OwnerInput
+ // Over this endpoint the owner must already exist (Paul,
+ // 2026-10-27), and must be the owner Paul typed at confirm.
+ if DecodeInput(r, &in) != nil || !in.ExistingOnly || !ownerAddress(in.Address) || !hmac.Equal([]byte(h.ownerIndex(in.Address)), []byte(w.OwnerIndex)) {
+ return nil, ErrRefused
+ }
+ return c.ownerSeed(ctx, conn, r)
+ case "credential.register-consumer":
+ return h.register(ctx, conn, r, w)
+ case "credential.retire-consumer":
+ return h.retire(ctx, conn, r, w)
+ }
+ return nil, ErrRefused
+ })
+}
+
+// claimedBindings reads a record's claimed bindings without trusting them;
+// VerifyProvisioning below is what decides.
+func claimedBindings(record []byte) (roster.Bindings, bool) {
+ var env envelope
+ if len(record) == 0 || len(record) > roster.BodyLimit || json.Unmarshal(record, &env, json.RejectUnknownMembers(true)) != nil {
+ return roster.Bindings{}, false
+ }
+ payload, ok := canonical(env.Payload, -1)
+ if !ok {
+ return roster.Bindings{}, false
+ }
+ var p roster.Provisioning
+ if json.Unmarshal(payload, &p, json.RejectUnknownMembers(true)) != nil {
+ return roster.Bindings{}, false
+ }
+ return p.Bindings, true
+}
+
+func (h *CredentialHTTP) register(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
+ var in RegisterInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial {
+ return nil, ErrRefused
+ }
+ claimed, ok := claimedBindings(in.Record)
+ if !ok {
+ return nil, ErrRefused
+ }
+ // Issuer and directory are fixed to the pinned values; the record must
+ // verify under the directory's provisioning key with exactly those.
+ expected := claimed
+ expected.Issuer = h.c.engine.verifier.pins.Origin
+ expected.Directory = h.c.directory
+ verified, e := roster.VerifyProvisioning(in.Record, h.provisioning, expected)
+ if e != nil {
+ return nil, ErrRefused
+ }
+ b := verified.Bindings()
+ if !h.apps[b.App] || !contains(w.Apps, b.App) || !atom(b.Consumer, 64) || !Origin(b.Audience) || !h.admit(b.Consumer, b.Audience) {
+ return nil, ErrRefused
+ }
+ for id, origin := range h.env {
+ if id == b.Consumer || origin == b.Audience {
+ return nil, ErrRefused
+ }
+ }
+ var clash, total int
+ e = c.QueryRowContext(ctx, "SELECT count(*) FROM consumers WHERE consumer_id=? OR origin=?", b.Consumer, b.Audience).Scan(&clash)
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if clash != 0 {
+ return nil, ErrRefused
+ }
+ // The cap is a refusal; the trigger behind it is the backstop, so any
+ // INSERT failure past this point is unavailable, not refused.
+ if e = c.QueryRowContext(ctx, "SELECT count(*) FROM consumers").Scan(&total); e != nil {
+ return nil, ErrUnavailable
+ }
+ if total >= ConsumerCap {
+ return nil, ErrRefused
+ }
+ now := h.c.engine.now()
+ if _, e = c.ExecContext(ctx, "INSERT INTO consumers(consumer_id,origin,app,state,created_at,operation_id) VALUES(?,?,?,'active',?,?)", b.Consumer, b.Audience, b.App, now.UTC().Format(time.DateOnly), r.authorization.OperationID); e != nil {
+ return nil, ErrUnavailable
+ }
+ return h.manifestResult(ctx, c, r)
+}
+
+func (h *CredentialHTTP) retire(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
+ var in RetireInput
+ if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !atom(in.Consumer, 64) {
+ return nil, ErrRefused
+ }
+ var app, state string
+ e := c.QueryRowContext(ctx, "SELECT app,state FROM consumers WHERE consumer_id=?", in.Consumer).Scan(&app, &state)
+ if errors.Is(e, sql.ErrNoRows) {
+ return nil, ErrRefused
+ }
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ if state != "active" || !contains(w.Apps, app) {
+ return nil, ErrRefused
+ }
+ if _, e = c.ExecContext(ctx, "UPDATE consumers SET state='retired' WHERE consumer_id=? AND state='active'", in.Consumer); e != nil {
+ return nil, ErrUnavailable
+ }
+ return h.manifestResult(ctx, c, r)
+}
+
+func (h *CredentialHTTP) manifestResult(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
+ table, e := ActiveConsumers(ctx, c)
+ if e != nil {
+ return nil, e
+ }
+ union := map[string]string{}
+ for id, origin := range h.env {
+ union[id] = origin
+ }
+ for id, origin := range table {
+ union[id] = origin
+ }
+ result := resultFor(r)
+ result.Manifest, e = ManifestDigest(union)
+ if e != nil {
+ return nil, e
+ }
+ return encode(result)
+}
+
+type queryer interface {
+ QueryContext(context.Context, string, ...any) (*sql.Rows, error)
+}
+
+// ActiveConsumers reads the credential registry table's active rows.
+func ActiveConsumers(ctx context.Context, q queryer) (map[string]string, error) {
+ rows, e := q.QueryContext(ctx, "SELECT consumer_id,origin FROM consumers WHERE state='active' LIMIT 4097")
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ defer rows.Close()
+ out := map[string]string{}
+ for rows.Next() {
+ var id, origin string
+ if rows.Scan(&id, &origin) != nil || !atom(id, 64) || !Origin(origin) {
+ return nil, ErrUnavailable
+ }
+ out[id] = origin
+ }
+ if rows.Err() != nil || len(out) > 4096 {
+ return nil, ErrUnavailable
+ }
+ return out, nil
+}
+
+// ManifestDigest is base64url(SHA-256(encoding/json.Marshal(
+// ["oficina/home/consumer-manifest/v1", [[id, origin], …]]))), entries sorted
+// by the unsigned byte order of consumer ID (team-provisioning-app.md §7).
+func ManifestDigest(consumers map[string]string) (string, error) {
+ ids := make([]string, 0, len(consumers))
+ for id := range consumers {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ entries := make([][2]string, 0, len(ids))
+ for _, id := range ids {
+ entries = append(entries, [2]string{id, consumers[id]})
+ }
+ b, e := stdjson.Marshal([]any{"oficina/home/consumer-manifest/v1", entries})
+ if e != nil {
+ return "", ErrUnavailable
+ }
+ sum := sha256.Sum256(b)
+ return base64.RawURLEncoding.EncodeToString(sum[:]), nil
+}
+
+// ---- inspect ----
+
+// HTTPInspection is <role>.inspect's answer: the stream position Alta
+// resynchronises from, the plan ids and expiries (never their contents),
+// and on the directory the generation and next team proposal.
+type HTTPInspection struct {
+ Version int `json:"version"`
+ Role string `json:"role"`
+ Challenge string `json:"challenge"`
+ Observed int64 `json:"observed_at"`
+ Sequence int64 `json:"sequence"`
+ Head string `json:"head"`
+ Generation *string `json:"generation,omitempty"`
+ TeamID int64 `json:"proposed_team_id,omitempty"`
+ TeamSQID string `json:"proposed_team_sqid,omitempty"`
+ PendingPlan string `json:"pending_plan,omitempty"`
+ PendingExpires int64 `json:"pending_expires_at,omitempty"`
+ OpenPlan string `json:"open_plan,omitempty"`
+ WindowExpires int64 `json:"window_expires_at,omitempty"`
+}
+
+func inspectHTTP(ctx context.Context, e *Engine, raw []byte, extra func(context.Context, *sql.Conn, *HTTPInspection) error) ([]byte, error) {
+ if e == nil {
+ return nil, ErrRefused
+ }
+ role := e.verifier.pins.Role
+ if !e.verifier.actions[role+".inspect"] {
+ return nil, ErrRefused
+ }
+ challenge, err := e.verifier.verifyInspect(raw, e.now())
+ if err != nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ c, err := e.db.Conn(ctx)
+ if err != nil {
+ return nil, ErrUnavailable
+ }
+ defer c.Close()
+ if _, err = c.ExecContext(ctx, "BEGIN"); err != nil {
+ return nil, ErrUnavailable
+ }
+ defer c.ExecContext(context.Background(), "ROLLBACK")
+ now := e.now().Unix()
+ out := HTTPInspection{Version: 1, Role: role, Challenge: challenge.Challenge, Observed: now}
+ var origin, installation, registry, device, kid string
+ var completed int64
+ err = c.QueryRowContext(ctx, "SELECT origin,installation,registry,device,sequence,head,completed_at,key_id FROM "+e.prefix+"_state WHERE singleton=1").Scan(&origin, &installation, &registry, &device, &out.Sequence, &out.Head, &completed, &kid)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrUnavailable
+ }
+ p := e.verifier.pins
+ if err == nil && (origin != p.Origin || installation != p.Installation || registry != p.Registry || device != p.Device || kid != e.verifier.kid || completed > now) {
+ return nil, ErrRefused
+ }
+ if v, _, err := scanPlan(ctx, c, role, "state='pending' AND expires_at>?", now); err == nil {
+ out.PendingPlan, out.PendingExpires = v.ID, v.Expires
+ } else if err != ErrRefused {
+ return nil, err
+ }
+ if v, _, err := scanPlan(ctx, c, role, "state='open' AND window_expires_at>?", now); err == nil {
+ out.OpenPlan, out.WindowExpires = v.ID, v.WindowExpires
+ } else if err != ErrRefused {
+ return nil, err
+ }
+ if extra != nil {
+ if err := extra(ctx, c, &out); err != nil {
+ return nil, err
+ }
+ }
+ return encode(out)
+}
+
+// InspectHTTP is directory.inspect over /operator/v1.
+func (d *Directory) InspectHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if d == nil {
+ return nil, ErrRefused
+ }
+ return inspectHTTP(ctx, d.engine, raw, func(ctx context.Context, c *sql.Conn, out *HTTPInspection) error {
+ var g string
+ err := c.QueryRowContext(ctx, "SELECT generation FROM roster_generation WHERE singleton=1").Scan(&g)
+ if err == nil {
+ if !CanonicalToken(g) {
+ return ErrUnavailable
+ }
+ out.Generation = &g
+ } else if !errors.Is(err, sql.ErrNoRows) {
+ return ErrUnavailable
+ }
+ id, sqid, err := nextTeam(ctx, c)
+ if err != nil {
+ return ErrUnavailable
+ }
+ out.TeamID, out.TeamSQID = id, sqid
+ return nil
+ })
+}
+
+// InspectHTTP is credential.inspect: new code, as the credential role had no
+// inspect before.
+func (h *CredentialHTTP) InspectHTTP(ctx context.Context, raw []byte) ([]byte, error) {
+ if h == nil {
+ return nil, ErrRefused
+ }
+ return inspectHTTP(ctx, h.c.engine, raw, nil)
+}
diff --git a/internal/operator/http_verbs_test.go b/internal/operator/http_verbs_test.go
new file mode 100644
index 0000000..e67545e
--- /dev/null
+++ b/internal/operator/http_verbs_test.go
@@ -0,0 +1,767 @@
+package operator
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ sharedseal "amadan.net/oficina/home/handoff/seal"
+ "amadan.net/oficina/home/internal/home/directorydata"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ rdb "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "github.com/go-json-experiment/json"
+)
+
+var httpApps = []string{"docs", "sheets"}
+
+// ---- directory ----
+
+type httpDirectory struct {
+ *directoryFixture
+ plans *PlanStore
+ plan byte
+}
+
+func newHTTPDirectory(t *testing.T) *httpDirectory {
+ t.Helper()
+ f := newDirectoryFixture(t)
+ p := f.engine.verifier.pins
+ p.Actions = []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"}
+ v, e := NewVerifier(p)
+ if e != nil {
+ t.Fatal(e)
+ }
+ f.engine.verifier = v
+ plans, e := NewPlanStore(f.db, "directory", f.engine.sealer)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return &httpDirectory{f, plans, 200}
+}
+
+func (f *httpDirectory) signPlan(t *testing.T, mutate func(*Plan)) (Plan, []byte) {
+ t.Helper()
+ pins := f.engine.verifier.pins
+ p := Plan{Version: 1, Purpose: "operator-plan", Role: pins.Role, Origin: pins.Origin, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device, PlanID: token(f.plan), Kind: "create-team", Apps: []string{"docs"}, Label: "alpha", DisplayName: "PRIVATE-TEAM-NAME-CANARY", Issued: f.now.Unix(), Expires: f.now.Unix() + PlanLifetime}
+ f.plan++
+ if mutate != nil {
+ mutate(&p)
+ }
+ raw, e := SignPlan(f.key, p, httpApps)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return p, raw
+}
+
+// openPlan submits and confirms a plan, as Alta then Paul would.
+func (f *httpDirectory) openPlan(t *testing.T, mutate func(*Plan)) Plan {
+ t.Helper()
+ _, raw := f.signPlan(t, mutate)
+ p, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = f.plans.Submit(context.Background(), p, "", *f.now); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = f.plans.Open(context.Background(), p.PlanID, *f.now, func(PlanView) bool { return true }); e != nil {
+ t.Fatal(e)
+ }
+ return p
+}
+
+func (f *httpDirectory) run(t *testing.T, action string, build func(InputBase) any) ([]byte, error) {
+ t.Helper()
+ return f.directory.ExecuteHTTP(context.Background(), f.input(t, action, build))
+}
+func (f *httpDirectory) seedHTTP(t *testing.T, id int64, label, name string) ([]byte, error) {
+ t.Helper()
+ sqid, _ := TeamSQID(id)
+ proof := f.receipt(t, id)
+ return f.run(t, "directory.seed-team", func(b InputBase) any {
+ return SeedInput{b, token(10), id, sqid, label, name, proof}
+ })
+}
+
+// initialized brings the stream to: generation present, a create-team window
+// for alpha/docs open.
+func initializedHTTP(t *testing.T) *httpDirectory {
+ t.Helper()
+ f := newHTTPDirectory(t)
+ f.openPlan(t, func(p *Plan) { p.Kind, p.Apps, p.Label, p.DisplayName = "initialize", nil, "", "" })
+ if _, e := f.run(t, "directory.initialize", func(b InputBase) any {
+ return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"}
+ }); e != nil {
+ t.Fatal(e)
+ }
+ // The initialize window stays open until it expires; one open per role.
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, nil)
+ return f
+}
+
+func TestOperatorPlanVerifyRefusesWrongKeyContextPinsAndClock(t *testing.T) {
+ f := newHTTPDirectory(t)
+ _, good := f.signPlan(t, nil)
+ if _, e := f.engine.verifier.VerifyPlan(good, httpApps, *f.now); e != nil {
+ t.Fatal(e)
+ }
+ other, _ := family.Generate()
+ pins := f.engine.verifier.pins
+ base := Plan{Version: 1, Purpose: "operator-plan", Role: pins.Role, Origin: pins.Origin, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device, PlanID: token(99), Kind: "create-team", Apps: []string{"docs"}, Label: "alpha", DisplayName: "Alpha", Issued: f.now.Unix(), Expires: f.now.Unix() + 600}
+ wrongKey, _ := SignPlan(other, base, httpApps)
+ payload, _ := encode(base)
+ sig, _ := family.Sign(f.key, InputContext, payload)
+ wrongContext, _ := encode(envelope{1, keyID(f.key.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)})
+ cases := map[string][]byte{"key": wrongKey, "context": wrongContext}
+ for name, mutate := range map[string]func(*Plan){
+ "role": func(p *Plan) { p.Role = "credential"; p.Label, p.DisplayName, p.Owner = "", "", "a@example.test" },
+ "origin": func(p *Plan) { p.Origin = "https://other.oficina.works" },
+ "device": func(p *Plan) { p.Device = token(77) },
+ "app": func(p *Plan) { p.Apps = []string{"calendar"} },
+ "duplicate": func(p *Plan) { p.Apps = []string{"docs", "docs"} },
+ "long": func(p *Plan) { p.Expires = p.Issued + PlanLifetime + 1 },
+ "future": func(p *Plan) { p.Issued, p.Expires = p.Issued+1, p.Issued+600 },
+ "name-on-add": func(p *Plan) { p.Kind = "add-apps" },
+ "no-name": func(p *Plan) { p.DisplayName = "" },
+ "owner": func(p *Plan) { p.Owner = "a@example.test" },
+ "label": func(p *Plan) { p.Label = "Alpha" },
+ "init-label": func(p *Plan) { p.Kind, p.Apps, p.DisplayName = "initialize", nil, "" },
+ "unknown-kind": func(p *Plan) { p.Kind = "rename" },
+ } {
+ p := base
+ mutate(&p)
+ payload, _ := encode(p)
+ sig, _ := family.Sign(f.key, PlanContext, payload)
+ cases[name], _ = encode(envelope{1, keyID(f.key.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)})
+ }
+ for name, raw := range cases {
+ if _, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now); e != ErrRefused {
+ t.Error(name, "accepted", e)
+ }
+ }
+ if _, e := f.engine.verifier.VerifyPlan(good, httpApps, f.now.Add(PlanLifetime*time.Second)); e != ErrRefused {
+ t.Fatal("expired plan accepted", e)
+ }
+}
+
+func TestOperatorPlanStoreOnePendingOneOpenAndExpiredRowsDeleted(t *testing.T) {
+ f := newHTTPDirectory(t)
+ ctx := context.Background()
+ _, raw := f.signPlan(t, nil)
+ p, _ := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now)
+ if e := f.plans.Submit(ctx, p, "", *f.now); e != nil {
+ t.Fatal(e)
+ }
+ _, raw2 := f.signPlan(t, func(p *Plan) { p.Label = "beta" })
+ p2, _ := f.engine.verifier.VerifyPlan(raw2, httpApps, *f.now)
+ if e := f.plans.Submit(ctx, p2, "", *f.now); e != ErrBusy {
+ t.Fatal("second pending plan accepted", e)
+ }
+ if e := f.plans.Submit(ctx, p, "", *f.now); e != ErrBusy {
+ t.Fatal("same plan twice", e)
+ }
+ view, e := f.plans.Pending(ctx, *f.now)
+ if e != nil || view.ID != p.PlanID || view.DisplayName != p.DisplayName || view.Label != "alpha" || view.Prefix() != hex.EncodeToString(bytes.Repeat([]byte{200}, 4)) {
+ t.Fatal("pending copy", e, view)
+ }
+ if _, e = f.plans.Open(ctx, p2.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrRefused {
+ t.Fatal("opened a plan that is not the pending one", e)
+ }
+ if _, e = f.plans.Open(ctx, p.PlanID, *f.now, func(PlanView) bool { return false }); e != ErrRefused {
+ t.Fatal("admit refusal ignored", e)
+ }
+ // Expiry: the row is deleted, not left behind, and the role is free.
+ *f.now = time.Unix(p.Expires, 0)
+ if _, e = f.plans.Open(ctx, p.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrRefused {
+ t.Fatal("expired plan opened", e)
+ }
+ if countRows(t, f.db, "operator_plans") != 0 {
+ t.Fatal("expired plan row left at rest")
+ }
+ // One open window blocks opening another until it expires.
+ f.openPlan(t, nil)
+ _, raw3 := f.signPlan(t, func(p *Plan) { p.Label = "gamma" })
+ p3, _ := f.engine.verifier.VerifyPlan(raw3, httpApps, *f.now)
+ if e = f.plans.Submit(ctx, p3, "", *f.now); e != nil {
+ t.Fatal("pending beside an open window", e)
+ }
+ if _, e = f.plans.Open(ctx, p3.PlanID, *f.now, func(PlanView) bool { return true }); e != ErrBusy {
+ t.Fatal("second open window", e)
+ }
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ if e = f.plans.Sweep(ctx, *f.now); e != nil || countRows(t, f.db, "operator_plans") != 0 {
+ t.Fatal("expired window row left", e)
+ }
+ // The display name is sealed at rest, and no plan bytes are stored.
+ for _, suffix := range []string{"", "-wal"} {
+ disk, e := os.ReadFile(f.path + suffix)
+ if e != nil && !errors.Is(e, os.ErrNotExist) {
+ t.Fatal(e)
+ }
+ secrets := [][]byte{[]byte("PRIVATE-TEAM-NAME-CANARY"), []byte(`"display_name":"PRIVATE-TEAM-NAME-CANARY"`)}
+ for _, signed := range [][]byte{raw, raw2, raw3} {
+ secrets = append(secrets, signedPlanParts(t, signed)...)
+ }
+ for _, secret := range secrets {
+ if bytes.Contains(disk, secret) {
+ t.Fatalf("plan bytes or name at rest: %.40q", secret)
+ }
+ }
+ }
+}
+
+func TestOperatorHTTPDirectoryNeedsAnOpenWindowOfTheRightKind(t *testing.T) {
+ f := newHTTPDirectory(t)
+ init := func(b InputBase) any { return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"} }
+ if _, e := f.run(t, "directory.initialize", init); e != ErrRefused {
+ t.Fatal("no window: initialize accepted", e)
+ }
+ f.openPlan(t, nil) // create-team, not initialize
+ if _, e := f.run(t, "directory.initialize", init); e != ErrRefused {
+ t.Fatal("verb outside kind accepted", e)
+ }
+ if countRows(t, f.db, "roster_generation") != 0 || countRows(t, f.db, "directory_operator_state") != 0 {
+ t.Fatal("refusal mutated")
+ }
+}
+
+func TestOperatorHTTPSeedTeamBindsLabelAndExactSealedName(t *testing.T) {
+ f := initializedHTTP(t)
+ if _, e := f.seedHTTP(t, 1, "beta", "PRIVATE-TEAM-NAME-CANARY"); e != ErrRefused {
+ t.Fatal("other label accepted", e)
+ }
+ for _, name := range []string{"PRIVATE-TEAM-NAME-CANARY ", "private-team-name-canary", "Other"} {
+ if _, e := f.seedHTTP(t, 1, "alpha", name); e != ErrRefused {
+ t.Fatalf("name %q accepted", name)
+ }
+ }
+ if countRows(t, f.db, "teams") != 0 {
+ t.Fatal("refused seed mutated")
+ }
+ if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil {
+ t.Fatal(e)
+ }
+ var team int64
+ if e := f.db.QueryRow("SELECT team_id FROM operator_http_teams").Scan(&team); e != nil || team != 1 {
+ t.Fatal("seed not fenced in", e)
+ }
+}
+
+func TestOperatorHTTPProvenanceFenceAndScope(t *testing.T) {
+ f := initializedHTTP(t)
+ if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil {
+ t.Fatal(e)
+ }
+ provision := func(sqid, app, consumer, audience string) error {
+ _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any {
+ return ProvisionInput{b, token(10), sqid, app, consumer, audience, 0}
+ })
+ return e
+ }
+ if e := provision("Uk", "sheets", "alpha-sheets", "https://alpha.sheets.oficina.works"); e != ErrRefused {
+ t.Fatal("app outside the window's apps", e)
+ }
+ // A team the native path seeded (not this stream) is outside the fence,
+ // even for a window naming its label.
+ if _, e := f.db.Exec("INSERT INTO teams(sqid,label,sealed_name,created_at) VALUES('gb','beta',zeroblob(40),1)"); e != nil {
+ t.Fatal(e)
+ }
+ if _, e := f.db.Exec("INSERT INTO memberships(team_id,person_ref,role) VALUES(2,'pr_aaaaaaaaaaaaaaaaaaaaaaaaaa','owner')"); e != nil {
+ t.Fatal(e)
+ }
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) { p.Kind, p.Label, p.DisplayName = "add-apps", "beta", "" })
+ if e := provision("gb", "docs", "beta-docs", "https://beta.docs.oficina.works"); e != ErrRefused {
+ t.Fatal("fence: unfenced team reached", e)
+ }
+ if e := provision("Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works"); e != ErrRefused {
+ t.Fatal("window for beta reached alpha", e)
+ }
+ if countRows(t, f.db, "team_instances") != 0 {
+ t.Fatal("refusal mutated")
+ }
+ // Window expiring mid-run: the next operation refuses.
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) { p.Kind, p.DisplayName = "add-apps", "" })
+ if e := provision("Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works"); e != nil {
+ t.Fatal(e)
+ }
+ *f.now = f.now.Add((WindowLifetime - 1) * time.Second)
+ in := VerificationInput{Consumer: "alpha-docs", TeamSQID: "Uk", App: "docs", Audience: "https://alpha.docs.oficina.works", Generation: token(10), RecordSequence: 1, Epoch: 2, Owner: "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", Issued: f.now.Unix(), Expires: f.now.Unix() + 600}
+ var digest []byte
+ if e := f.db.QueryRow("SELECT record_digest FROM directory_operator_consumer_records").Scan(&digest); e != nil {
+ t.Fatal(e)
+ }
+ in.RecordDigest = base64.RawURLEncoding.EncodeToString(digest)
+ if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != nil {
+ t.Fatal("inside window", e)
+ }
+ *f.now = f.now.Add(time.Second)
+ if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != ErrRefused {
+ t.Fatal("window expired mid-run but admitted", e)
+ }
+}
+
+func TestOperatorHTTPDisableConsumerUnderRetireApps(t *testing.T) {
+ f := initializedHTTP(t)
+ if _, e := f.seedHTTP(t, 1, "alpha", "PRIVATE-TEAM-NAME-CANARY"); e != nil {
+ t.Fatal(e)
+ }
+ if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any {
+ return ProvisionInput{b, token(10), "Uk", "docs", "alpha-docs", "https://alpha.docs.oficina.works", 0}
+ }); e != nil {
+ t.Fatal(e)
+ }
+ disable := func(b InputBase) any { return DisableInput{b, token(10), "Uk", "docs", "alpha-docs"} }
+ if _, e := f.run(t, "directory.disable-consumer", disable); e != ErrRefused {
+ t.Fatal("disable under create-team", e)
+ }
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) { p.Kind, p.DisplayName = "retire-apps", "" })
+ if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any {
+ return ProvisionInput{b, token(10), "Uk", "sheets", "alpha-sheets", "https://alpha.sheets.oficina.works", 0}
+ }); e != ErrRefused {
+ t.Fatal("provision under retire-apps", e)
+ }
+ if _, e := f.run(t, "directory.disable-consumer", disable); e != nil {
+ t.Fatal(e)
+ }
+ var state string
+ var enabled int
+ if e := f.db.QueryRow("SELECT i.state,c.enabled FROM team_instances i JOIN roster_consumers c USING(consumer_id)").Scan(&state, &enabled); e != nil || state != "disabled" || enabled != 0 {
+ t.Fatal("not disabled", e)
+ }
+ var kind string
+ if e := f.db.QueryRow("SELECT operation FROM roster_operator_receipts WHERE consumer_id='alpha-docs' ORDER BY rowid DESC LIMIT 1").Scan(&kind); e != nil || kind != "disable" {
+ t.Fatal("no disable receipt", e)
+ }
+ if _, e := f.run(t, "directory.disable-consumer", disable); e != ErrRefused {
+ t.Fatal("disabled twice", e)
+ }
+}
+
+func TestOperatorHTTPReplayAfterWindowExpiryReturnsStoredResult(t *testing.T) {
+ f := initializedHTTP(t)
+ sqid, _ := TeamSQID(1)
+ proof := f.receipt(t, 1)
+ raw := f.input(t, "directory.seed-team", func(b InputBase) any {
+ return SeedInput{b, token(10), 1, sqid, "alpha", "PRIVATE-TEAM-NAME-CANARY", proof}
+ })
+ out, e := f.directory.ExecuteHTTP(context.Background(), raw)
+ if e != nil {
+ t.Fatal(e)
+ }
+ *f.now = f.now.Add(2 * WindowLifetime * time.Second)
+ again, e := f.directory.ExecuteHTTP(context.Background(), raw)
+ if e != nil || !bytes.Equal(again, out) || countRows(t, f.db, "teams") != 1 {
+ t.Fatal("exact replay after expiry", e)
+ }
+}
+
+func TestOperatorHTTPDirectoryInspectReportsStreamAndPlansOnly(t *testing.T) {
+ f := initializedHTTP(t)
+ pins := f.engine.verifier.pins
+ raw, e := SignInspect(f.key, InspectChallenge{1, "operator-inspect", pins.Role, pins.Origin, pins.Installation, pins.Registry, pins.Device, token(66), f.now.Unix(), f.now.Unix() + 60})
+ if e != nil {
+ t.Fatal(e)
+ }
+ out, e := f.directory.InspectHTTP(context.Background(), raw)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var got HTTPInspection
+ var head string
+ if e = f.db.QueryRow("SELECT head FROM directory_operator_state").Scan(&head); e != nil {
+ t.Fatal(e)
+ }
+ if json.Unmarshal(out, &got) != nil || got.Sequence != 1 || got.Head != head || got.Generation == nil || got.TeamSQID != "Uk" || got.OpenPlan == "" || got.WindowExpires == 0 {
+ t.Fatal("inspection", string(out))
+ }
+ if strings.Contains(string(out), "alpha") || strings.Contains(string(out), "CANARY") {
+ t.Fatal("inspection carried plan contents")
+ }
+}
+
+// ---- credential ----
+
+type httpCredential struct {
+ db *sql.DB
+ path string
+ now *time.Time
+ key *family.Keypair
+ auth Authorization
+ http *CredentialHTTP
+ plans *PlanStore
+ dirKey *family.Keypair
+ attempt byte
+ pepper []byte
+ resolved int
+}
+
+const ownerCanary = "owner-canary@example.test"
+
+func credentialIndex(pepper []byte, address string) string {
+ m := hmac.New(sha256.New, pepper)
+ m.Write([]byte(strings.ToLower(address)))
+ return hex.EncodeToString(m.Sum(nil))
+}
+
+func newHTTPCredential(t *testing.T) *httpCredential {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "credential.db")
+ handle, e := rdb.Open(path, nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() { handle.Close() })
+ if _, e = migrate.Apply(context.Background(), handle, migrate.Merge(CredentialSchema, CredentialHTTPSchema)); e != nil {
+ t.Fatal(e)
+ }
+ db := handle.Writer()
+ if _, e = db.Exec("CREATE TABLE people(person_ref TEXT PRIMARY KEY, blind_index TEXT UNIQUE)"); e != nil {
+ t.Fatal(e)
+ }
+ f := &httpCredential{db: db, path: path, attempt: 30, pepper: bytes.Repeat([]byte{9}, 32)}
+ if _, e = db.Exec("INSERT INTO people VALUES('pr_aaaaaaaaaaaaaaaaaaaaaaaaaa',?)", credentialIndex(f.pepper, ownerCanary)); e != nil {
+ t.Fatal(e)
+ }
+ f.key, _ = family.Generate()
+ f.dirKey, _ = family.Generate()
+ owner, _ := family.Generate()
+ browser, _ := family.Generate()
+ f.auth = Authorization{Version: 1, Purpose: "operator-input", Role: "credential", Origin: "https://id.oficina.works", Installation: token(1), Registry: token(2), Device: token(3), JournalSequence: 1, Issued: 2000000000, Expires: 2000000300}
+ v, e := NewVerifier(Pins{"credential", f.auth.Origin, token(1), token(2), token(3), base64.RawURLEncoding.EncodeToString(f.key.SignPub()), []string{"credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect"}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ now := time.Unix(f.auth.Issued, 0)
+ f.now = &now
+ sealer, _ := sharedseal.New(bytes.Repeat([]byte{6}, 32), "oficina/operator")
+ engine, e := NewEngine(db, v, sealer, bytes.Repeat([]byte{7}, 32), func() time.Time { return *f.now })
+ if e != nil {
+ t.Fatal(e)
+ }
+ resolve := func(ctx context.Context, c *sql.Conn, address string, existing bool, _ time.Time) (string, bool, error) {
+ f.resolved++
+ var ref string
+ e := c.QueryRowContext(ctx, "SELECT person_ref FROM people WHERE blind_index=?", credentialIndex(f.pepper, address)).Scan(&ref)
+ if errors.Is(e, sql.ErrNoRows) {
+ return "", false, nil
+ }
+ return ref, e == nil, e
+ }
+ c, e := NewCredential(engine, "https://oficina.works", owner, [][]byte{browser.SignPub()}, resolve)
+ if e != nil {
+ t.Fatal(e)
+ }
+ env := map[string]string{"directory": "https://oficina.works", "docs": "https://docs.oficina.works"}
+ // The registry reload's own admission (internal/home registryAdmits):
+ // a consumer-name ID and an audience the assertion verifier accepts.
+ assertionKeys := map[string][]byte{keyID(browser.SignPub()): browser.SignPub()}
+ admit := func(id, origin string) bool {
+ _, err := assertion.NewVerifier(f.auth.Origin, origin, assertionKeys)
+ return atom(id, 64) && err == nil
+ }
+ f.http, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.dirKey.SignPub()), env, httpApps, func(a string) string { return credentialIndex(f.pepper, a) }, admit)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = NewCredentialHTTP(c, base64.RawURLEncoding.EncodeToString(f.key.SignPub()), env, httpApps, func(string) string { return "" }, admit); e != ErrRefused {
+ t.Fatal("Alta's key accepted as the directory provisioning pin")
+ }
+ f.plans, _ = NewPlanStore(db, "credential", sealer)
+ return f
+}
+
+func (f *httpCredential) openPlan(t *testing.T, kind string, apps ...string) {
+ t.Helper()
+ p := Plan{Version: 1, Purpose: "operator-plan", Role: "credential", Origin: f.auth.Origin, Installation: token(1), Registry: token(2), Device: token(3), PlanID: token(f.attempt + 100), Kind: kind, Apps: apps, Issued: f.now.Unix(), Expires: f.now.Unix() + 600}
+ index := ""
+ if kind == "create-team" {
+ p.Owner = ownerCanary
+ index = credentialIndex(f.pepper, ownerCanary)
+ }
+ raw, e := SignPlan(f.key, p, httpApps)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if p, e = f.http.c.engine.verifier.VerifyPlan(raw, httpApps, *f.now); e != nil {
+ t.Fatal(e)
+ }
+ if e = f.plans.Submit(context.Background(), p, index, *f.now); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = f.plans.Open(context.Background(), p.PlanID, *f.now, func(PlanView) bool { return true }); e != nil {
+ t.Fatal(e)
+ }
+}
+
+func (f *httpCredential) run(t *testing.T, action string, input func(InputBase) any) ([]byte, error) {
+ t.Helper()
+ a := f.auth
+ var sequence int64
+ var head string
+ if e := f.db.QueryRow("SELECT sequence,head FROM credential_operator_state").Scan(&sequence, &head); e != nil && !errors.Is(e, sql.ErrNoRows) {
+ t.Fatal(e)
+ }
+ a.Sequence, a.Previous, a.Initial = sequence+1, head, sequence == 0
+ a.Action, a.OperationID = action, token(f.attempt)
+ f.attempt++
+ a.Issued, a.Expires = f.now.Unix(), f.now.Unix()+300
+ raw, e := SignRequest(f.key, a, input(InputBase{1, action, a.OperationID}))
+ if e != nil {
+ t.Fatal(e)
+ }
+ return f.http.ExecuteHTTP(context.Background(), raw)
+}
+
+func (f *httpCredential) record(t *testing.T, key *family.Keypair, consumer, app, audience string) []byte {
+ t.Helper()
+ page, _ := family.Generate()
+ b := roster.Bindings{Issuer: f.auth.Origin, Directory: "https://oficina.works", Consumer: consumer, App: app, Team: "Uk", Audience: audience}
+ raw, e := roster.SignProvisioning(key, keyID(key.SignPub()), roster.Provisioning{Version: 1, Operation: token(70), Sequence: 1, Bindings: b, Generation: token(10), MinEpoch: 2, Keys: []roster.Key{{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(page.SignPub())}}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ return raw
+}
+
+func ownerSeedInput(address string, existing bool) func(InputBase) any {
+ return func(b InputBase) any { return OwnerInput{b, "https://oficina.works", 1, "Uk", address, existing} }
+}
+
+func TestOperatorHTTPOwnerSeedIsExistingOnlyAndTheTypedOwner(t *testing.T) {
+ f := newHTTPCredential(t)
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != ErrRefused {
+ t.Fatal("no window", e)
+ }
+ f.openPlan(t, "create-team", "docs")
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, false)); e != ErrRefused {
+ t.Fatal("minting owner-seed admitted", e)
+ }
+ if _, e := f.db.Exec("INSERT INTO people VALUES('pr_bbbbbbbbbbbbbbbbbbbbbbbbbb',?)", credentialIndex(f.pepper, "other@example.test")); e != nil {
+ t.Fatal(e)
+ }
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput("other@example.test", true)); e != ErrRefused {
+ t.Fatal("owner other than the confirmed one", e)
+ }
+ if f.resolved != 0 {
+ t.Fatal("refused owner reached resolution")
+ }
+ out, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true))
+ if e != nil {
+ t.Fatal(e)
+ }
+ var result Result
+ if json.Unmarshal(out, &result) != nil || len(result.Receipt) == 0 {
+ t.Fatal("no receipt")
+ }
+ // An expired receipt needs a new owner-seed operation under a live window.
+ *f.now = f.now.Add(301 * time.Second)
+ if _, e = f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil {
+ t.Fatal("fresh owner-seed in a live window", e)
+ }
+ disk, _ := os.ReadFile(f.path)
+ wal, _ := os.ReadFile(f.path + "-wal")
+ if bytes.Contains(append(disk, wal...), []byte(ownerCanary)) {
+ t.Fatal("owner address at rest")
+ }
+}
+
+func TestOperatorHTTPRegisterConsumerOnlyFromTheDirectoryRecord(t *testing.T) {
+ f := newHTTPCredential(t)
+ // The credential stream opens with owner-seed (sequence 1, initial
+ // authority); every other verb refuses Initial.
+ f.openPlan(t, "create-team", "docs")
+ if _, e := f.run(t, "credential.register-consumer", func(b InputBase) any {
+ return RegisterInput{b, f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works")}
+ }); e != ErrRefused {
+ t.Fatal("register as the stream's first operation", e)
+ }
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil {
+ t.Fatal(e)
+ }
+ register := func(record []byte) error {
+ _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, record} })
+ return e
+ }
+ other, _ := family.Generate()
+ for name, record := range map[string][]byte{
+ "none": []byte(`{}`),
+ "other-key": f.record(t, other, "alpha-docs", "docs", "https://alpha.docs.oficina.works"),
+ "alta-key": f.record(t, f.key, "alpha-docs", "docs", "https://alpha.docs.oficina.works"),
+ "app": f.record(t, f.dirKey, "alpha-sheets", "sheets", "https://alpha.sheets.oficina.works"),
+ "env-origin": f.record(t, f.dirKey, "team-docs", "docs", "https://docs.oficina.works"),
+ "env-id": f.record(t, f.dirKey, "docs", "docs", "https://alpha.docs.oficina.works"),
+ "directory": f.record(t, f.dirKey, "directory", "docs", "https://alpha.docs.oficina.works"),
+ // Blocker 1, #94: an audience the registry reload refuses (the
+ // credential origin itself) must never be committed.
+ "credential-origin": f.record(t, f.dirKey, "alpha-docs", "docs", f.auth.Origin),
+ "issuer-swap": nil,
+ } {
+ if record == nil {
+ page, _ := family.Generate()
+ b := roster.Bindings{Issuer: "https://id.other.works", Directory: "https://oficina.works", Consumer: "alpha-docs", App: "docs", Team: "Uk", Audience: "https://alpha.docs.oficina.works"}
+ record, _ = roster.SignProvisioning(f.dirKey, keyID(f.dirKey.SignPub()), roster.Provisioning{Version: 1, Operation: token(70), Sequence: 1, Bindings: b, Generation: token(10), MinEpoch: 2, Keys: []roster.Key{{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(page.SignPub())}}})
+ }
+ if e := register(record); e != ErrRefused {
+ t.Error(name, "registered", e)
+ }
+ }
+ if countRows(t, f.db, "consumers") != 0 {
+ t.Fatal("refused registration wrote")
+ }
+ good := f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works")
+ if e := register(good); e != nil {
+ t.Fatal(e)
+ }
+ if e := register(good); e != ErrRefused {
+ t.Fatal("same consumer twice", e)
+ }
+ var id, origin, app, state string
+ if e := f.db.QueryRow("SELECT consumer_id,origin,app,state FROM consumers").Scan(&id, &origin, &app, &state); e != nil || id != "alpha-docs" || origin != "https://alpha.docs.oficina.works" || app != "docs" || state != "active" {
+ t.Fatal("registered row", e)
+ }
+ // Retire needs a retire-apps window, and a retired origin is dead for good.
+ retire := func() error {
+ _, e := f.run(t, "credential.retire-consumer", func(b InputBase) any { return RetireInput{b, "alpha-docs"} })
+ return e
+ }
+ if e := retire(); e != ErrRefused {
+ t.Fatal("retire under add-apps", e)
+ }
+ // A retire-apps window for another app does not reach this one.
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, "retire-apps", "sheets")
+ if e := retire(); e != ErrRefused {
+ t.Fatal("retired an app outside the window's apps", e)
+ }
+ var still string
+ if e := f.db.QueryRow("SELECT state FROM consumers WHERE consumer_id='alpha-docs'").Scan(&still); e != nil || still != "active" {
+ t.Fatal("refused retire changed the row", still, e)
+ }
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, "retire-apps", "docs")
+ out, e := f.run(t, "credential.retire-consumer", func(b InputBase) any { return RetireInput{b, "alpha-docs"} })
+ if e != nil {
+ t.Fatal(e)
+ }
+ var result Result
+ want, _ := ManifestDigest(map[string]string{"directory": "https://oficina.works", "docs": "https://docs.oficina.works"})
+ if json.Unmarshal(out, &result) != nil || result.Manifest != want {
+ t.Fatal("manifest digest after retire", result.Manifest)
+ }
+ if _, e = f.db.Exec("UPDATE consumers SET state='active'"); e == nil {
+ t.Fatal("retired consumer reactivated")
+ }
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, "add-apps", "docs")
+ if e := register(good); e != ErrRefused {
+ t.Fatal("retired hostname reused", e)
+ }
+}
+
+func TestOperatorHTTPConsumerTableCap(t *testing.T) {
+ f := newHTTPCredential(t)
+ tx, _ := f.db.Begin()
+ for i := 0; i < 4096; i++ {
+ if _, e := tx.Exec("INSERT INTO consumers VALUES(?,?,'docs','active','2026-10-27',?)", "c"+strings.Repeat("x", 1)+itoa(i), "https://t"+itoa(i)+".docs.oficina.works", token(1)); e != nil {
+ t.Fatal(i, e)
+ }
+ }
+ if e := tx.Commit(); e != nil {
+ t.Fatal(e)
+ }
+ f.openPlan(t, "create-team", "docs")
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil {
+ t.Fatal(e)
+ }
+ _, e := f.run(t, "credential.register-consumer", func(b InputBase) any {
+ return RegisterInput{b, f.record(t, f.dirKey, "alpha-docs", "docs", "https://alpha.docs.oficina.works")}
+ })
+ if e != ErrRefused || countRows(t, f.db, "consumers") != 4096 {
+ t.Fatal("4,097th consumer", e)
+ }
+}
+
+func itoa(i int) string {
+ if i == 0 {
+ return "0"
+ }
+ s := ""
+ for ; i > 0; i /= 10 {
+ s = string(rune('0'+i%10)) + s
+ }
+ return s
+}
+
+func TestOperatorHTTPCredentialInspect(t *testing.T) {
+ f := newHTTPCredential(t)
+ f.openPlan(t, "create-team", "docs")
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil {
+ t.Fatal(e)
+ }
+ raw, e := SignInspect(f.key, InspectChallenge{1, "operator-inspect", "credential", f.auth.Origin, token(1), token(2), token(3), token(66), f.now.Unix(), f.now.Unix() + 60})
+ if e != nil {
+ t.Fatal(e)
+ }
+ out, e := f.http.InspectHTTP(context.Background(), raw)
+ var got HTTPInspection
+ if e != nil || json.Unmarshal(out, &got) != nil || got.Role != "credential" || got.Sequence != 1 || !CanonicalToken(got.Head) || got.OpenPlan == "" || got.Generation != nil {
+ t.Fatal("credential inspect", e, string(out))
+ }
+ other, _ := family.Generate()
+ raw, _ = SignInspect(other, InspectChallenge{1, "operator-inspect", "credential", f.auth.Origin, token(1), token(2), token(3), token(66), f.now.Unix(), f.now.Unix() + 60})
+ if _, e = f.http.InspectHTTP(context.Background(), raw); e != ErrRefused {
+ t.Fatal("foreign inspect key", e)
+ }
+ _ = directorydata.ValidLabel
+}
+
+// signedPlanParts is what "the signed plan bytes" means at rest: the payload
+// and the signature, raw and as their base64url text.
+func signedPlanParts(t *testing.T, raw []byte) [][]byte {
+ t.Helper()
+ var env envelope
+ if e := json.Unmarshal(raw, &env); e != nil {
+ t.Fatal(e)
+ }
+ payload, ok := canonical(env.Payload, -1)
+ sig, ok2 := canonical(env.Signature, 64)
+ if !ok || !ok2 {
+ t.Fatal("plan envelope")
+ }
+ return [][]byte{payload, sig, []byte(env.Payload), []byte(env.Signature)}
+}
+
+// An open window's row is gone once it expires, swept before the next
+// operation even though that operation is refused (its rollback must not
+// bring the row back).
+func TestOperatorHTTPExpiredWindowRowSweptBeforeARefusedOperation(t *testing.T) {
+ f := newHTTPDirectory(t)
+ f.openPlan(t, nil)
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ if _, e := f.run(t, "directory.initialize", func(b InputBase) any {
+ return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"}
+ }); e != ErrRefused {
+ t.Fatal("operation after the window", e)
+ }
+ if countRows(t, f.db, "operator_plans") != 0 {
+ t.Fatal("expired window row left at rest")
+ }
+}
diff --git a/internal/operator/plan.go b/internal/operator/plan.go
new file mode 100644
index 0000000..921300b
--- /dev/null
+++ b/internal/operator/plan.go
@@ -0,0 +1,444 @@
+package operator
+
+import (
+ "context"
+ "database/sql"
+ "embed"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "io/fs"
+ "net/mail"
+ "slices"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+// The HTTP operator transport (implementation/team-provisioning-amendment.md)
+// keeps its tables in their own migration sets, so the frozen native-command
+// schema profiles do not move. A database carrying them is refused by the
+// native command's exact ledger check, as any additive foreign ledger is.
+//
+//go:embed http_migrations
+var httpMigrations embed.FS
+
+var CredentialHTTPSchema = httpSchema("credential")
+var DirectoryHTTPSchema = httpSchema("directory")
+
+func httpSchema(role string) *migrate.Set {
+ f, e := fs.Sub(httpMigrations, "http_migrations/"+role)
+ if e != nil {
+ panic(e)
+ }
+ return migrate.MustFromFS(f, "oficina_"+role+"_operator_http")
+}
+
+const (
+ PlanContext = "oficina/home/operator-plan/v1"
+ PlanLimit = 8 << 10
+ // PlanLifetime bounds a pending plan, and WindowLifetime the window its
+ // confirmation opens. Neither is ever extended.
+ PlanLifetime = 900
+ WindowLifetime = 900
+)
+
+// ErrBusy is a refusal that says only "a plan is already pending or open".
+var ErrBusy = errors.New("operator: busy")
+
+// Plan is what Alta signs and submits to each role. Home verifies it, keeps
+// only the closed fields it needs (sealed or blind-indexed where they are
+// account-authored) and never stores these bytes.
+type Plan struct {
+ Version int `json:"version"`
+ Purpose string `json:"purpose"`
+ Role string `json:"role"`
+ Origin string `json:"origin"`
+ Installation string `json:"installation"`
+ Registry string `json:"registry"`
+ Device string `json:"device"`
+ PlanID string `json:"plan_id"`
+ Kind string `json:"kind"`
+ Apps []string `json:"apps"`
+ Label string `json:"label,omitzero"`
+ DisplayName string `json:"display_name,omitzero"`
+ Owner string `json:"owner,omitzero"`
+ Issued int64 `json:"issued_at"`
+ Expires int64 `json:"expires_at"`
+}
+
+func planKind(role, kind string) bool {
+ switch kind {
+ case "create-team", "add-apps", "retire-apps":
+ return role == "credential" || role == "directory"
+ case "initialize":
+ return role == "directory"
+ }
+ return false
+}
+
+// teamName is the directory's own team-name rule, restated so a plan is
+// refused at submit rather than at seed-team.
+func teamName(s string) bool {
+ if len(s) == 0 || len(s) > 255 || !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
+ return false
+ }
+ for _, r := range s {
+ if unicode.IsControl(r) {
+ return false
+ }
+ }
+ return true
+}
+
+// ownerAddress is the exact form owner-seed accepts.
+func ownerAddress(s string) bool {
+ if len(s) == 0 || len(s) > 320 || !utf8.ValidString(s) {
+ return false
+ }
+ a, e := mail.ParseAddress(s)
+ return e == nil && a.Address == s && a.Name == ""
+}
+
+func (p Plan) valid(apps map[string]bool) bool {
+ if p.Version != 1 || p.Purpose != "operator-plan" || !planKind(p.Role, p.Kind) || !Origin(p.Origin) || !CanonicalToken(p.Installation) || !CanonicalToken(p.Registry) || !CanonicalToken(p.Device) || !CanonicalToken(p.PlanID) || p.Issued <= 0 || p.Expires <= p.Issued || p.Expires-p.Issued > PlanLifetime {
+ return false
+ }
+ if p.Kind == "initialize" {
+ return len(p.Apps) == 0 && p.Label == "" && p.DisplayName == "" && p.Owner == ""
+ }
+ if len(p.Apps) == 0 || len(p.Apps) > 8 {
+ return false
+ }
+ seen := map[string]bool{}
+ for _, app := range p.Apps {
+ if !apps[app] || seen[app] {
+ return false
+ }
+ seen[app] = true
+ }
+ if p.Role == "directory" {
+ return p.Owner == "" && directorydata.ValidLabel(p.Label) && (p.Kind == "create-team") == (p.DisplayName != "") && (p.DisplayName == "" || teamName(p.DisplayName))
+ }
+ return p.Label == "" && p.DisplayName == "" && (p.Kind == "create-team") == (p.Owner != "") && (p.Owner == "" || ownerAddress(p.Owner))
+}
+
+// SignPlan is Alta's half, kept here so tests and Alta sign the one format.
+func SignPlan(k *family.Keypair, p Plan, apps []string) ([]byte, error) {
+ set := map[string]bool{}
+ for _, a := range apps {
+ set[a] = true
+ }
+ if !signingKey(k) || !p.valid(set) {
+ return nil, ErrRefused
+ }
+ payload, e := encode(p)
+ if e != nil {
+ return nil, ErrRefused
+ }
+ sig, e := family.Sign(k, PlanContext, payload)
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ out, e := encode(envelope{1, keyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)})
+ if e != nil || len(out) > PlanLimit {
+ return nil, ErrRefused
+ }
+ return out, nil
+}
+
+// VerifyPlan checks the pinned key, the plan context, this role's exact pins,
+// the closed fields and the clock. apps is the compiled registry.
+func (v *Verifier) VerifyPlan(raw []byte, apps []string, now time.Time) (Plan, error) {
+ var env envelope
+ var p Plan
+ if v == nil || len(raw) == 0 || len(raw) > PlanLimit || strictCanonical(raw, &env) != nil || env.Version != 1 || env.KeyID != v.kid {
+ return Plan{}, ErrRefused
+ }
+ payload, ok := canonical(env.Payload, -1)
+ sig, ok2 := canonical(env.Signature, 64)
+ if !ok || !ok2 || len(payload) > PlanLimit || !family.Verify(v.key, PlanContext, payload, sig) || strictCanonical(payload, &p) != nil {
+ return Plan{}, ErrRefused
+ }
+ set := map[string]bool{}
+ for _, a := range apps {
+ set[a] = true
+ }
+ pins := v.pins
+ if !p.valid(set) || p.Role != pins.Role || p.Origin != pins.Origin || p.Installation != pins.Installation || p.Registry != pins.Registry || p.Device != pins.Device || now.Unix() <= 0 || p.Issued > now.Unix() || now.Unix() >= p.Expires {
+ return Plan{}, ErrRefused
+ }
+ return p, nil
+}
+
+// PlanView is Home's own copy of a stored plan: never the signed bytes, never
+// the owner's address. DisplayName is opened only on the directory.
+type PlanView struct {
+ ID, State, Kind, Label, DisplayName, OwnerIndex string
+ Apps []string
+ Expires, WindowExpires int64
+}
+
+// Prefix is the first 8 hex digits of the plan id, the one thing Paul
+// compares across the two confirm pages.
+func (p PlanView) Prefix() string { return planPrefix(p.ID) }
+func planPrefix(id string) string {
+ b, ok := canonical(id, 32)
+ if !ok {
+ return ""
+ }
+ return hex.EncodeToString(b[:4])
+}
+
+// PlanStore keeps one role's plan rows. Expired rows are deleted, never
+// left (secure_delete is on), so an unconfirmed blind index does not linger.
+type PlanStore struct {
+ db *sql.DB
+ role string
+ sealer Sealer
+}
+
+func NewPlanStore(db *sql.DB, role string, sealer Sealer) (*PlanStore, error) {
+ if db == nil || sealer == nil || (role != "credential" && role != "directory") {
+ return nil, ErrRefused
+ }
+ return &PlanStore{db, role, sealer}, nil
+}
+
+func hexHash(s string) bool {
+ b, e := hex.DecodeString(s)
+ return e == nil && len(b) == 32 && hex.EncodeToString(b) == s
+}
+
+func planNamePurpose(id string) string { return "directory.operator-plan-name/" + id }
+
+type execer interface {
+ ExecContext(context.Context, string, ...any) (sql.Result, error)
+ QueryRowContext(context.Context, string, ...any) *sql.Row
+}
+
+func sweepPlans(ctx context.Context, x execer, now int64) error {
+ _, e := x.ExecContext(ctx, "DELETE FROM operator_plans WHERE (state='pending' AND expires_at<=?) OR (state='open' AND window_expires_at<=?)", now, now)
+ if e != nil {
+ return ErrUnavailable
+ }
+ return nil
+}
+
+// Sweep deletes every expired plan row.
+func (s *PlanStore) Sweep(ctx context.Context, now time.Time) error {
+ return sweepPlans(ctx, s.db, now.Unix())
+}
+
+// withTx runs f inside BEGIN IMMEDIATE on one connection.
+func withTx(ctx context.Context, db *sql.DB, f func(*sql.Conn) error) error {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ c, e := db.Conn(ctx)
+ if e != nil {
+ return ErrUnavailable
+ }
+ defer c.Close()
+ if _, e = c.ExecContext(ctx, "BEGIN IMMEDIATE"); e != nil {
+ return ErrUnavailable
+ }
+ if e = f(c); e != nil {
+ _, _ = c.ExecContext(context.Background(), "ROLLBACK")
+ return e
+ }
+ if _, e = c.ExecContext(ctx, "COMMIT"); e != nil {
+ _, _ = c.ExecContext(context.Background(), "ROLLBACK")
+ return ErrUnavailable
+ }
+ return nil
+}
+
+// Submit stores a verified plan's closed fields. ownerIndex is the credential
+// role's blind index of the owner, computed by the caller from an existing
+// person; the address itself never reaches this function's writes.
+func (s *PlanStore) Submit(ctx context.Context, p Plan, ownerIndex string, now time.Time) error {
+ if s == nil || p.Role != s.role {
+ return ErrRefused
+ }
+ if s.role == "credential" && ((p.Kind == "create-team") != (ownerIndex != "") || (ownerIndex != "" && !hexHash(ownerIndex))) {
+ return ErrRefused
+ }
+ if s.role == "directory" && ownerIndex != "" {
+ return ErrRefused
+ }
+ apps := slices.Clone(p.Apps)
+ slices.Sort(apps)
+ // Swept in its own statement, so a refusal below cannot roll it back.
+ if e := s.Sweep(ctx, now); e != nil {
+ return e
+ }
+ return withTx(ctx, s.db, func(c *sql.Conn) error {
+ var n int
+ if c.QueryRowContext(ctx, "SELECT count(*) FROM operator_plans WHERE state='pending' OR plan_id=?", p.PlanID).Scan(&n) != nil {
+ return ErrUnavailable
+ }
+ if n != 0 {
+ return ErrBusy
+ }
+ if s.role == "credential" {
+ var index any
+ if ownerIndex != "" {
+ index = ownerIndex
+ }
+ if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,apps,owner_index,expires_at) VALUES(?,'pending',?,?,?,?)", p.PlanID, p.Kind, strings.Join(apps, ","), index, p.Expires); e != nil {
+ return ErrUnavailable
+ }
+ return nil
+ }
+ var label, name any
+ if p.Label != "" {
+ label = p.Label
+ }
+ if p.DisplayName != "" {
+ sealed, e := s.sealer.Seal(planNamePurpose(p.PlanID), []byte(p.DisplayName))
+ if e != nil {
+ return ErrUnavailable
+ }
+ name = sealed
+ }
+ if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,label,apps,sealed_name,expires_at) VALUES(?,'pending',?,?,?,?,?)", p.PlanID, p.Kind, label, strings.Join(apps, ","), name, p.Expires); e != nil {
+ return ErrUnavailable
+ }
+ return nil
+ })
+}
+
+func scanPlan(ctx context.Context, q execer, role, where string, args ...any) (PlanView, []byte, error) {
+ var v PlanView
+ var apps string
+ var label, index sql.NullString
+ var window sql.NullInt64
+ var sealed []byte
+ var e error
+ if role == "credential" {
+ e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,apps,owner_index,expires_at,window_expires_at FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &apps, &index, &v.Expires, &window)
+ } else {
+ e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,label,apps,sealed_name,expires_at,window_expires_at FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &label, &apps, &sealed, &v.Expires, &window)
+ }
+ if errors.Is(e, sql.ErrNoRows) {
+ return PlanView{}, nil, ErrRefused
+ }
+ if e != nil {
+ return PlanView{}, nil, ErrUnavailable
+ }
+ if apps != "" {
+ v.Apps = strings.Split(apps, ",")
+ }
+ v.Label, v.OwnerIndex, v.WindowExpires = label.String, index.String, window.Int64
+ return v, sealed, nil
+}
+
+func (s *PlanStore) open(v PlanView, sealed []byte) (PlanView, error) {
+ if sealed == nil {
+ return v, nil
+ }
+ name, e := s.sealer.Open(planNamePurpose(v.ID), sealed)
+ if e != nil {
+ return PlanView{}, ErrUnavailable
+ }
+ v.DisplayName = string(name)
+ return v, nil
+}
+
+// Ends lists when each surviving plan row ends: a pending plan's expiry, an
+// open window's. Boot schedules a sweep for each, so a row that survives a
+// restart is still deleted on time.
+func (s *PlanStore) Ends(ctx context.Context, now time.Time) ([]int64, error) {
+ rows, e := s.db.QueryContext(ctx, "SELECT CASE state WHEN 'open' THEN window_expires_at ELSE expires_at END FROM operator_plans LIMIT 2")
+ if e != nil {
+ return nil, ErrUnavailable
+ }
+ defer rows.Close()
+ var out []int64
+ for rows.Next() {
+ var end int64
+ if rows.Scan(&end) != nil {
+ return nil, ErrUnavailable
+ }
+ out = append(out, end)
+ }
+ if rows.Err() != nil {
+ return nil, ErrUnavailable
+ }
+ return out, nil
+}
+
+// Pending returns the role's one pending, unexpired plan.
+func (s *PlanStore) Pending(ctx context.Context, now time.Time) (PlanView, error) {
+ v, sealed, e := scanPlan(ctx, s.db, s.role, "state='pending' AND expires_at>?", now.Unix())
+ if e != nil {
+ return PlanView{}, e
+ }
+ return s.open(v, sealed)
+}
+
+// Open opens the window for the pending plan named id, re-checking expiry
+// inside the write. admit sees Home's copy before anything changes; the
+// credential role compares the typed owner's blind index there.
+func (s *PlanStore) Open(ctx context.Context, id string, now time.Time, admit func(PlanView) bool) (PlanView, error) {
+ var out PlanView
+ if s == nil || !CanonicalToken(id) || admit == nil {
+ return out, ErrRefused
+ }
+ if e := s.Sweep(ctx, now); e != nil {
+ return out, e
+ }
+ e := withTx(ctx, s.db, func(c *sql.Conn) error {
+ v, sealed, e := scanPlan(ctx, c, s.role, "plan_id=? AND state='pending' AND expires_at>?", id, now.Unix())
+ if e != nil {
+ return e
+ }
+ if v, e = s.open(v, sealed); e != nil {
+ return e
+ }
+ if !admit(v) {
+ return ErrRefused
+ }
+ var open int
+ if c.QueryRowContext(ctx, "SELECT count(*) FROM operator_plans WHERE state='open'").Scan(&open) != nil {
+ return ErrUnavailable
+ }
+ if open != 0 {
+ return ErrBusy
+ }
+ window := now.Unix() + WindowLifetime
+ if _, e = c.ExecContext(ctx, "UPDATE operator_plans SET state='open',window_expires_at=? WHERE plan_id=? AND state='pending'", window, id); e != nil {
+ return ErrUnavailable
+ }
+ v.State, v.WindowExpires = "open", window
+ out = v
+ return nil
+ })
+ return out, e
+}
+
+// window is the role's one open, unexpired window, read on the operation's
+// own locked connection. No window is a refusal.
+func window(ctx context.Context, c *sql.Conn, role string, now int64) (PlanView, []byte, error) {
+ return scanPlan(ctx, c, role, "state='open' AND window_expires_at>?", now)
+}
+
+// windowKinds is §5's table: which plan kinds admit which verb.
+func windowAdmits(kind, action string) bool {
+ switch action {
+ case "directory.initialize":
+ return kind == "initialize"
+ case "directory.seed-team", "credential.owner-seed":
+ return kind == "create-team"
+ case "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "credential.register-consumer":
+ return kind == "create-team" || kind == "add-apps"
+ case "directory.disable-consumer", "credential.retire-consumer":
+ return kind == "retire-apps"
+ }
+ return false
+}
diff --git a/internal/operator/protocol.go b/internal/operator/protocol.go
index c56c1d6..e022651 100644
--- a/internal/operator/protocol.go
+++ b/internal/operator/protocol.go
@@ -129,11 +129,14 @@ func public(encoded string) ([]byte, error) {
}
func allowedAction(role, a string) bool {
if role == "credential" {
- return a == "credential.owner-seed"
+ switch a {
+ case "credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect":
+ return true
+ }
}
if role == "directory" {
switch a {
- case "directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer":
+ case "directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer":
return true
}
}