oficina / alta Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package homeop is Alta's half of Home's operator endpoint
2// (home implementation/team-provisioning-amendment.md §3–§7): the signed
3// operation, the signed plan, the signed inspect challenge, every verb's
4// input and the result Home returns.
5//
6// Home verifies each of these by decoding it strictly and re-encoding it
7// with go-json-experiment's deterministic encoder, then comparing bytes
8// (internal/operator/protocol.go strictCanonical). So the structs here are
9// Home's own, field for field and tag for tag, in the same order: a field
10// moved here is a request Home refuses. homecompat/ checks every one of
11// them against Home's real verifier and engine.
12package homeop
13
14import (
15 "crypto/elliptic"
16 "crypto/rand"
17 "crypto/sha256"
18 "encoding/base64"
19 "encoding/hex"
20 "errors"
21 "net/mail"
22 "net/url"
23 "strings"
24 "unicode"
25 "unicode/utf8"
26
27 family "amadan.net/rastrillo/rastrillo/crypto"
28 "github.com/go-json-experiment/json"
29 "github.com/go-json-experiment/json/jsontext"
30)
31
32// Contexts and limits, as Home declares them.
33const (
34 InputContext = "oficina/home/operator-input/v1"
35 PlanContext = "oficina/home/operator-plan/v1"
36 InspectContext = "oficina/home/operator-inspect/v1"
37 OwnerContext = "oficina/home/owner-seed/v1"
38
39 BodyLimit = 64 << 10
40 InputLimit = 48 << 10
41 AuthorizationLimit = 16 << 10
42 PlanLimit = 8 << 10
43
44 // RequestLifetime is an operation's and an inspect challenge's
45 // signed life; Home refuses more than 300 s.
46 RequestLifetime = 300
47 // PlanLifetime bounds a plan; WindowLifetime is the window Paul's
48 // confirmation opens. Home never extends either.
49 PlanLifetime = 900
50 WindowLifetime = 900
51
52 // Skew is how far back Alta dates what it signs: Home refuses an
53 // issued_at in its future, so a few seconds of clock skew must not
54 // refuse every request. Lifetimes still count from the back-dated
55 // issue.
56 Skew = 30
57
58 // Baseline is the only baseline_attestation directory.initialize
59 // accepts. Alta sends it only after Paul types it (§6 step 1).
60 Baseline = "operator-attests-never-provisioned"
61 // ActivationPolicy is ActivationEvidence.Policy.
62 ActivationPolicy = "oficina/team-activation/v1"
63 // ExistingActivationPolicy is the policy an adoption window's
64 // activation carries; Home picks the policy from the window.
65 ExistingActivationPolicy = "oficina/existing-app-activation/v1"
66 // ManifestContext is the consumer manifest digest's domain string.
67 ManifestContext = "oficina/home/consumer-manifest/v1"
68)
69
70// Roles.
71const (
72 Credential = "credential"
73 Directory = "directory"
74)
75
76// Plan kinds.
77const (
78 KindInitialize = "initialize"
79 KindCreateTeam = "create-team"
80 KindAddApps = "add-apps"
81 KindRetireApps = "retire-apps"
82)
83
84// Verbs.
85const (
86 DirectoryInspect = "directory.inspect"
87 DirectoryInitialize = "directory.initialize"
88 DirectorySeedTeam = "directory.seed-team"
89 DirectoryProvision = "directory.provision-consumer"
90 DirectoryVerify = "directory.verify-consumer"
91 DirectoryActivate = "directory.activate-consumer"
92 DirectoryDisable = "directory.disable-consumer"
93 CredentialInspect = "credential.inspect"
94 CredentialOwnerSeed = "credential.owner-seed"
95 CredentialRegister = "credential.register-consumer"
96 CredentialRetire = "credential.retire-consumer"
97)
98
99var ErrRefused = errors.New("homeop: refused")
100
101// Authorization is Home's signed operator authority (protocol.go).
102type Authorization struct {
103 Version int `json:"version"`
104 Purpose string `json:"purpose"`
105 Role string `json:"role"`
106 Origin string `json:"origin"`
107 Installation string `json:"installation"`
108 Registry string `json:"registry"`
109 Device string `json:"device"`
110 Sequence int64 `json:"sequence"`
111 Initial bool `json:"initial_authority"`
112 Previous string `json:"previous"`
113 JournalSequence int64 `json:"journal_sequence"`
114 OperationID string `json:"operation_id"`
115 Action string `json:"action"`
116 InputDigest string `json:"input_digest"`
117 Issued int64 `json:"issued_at"`
118 Expires int64 `json:"expires_at"`
119}
120
121type envelope struct {
122 Version int `json:"v"`
123 KeyID string `json:"kid"`
124 Payload string `json:"payload"`
125 Signature string `json:"signature"`
126}
127
128type wrapper struct {
129 Version int `json:"version"`
130 Authorization jsontext.Value `json:"signed_authorization"`
131 Input jsontext.Value `json:"operation_input"`
132}
133
134// Plan is what Alta signs and submits to each role (plan.go).
135type Plan struct {
136 Version int `json:"version"`
137 Purpose string `json:"purpose"`
138 Role string `json:"role"`
139 Origin string `json:"origin"`
140 Installation string `json:"installation"`
141 Registry string `json:"registry"`
142 Device string `json:"device"`
143 PlanID string `json:"plan_id"`
144 Kind string `json:"kind"`
145 Apps []string `json:"apps"`
146 Label string `json:"label,omitzero"`
147 DisplayName string `json:"display_name,omitzero"`
148 Owner string `json:"owner,omitzero"`
149 // ExistingTeam is the team SQID an adoption plan binds, never the
150 // dashboard label (internal/operator/plan.go).
151 ExistingTeam string `json:"existing_team,omitzero"`
152 Issued int64 `json:"issued_at"`
153 Expires int64 `json:"expires_at"`
154}
155
156// CanonicalOrigin is Alta's one copy of Home's closed registry of the
157// existing suite instances (internal/home/directorydata/canonical.go): the
158// canonical apps' consumer id is the slug and the origin is
159// https://<app>.oficina.works. It is empty for any other app. It lives
160// here, not in provision, because fakehome (imported by provision's tests)
161// needs it too. homecompat pins it against Home's own.
162func CanonicalOrigin(app string) string {
163 switch app {
164 case "docs", "sheets", "slides", "memoria", "calendar", "calls", "equipo", "base":
165 return "https://" + app + ".oficina.works"
166 }
167 return ""
168}
169
170// InspectChallenge is <role>.inspect's signed request (inspect.go).
171type InspectChallenge struct {
172 Version int `json:"version"`
173 Purpose string `json:"purpose"`
174 Role string `json:"role"`
175 Origin string `json:"origin"`
176 Installation string `json:"installation"`
177 Registry string `json:"registry"`
178 Device string `json:"device"`
179 Challenge string `json:"challenge"`
180 Issued int64 `json:"issued_at"`
181 Expires int64 `json:"expires_at"`
182}
183
184// Inspection is <role>.inspect's answer (http_verbs.go HTTPInspection).
185type Inspection struct {
186 Version int `json:"version"`
187 Role string `json:"role"`
188 Challenge string `json:"challenge"`
189 Observed int64 `json:"observed_at"`
190 Sequence int64 `json:"sequence"`
191 Head string `json:"head"`
192 Generation *string `json:"generation,omitempty"`
193 TeamID int64 `json:"proposed_team_id,omitempty"`
194 TeamSQID string `json:"proposed_team_sqid,omitempty"`
195 PendingPlan string `json:"pending_plan,omitempty"`
196 PendingExpires int64 `json:"pending_expires_at,omitempty"`
197 OpenPlan string `json:"open_plan,omitempty"`
198 WindowExpires int64 `json:"window_expires_at,omitempty"`
199}
200
201// InputBase opens every operation input.
202type InputBase struct {
203 Version int `json:"version"`
204 Operation string `json:"operation"`
205 OperationID string `json:"operation_id"`
206}
207
208type InitializeInput struct {
209 InputBase
210 ExpectedGeneration *string `json:"expected_generation"`
211 Generation string `json:"generation"`
212 Baseline string `json:"baseline_attestation"`
213}
214
215type SeedInput struct {
216 InputBase
217 Generation string `json:"expected_generation"`
218 TeamID int64 `json:"team_id"`
219 TeamSQID string `json:"team_sqid"`
220 Label string `json:"label"`
221 Name string `json:"display_name"`
222 Receipt jsontext.Value `json:"receipt"`
223}
224
225type ProvisionInput struct {
226 InputBase
227 Generation string `json:"expected_generation"`
228 TeamSQID string `json:"team_sqid"`
229 App string `json:"app"`
230 Consumer string `json:"consumer"`
231 Audience string `json:"audience"`
232 Sequence int64 `json:"expected_sequence"`
233}
234
235type OwnerInput struct {
236 InputBase
237 Directory string `json:"directory"`
238 TeamID int64 `json:"team_id"`
239 TeamSQID string `json:"team_sqid"`
240 Address string `json:"address"`
241 ExistingOnly bool `json:"existing_only"`
242}
243
244type RegisterInput struct {
245 InputBase
246 Record jsontext.Value `json:"record"`
247}
248
249type RetireInput struct {
250 InputBase
251 Consumer string `json:"consumer"`
252}
253
254type DisableInput struct {
255 InputBase
256 Generation string `json:"expected_generation"`
257 TeamSQID string `json:"team_sqid"`
258 App string `json:"app"`
259 Consumer string `json:"consumer"`
260}
261
262type VerificationInput struct {
263 InputBase
264 Consumer string `json:"consumer"`
265 TeamSQID string `json:"team_sqid"`
266 App string `json:"app"`
267 Audience string `json:"audience"`
268 Generation string `json:"generation"`
269 RecordSequence int64 `json:"record_sequence"`
270 RecordDigest string `json:"record_digest"`
271 Epoch int64 `json:"expected_epoch"`
272 Owner string `json:"owner_ref"`
273 Issued int64 `json:"issued_at"`
274 Expires int64 `json:"expires_at"`
275}
276
277type ActivationEvidence struct {
278 Version int `json:"version"`
279 Policy string `json:"policy"`
280 Attempt string `json:"attempt_id"`
281 Consumer string `json:"consumer"`
282 TeamSQID string `json:"team_sqid"`
283 App string `json:"app"`
284 Audience string `json:"audience"`
285 Generation string `json:"generation"`
286 RecordSequence int64 `json:"record_sequence"`
287 RecordDigest string `json:"record_digest"`
288 Epoch int64 `json:"epoch"`
289 Owner string `json:"owner_ref"`
290 AppVersion string `json:"app_version"`
291 ArtifactDigest string `json:"artifact_digest"`
292 EnvironmentBinding string `json:"environment_binding"`
293 ManifestDigest string `json:"credential_manifest_digest"`
294 AliasHost string `json:"alias_host"`
295 Started int64 `json:"started_at"`
296 Completed int64 `json:"completed_at"`
297}
298
299type ActivationInput struct {
300 InputBase
301 Evidence ActivationEvidence `json:"evidence"`
302}
303
304// Result is the engine's result JSON (directory.go Result).
305type Result struct {
306 Attempt string `json:"attempt_id,omitempty"`
307 Expires int64 `json:"expires_at,omitempty"`
308 Version int `json:"version"`
309 OperationID string `json:"operation_id"`
310 Outcome string `json:"outcome"`
311 Generation string `json:"generation,omitempty"`
312 TeamID int64 `json:"team_id,omitempty"`
313 TeamSQID string `json:"team_sqid,omitempty"`
314 Epoch int64 `json:"epoch,omitempty"`
315 Record jsontext.Value `json:"record,omitempty"`
316 Bearer string `json:"bearer,omitempty"`
317 Receipt jsontext.Value `json:"receipt,omitempty"`
318 Manifest string `json:"credential_manifest_digest,omitempty"`
319}
320
321// OwnerReceipt is the payload of the credential role's signed owner
322// receipt. Alta reads it (person_ref, expiry) but never verifies it: the
323// directory does.
324type OwnerReceipt struct {
325 Version int `json:"version"`
326 Purpose string `json:"purpose"`
327 OperationID string `json:"operation_id"`
328 Issuer string `json:"issuer"`
329 Directory string `json:"directory"`
330 TeamID int64 `json:"team_id"`
331 TeamSQID string `json:"team_sqid"`
332 PersonRef string `json:"person_ref"`
333 Role string `json:"role"`
334 Issued int64 `json:"issued_at"`
335 Expires int64 `json:"expires_at"`
336}
337
338// Encode is Home's canonical encoding.
339func Encode(v any) ([]byte, error) {
340 b, err := json.Marshal(v, json.Deterministic(true))
341 if err != nil {
342 return nil, ErrRefused
343 }
344 return b, nil
345}
346
347// Decode is Home's strict decoding: valid UTF-8, no unknown members.
348func Decode(b []byte, v any) error {
349 if !utf8.Valid(b) || json.Unmarshal(b, v, json.RejectUnknownMembers(true)) != nil {
350 return ErrRefused
351 }
352 return nil
353}
354
355// Token is 32 random bytes, base64url without padding: an operation id,
356// a plan id, a challenge, a generation.
357func Token() string {
358 b := make([]byte, 32)
359 if _, err := rand.Read(b); err != nil {
360 panic(err)
361 }
362 return base64.RawURLEncoding.EncodeToString(b)
363}
364
365// CanonicalToken is Home's token rule: exactly 32 bytes, canonical
366// unpadded base64url.
367func CanonicalToken(s string) bool {
368 b, err := base64.RawURLEncoding.Strict().DecodeString(s)
369 return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == s
370}
371
372// Digest is base64url(SHA-256(b)), Home's input digest and stream head.
373func Digest(b []byte) string {
374 h := sha256.Sum256(b)
375 return base64.RawURLEncoding.EncodeToString(h[:])
376}
377
378// KeyID is hex(SHA-256(public key)), the envelope's kid.
379func KeyID(public []byte) string {
380 h := sha256.Sum256(public)
381 return hex.EncodeToString(h[:])
382}
383
384// Origin is Home's origin rule.
385func Origin(s string) bool {
386 if len(s) == 0 || len(s) > 253 {
387 return false
388 }
389 u, e := url.Parse(s)
390 return e == nil && u.Scheme == "https" && u.Host != "" && u.Host == strings.ToLower(u.Host) && u.User == nil && u.Path == "" && u.RawPath == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.RawFragment == "" && !strings.ContainsAny(u.Host, "%\\:") && !strings.HasSuffix(u.Host, ".") && u.String() == s
391}
392
393// OwnerAddress is the exact form owner-seed accepts: a bare address that
394// parses to itself.
395func OwnerAddress(s string) bool {
396 if len(s) == 0 || len(s) > 320 || !utf8.ValidString(s) {
397 return false
398 }
399 a, e := mail.ParseAddress(s)
400 return e == nil && a.Address == s && a.Name == ""
401}
402
403// TeamName is the directory's team-name rule.
404func TeamName(s string) bool {
405 if len(s) == 0 || len(s) > 255 || !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
406 return false
407 }
408 for _, r := range s {
409 if unicode.IsControl(r) {
410 return false
411 }
412 }
413 return true
414}
415
416// PersonRef is Home's person reference shape.
417func PersonRef(s string) bool {
418 if len(s) != 29 || !strings.HasPrefix(s, "pr_") {
419 return false
420 }
421 for _, c := range s[3:] {
422 if !(c >= 'a' && c <= 'z' || c >= '2' && c <= '7') {
423 return false
424 }
425 }
426 return true
427}
428
429// PlanPrefix is the first 8 hex digits of a plan id: what Paul matches on
430// both Home confirm pages.
431func PlanPrefix(id string) string {
432 b, err := base64.RawURLEncoding.Strict().DecodeString(id)
433 if err != nil || len(b) != 32 {
434 return ""
435 }
436 return hex.EncodeToString(b[:4])
437}
438
439// signingKey mirrors Home's check on the signer.
440func signingKey(k *family.Keypair) bool {
441 if k == nil || k.SignPriv == nil {
442 return false
443 }
444 p := k.SignPriv
445 return p.Curve == elliptic.P256() && p.D != nil && p.D.Sign() > 0 && p.D.Cmp(elliptic.P256().Params().N) < 0 && p.X != nil && p.Y != nil && elliptic.P256().IsOnCurve(p.X, p.Y)
446}
447
448func sealEnvelope(k *family.Keypair, context string, payload []byte) ([]byte, error) {
449 sig, err := family.Sign(k, context, payload)
450 if err != nil {
451 return nil, ErrRefused
452 }
453 return Encode(envelope{1, KeyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)})
454}
455
456// EnvelopePayload returns the payload bytes of a signed envelope without
457// verifying it. Alta uses it to read an owner receipt Home produced.
458func EnvelopePayload(raw []byte) ([]byte, error) {
459 var env envelope
460 if Decode(raw, &env) != nil || env.Version != 1 {
461 return nil, ErrRefused
462 }
463 b, err := base64.RawURLEncoding.Strict().DecodeString(env.Payload)
464 if err != nil {
465 return nil, ErrRefused
466 }
467 return b, nil
468}
469
470// ReadReceipt reads an owner receipt's payload.
471func ReadReceipt(raw []byte) (OwnerReceipt, error) {
472 var r OwnerReceipt
473 p, err := EnvelopePayload(raw)
474 if err != nil || Decode(p, &r) != nil || r.Version != 1 || r.Purpose != "owner-seed" || !PersonRef(r.PersonRef) {
475 return OwnerReceipt{}, ErrRefused
476 }
477 return r, nil
478}
479
480// Request is one signed operation: the exact bytes Alta sends (and keeps,
481// sealed, for exact replay) and the stream head it becomes once committed.
482type Request struct {
483 Bytes []byte
484 Head string
485 Authorization Authorization
486}
487
488// SignRequest signs input under a, filling a's input digest. a must
489// already carry the sequence, previous head, operation id and clock.
490func SignRequest(k *family.Keypair, a Authorization, input any) (Request, error) {
491 if !signingKey(k) {
492 return Request{}, ErrRefused
493 }
494 in, err := Encode(input)
495 if err != nil || len(in) > InputLimit {
496 return Request{}, ErrRefused
497 }
498 a.Version, a.Purpose = 1, "operator-input"
499 a.InputDigest = Digest(in)
500 a.Initial = a.Sequence == 1
501 if !validAuthorization(a) {
502 return Request{}, ErrRefused
503 }
504 payload, err := Encode(a)
505 if err != nil {
506 return Request{}, err
507 }
508 env, err := sealEnvelope(k, InputContext, payload)
509 if err != nil || len(env) > AuthorizationLimit {
510 return Request{}, ErrRefused
511 }
512 out, err := Encode(wrapper{1, env, in})
513 if err != nil || len(out) > BodyLimit {
514 return Request{}, ErrRefused
515 }
516 return Request{Bytes: out, Head: Digest(env), Authorization: a}, nil
517}
518
519// ReadRequest recovers the authorization of a request Alta signed, so a
520// sealed request row needs no copy of it.
521func ReadRequest(raw []byte) (Request, error) {
522 var w wrapper
523 if Decode(raw, &w) != nil || w.Version != 1 {
524 return Request{}, ErrRefused
525 }
526 p, err := EnvelopePayload(w.Authorization)
527 if err != nil {
528 return Request{}, err
529 }
530 var a Authorization
531 if Decode(p, &a) != nil {
532 return Request{}, ErrRefused
533 }
534 return Request{Bytes: raw, Head: Digest(w.Authorization), Authorization: a}, nil
535}
536
537func validAuthorization(a Authorization) bool {
538 return a.Version == 1 && a.Purpose == "operator-input" && Origin(a.Origin) && CanonicalToken(a.Installation) && CanonicalToken(a.Registry) && CanonicalToken(a.Device) && CanonicalToken(a.OperationID) && CanonicalToken(a.InputDigest) && a.Sequence > 0 && a.Initial == (a.Sequence == 1) && a.JournalSequence > 0 && ((a.Sequence == 1 && a.Previous == "") || (a.Sequence > 1 && CanonicalToken(a.Previous))) && a.Issued > 0 && a.Expires > a.Issued && a.Expires-a.Issued <= RequestLifetime && allowedAction(a.Role, a.Action)
539}
540
541func allowedAction(role, a string) bool {
542 switch role {
543 case Credential:
544 switch a {
545 case CredentialOwnerSeed, CredentialRegister, CredentialRetire, CredentialInspect:
546 return true
547 }
548 case Directory:
549 switch a {
550 case DirectoryInspect, DirectoryInitialize, DirectorySeedTeam, DirectoryProvision, DirectoryVerify, DirectoryActivate, DirectoryDisable:
551 return true
552 }
553 }
554 return false
555}
556
557// SignPlan signs a plan under the plan context.
558func SignPlan(k *family.Keypair, p Plan) ([]byte, error) {
559 if !signingKey(k) {
560 return nil, ErrRefused
561 }
562 p.Version, p.Purpose = 1, "operator-plan"
563 if p.Apps == nil {
564 p.Apps = []string{}
565 }
566 payload, err := Encode(p)
567 if err != nil {
568 return nil, err
569 }
570 out, err := sealEnvelope(k, PlanContext, payload)
571 if err != nil || len(out) > PlanLimit {
572 return nil, ErrRefused
573 }
574 return out, nil
575}
576
577// SignInspect signs an inspect challenge.
578func SignInspect(k *family.Keypair, c InspectChallenge) ([]byte, error) {
579 if !signingKey(k) {
580 return nil, ErrRefused
581 }
582 c.Version, c.Purpose = 1, "operator-inspect"
583 payload, err := Encode(c)
584 if err != nil {
585 return nil, err
586 }
587 return sealEnvelope(k, InspectContext, payload)
588}
589
590// ManifestDigest is §7's credential_manifest_digest: base64url(SHA-256(
591// encoding/json.Marshal(["oficina/home/consumer-manifest/v1", [[id,
592// origin], …]]))), entries sorted by consumer id bytes. Alta computes it
593// only to check what step 6 returned against what it expects.
594func ManifestDigest(consumers map[string]string) string {
595 return manifestDigest(consumers)
596}
597