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 "bufio"
5 "bytes"
6 "crypto/ecdsa"
7 "crypto/elliptic"
8 "crypto/rand"
9 "crypto/sha256"
10 "encoding/base64"
11 "encoding/hex"
12 "errors"
13 "flag"
14 "fmt"
15 "io"
16 "os"
17 "regexp"
18 "slices"
19 "sort"
20 "strings"
21
22 "amadan.net/oficina/home/internal/operator"
23 "amadan.net/oficina/home/roster"
24 assertionverifier "amadan.net/rastrillo/rastrillo/assertion"
25 family "amadan.net/rastrillo/rastrillo/crypto"
26 json "github.com/go-json-experiment/json"
27)
28
29// home team-keygen generates the Home half of team provisioning's
30// configuration (discussion 101 §5): both roles' HOME_OPERATOR_MATERIAL,
31// the directory's roster key, and the member-resolution pair, plus each
32// role's HOME_OPERATOR_HTTP, which is alta keygen's pins with
33// operator_subject and the directory's provisioning key filled in.
34//
35// What it prints always boots: before printing, it loads each role's set
36// through Home's own loaders (loadRosterRuntime, loadResolveKeys,
37// loadOperatorHTTP and NewRuntime's checks), the path -check takes too.
38// Secrets go to stdout or to a new file at mode 0600, never to stderr: no
39// error names a value, and nothing here uses a logger.
40
41const (
42 altaSubjectPlaceholder = "<Paul's person ref>"
43 altaProvisioningPlaceholder = "<the directory's provisioning public key>"
44)
45
46// The sections of a team env set, in the order they are applied (§5's
47// "every intermediate state is a valid boot"). Each is one carlos call.
48const (
49 teamCredentialSecrets = "credential secrets"
50 teamCredentialEnv = "credential env"
51 teamDirectorySecrets = "directory secrets"
52 teamDirectoryEnv = "directory env"
53 teamAltaEnv = "alta env"
54)
55
56var teamSectionOrder = []string{teamCredentialSecrets, teamCredentialEnv, teamDirectorySecrets, teamDirectoryEnv, teamAltaEnv}
57
58// teamSectionVars is closed: a section holds exactly these variables.
59var teamSectionVars = map[string][]string{
60 teamCredentialSecrets: {"HOME_OPERATOR_MATERIAL_BASE64", "HOME_RESOLVE_KEY"},
61 teamCredentialEnv: {"HOME_OPERATOR_HTTP_BASE64"},
62 teamDirectorySecrets: {"HOME_ROSTER_MODE", "HOME_ROSTER_KEY", "HOME_OPERATOR_MATERIAL_BASE64"},
63 teamDirectoryEnv: {"HOME_RESOLVE_PUBLIC_KEY", "HOME_OPERATOR_HTTP_BASE64"},
64 teamAltaEnv: {"ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY", "ALTA_OPERATOR_SUBJECT"},
65}
66
67// teamLoaderVars is every variable the loaders below read; a check clears
68// all of them first, so nothing in the caller's environment takes part.
69var teamLoaderVars = []string{
70 "HOME_ROSTER_MODE", "HOME_ROSTER_KEY", "HOME_RESOLVE_KEY", "HOME_RESOLVE_PUBLIC_KEY",
71 "HOME_OPERATOR_HTTP", "HOME_OPERATOR_HTTP_BASE64", "HOME_OPERATOR_MATERIAL", "HOME_OPERATOR_MATERIAL_BASE64",
72}
73
74// teamEnv is section → variable → value.
75type teamEnv map[string]map[string]string
76
77func (env teamEnv) role(role string) map[string]string {
78 vars := map[string]string{}
79 for _, section := range []string{role + " secrets", role + " env"} {
80 for k, v := range env[section] {
81 vars[k] = v
82 }
83 }
84 return vars
85}
86
87// teamKeySource is where fresh keys come from: family.Generate and
88// crypto/rand outside tests.
89type teamKeySource struct {
90 keypair func() (*family.Keypair, error)
91 random func([]byte) error
92}
93
94func defaultTeamKeySource() teamKeySource {
95 return teamKeySource{keypair: family.Generate, random: func(b []byte) error { _, err := rand.Read(b); return err }}
96}
97
98// altaKeyset is alta keygen's output: both roles' HOME_OPERATOR_HTTP, and
99// the ALTA_* lines it printed beside them (used only to cross-check).
100type altaKeyset struct {
101 pins map[string]operatorHTTPConfig
102 vars map[string]string
103}
104
105var altaHTTPHeader = regexp.MustCompile(`^# HOME_OPERATOR_HTTP for the (credential|directory) role:$`)
106var altaKeygenVars = []string{"ALTA_OPERATOR_KEY", "ALTA_OPERATOR_PREFILTER", "ALTA_DEK", "ALTA_OPERATOR_INSTALLATION", "ALTA_OPERATOR_REGISTRY", "ALTA_OPERATOR_DEVICE"}
107
108// parseAltaKeygen reads alta keygen's output. Errors name a line number
109// and a rule, never a line's content: some of its lines are Alta's secrets.
110func parseAltaKeygen(r io.Reader) (altaKeyset, error) {
111 ks := altaKeyset{pins: map[string]operatorHTTPConfig{}, vars: map[string]string{}}
112 sc := bufio.NewScanner(r)
113 sc.Buffer(make([]byte, 0, 64<<10), 64<<10)
114 pending, n := "", 0
115 for sc.Scan() {
116 n++
117 line := strings.TrimRight(sc.Text(), "\r")
118 if pending != "" {
119 var c operatorHTTPConfig
120 if len(line) > 8192 || json.Unmarshal([]byte(line), &c, json.RejectUnknownMembers(true)) != nil {
121 return ks, fmt.Errorf("alta keygen line %d: the %s role's HOME_OPERATOR_HTTP is not its closed JSON", n, pending)
122 }
123 ks.pins[pending], pending = c, ""
124 continue
125 }
126 if m := altaHTTPHeader.FindStringSubmatch(line); m != nil {
127 if _, dup := ks.pins[m[1]]; dup {
128 return ks, fmt.Errorf("alta keygen line %d: a second HOME_OPERATOR_HTTP for the %s role", n, m[1])
129 }
130 pending = m[1]
131 continue
132 }
133 if line == "" || strings.HasPrefix(line, "#") {
134 continue
135 }
136 name, value, ok := strings.Cut(line, "=")
137 if !ok || !slices.Contains(altaKeygenVars, name) {
138 return ks, fmt.Errorf("alta keygen line %d: not a line alta keygen prints", n)
139 }
140 if _, dup := ks.vars[name]; dup {
141 return ks, fmt.Errorf("alta keygen line %d: %s twice", n, name)
142 }
143 ks.vars[name] = value
144 }
145 if err := sc.Err(); err != nil {
146 return ks, errors.New("alta keygen: unreadable (a line over 64 KiB?)")
147 }
148 if pending != "" {
149 return ks, fmt.Errorf("alta keygen: the %s role's HOME_OPERATOR_HTTP header has no JSON after it", pending)
150 }
151 for _, role := range []string{"credential", "directory"} {
152 if _, ok := ks.pins[role]; !ok {
153 return ks, fmt.Errorf("alta keygen: no HOME_OPERATOR_HTTP for the %s role", role)
154 }
155 }
156 return ks, nil
157}
158
159// validateAltaPins refuses pins Home would refuse, pins the two roles
160// disagree on, and placeholders already filled with something else. Home's
161// loaders check the filled result again before anything is printed.
162func validateAltaPins(ks altaKeyset, origins Origins, subject string) error {
163 cred, dir := ks.pins["credential"], ks.pins["directory"]
164 for role, c := range map[string]operatorHTTPConfig{"credential": cred, "directory": dir} {
165 want := origins.Directory
166 if role == "credential" {
167 want = origins.Credential
168 }
169 switch {
170 case c.Version != 1 || c.Role != role:
171 return fmt.Errorf("alta pins: the %s role's line is not a version-1 config for that role", role)
172 case c.Origin != want:
173 return fmt.Errorf("alta pins: the %s origin is %q; this Home's is %q", role, c.Origin, want)
174 case c.OperatorSubject != altaSubjectPlaceholder && c.OperatorSubject != subject:
175 return fmt.Errorf("alta pins: the %s operator_subject is already set, and not to -subject", role)
176 case role == "credential" && c.DirectoryProvisioningPublicKey != altaProvisioningPlaceholder && c.DirectoryProvisioningPublicKey != "":
177 return errors.New("alta pins: the credential directory_provisioning_public_key is already filled; team-keygen generates that key")
178 case role == "directory" && c.DirectoryProvisioningPublicKey != "":
179 return errors.New("alta pins: the directory role takes no directory_provisioning_public_key")
180 }
181 pub, err := operatorPublic(c.PublicKey)
182 if err != nil {
183 return fmt.Errorf("alta pins: the %s public_key is not a canonical P-256 point", role)
184 }
185 if sum := sha256.Sum256(pub); c.KeyID != hex.EncodeToString(sum[:]) {
186 return fmt.Errorf("alta pins: the %s key_id is not sha256(public_key)", role)
187 }
188 if p, err := hex.DecodeString(c.PrefilterSHA256); err != nil || len(p) != 32 || hex.EncodeToString(p) != c.PrefilterSHA256 {
189 return fmt.Errorf("alta pins: the %s prefilter_token_sha256 is not 64 lowercase hex", role)
190 }
191 if !slices.Contains(c.Actions, role+".inspect") {
192 return fmt.Errorf("alta pins: the %s actions lack %s.inspect", role, role)
193 }
194 if _, err := operator.NewVerifier(operator.Pins{Role: role, Origin: c.Origin, Installation: c.Installation, Registry: c.Registry, Device: c.Device, PublicKey: c.PublicKey, Actions: c.Actions}); err != nil {
195 return fmt.Errorf("alta pins: Home's verifier refuses the %s pins (installation, registry, device or actions)", role)
196 }
197 }
198 if cred.Installation != dir.Installation || cred.Registry != dir.Registry || cred.Device != dir.Device || cred.PublicKey != dir.PublicKey || cred.KeyID != dir.KeyID || cred.PrefilterSHA256 != dir.PrefilterSHA256 {
199 return errors.New("alta pins: the two roles' lines are from different alta keygen runs")
200 }
201 for name, pin := range map[string]string{"ALTA_OPERATOR_INSTALLATION": cred.Installation, "ALTA_OPERATOR_REGISTRY": cred.Registry, "ALTA_OPERATOR_DEVICE": cred.Device} {
202 if v, ok := ks.vars[name]; ok && v != pin {
203 return fmt.Errorf("alta pins: %s is not the value pinned in HOME_OPERATOR_HTTP", name)
204 }
205 }
206 if v, ok := ks.vars["ALTA_OPERATOR_PREFILTER"]; ok {
207 raw, err := base64.RawURLEncoding.Strict().DecodeString(v)
208 sum := sha256.Sum256(raw)
209 if err != nil || hex.EncodeToString(sum[:]) != cred.PrefilterSHA256 {
210 return errors.New("alta pins: sha256(ALTA_OPERATOR_PREFILTER) is not prefilter_token_sha256")
211 }
212 }
213 if v, ok := ks.vars["ALTA_OPERATOR_KEY"]; ok {
214 k, err := decodeHomeKeypair(v)
215 if err != nil || rawURL(k.SignPub()) != cred.PublicKey {
216 return errors.New("alta pins: ALTA_OPERATOR_KEY's public half is not public_key")
217 }
218 }
219 return nil
220}
221
222// parseTeamAssertionKeys reads the directory's HOME_ASSERTION_KEYS as
223// LoadRuntime does: its JSON, or the _BASE64 form's value.
224func parseTeamAssertionKeys(raw string, origins Origins) (map[string][]byte, error) {
225 raw = strings.TrimSpace(raw)
226 if !strings.HasPrefix(raw, "{") {
227 b, err := base64.StdEncoding.Strict().DecodeString(raw)
228 if err != nil || base64.StdEncoding.EncodeToString(b) != raw {
229 return nil, errors.New("-assertion-keys is neither HOME_ASSERTION_KEYS's JSON nor its _BASE64 value")
230 }
231 raw = string(b)
232 }
233 var encoded map[string]string
234 if len(raw) > 4096 || json.Unmarshal([]byte(raw), &encoded) != nil || len(encoded) == 0 || len(encoded) > 8 {
235 return nil, errors.New("-assertion-keys: not a HOME_ASSERTION_KEYS manifest (1 to 8 entries)")
236 }
237 keys := make(map[string][]byte, len(encoded))
238 for kid, value := range encoded {
239 key, err := base64.StdEncoding.DecodeString(value)
240 if err != nil {
241 return nil, errors.New("-assertion-keys: a value is not standard base64")
242 }
243 if _, err := operatorPublic(rawURL(key)); err != nil {
244 return nil, errors.New("-assertion-keys: a value is not a P-256 public key")
245 }
246 keys[kid] = key
247 }
248 // The directory's own check (LoadRuntime), so a manifest Home would
249 // refuse is refused here rather than reported as a key problem.
250 if _, err := assertionverifier.NewVerifier(origins.Credential, origins.Directory, keys); err != nil {
251 return nil, errors.New("-assertion-keys: Home's assertion verifier refuses this manifest for these origins")
252 }
253 return keys, nil
254}
255
256// teamKey is a public key and the name an error may print for it.
257type teamKey struct {
258 name string
259 key []byte
260}
261
262// distinctTeamKeys is every inequality Home checks at boot, over the
263// union of both roles' keys: loadOperatorHTTP's distinctOperatorKeys on
264// each role, rosterRuntime.valid, validResolveKeys, NewCredential's and
265// NewDirectory's own refusals and the native command's are each a subset
266// of "all distinct".
267func distinctTeamKeys(keys []teamKey) error {
268 seen := map[string]string{}
269 for _, k := range keys {
270 if len(k.key) == 0 {
271 return fmt.Errorf("%s is empty", k.name)
272 }
273 if prev, dup := seen[string(k.key)]; dup {
274 return fmt.Errorf("%s equals %s; Home refuses to boot with equal keys", k.name, prev)
275 }
276 seen[string(k.key)] = k.name
277 }
278 return nil
279}
280
281func assertionTeamKeys(assertion map[string][]byte) []teamKey {
282 kids := make([]string, 0, len(assertion))
283 for kid := range assertion {
284 kids = append(kids, kid)
285 }
286 sort.Strings(kids)
287 var keys []teamKey
288 for _, kid := range kids {
289 name := kid
290 if len(name) > 12 {
291 name = name[:12] + "…"
292 }
293 keys = append(keys, teamKey{"assertion key " + name, assertion[kid]})
294 }
295 return keys
296}
297
298func encodeTeamKeypair(k *family.Keypair) (string, error) {
299 raw, err := family.MarshalKeypair(k)
300 if err != nil {
301 return "", err
302 }
303 return base64.StdEncoding.EncodeToString(raw), nil
304}
305
306func encodeTeamJSON(v any) (string, error) {
307 b, err := json.Marshal(v, json.Deterministic(true))
308 if err != nil {
309 return "", err
310 }
311 return base64.StdEncoding.EncodeToString(b), nil
312}
313
314// generateTeamEnv makes fresh material for both roles from alta's pins.
315func generateTeamEnv(ks altaKeyset, origins Origins, subject string, assertion map[string][]byte, src teamKeySource) (teamEnv, error) {
316 if !ValidPersonRef(subject) {
317 return nil, errors.New("-subject is not a person ref (pr_ and 26 base32)")
318 }
319 if err := validateAltaPins(ks, origins, subject); err != nil {
320 return nil, err
321 }
322 alta, _ := operatorPublic(ks.pins["credential"].PublicKey)
323 var k [4]*family.Keypair
324 for i := range k {
325 var err error
326 if k[i], err = src.keypair(); err != nil || !validRosterKey(k[i]) {
327 return nil, errors.New("could not generate a key")
328 }
329 }
330 owner, provisioning, rosterKey, resolve := k[0], k[1], k[2], k[3]
331 keys := append([]teamKey{
332 {"Alta's operator key", alta},
333 {"the owner-seed key", owner.SignPub()},
334 {"the directory provisioning key", provisioning.SignPub()},
335 {"the roster key", rosterKey.SignPub()},
336 {"the member-resolution key", resolve.SignPub()},
337 }, assertionTeamKeys(assertion)...)
338 if err := distinctTeamKeys(keys); err != nil {
339 return nil, err
340 }
341 macs := [2][]byte{make([]byte, 32), make([]byte, 32)}
342 for _, m := range macs {
343 if src.random(m) != nil {
344 return nil, errors.New("could not read random bytes")
345 }
346 }
347 if err := distinctTeamMACs(macs[0], macs[1]); err != nil {
348 return nil, err
349 }
350
351 ownerEncoded, err1 := encodeTeamKeypair(owner)
352 provisioningEncoded, err2 := encodeTeamKeypair(provisioning)
353 rosterEncoded, err3 := encodeTeamKeypair(rosterKey)
354 resolveEncoded, err4 := encodeTeamKeypair(resolve)
355 credMaterial, err5 := encodeTeamJSON(credentialOperatorMaterial{Version: 1, Role: "credential", MAC: base64.StdEncoding.EncodeToString(macs[0]), Owner: ownerEncoded})
356 dirMaterial, err6 := encodeTeamJSON(directoryOperatorMaterial{Version: 1, Role: "directory", MAC: base64.StdEncoding.EncodeToString(macs[1]), Owner: rawURL(owner.SignPub()), Provisioning: provisioningEncoded,
357 Roster: []roster.Key{{ID: rosterKeyID(rosterKey), Public: rawURL(rosterKey.SignPub())}}})
358 credHTTP, dirHTTP := ks.pins["credential"], ks.pins["directory"]
359 credHTTP.OperatorSubject, credHTTP.DirectoryProvisioningPublicKey = subject, rawURL(provisioning.SignPub())
360 dirHTTP.OperatorSubject = subject
361 credHTTPEncoded, err7 := encodeTeamJSON(credHTTP)
362 dirHTTPEncoded, err8 := encodeTeamJSON(dirHTTP)
363 if err := errors.Join(err1, err2, err3, err4, err5, err6, err7, err8); err != nil {
364 return nil, errors.New("could not encode the material")
365 }
366 env := teamEnv{
367 teamCredentialSecrets: {"HOME_OPERATOR_MATERIAL_BASE64": credMaterial, "HOME_RESOLVE_KEY": resolveEncoded},
368 teamCredentialEnv: {"HOME_OPERATOR_HTTP_BASE64": credHTTPEncoded},
369 teamDirectorySecrets: {"HOME_ROSTER_MODE": "serve", "HOME_ROSTER_KEY": rosterEncoded, "HOME_OPERATOR_MATERIAL_BASE64": dirMaterial},
370 teamDirectoryEnv: {"HOME_RESOLVE_PUBLIC_KEY": rawURL(resolve.SignPub()), "HOME_OPERATOR_HTTP_BASE64": dirHTTPEncoded},
371 teamAltaEnv: {"ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY": rawURL(provisioning.SignPub()), "ALTA_OPERATOR_SUBJECT": subject},
372 }
373 if err := checkTeamEnv(env, origins, assertion); err != nil {
374 return nil, fmt.Errorf("the generated set fails Home's own loaders: %w", err)
375 }
376 return env, nil
377}
378
379// distinctTeamMACs: Home refuses an all-zero MAC key; the two roles' keys
380// differ by construction (§5: "All must be distinct").
381func distinctTeamMACs(credential, directory []byte) error {
382 zero := make([]byte, 32)
383 if len(credential) != 32 || len(directory) != 32 || bytes.Equal(credential, zero) || bytes.Equal(directory, zero) {
384 return errors.New("a MAC key is not 32 non-zero bytes")
385 }
386 if bytes.Equal(credential, directory) {
387 return errors.New("the credential and directory MAC keys are equal")
388 }
389 return nil
390}
391
392// withTeamEnv runs f with exactly vars set among teamLoaderVars, then
393// restores the environment. The loaders read os.Getenv; this is how a
394// check reaches them unchanged. Not safe for concurrent use.
395func withTeamEnv(vars map[string]string, f func() error) error {
396 saved := map[string]string{}
397 for _, name := range teamLoaderVars {
398 if v, ok := os.LookupEnv(name); ok {
399 saved[name] = v
400 }
401 os.Unsetenv(name)
402 }
403 defer func() {
404 for _, name := range teamLoaderVars {
405 os.Unsetenv(name)
406 if v, ok := saved[name]; ok {
407 os.Setenv(name, v)
408 }
409 }
410 }()
411 for name, value := range vars {
412 if !slices.Contains(teamLoaderVars, name) {
413 return errors.New("not a variable Home's team loaders read")
414 }
415 os.Setenv(name, value)
416 }
417 return f()
418}
419
420// publicSigner is a Keypair carrying only the assertion key's public half:
421// all the loaders read of Runtime.signer is SignPub.
422func publicSigner(pub []byte) (*family.Keypair, error) {
423 x, y := elliptic.Unmarshal(elliptic.P256(), pub)
424 if x == nil {
425 return nil, errExchangeConfig
426 }
427 return &family.Keypair{SignPriv: &ecdsa.PrivateKey{PublicKey: ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y}}}, nil
428}
429
430// loadTeamRole is LoadRuntime's tail for one role, in its order, and
431// requires every team feature on. NewRuntime's re-checks of these
432// (roster.valid, validResolveKeys) are the ones the two loaders already
433// applied; the tests boot through NewRuntime itself.
434func loadTeamRole(cfg *Runtime) error {
435 var err error
436 rosterKeys := cfg.keys
437 if cfg.role != "directory" {
438 rosterKeys = nil
439 }
440 if cfg.roster, err = loadRosterRuntime(cfg.role, rosterKeys); err != nil {
441 return fmt.Errorf("%s role: Home refuses HOME_ROSTER_MODE/HOME_ROSTER_KEY", cfg.role)
442 }
443 if err = loadResolveKeys(cfg); err != nil {
444 return fmt.Errorf("%s role: Home refuses the member-resolution key", cfg.role)
445 }
446 if err = loadOperatorHTTP(cfg); err != nil {
447 return fmt.Errorf("%s role: Home refuses HOME_OPERATOR_HTTP with this HOME_OPERATOR_MATERIAL (format, pins, or two equal keys)", cfg.role)
448 }
449 if cfg.operator == nil {
450 return fmt.Errorf("%s role: the operator endpoint would be off", cfg.role)
451 }
452 if cfg.role == "credential" && cfg.resolveSigner == nil {
453 return errors.New("credential role: no member-resolution key")
454 }
455 if cfg.role == "directory" && (cfg.roster.mode != "serve" || cfg.resolvePublic == nil) {
456 return errors.New("directory role: the roster endpoint or member resolution would be off")
457 }
458 return nil
459}
460
461// checkTeamRole loads one role's variables through Home's loaders. The
462// credential role is checked once per assertion key, as its signer: the
463// check passes whichever key the credential holds.
464func checkTeamRole(role string, vars map[string]string, origins Origins, assertion map[string][]byte) (Runtime, error) {
465 var out Runtime
466 err := withTeamEnv(vars, func() error {
467 if role == "directory" {
468 out = Runtime{role: role, origins: origins, keys: assertion}
469 return loadTeamRole(&out)
470 }
471 for _, k := range assertionTeamKeys(assertion) {
472 signer, err := publicSigner(k.key)
473 if err != nil {
474 return err
475 }
476 sum := sha256.Sum256(k.key)
477 kid := hex.EncodeToString(sum[:])
478 out = Runtime{role: role, origins: origins, signer: signer, keyID: kid, keys: map[string][]byte{kid: k.key}}
479 if err := loadTeamRole(&out); err != nil {
480 return err
481 }
482 }
483 return nil
484 })
485 return out, err
486}
487
488// checkTeamEnv confirms both roles boot with env, and that the roles agree
489// with each other (and with Alta's section, when present).
490func checkTeamEnv(env teamEnv, origins Origins, assertion map[string][]byte) error {
491 for _, section := range teamSectionOrder {
492 vars, ok := env[section]
493 if !ok && section == teamAltaEnv {
494 continue
495 }
496 if !ok {
497 return fmt.Errorf("no [%s] section", section)
498 }
499 for _, name := range teamSectionVars[section] {
500 if _, ok := vars[name]; !ok {
501 return fmt.Errorf("[%s] lacks %s", section, name)
502 }
503 }
504 if len(vars) != len(teamSectionVars[section]) {
505 return fmt.Errorf("[%s] holds a variable it does not take", section)
506 }
507 }
508 for section := range env {
509 if _, ok := teamSectionVars[section]; !ok {
510 return errors.New("an unknown section")
511 }
512 }
513 cred, err := checkTeamRole("credential", env.role("credential"), origins, assertion)
514 if err != nil {
515 return err
516 }
517 dir, err := checkTeamRole("directory", env.role("directory"), origins, assertion)
518 if err != nil {
519 return err
520 }
521
522 c, d := cred.operator.config, dir.operator.config
523 if c.Installation != d.Installation || c.Registry != d.Registry || c.Device != d.Device || c.PublicKey != d.PublicKey || c.KeyID != d.KeyID || c.PrefilterSHA256 != d.PrefilterSHA256 {
524 return errors.New("the two roles pin different Alta keysets")
525 }
526 if c.OperatorSubject != d.OperatorSubject {
527 return errors.New("the two roles name different operator_subjects")
528 }
529 var dm directoryOperatorMaterial
530 raw, err := base64.StdEncoding.Strict().DecodeString(env[teamDirectorySecrets]["HOME_OPERATOR_MATERIAL_BASE64"])
531 if err != nil || json.Unmarshal(raw, &dm, json.RejectUnknownMembers(true)) != nil {
532 return errors.New("directory role: HOME_OPERATOR_MATERIAL_BASE64 is unreadable")
533 }
534 if dm.Owner != rawURL(cred.operator.owner.SignPub()) {
535 return errors.New("the directory's owner_seed_public is not the credential's owner-seed key")
536 }
537 if c.DirectoryProvisioningPublicKey != rawURL(dir.operator.provisioning.SignPub()) {
538 return errors.New("the credential's directory_provisioning_public_key is not the directory's provisioning key")
539 }
540 if !bytes.Equal(dir.resolvePublic, cred.resolveSigner.SignPub()) {
541 return errors.New("HOME_RESOLVE_PUBLIC_KEY is not HOME_RESOLVE_KEY's public half")
542 }
543 if err := distinctTeamMACs(cred.operator.mac, dir.operator.mac); err != nil {
544 return err
545 }
546 // No union check of the keys here: with the cross-checks above, the
547 // directory's own distinct set (Alta, owner-seed, provisioning, every
548 // assertion key, the roster keys, resolve) already is the union of both
549 // roles', and loadOperatorHTTP refused any equality in it.
550 if a, ok := env[teamAltaEnv]; ok {
551 if a["ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY"] != c.DirectoryProvisioningPublicKey {
552 return errors.New("[alta env] ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY is not the directory's provisioning key")
553 }
554 if a["ALTA_OPERATOR_SUBJECT"] != c.OperatorSubject {
555 return errors.New("[alta env] ALTA_OPERATOR_SUBJECT is not operator_subject")
556 }
557 }
558 return nil
559}
560
561// parseTeamEnv reads the format writeTeamEnv prints. Like the Alta parser,
562// its errors never quote a line.
563func parseTeamEnv(r io.Reader) (teamEnv, error) {
564 env := teamEnv{}
565 section := ""
566 sc := bufio.NewScanner(r)
567 sc.Buffer(make([]byte, 0, 64<<10), 64<<10)
568 for n := 1; sc.Scan(); n++ {
569 line := strings.TrimRight(sc.Text(), "\r")
570 if line == "" || strings.HasPrefix(line, "#") {
571 continue
572 }
573 if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
574 name := line[1 : len(line)-1]
575 if _, ok := teamSectionVars[name]; !ok || env[name] != nil {
576 return nil, fmt.Errorf("line %d: an unknown or repeated section", n)
577 }
578 env[name], section = map[string]string{}, name
579 continue
580 }
581 name, value, ok := strings.Cut(line, "=")
582 if !ok || section == "" || !slices.Contains(teamSectionVars[section], name) {
583 return nil, fmt.Errorf("line %d: not a variable this section takes", n)
584 }
585 if _, dup := env[section][name]; dup {
586 return nil, fmt.Errorf("line %d: %s twice in [%s]", n, name, section)
587 }
588 env[section][name] = value
589 }
590 if sc.Err() != nil {
591 return nil, errors.New("unreadable (a line over 64 KiB?)")
592 }
593 return env, nil
594}
595
596// writeTeamEnv prints env in its section order, each section headed with
597// the one carlos call it is.
598func writeTeamEnv(w io.Writer, env teamEnv, origins Origins, keyID, subject string) error {
599 production := origins == Origins{Origin, directoryOrigin}
600 app := map[string]string{"credential": "<the credential role's app>", "directory": "<the directory role's app>", "alta": "alta"}
601 if production {
602 app["credential"], app["directory"] = "oficina-id", "oficina"
603 }
604 notes := map[string][]string{
605 teamCredentialSecrets: {
606 "Credential role, " + origins.Credential + ". Step 1, one call:",
607 " carlos secrets set --account oficina --app " + app["credential"] + " <these lines>",
608 "Inert until step 2: Home reads the material only beside HOME_OPERATOR_HTTP.",
609 },
610 teamCredentialEnv: {
611 "Step 2, one call, in which HOME_CONSUMERS_BASE64 also gains \"alta\" (not generated here):",
612 " carlos env set --account oficina --app " + app["credential"] + " <these lines> HOME_CONSUMERS_BASE64=…",
613 "Then restart the role and sign in to one app end to end.",
614 },
615 teamDirectorySecrets: {
616 "Directory role, " + origins.Directory + ". Step 3, one call (mode and key together):",
617 " carlos secrets set --account oficina --app " + app["directory"] + " <these lines>",
618 },
619 teamDirectoryEnv: {
620 "Step 4, one call, last:",
621 " carlos env set --account oficina --app " + app["directory"] + " <these lines>",
622 },
623 teamAltaEnv: {
624 "Alta, to match, in one call with ALTA_HOME_CONSUMER_ID=alta, ALTA_ORIGIN (equal to the",
625 "\"alta\" entry of the credential's HOME_CONSUMERS) and HOME_DIRECTORY_ORIGIN=" + origins.Directory + ",",
626 "beside alta keygen's own lines:",
627 " carlos env set --account oficina --app alta <these lines> ALTA_HOME_CONSUMER_ID=alta ALTA_ORIGIN=… HOME_DIRECTORY_ORIGIN=" + origins.Directory,
628 },
629 }
630 var b strings.Builder
631 b.WriteString("# home team-keygen: team-provisioning keys for both Home roles (oficina/home #101 §5).\n")
632 b.WriteString("# PRIVATE KEYS. Keep this at mode 0600 and delete it once every value is set.\n")
633 b.WriteString("# Alta key_id " + keyID + "; operator_subject " + subject + "\n")
634 b.WriteString("# Re-check before setting: home team-keygen -check -assertion-keys '<HOME_ASSERTION_KEYS>' <this file>\n")
635 for _, section := range teamSectionOrder {
636 vars, ok := env[section]
637 if !ok {
638 continue
639 }
640 b.WriteString("\n")
641 for _, note := range notes[section] {
642 b.WriteString("# " + note + "\n")
643 }
644 b.WriteString("[" + section + "]\n")
645 for _, name := range teamSectionVars[section] {
646 b.WriteString(name + "=" + vars[name] + "\n")
647 }
648 }
649 _, err := io.WriteString(w, b.String())
650 return err
651}
652
653func openTeamInput(path string, stdin io.Reader) (io.ReadCloser, error) {
654 if path == "-" {
655 return io.NopCloser(stdin), nil
656 }
657 return os.Open(path)
658}
659
660// writeTeamFile creates path (refusing one that exists) at mode 0600.
661func writeTeamFile(path string, write func(io.Writer) error) error {
662 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
663 if err != nil {
664 return errors.New("-out: cannot create the file (it must not exist yet)")
665 }
666 if err = f.Chmod(0o600); err == nil {
667 err = write(f)
668 }
669 if cerr := f.Close(); err == nil {
670 err = cerr
671 }
672 if err != nil {
673 os.Remove(path)
674 return errors.New("-out: could not write the file; nothing was kept")
675 }
676 return nil
677}
678
679const teamKeygenUsage = `usage:
680 home team-keygen -alta FILE -subject pr_… -assertion-keys MANIFEST [-out FILE]
681 home team-keygen -check -assertion-keys MANIFEST FILE
682
683Generates fresh team-provisioning material for both Home roles from alta
684keygen's output (FILE, or - for stdin), and prints each role's env set,
685one [section] per carlos call. -assertion-keys is the directory's
686HOME_ASSERTION_KEYS (its JSON, or HOME_ASSERTION_KEYS_BASE64's value).
687Secrets go to stdout, or with -out to a new file at mode 0600.
688
689-check loads a set this command printed through Home's own loaders and
690confirms both roles would boot with it.
691
692flags:
693`
694
695// RunTeamKeygen is `home team-keygen`. 0: done; 1: refused; 2: usage.
696func RunTeamKeygen(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
697 fs := flag.NewFlagSet("home team-keygen", flag.ContinueOnError)
698 fs.SetOutput(stderr)
699 fs.Usage = func() { fmt.Fprint(stderr, teamKeygenUsage); fs.PrintDefaults() }
700 altaPath := fs.String("alta", "", "alta keygen's output: a file, or - for stdin")
701 subject := fs.String("subject", "", "operator_subject: Paul's person ref (pr_ and 26 base32); required")
702 assertionRaw := fs.String("assertion-keys", "", "the directory's HOME_ASSERTION_KEYS, JSON or its _BASE64 value; required")
703 out := fs.String("out", "", "write the env set to this new file at mode 0600, not stdout")
704 check := fs.Bool("check", false, "check the env set in the file named after the flags (or -)")
705 credentialOrigin := fs.String("credential-origin", Origin, "the credential role's origin")
706 dirOrigin := fs.String("directory-origin", directoryOrigin, "the directory role's origin")
707 if fs.Parse(args) != nil {
708 return 2
709 }
710 refuse := func(code int, err error) int {
711 fmt.Fprintln(stderr, "home team-keygen:", err)
712 return code
713 }
714 origins := Origins{*credentialOrigin, *dirOrigin}
715 if origins.validate() != nil {
716 return refuse(2, errors.New("-credential-origin/-directory-origin are not a valid pair of Home origins"))
717 }
718 if *assertionRaw == "" {
719 return refuse(2, errors.New("-assertion-keys is required"))
720 }
721 assertion, err := parseTeamAssertionKeys(*assertionRaw, origins)
722 if err != nil {
723 return refuse(1, err)
724 }
725
726 if *check {
727 if fs.NArg() != 1 || *altaPath != "" || *subject != "" || *out != "" {
728 return refuse(2, errors.New("-check takes -assertion-keys, optional origins, and one file"))
729 }
730 in, err := openTeamInput(fs.Arg(0), stdin)
731 if err != nil {
732 return refuse(1, errors.New("cannot open the env set"))
733 }
734 env, err := parseTeamEnv(in)
735 in.Close()
736 if err == nil {
737 err = checkTeamEnv(env, origins, assertion)
738 }
739 if err != nil {
740 return refuse(1, fmt.Errorf("check failed: %w", err))
741 }
742 fmt.Fprintln(stdout, "ok: both roles boot with this set (credential "+origins.Credential+", directory "+origins.Directory+"), and the roles agree")
743 return 0
744 }
745
746 if fs.NArg() != 0 || *altaPath == "" || *subject == "" {
747 return refuse(2, errors.New("-alta, -subject and -assertion-keys are required"))
748 }
749 in, err := openTeamInput(*altaPath, stdin)
750 if err != nil {
751 return refuse(1, errors.New("cannot open -alta"))
752 }
753 ks, err := parseAltaKeygen(in)
754 in.Close()
755 if err != nil {
756 return refuse(1, err)
757 }
758 env, err := generateTeamEnv(ks, origins, *subject, assertion, defaultTeamKeySource())
759 if err != nil {
760 return refuse(1, err)
761 }
762 write := func(w io.Writer) error { return writeTeamEnv(w, env, origins, ks.pins["credential"].KeyID, *subject) }
763 if *out == "" {
764 if write(stdout) != nil {
765 return refuse(1, errors.New("could not write stdout"))
766 }
767 return 0
768 }
769 if err := writeTeamFile(*out, write); err != nil {
770 return refuse(1, err)
771 }
772 fmt.Fprintln(stdout, "wrote", *out, "(mode 0600); check it with: home team-keygen -check -assertion-keys '<HOME_ASSERTION_KEYS>'", *out)
773 return 0
774}
775