oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "crypto/subtle"
8 "database/sql"
9 "encoding/base64"
10 "encoding/hex"
11 "errors"
12 "io"
13 "mime"
14 "net/http"
15 "strings"
16 "time"
17
18 "amadan.net/oficina/home/internal/home/directorydata"
19 "amadan.net/oficina/home/internal/operator"
20 "amadan.net/oficina/home/roster"
21 family "amadan.net/rastrillo/rastrillo/crypto"
22 json "github.com/go-json-experiment/json"
23)
24
25// The operator endpoint (implementation/team-provisioning-amendment.md):
26// POST /operator/v1 and POST /operator/v1/plan on each role's own origin,
27// callable only by one pinned external signer (Alta), outside csrf.Protect
28// and before any session middleware, refusing anything a browser sends.
29// Off unless HOME_OPERATOR_HTTP is configured: then neither route exists.
30const (
31 operatorPath = "/operator/v1"
32 operatorPlanPath = "/operator/v1/plan"
33 operatorConfirm = "/operator/confirm"
34 // operatorConfirmConsumer is the reserved consumer value in the
35 // credential confirm page's fresh intent. It is not a valid consumer
36 // name, so no registration can take it, and handleAssertion refuses it.
37 operatorConfirmConsumer = ":operator-confirm"
38)
39
40// operatorHTTPConfig is HOME_OPERATOR_HTTP: closed fields, ≤ 8 KiB.
41type operatorHTTPConfig struct {
42 Version int `json:"version"`
43 Role string `json:"role"`
44 Origin string `json:"origin"`
45 Installation string `json:"installation"`
46 Registry string `json:"registry"`
47 Device string `json:"device"`
48 PublicKey string `json:"public_key"`
49 KeyID string `json:"key_id"`
50 Actions []string `json:"actions"`
51 OperatorSubject string `json:"operator_subject"`
52 PrefilterSHA256 string `json:"prefilter_token_sha256"`
53 DirectoryProvisioningPublicKey string `json:"directory_provisioning_public_key,omitzero"`
54}
55
56// operatorHTTPSettings is what LoadRuntime validated: the pins and the role's
57// own operator material (HOME_OPERATOR_MATERIAL), not yet bound to a DB.
58type operatorHTTPSettings struct {
59 config operatorHTTPConfig
60 verifier *operator.Verifier
61 prefilter []byte
62 mac []byte
63 // credential role
64 owner *family.Keypair
65 // directory role
66 ownerVerifier *operator.OwnerVerifier
67 provisioning *family.Keypair
68 rosterKeys []roster.Key
69 now func() time.Time
70 // after schedules expiry sweeps; nil is time.AfterFunc (tests capture).
71 after func(time.Duration, func())
72}
73
74var errOperatorConfig = errExchangeConfig
75
76func operatorApps() []string {
77 var apps []string
78 for _, app := range directoryApps() {
79 if app.integrated {
80 apps = append(apps, app.slug)
81 }
82 }
83 return apps
84}
85
86// loadOperatorHTTP reads HOME_OPERATOR_HTTP for an explicit role. Absent is
87// off; anything malformed refuses boot.
88func loadOperatorHTTP(cfg *Runtime) error {
89 raw, err := exchangeJSON("HOME_OPERATOR_HTTP", 8192)
90 if err != nil {
91 return err
92 }
93 if raw == "" {
94 return nil
95 }
96 if cfg.role != "credential" && cfg.role != "directory" {
97 return errOperatorConfig
98 }
99 var c operatorHTTPConfig
100 if len(raw) > 8192 || json.Unmarshal([]byte(raw), &c, json.RejectUnknownMembers(true)) != nil || c.Version != 1 || c.Role != cfg.role {
101 return errOperatorConfig
102 }
103 own := cfg.origins.Credential
104 if cfg.role == "directory" {
105 own = cfg.origins.Directory
106 }
107 if c.Origin != own || !ValidPersonRef(c.OperatorSubject) || (cfg.role == "credential") != (c.DirectoryProvisioningPublicKey != "") {
108 return errOperatorConfig
109 }
110 alta, err := operatorPublic(c.PublicKey)
111 if err != nil {
112 return errOperatorConfig
113 }
114 sum := sha256.Sum256(alta)
115 if c.KeyID != hex.EncodeToString(sum[:]) {
116 return errOperatorConfig
117 }
118 prefilter, err := hex.DecodeString(c.PrefilterSHA256)
119 if err != nil || len(prefilter) != 32 || hex.EncodeToString(prefilter) != c.PrefilterSHA256 {
120 return errOperatorConfig
121 }
122 inspect := false
123 for _, a := range c.Actions {
124 inspect = inspect || a == cfg.role+".inspect"
125 }
126 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})
127 if err != nil || !inspect {
128 return errOperatorConfig
129 }
130 s := &operatorHTTPSettings{config: c, verifier: verifier, prefilter: prefilter, now: time.Now}
131 material, err := exchangeJSON("HOME_OPERATOR_MATERIAL", 16384)
132 if err != nil || material == "" {
133 return errOperatorConfig
134 }
135 // Alta's key is distinct from every key this role holds or pins:
136 // assertion, owner-seed, directory provisioning, roster and
137 // member-resolution keys.
138 keys := [][]byte{alta}
139 if cfg.role == "credential" {
140 var m credentialOperatorMaterial
141 if json.Unmarshal([]byte(material), &m, json.RejectUnknownMembers(true)) != nil || m.Version != 1 || m.Role != cfg.role {
142 return errOperatorConfig
143 }
144 if s.mac, err = operatorMAC(m.MAC); err != nil {
145 return errOperatorConfig
146 }
147 if s.owner, err = decodeHomeKeypair(m.Owner); err != nil {
148 return errOperatorConfig
149 }
150 provisioning, err := operatorPublic(c.DirectoryProvisioningPublicKey)
151 if err != nil || cfg.signer == nil {
152 return errOperatorConfig
153 }
154 keys = append(keys, s.owner.SignPub(), provisioning, cfg.signer.SignPub())
155 } else {
156 var m directoryOperatorMaterial
157 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 {
158 return errOperatorConfig
159 }
160 if s.mac, err = operatorMAC(m.MAC); err != nil {
161 return errOperatorConfig
162 }
163 if s.ownerVerifier, err = operator.NewOwnerVerifier(m.Owner, cfg.origins.Credential, cfg.origins.Directory); err != nil {
164 return errOperatorConfig
165 }
166 ownerPub, err := operatorPublic(m.Owner)
167 if err != nil {
168 return errOperatorConfig
169 }
170 if s.provisioning, err = decodeHomeKeypair(m.Provisioning); err != nil {
171 return errOperatorConfig
172 }
173 keys = append(keys, ownerPub, s.provisioning.SignPub())
174 for _, k := range cfg.keys {
175 keys = append(keys, k)
176 }
177 ids := map[string]bool{}
178 matched := cfg.roster.mode != "serve"
179 for _, k := range m.Roster {
180 pub, err := operatorPublic(k.Public)
181 sum := sha256.Sum256(pub)
182 if err != nil || k.ID != hex.EncodeToString(sum[:]) || ids[k.ID] {
183 return errOperatorConfig
184 }
185 ids[k.ID] = true
186 keys = append(keys, pub)
187 if cfg.roster.mode == "serve" && bytes.Equal(pub, cfg.roster.signer.SignPub()) {
188 matched = true
189 }
190 s.rosterKeys = append(s.rosterKeys, k)
191 }
192 if !matched {
193 return errOperatorConfig
194 }
195 }
196 // The member-resolution key joins the set on whichever role holds it.
197 if resolve := cfg.resolvePublicKey(); resolve != nil {
198 keys = append(keys, resolve)
199 }
200 if !distinctOperatorKeys(keys) {
201 return errOperatorConfig
202 }
203 cfg.operator = s
204 return nil
205}
206
207// operatorEndpoint is one role's mounted endpoint, bound to its database.
208type operatorEndpoint struct {
209 role, host, subject string
210 prefilter []byte
211 verifier *operator.Verifier
212 plans *operator.PlanStore
213 directory *operator.Directory
214 credential *operator.CredentialHTTP
215 apps []string
216 now func() time.Time
217 // after schedules the expiry sweeps; time.AfterFunc outside tests.
218 after func(time.Duration, func())
219}
220
221// sweepAt deletes the role's expired plan rows one second after unix (a
222// plan's expiry, or an open window's), even if nothing else touches the role
223// before then. Boot and every plan access sweep too; this is what keeps an
224// unconfirmed owner blind index from lingering on an idle role.
225func (e *operatorEndpoint) sweepAt(unix int64) {
226 wait := time.Unix(unix, 0).Sub(e.now()) + time.Second
227 if wait < 0 {
228 wait = 0
229 }
230 if wait > (operator.PlanLifetime+operator.WindowLifetime+5)*time.Second {
231 return
232 }
233 plans, clock := e.plans, e.now
234 e.after(wait, func() { _ = plans.Sweep(context.Background(), clock()) })
235}
236
237func (a *App) newOperatorEndpoint(cfg *Runtime) error {
238 s := cfg.operator
239 if s == nil {
240 return nil
241 }
242 sealer := a.secrets.Sealer
243 engine, err := operator.NewEngine(a.db.Writer(), s.verifier, sealer, s.mac, s.now)
244 if err != nil {
245 return errOperatorConfig
246 }
247 plans, err := operator.NewPlanStore(a.db.Writer(), cfg.role, sealer)
248 if err != nil {
249 return errOperatorConfig
250 }
251 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}
252 if e.after == nil {
253 e.after = func(d time.Duration, f func()) { time.AfterFunc(d, f) }
254 }
255 if cfg.role == "credential" {
256 e.host = a.credentialHost
257 resolve, err := NewOperatorPersonResolver(a.secrets.Pepper)
258 if err != nil {
259 return errOperatorConfig
260 }
261 c, err := operator.NewCredential(engine, cfg.origins.Directory, s.owner, [][]byte{cfg.signer.SignPub()}, resolve)
262 if err != nil {
263 return errOperatorConfig
264 }
265 pepper := a.secrets.Pepper
266 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))
267 if err != nil {
268 return errOperatorConfig
269 }
270 } else {
271 e.host = a.directoryHost
272 e.directory, err = operator.NewDirectory(engine, s.ownerVerifier, s.provisioning, s.rosterKeys, directorydata.Config{Apps: e.apps, ValidateRoute: directoryRouteAllowed})
273 if err != nil {
274 return errOperatorConfig
275 }
276 }
277 if err = plans.Sweep(context.Background(), s.now()); err != nil {
278 return err
279 }
280 // A row that survived a restart is still deleted at its end.
281 ends, err := plans.Ends(context.Background(), s.now())
282 if err != nil {
283 return err
284 }
285 for _, end := range ends {
286 e.sweepAt(end)
287 }
288 a.op = e
289 return nil
290}
291
292// serveOperator answers the two transport routes and reports whether it did.
293// Off (no HOME_OPERATOR_HTTP) it answers nothing, so they 404 like any
294// unknown path.
295func (a *App) serveOperator(w http.ResponseWriter, r *http.Request) bool {
296 if a.op == nil || (r.URL.Path != operatorPath && r.URL.Path != operatorPlanPath) {
297 return false
298 }
299 a.handleOperator(w, r)
300 return true
301}
302
303type operatorOutcome struct {
304 status int
305 code string
306}
307
308var (
309 operatorNotFound = operatorOutcome{http.StatusNotFound, "not_found"}
310 operatorMethod = operatorOutcome{http.StatusMethodNotAllowed, "method"}
311 operatorBrowser = operatorOutcome{http.StatusForbidden, "browser"}
312 operatorMedia = operatorOutcome{http.StatusUnsupportedMediaType, "media"}
313 operatorBearer = operatorOutcome{http.StatusUnauthorized, "prefilter"}
314 operatorTooLarge = operatorOutcome{http.StatusRequestEntityTooLarge, "size"}
315 operatorRefused = operatorOutcome{http.StatusForbidden, "refused"}
316 operatorBusy = operatorOutcome{http.StatusConflict, "busy"}
317 operatorDown = operatorOutcome{http.StatusServiceUnavailable, "unavailable"}
318)
319
320// operatorLog is gate 9's whole vocabulary here: a fixed route label, a verb
321// from the closed allowedAction set (or a fixed placeholder), an outcome code
322// and the operation id's first 8 characters. Nothing from a refused body.
323func (a *App) operatorLog(route, verb string, o operatorOutcome, op string) {
324 if len(op) > 8 {
325 op = op[:8]
326 }
327 a.logger.Info("operator http", "route", route, "verb", verb, "outcome", o.code, "op", op)
328}
329
330func (a *App) operatorAnswer(w http.ResponseWriter, route, verb, op string, o operatorOutcome) {
331 a.operatorLog(route, verb, o, op)
332 w.Header().Set("Content-Type", "application/json")
333 if o == operatorBearer {
334 w.Header().Set("WWW-Authenticate", "Bearer")
335 }
336 w.WriteHeader(o.status)
337 _, _ = io.WriteString(w, `{"outcome":"`+o.code+`"}`)
338}
339
340func browserMarked(r *http.Request) bool {
341 if len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Origin")) != 0 {
342 return true
343 }
344 for name := range r.Header {
345 if strings.HasPrefix(http.CanonicalHeaderKey(name), "Sec-Fetch-") {
346 return true
347 }
348 }
349 return false
350}
351
352func (a *App) prefilterPasses(r *http.Request) bool {
353 values := r.Header.Values("Authorization")
354 if len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") {
355 return false
356 }
357 token := strings.TrimPrefix(values[0], "Bearer ")
358 raw, err := base64.RawURLEncoding.Strict().DecodeString(token)
359 if err != nil || len(raw) != 32 || base64.RawURLEncoding.EncodeToString(raw) != token {
360 return false
361 }
362 sum := sha256.Sum256(raw)
363 return subtle.ConstantTimeCompare(sum[:], a.op.prefilter) == 1
364}
365
366func (a *App) handleOperator(w http.ResponseWriter, r *http.Request) {
367 w.Header().Set("Cache-Control", "no-store")
368 route := "operation"
369 if r.URL.Path == operatorPlanPath {
370 route = "plan"
371 }
372 // Each role answers on its own origin only.
373 if strings.ToLower(r.Host) != a.op.host {
374 a.operatorAnswer(w, route, "-", "", operatorNotFound)
375 return
376 }
377 if r.Method != http.MethodPost {
378 w.Header().Set("Allow", http.MethodPost)
379 a.operatorAnswer(w, route, "-", "", operatorMethod)
380 return
381 }
382 // 1. Not a browser: no cookie is read, no session is minted here.
383 if browserMarked(r) || r.URL.RawQuery != "" {
384 a.operatorAnswer(w, route, "-", "", operatorBrowser)
385 return
386 }
387 media, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
388 if err != nil || media != "application/json" || len(params) != 0 {
389 a.operatorAnswer(w, route, "-", "", operatorMedia)
390 return
391 }
392 // 2. The prefilter bearer: a DoS filter, not authority.
393 if !a.prefilterPasses(r) {
394 a.operatorAnswer(w, route, "-", "", operatorBearer)
395 return
396 }
397 body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, operator.BodyLimit))
398 if err != nil {
399 a.operatorAnswer(w, route, "-", "", operatorTooLarge)
400 return
401 }
402 if route == "plan" {
403 a.submitPlan(w, body)
404 return
405 }
406 // 3 and 4 — Alta's signature, then the window — happen inside the
407 // engine's transaction. Verify here only to name the verb in the log.
408 if req, err := a.op.verifier.Verify(body); err == nil {
409 action, op := req.Authorization().Action, req.Authorization().OperationID
410 var out []byte
411 if a.op.role == "directory" {
412 out, err = a.op.directory.ExecuteHTTP(r.Context(), body)
413 } else {
414 out, err = a.op.credential.ExecuteHTTP(r.Context(), body)
415 // On replay too: a reload that failed after the commit is retried.
416 if err == nil && (action == "credential.register-consumer" || action == "credential.retire-consumer") {
417 // The committed write is visible; swap the union in. If that
418 // fails, answer unavailable: Alta's exact replay returns the
419 // stored result and reloads again, so a retired consumer never
420 // stays admitted behind a 200.
421 // Not the request's context: a client gone after the commit
422 // must not leave the union stale (load bounds itself).
423 if err = a.runtime.registry.load(context.Background(), a.db.Writer(), a.origins.Credential, a.runtime.keys); err != nil {
424 err = operator.ErrUnavailable
425 }
426 }
427 }
428 a.operatorResult(w, route, action, op, out, err)
429 return
430 }
431 var out []byte
432 if a.op.role == "directory" {
433 out, err = a.op.directory.InspectHTTP(r.Context(), body)
434 } else {
435 out, err = a.op.credential.InspectHTTP(r.Context(), body)
436 }
437 // Neither a verified operation nor a verified inspect: the log says
438 // "-", not which of the two it failed to be.
439 verb := a.op.role + ".inspect"
440 if errors.Is(err, operator.ErrRefused) {
441 route, verb = "operation", "-"
442 } else {
443 route = "inspect"
444 }
445 a.operatorResult(w, route, verb, "", out, err)
446}
447
448func (a *App) operatorResult(w http.ResponseWriter, route, verb, op string, out []byte, err error) {
449 switch {
450 case err == nil:
451 a.operatorLog(route, verb, operatorOutcome{http.StatusOK, "ok"}, op)
452 w.Header().Set("Content-Type", "application/json")
453 w.WriteHeader(http.StatusOK)
454 _, _ = w.Write(out)
455 case errors.Is(err, operator.ErrRefused):
456 a.operatorAnswer(w, route, verb, op, operatorRefused)
457 default:
458 a.operatorAnswer(w, route, verb, op, operatorDown)
459 }
460}
461
462// submitPlan stores a verified plan's closed fields; never the signed bytes,
463// never the address. On the credential role the owner must already exist.
464func (a *App) submitPlan(w http.ResponseWriter, body []byte) {
465 now := a.op.now()
466 plan, err := a.op.verifier.VerifyPlan(body, a.op.apps, now)
467 if err != nil {
468 a.operatorAnswer(w, "plan", "plan", "", operatorRefused)
469 return
470 }
471 index := ""
472 if a.op.role == "credential" && plan.Owner != "" {
473 index = blindIndex(a.secrets.Pepper, plan.Owner)
474 var found int
475 err := a.db.Writer().QueryRow("SELECT 1 FROM people WHERE blind_index=?", index).Scan(&found)
476 if err != nil {
477 o := operatorRefused
478 if !errors.Is(err, sql.ErrNoRows) {
479 o = operatorDown
480 }
481 a.operatorAnswer(w, "plan", "plan", "", o)
482 return
483 }
484 }
485 err = a.op.plans.Submit(context.Background(), plan, index, now)
486 switch {
487 case errors.Is(err, operator.ErrBusy):
488 a.operatorAnswer(w, "plan", "plan", "", operatorBusy)
489 return
490 case errors.Is(err, operator.ErrRefused):
491 a.operatorAnswer(w, "plan", "plan", "", operatorRefused)
492 return
493 case err != nil:
494 a.operatorAnswer(w, "plan", "plan", "", operatorDown)
495 return
496 }
497 a.op.sweepAt(plan.Expires)
498 a.operatorLog("plan", "plan", operatorOutcome{http.StatusOK, "ok"}, "")
499 w.Header().Set("Content-Type", "application/json")
500 w.WriteHeader(http.StatusOK)
501 out, _ := json.Marshal(struct {
502 Outcome string `json:"outcome"`
503 Expires int64 `json:"expires_at"`
504 }{"pending", plan.Expires})
505 _, _ = w.Write(out)
506}
507