Operator HTTP transport: POST /operator/v1 and /operator/v1/plan on both roles
team-provisioning-amendment.md §3, §4 (transport and plan submit), §6. - HOME_OPERATOR_HTTP (closed JSON <= 8 KiB): Alta's pinned P-256 key and key id, the role's exact origin/installation/registry/device, actions (must include <role>.inspect), operator_subject, prefilter SHA-256, and on the credential role directory_provisioning_public_key. Absent: no route (404 like any unknown path). Malformed: boot refuses. The role's own keys come from the reviewed HOME_OPERATOR_MATERIAL (the native command's helpers move to operator_material.go). Alta's key must differ from every assertion, owner-seed, provisioning and roster key. - Both routes mounted outside csrf.Protect and before any session check (the directory dispatches them beside the roster path; the credential router is wrapped), answering only on the role's own host. - Transport order: browser markers (Cookie, Origin, Sec-Fetch-*, a query) 403; application/json exactly 415; prefilter bearer 401 with a fixed body; 64 KiB hard read limit 413; then Alta's signature and the window inside the engine's transaction. A registry write swaps the union in. - Plan submit verifies and stores the closed fields only; on the credential role the owner is blind-indexed existing-only (unknown owner refuses, nothing stored); one pending plan (409); a timer deletes it at expiry. - Gate 9: logs carry a fixed route, a verb from the closed action set, an outcome code and the operation id's first 8 characters. Tests: off without configuration; closed config and key distinctness; browser markers, size, media type, prefilter, method, Host spoofing and role separation; owner must exist; foreign-key plan; second pending plan; gate 2 plan-submit path (signed plan bytes and canary absent from file, WAL, SHM; expired row gone); gate 2 static half reaches the new migrations.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+1,108
−47
internal/guardstest/noaddress_test.go+21 −0internal/home/app.go+12 −1internal/home/directory.go+8 −0internal/home/operator_command_linux.go+0 −46internal/home/operator_http.go+461 −0internal/home/operator_http_test.go+540 −0internal/home/operator_material.go+57 −0internal/home/runtime.go+9 −0
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 08a5f3b..e874001 100644 |
| --- a/internal/home/app.go |
| +++ b/internal/home/app.go |
| @@ -43,6 +43,7 @@ type App struct { |
| directory *directoryFeatures |
| consumer *handoff.Consumer |
| fresh *handoff.Consumer |
| + op *operatorEndpoint |
| origins Origins |
| credentialHost string |
| directoryHost string |
| @@ -258,5 +259,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/directory.go b/internal/home/directory.go| index 34d17c7..5621501 100644 |
| --- a/internal/home/directory.go |
| +++ b/internal/home/directory.go |
| @@ -82,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 { |
| @@ -164,6 +167,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/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_http.go b/internal/home/operator_http.go| new file mode 100644 |
| index 0000000..bfed46e |
| --- /dev/null |
| +++ b/internal/home/operator_http.go |
| @@ -0,0 +1,461 @@ |
| +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 |
| +} |
| + |
| +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 |
| +} |
| + |
| +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} |
| + 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) }) |
| + 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.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) |
| + if err == nil && (action == "credential.register-consumer" || action == "credential.retire-consumer") { |
| + // The committed write is visible; swap the union in. |
| + if err = a.runtime.registry.load(r.Context(), a.db.Writer(), a.origins.Credential, a.runtime.keys); err != nil { |
| + a.logger.Error("operator http registry reload failed") |
| + err = nil |
| + } |
| + } |
| + } |
| + 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) |
| + } |
| + a.operatorResult(w, "inspect", a.op.role+".inspect", "", 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 |
| + } |
| + // Deleted at expiry even if nothing else touches the role before then. |
| + if wait := time.Until(time.Unix(plan.Expires, 0)) + time.Second; wait > 0 && wait <= (operator.PlanLifetime+5)*time.Second { |
| + plans, clock := a.op.plans, a.op.now |
| + time.AfterFunc(wait, func() { _ = plans.Sweep(context.Background(), clock()) }) |
| + } |
| + 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..9828dd4 |
| --- /dev/null |
| +++ b/internal/home/operator_http_test.go |
| @@ -0,0 +1,540 @@ |
| +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) |
| + if bytes.Contains(b, plan) || bytes.Contains(b, []byte(plan[20:80])) { |
| + t.Fatal("signed plan bytes at rest in", filepath.Base(path+suffix)) |
| + } |
| + } |
| + } |
| + // 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) |
| +} |
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/runtime.go b/internal/home/runtime.go| index 842cf83..1d92e6c 100644 |
| --- a/internal/home/runtime.go |
| +++ b/internal/home/runtime.go |
| @@ -40,6 +40,9 @@ type Runtime struct { |
| // 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 |
| @@ -154,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 |
| } |
| @@ -223,6 +229,9 @@ func NewRuntime(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) { |
| return nil, err |
| } |
| } |
| + if err := a.newOperatorEndpoint(a.runtime); err != nil { |
| + return nil, err |
| + } |
| return a, nil |
| } |