oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package operator
2
3import (
4 "bytes"
5 "context"
6 "crypto/hmac"
7 "crypto/sha256"
8 "database/sql"
9 "encoding/base64"
10 stdjson "encoding/json"
11 "errors"
12 "slices"
13 "time"
14
15 "amadan.net/oficina/home/internal/home/directorydata"
16 "amadan.net/oficina/home/roster"
17 "github.com/go-json-experiment/json"
18 "github.com/go-json-experiment/json/jsontext"
19)
20
21// The verbs reachable over POST /operator/v1 (team-provisioning-amendment.md
22// §5). The engine is unchanged; each verb is wrapped by a window check, and on
23// the directory by the provenance fence, inside the operation's own
24// transaction. The native command's Execute methods are untouched.
25
26func contains(list []string, s string) bool { return slices.Contains(list, s) }
27
28// ---- directory ----
29
30type DisableInput struct {
31 InputBase
32 Generation string `json:"expected_generation"`
33 TeamSQID string `json:"team_sqid"`
34 App string `json:"app"`
35 Consumer string `json:"consumer"`
36}
37
38// fence admits only a team whose seed committed through this HTTP stream, and
39// only the window's label. It returns the team id.
40func fence(ctx context.Context, c *sql.Conn, sqid, label string) (int64, error) {
41 var id int64
42 var stored string
43 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)
44 if errors.Is(e, sql.ErrNoRows) {
45 return 0, ErrRefused
46 }
47 if e != nil {
48 return 0, ErrUnavailable
49 }
50 if stored != label {
51 return 0, ErrRefused
52 }
53 return id, nil
54}
55
56// ExecuteHTTP is the directory's /operator/v1 operation path.
57func (d *Directory) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error) {
58 if d == nil {
59 return nil, ErrRefused
60 }
61 // Expired plan rows go before the operation, in their own statement, so
62 // a refused operation's rollback cannot bring them back.
63 if e := sweepPlans(ctx, d.engine.db, d.engine.now().Unix()); e != nil {
64 return nil, e
65 }
66 return d.engine.Execute(ctx, raw, func(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
67 action := r.authorization.Action
68 now := d.engine.now().Unix()
69 w, sealed, e := window(ctx, c, "directory", now)
70 if e != nil {
71 return nil, e
72 }
73 if !windowAdmits(w.Kind, action) {
74 return nil, ErrRefused
75 }
76 switch action {
77 case "directory.initialize":
78 return d.initialize(ctx, c, r)
79 case "directory.seed-team":
80 var in SeedInput
81 if DecodeInput(r, &in) != nil || in.Label != w.Label || sealed == nil {
82 return nil, ErrRefused
83 }
84 // The display name Paul saw on Home is the one the team gets:
85 // opened inside this transaction and compared byte for byte.
86 name, e := d.engine.sealer.Open(planNamePurpose(w.ID), sealed)
87 if e != nil {
88 return nil, ErrUnavailable
89 }
90 if !bytes.Equal(name, []byte(in.Name)) {
91 return nil, ErrRefused
92 }
93 out, e := d.seedTeamForWindow(ctx, c, r, true, w.ExistingTeam)
94 if e != nil {
95 return nil, e
96 }
97 var result Result
98 if json.Unmarshal(out, &result) != nil || result.TeamID <= 0 {
99 return nil, ErrUnavailable
100 }
101 if _, e = c.ExecContext(ctx, "INSERT INTO operator_http_teams(team_id,operation_id) VALUES(?,?)", result.TeamID, r.authorization.OperationID); e != nil {
102 return nil, ErrUnavailable
103 }
104 return out, nil
105 case "directory.provision-consumer":
106 var in ProvisionInput
107 if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) {
108 return nil, ErrRefused
109 }
110 if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
111 return nil, e
112 }
113 return d.provisionForWindow(ctx, c, r, w.ExistingTeam)
114 case "directory.verify-consumer":
115 var in VerificationInput
116 if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) || !routeScope(w.ExistingTeam, w.Label, in.TeamSQID, in.App, in.Consumer, in.Audience) {
117 return nil, ErrRefused
118 }
119 if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
120 return nil, e
121 }
122 return d.verifyConsumerForWindow(ctx, c, r, w.ExistingTeam)
123 case "directory.activate-consumer":
124 var in ActivationInput
125 if DecodeInput(r, &in) != nil || !contains(w.Apps, in.Evidence.App) || !routeScope(w.ExistingTeam, w.Label, in.Evidence.TeamSQID, in.Evidence.App, in.Evidence.Consumer, in.Evidence.Audience) {
126 return nil, ErrRefused
127 }
128 if _, e := fence(ctx, c, in.Evidence.TeamSQID, w.Label); e != nil {
129 return nil, e
130 }
131 return d.activateForWindow(ctx, c, r, w.ExistingTeam)
132 case "directory.disable-consumer":
133 return d.disable(ctx, c, r, w)
134 }
135 return nil, ErrRefused
136 })
137}
138
139func (d *Directory) disable(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
140 var in DisableInput
141 if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !d.apps[in.App] || !contains(w.Apps, in.App) || !atom(in.Consumer, 64) {
142 return nil, ErrRefused
143 }
144 if e := generation(ctx, c, in.Generation); e != nil {
145 return nil, e
146 }
147 team, e := fence(ctx, c, in.TeamSQID, w.Label)
148 if e != nil {
149 return nil, e
150 }
151 var state string
152 e = c.QueryRowContext(ctx, "SELECT state FROM team_instances WHERE team_id=? AND app=? AND consumer_id=?", team, in.App, in.Consumer).Scan(&state)
153 if errors.Is(e, sql.ErrNoRows) {
154 return nil, ErrRefused
155 }
156 if e != nil {
157 return nil, ErrUnavailable
158 }
159 if state == "disabled" {
160 return nil, ErrRefused
161 }
162 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 {
163 return nil, ErrUnavailable
164 }
165 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 {
166 return nil, ErrUnavailable
167 }
168 result := resultFor(r)
169 result.Generation = in.Generation
170 result.TeamID = team
171 result.TeamSQID = in.TeamSQID
172 out, e := encode(result)
173 if e != nil {
174 return nil, e
175 }
176 h := sha256.Sum256(out)
177 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 {
178 return nil, ErrUnavailable
179 }
180 return out, nil
181}
182
183// ---- credential ----
184
185// ConsumerCap is the consumers table's limit (and its trigger's): a runaway
186// provisioner's ceiling, not a scale target.
187const ConsumerCap = 4096
188
189// RegisterInput carries the directory's signed provisioning record and
190// nothing else: the consumer, audience and app come from what verifies.
191type RegisterInput struct {
192 InputBase
193 Record jsontext.Value `json:"record"`
194}
195type RetireInput struct {
196 InputBase
197 Consumer string `json:"consumer"`
198}
199
200// CredentialHTTP is the credential role's /operator/v1 path.
201type CredentialHTTP struct {
202 c *Credential
203 provisioning []roster.Key
204 env map[string]string
205 apps map[string]bool
206 ownerIndex func(string) string
207 admit func(id, origin string) bool
208}
209
210// NewCredentialHTTP pins the directory's provisioning public key (the
211// credential role's first pin of anything the directory signs), the
212// HOME_CONSUMERS manifest it must never collide with, the compiled app
213// registry and the blind index that compares the typed owner. admit is the
214// registry reload's own admission predicate: no row is committed that the
215// reload — and so the next boot — would refuse (discussion 94, blocker 1).
216func NewCredentialHTTP(c *Credential, provisioningPublic string, env map[string]string, apps []string, ownerIndex func(string) string, admit func(id, origin string) bool) (*CredentialHTTP, error) {
217 if c == nil || ownerIndex == nil || admit == nil || len(env) == 0 || len(apps) == 0 {
218 return nil, ErrRefused
219 }
220 k, e := public(provisioningPublic)
221 if e != nil || bytes.Equal(k, c.engine.verifier.key) || bytes.Equal(k, c.signer.SignPub()) {
222 return nil, ErrRefused
223 }
224 h := &CredentialHTTP{c, []roster.Key{{ID: keyID(k), Public: provisioningPublic}}, map[string]string{}, map[string]bool{}, ownerIndex, admit}
225 for id, origin := range env {
226 if !atom(id, 64) || !Origin(origin) {
227 return nil, ErrRefused
228 }
229 h.env[id] = origin
230 }
231 for _, a := range apps {
232 h.apps[a] = true
233 }
234 return h, nil
235}
236
237func (h *CredentialHTTP) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error) {
238 if h == nil {
239 return nil, ErrRefused
240 }
241 c := h.c
242 if e := sweepPlans(ctx, c.engine.db, c.engine.now().Unix()); e != nil {
243 return nil, e
244 }
245 return c.engine.Execute(ctx, raw, func(ctx context.Context, conn *sql.Conn, r Request) ([]byte, error) {
246 action := r.authorization.Action
247 now := c.engine.now().Unix()
248 w, _, e := window(ctx, conn, "credential", now)
249 if e != nil {
250 return nil, e
251 }
252 if !windowAdmits(w.Kind, action) {
253 return nil, ErrRefused
254 }
255 switch action {
256 case "credential.owner-seed":
257 var in OwnerInput
258 // Over this endpoint the owner must already exist (Paul,
259 // 2026-10-27), and must be the owner Paul typed at confirm.
260 if DecodeInput(r, &in) != nil || !in.ExistingOnly || !ownerAddress(in.Address) || !hmac.Equal([]byte(h.ownerIndex(in.Address)), []byte(w.OwnerIndex)) {
261 return nil, ErrRefused
262 }
263 if w.ExistingTeam != "" && in.TeamSQID != w.ExistingTeam {
264 return nil, ErrRefused
265 }
266 return c.ownerSeed(ctx, conn, r)
267 case "credential.register-consumer":
268 return h.register(ctx, conn, r, w)
269 case "credential.retire-consumer":
270 return h.retire(ctx, conn, r, w)
271 }
272 return nil, ErrRefused
273 })
274}
275
276// claimedBindings reads a record's claimed bindings without trusting them;
277// VerifyProvisioning below is what decides.
278func claimedBindings(record []byte) (roster.Bindings, bool) {
279 var env envelope
280 if len(record) == 0 || len(record) > roster.BodyLimit || json.Unmarshal(record, &env, json.RejectUnknownMembers(true)) != nil {
281 return roster.Bindings{}, false
282 }
283 payload, ok := canonical(env.Payload, -1)
284 if !ok {
285 return roster.Bindings{}, false
286 }
287 var p roster.Provisioning
288 if json.Unmarshal(payload, &p, json.RejectUnknownMembers(true)) != nil {
289 return roster.Bindings{}, false
290 }
291 return p.Bindings, true
292}
293
294func (h *CredentialHTTP) register(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
295 var in RegisterInput
296 if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial {
297 return nil, ErrRefused
298 }
299 claimed, ok := claimedBindings(in.Record)
300 if !ok {
301 return nil, ErrRefused
302 }
303 // Issuer and directory are fixed to the pinned values; the record must
304 // verify under the directory's provisioning key with exactly those.
305 expected := claimed
306 expected.Issuer = h.c.engine.verifier.pins.Origin
307 expected.Directory = h.c.directory
308 verified, e := roster.VerifyProvisioning(in.Record, h.provisioning, expected)
309 if e != nil {
310 return nil, ErrRefused
311 }
312 b := verified.Bindings()
313 if !h.apps[b.App] || !contains(w.Apps, b.App) || !atom(b.Consumer, 64) || !Origin(b.Audience) || !h.admit(b.Consumer, b.Audience) {
314 return nil, ErrRefused
315 }
316 if w.ExistingTeam != "" {
317 if b.Team != w.ExistingTeam || !directorydata.CanonicalBinding("oficina", b.App, b.Consumer, b.Audience) || h.env[b.Consumer] != b.Audience {
318 return nil, ErrRefused
319 }
320 for id, origin := range h.env {
321 if id != b.Consumer && origin == b.Audience {
322 return nil, ErrRefused
323 }
324 }
325 var clash int
326 if c.QueryRowContext(ctx, "SELECT count(*) FROM consumers WHERE consumer_id=? OR origin=?", b.Consumer, b.Audience).Scan(&clash) != nil {
327 return nil, ErrUnavailable
328 }
329 if clash != 0 {
330 return nil, ErrRefused
331 }
332 // Verify the existing registration; never duplicate it in the table.
333 return h.manifestResult(ctx, c, r)
334 }
335 for id, origin := range h.env {
336 if id == b.Consumer || origin == b.Audience {
337 return nil, ErrRefused
338 }
339 }
340 var clash, total int
341 e = c.QueryRowContext(ctx, "SELECT count(*) FROM consumers WHERE consumer_id=? OR origin=?", b.Consumer, b.Audience).Scan(&clash)
342 if e != nil {
343 return nil, ErrUnavailable
344 }
345 if clash != 0 {
346 return nil, ErrRefused
347 }
348 // The cap is a refusal; the trigger behind it is the backstop, so any
349 // INSERT failure past this point is unavailable, not refused.
350 if e = c.QueryRowContext(ctx, "SELECT count(*) FROM consumers").Scan(&total); e != nil {
351 return nil, ErrUnavailable
352 }
353 if total >= ConsumerCap {
354 return nil, ErrRefused
355 }
356 now := h.c.engine.now()
357 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 {
358 return nil, ErrUnavailable
359 }
360 return h.manifestResult(ctx, c, r)
361}
362
363func (h *CredentialHTTP) retire(ctx context.Context, c *sql.Conn, r Request, w PlanView) ([]byte, error) {
364 var in RetireInput
365 if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !atom(in.Consumer, 64) {
366 return nil, ErrRefused
367 }
368 var app, state string
369 e := c.QueryRowContext(ctx, "SELECT app,state FROM consumers WHERE consumer_id=?", in.Consumer).Scan(&app, &state)
370 if errors.Is(e, sql.ErrNoRows) {
371 return nil, ErrRefused
372 }
373 if e != nil {
374 return nil, ErrUnavailable
375 }
376 if state != "active" || !contains(w.Apps, app) {
377 return nil, ErrRefused
378 }
379 if _, e = c.ExecContext(ctx, "UPDATE consumers SET state='retired' WHERE consumer_id=? AND state='active'", in.Consumer); e != nil {
380 return nil, ErrUnavailable
381 }
382 return h.manifestResult(ctx, c, r)
383}
384
385func (h *CredentialHTTP) manifestResult(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
386 table, e := ActiveConsumers(ctx, c)
387 if e != nil {
388 return nil, e
389 }
390 union := map[string]string{}
391 for id, origin := range h.env {
392 union[id] = origin
393 }
394 for id, origin := range table {
395 union[id] = origin
396 }
397 result := resultFor(r)
398 result.Manifest, e = ManifestDigest(union)
399 if e != nil {
400 return nil, e
401 }
402 return encode(result)
403}
404
405type queryer interface {
406 QueryContext(context.Context, string, ...any) (*sql.Rows, error)
407}
408
409// ActiveConsumers reads the credential registry table's active rows.
410func ActiveConsumers(ctx context.Context, q queryer) (map[string]string, error) {
411 rows, e := q.QueryContext(ctx, "SELECT consumer_id,origin FROM consumers WHERE state='active' LIMIT 4097")
412 if e != nil {
413 return nil, ErrUnavailable
414 }
415 defer rows.Close()
416 out := map[string]string{}
417 for rows.Next() {
418 var id, origin string
419 if rows.Scan(&id, &origin) != nil || !atom(id, 64) || !Origin(origin) {
420 return nil, ErrUnavailable
421 }
422 out[id] = origin
423 }
424 if rows.Err() != nil || len(out) > 4096 {
425 return nil, ErrUnavailable
426 }
427 return out, nil
428}
429
430// ManifestDigest is base64url(SHA-256(encoding/json.Marshal(
431// ["oficina/home/consumer-manifest/v1", [[id, origin], …]]))), entries sorted
432// by the unsigned byte order of consumer ID (team-provisioning-app.md §7).
433func ManifestDigest(consumers map[string]string) (string, error) {
434 ids := make([]string, 0, len(consumers))
435 for id := range consumers {
436 ids = append(ids, id)
437 }
438 slices.Sort(ids)
439 entries := make([][2]string, 0, len(ids))
440 for _, id := range ids {
441 entries = append(entries, [2]string{id, consumers[id]})
442 }
443 b, e := stdjson.Marshal([]any{"oficina/home/consumer-manifest/v1", entries})
444 if e != nil {
445 return "", ErrUnavailable
446 }
447 sum := sha256.Sum256(b)
448 return base64.RawURLEncoding.EncodeToString(sum[:]), nil
449}
450
451// ---- inspect ----
452
453// HTTPInspection is <role>.inspect's answer: the stream position Alta
454// resynchronises from, the plan ids and expiries (never their contents),
455// and on the directory the generation and next team proposal.
456type HTTPInspection struct {
457 Version int `json:"version"`
458 Role string `json:"role"`
459 Challenge string `json:"challenge"`
460 Observed int64 `json:"observed_at"`
461 Sequence int64 `json:"sequence"`
462 Head string `json:"head"`
463 Generation *string `json:"generation,omitempty"`
464 TeamID int64 `json:"proposed_team_id,omitempty"`
465 TeamSQID string `json:"proposed_team_sqid,omitempty"`
466 PendingPlan string `json:"pending_plan,omitempty"`
467 PendingExpires int64 `json:"pending_expires_at,omitempty"`
468 OpenPlan string `json:"open_plan,omitempty"`
469 WindowExpires int64 `json:"window_expires_at,omitempty"`
470}
471
472func inspectHTTP(ctx context.Context, e *Engine, raw []byte, extra func(context.Context, *sql.Conn, *HTTPInspection) error) ([]byte, error) {
473 if e == nil {
474 return nil, ErrRefused
475 }
476 role := e.verifier.pins.Role
477 if !e.verifier.actions[role+".inspect"] {
478 return nil, ErrRefused
479 }
480 challenge, err := e.verifier.verifyInspect(raw, e.now())
481 if err != nil {
482 return nil, err
483 }
484 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
485 defer cancel()
486 c, err := e.db.Conn(ctx)
487 if err != nil {
488 return nil, ErrUnavailable
489 }
490 defer c.Close()
491 if _, err = c.ExecContext(ctx, "BEGIN"); err != nil {
492 return nil, ErrUnavailable
493 }
494 defer c.ExecContext(context.Background(), "ROLLBACK")
495 now := e.now().Unix()
496 out := HTTPInspection{Version: 1, Role: role, Challenge: challenge.Challenge, Observed: now}
497 var origin, installation, registry, device, kid string
498 var completed int64
499 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)
500 if err != nil && !errors.Is(err, sql.ErrNoRows) {
501 return nil, ErrUnavailable
502 }
503 p := e.verifier.pins
504 if err == nil && (origin != p.Origin || installation != p.Installation || registry != p.Registry || device != p.Device || kid != e.verifier.kid || completed > now) {
505 return nil, ErrRefused
506 }
507 if v, _, err := scanPlan(ctx, c, role, "state='pending' AND expires_at>?", now); err == nil {
508 out.PendingPlan, out.PendingExpires = v.ID, v.Expires
509 } else if err != ErrRefused {
510 return nil, err
511 }
512 if v, _, err := scanPlan(ctx, c, role, "state='open' AND window_expires_at>?", now); err == nil {
513 out.OpenPlan, out.WindowExpires = v.ID, v.WindowExpires
514 } else if err != ErrRefused {
515 return nil, err
516 }
517 if extra != nil {
518 if err := extra(ctx, c, &out); err != nil {
519 return nil, err
520 }
521 }
522 return encode(out)
523}
524
525// InspectHTTP is directory.inspect over /operator/v1.
526func (d *Directory) InspectHTTP(ctx context.Context, raw []byte) ([]byte, error) {
527 if d == nil {
528 return nil, ErrRefused
529 }
530 return inspectHTTP(ctx, d.engine, raw, func(ctx context.Context, c *sql.Conn, out *HTTPInspection) error {
531 var g string
532 err := c.QueryRowContext(ctx, "SELECT generation FROM roster_generation WHERE singleton=1").Scan(&g)
533 if err == nil {
534 if !CanonicalToken(g) {
535 return ErrUnavailable
536 }
537 out.Generation = &g
538 } else if !errors.Is(err, sql.ErrNoRows) {
539 return ErrUnavailable
540 }
541 id, sqid, err := nextTeam(ctx, c)
542 if err != nil {
543 return ErrUnavailable
544 }
545 out.TeamID, out.TeamSQID = id, sqid
546 return nil
547 })
548}
549
550// InspectHTTP is credential.inspect: new code, as the credential role had no
551// inspect before.
552func (h *CredentialHTTP) InspectHTTP(ctx context.Context, raw []byte) ([]byte, error) {
553 if h == nil {
554 return nil, ErrRefused
555 }
556 return inspectHTTP(ctx, h.c.engine, raw, nil)
557}
558