oficina / home Public

home team-keygen: production keys for team provisioning

Adds the home team-keygen subcommand: from alta keygen's output, the operator subject and the deployed HOME_ASSERTION_KEYS it generates fresh HOME_OPERATOR_MATERIAL for both roles, HOME_ROSTER_KEY and the HOME_RESOLVE_KEY/HOME_RESOLVE_PUBLIC_KEY pair, and emits the per-role carlos env/secret sets in the apply order of #101 s5. Every key is crypto/rand in the exact format Home parses; all keys are pairwise distinct (operator, provisioning, roster, resolve, Alta, every assertion key) and both MACs non-zero and unequal; the output is loaded through Home's real loaders for both roles before it is printed, and -check re-runs that on a file. Secrets go only to stdout or a new 0600 file; errors carry rules, never values. Generates nothing in production by itself and changes no config. Reviewed by Claude Fable 5.1 (claude-fable-5-1), oficina/home #102, APPROVED at 17925de, notes N1/N2 applied; CI green at 375f704.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from team-keygen into main.
claude agent, operated by paul@keymail.dev 64e30e1b2cf66765a184ab5fc7da4ec93c596159 parent ddde992
5 files changed, +1,657 −0
  • cmd/home/main.go +9 −0
  • internal/guardstest/logsinks_test.go +31 −0
  • internal/home/team_keygen.go +774 −0
  • internal/home/team_keygen_test.go +833 −0
  • internal/home/testdata/alta-keygen-f78d993.txt +10 −0

CI passed — run details

diff --git a/cmd/home/main.go b/cmd/home/main.go
index 5f32a85..0610f93 100644
--- a/cmd/home/main.go
+++ b/cmd/home/main.go
@@ -34,6 +34,12 @@
// that is what a promote does, not a deploy. Nothing in .amadan/ci.d
// deploys on merge, so merging is safe; deploying is the step that
// needs the secrets first.
+//
+// `home team-keygen` is not the platform's either: an offline command,
+// run on Paul's machine, that generates
+// both roles' team-provisioning keys from `alta keygen`'s output and checks
+// a set through the loaders below (internal/home/team_keygen.go). It
+// opens no database and reads none of this binary's secrets.
package main
import (
@@ -50,6 +56,9 @@ import (
)
func main() {
+ if len(os.Args) > 1 && os.Args[1] == "team-keygen" {
+ os.Exit(home.RunTeamKeygen(os.Args[2:], os.Stdin, os.Stdout, os.Stderr))
+ }
if len(os.Args) > 1 && os.Args[1] == "operator-v1" {
if len(os.Args) != 4 || os.Args[2] != "--db" {
os.Exit(2)
diff --git a/internal/guardstest/logsinks_test.go b/internal/guardstest/logsinks_test.go
index f6da0cd..2ef8047 100644
--- a/internal/guardstest/logsinks_test.go
+++ b/internal/guardstest/logsinks_test.go
@@ -126,6 +126,37 @@ func TestNoLogSinkOutsideSlog(t *testing.T) {
return true
})
}
+ // `home team-keygen` is an offline command whose output is its
+ // product: the generated env set on stdout, refusals on stderr
+ // (none of which names a value; team_keygen_test.go checks). Permit
+ // the two streams only as RunTeamKeygen's own arguments in
+ // cmd/home/main.go, never as a sink anywhere else in that file.
+ if rel == "cmd/home/main.go" {
+ ast.Inspect(f, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok || len(call.Args) != 4 {
+ return true
+ }
+ fun, ok := call.Fun.(*ast.SelectorExpr)
+ if !ok || fun.Sel.Name != "RunTeamKeygen" {
+ return true
+ }
+ pkg, ok := fun.X.(*ast.Ident)
+ if !ok || local[pkg.Name] != "amadan.net/oficina/home/internal/home" {
+ return true
+ }
+ for i, want := range map[int]string{2: "Stdout", 3: "Stderr"} {
+ sink, ok := call.Args[i].(*ast.SelectorExpr)
+ if !ok || sink.Sel.Name != want {
+ continue
+ }
+ if owner, ok := sink.X.(*ast.Ident); ok && local[owner.Name] == "os" {
+ structuredResult[sink] = true
+ }
+ }
+ return true
+ })
+ }
ast.Inspect(f, func(n ast.Node) bool {
sel, ok := n.(*ast.SelectorExpr)
if !ok {
diff --git a/internal/home/team_keygen.go b/internal/home/team_keygen.go
new file mode 100644
index 0000000..a8eb5c4
--- /dev/null
+++ b/internal/home/team_keygen.go
@@ -0,0 +1,774 @@
+package home
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "regexp"
+ "slices"
+ "sort"
+ "strings"
+
+ "amadan.net/oficina/home/internal/operator"
+ "amadan.net/oficina/home/roster"
+ assertionverifier "amadan.net/rastrillo/rastrillo/assertion"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ json "github.com/go-json-experiment/json"
+)
+
+// home team-keygen generates the Home half of team provisioning's
+// configuration (discussion 101 §5): both roles' HOME_OPERATOR_MATERIAL,
+// the directory's roster key, and the member-resolution pair, plus each
+// role's HOME_OPERATOR_HTTP, which is alta keygen's pins with
+// operator_subject and the directory's provisioning key filled in.
+//
+// What it prints always boots: before printing, it loads each role's set
+// through Home's own loaders (loadRosterRuntime, loadResolveKeys,
+// loadOperatorHTTP and NewRuntime's checks), the path -check takes too.
+// Secrets go to stdout or to a new file at mode 0600, never to stderr: no
+// error names a value, and nothing here uses a logger.
+
+const (
+ altaSubjectPlaceholder = "<Paul's person ref>"
+ altaProvisioningPlaceholder = "<the directory's provisioning public key>"
+)
+
+// The sections of a team env set, in the order they are applied (§5's
+// "every intermediate state is a valid boot"). Each is one carlos call.
+const (
+ teamCredentialSecrets = "credential secrets"
+ teamCredentialEnv = "credential env"
+ teamDirectorySecrets = "directory secrets"
+ teamDirectoryEnv = "directory env"
+ teamAltaEnv = "alta env"
+)
+
+var teamSectionOrder = []string{teamCredentialSecrets, teamCredentialEnv, teamDirectorySecrets, teamDirectoryEnv, teamAltaEnv}
+
+// teamSectionVars is closed: a section holds exactly these variables.
+var teamSectionVars = map[string][]string{
+ teamCredentialSecrets: {"HOME_OPERATOR_MATERIAL_BASE64", "HOME_RESOLVE_KEY"},
+ teamCredentialEnv: {"HOME_OPERATOR_HTTP_BASE64"},
+ teamDirectorySecrets: {"HOME_ROSTER_MODE", "HOME_ROSTER_KEY", "HOME_OPERATOR_MATERIAL_BASE64"},
+ teamDirectoryEnv: {"HOME_RESOLVE_PUBLIC_KEY", "HOME_OPERATOR_HTTP_BASE64"},
+ teamAltaEnv: {"ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY", "ALTA_OPERATOR_SUBJECT"},
+}
+
+// teamLoaderVars is every variable the loaders below read; a check clears
+// all of them first, so nothing in the caller's environment takes part.
+var teamLoaderVars = []string{
+ "HOME_ROSTER_MODE", "HOME_ROSTER_KEY", "HOME_RESOLVE_KEY", "HOME_RESOLVE_PUBLIC_KEY",
+ "HOME_OPERATOR_HTTP", "HOME_OPERATOR_HTTP_BASE64", "HOME_OPERATOR_MATERIAL", "HOME_OPERATOR_MATERIAL_BASE64",
+}
+
+// teamEnv is section → variable → value.
+type teamEnv map[string]map[string]string
+
+func (env teamEnv) role(role string) map[string]string {
+ vars := map[string]string{}
+ for _, section := range []string{role + " secrets", role + " env"} {
+ for k, v := range env[section] {
+ vars[k] = v
+ }
+ }
+ return vars
+}
+
+// teamKeySource is where fresh keys come from: family.Generate and
+// crypto/rand outside tests.
+type teamKeySource struct {
+ keypair func() (*family.Keypair, error)
+ random func([]byte) error
+}
+
+func defaultTeamKeySource() teamKeySource {
+ return teamKeySource{keypair: family.Generate, random: func(b []byte) error { _, err := rand.Read(b); return err }}
+}
+
+// altaKeyset is alta keygen's output: both roles' HOME_OPERATOR_HTTP, and
+// the ALTA_* lines it printed beside them (used only to cross-check).
+type altaKeyset struct {
+ pins map[string]operatorHTTPConfig
+ vars map[string]string
+}
+
+var altaHTTPHeader = regexp.MustCompile(`^# HOME_OPERATOR_HTTP for the (credential|directory) role:$`)
+var altaKeygenVars = []string{"ALTA_OPERATOR_KEY", "ALTA_OPERATOR_PREFILTER", "ALTA_DEK", "ALTA_OPERATOR_INSTALLATION", "ALTA_OPERATOR_REGISTRY", "ALTA_OPERATOR_DEVICE"}
+
+// parseAltaKeygen reads alta keygen's output. Errors name a line number
+// and a rule, never a line's content: some of its lines are Alta's secrets.
+func parseAltaKeygen(r io.Reader) (altaKeyset, error) {
+ ks := altaKeyset{pins: map[string]operatorHTTPConfig{}, vars: map[string]string{}}
+ sc := bufio.NewScanner(r)
+ sc.Buffer(make([]byte, 0, 64<<10), 64<<10)
+ pending, n := "", 0
+ for sc.Scan() {
+ n++
+ line := strings.TrimRight(sc.Text(), "\r")
+ if pending != "" {
+ var c operatorHTTPConfig
+ if len(line) > 8192 || json.Unmarshal([]byte(line), &c, json.RejectUnknownMembers(true)) != nil {
+ return ks, fmt.Errorf("alta keygen line %d: the %s role's HOME_OPERATOR_HTTP is not its closed JSON", n, pending)
+ }
+ ks.pins[pending], pending = c, ""
+ continue
+ }
+ if m := altaHTTPHeader.FindStringSubmatch(line); m != nil {
+ if _, dup := ks.pins[m[1]]; dup {
+ return ks, fmt.Errorf("alta keygen line %d: a second HOME_OPERATOR_HTTP for the %s role", n, m[1])
+ }
+ pending = m[1]
+ continue
+ }
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ name, value, ok := strings.Cut(line, "=")
+ if !ok || !slices.Contains(altaKeygenVars, name) {
+ return ks, fmt.Errorf("alta keygen line %d: not a line alta keygen prints", n)
+ }
+ if _, dup := ks.vars[name]; dup {
+ return ks, fmt.Errorf("alta keygen line %d: %s twice", n, name)
+ }
+ ks.vars[name] = value
+ }
+ if err := sc.Err(); err != nil {
+ return ks, errors.New("alta keygen: unreadable (a line over 64 KiB?)")
+ }
+ if pending != "" {
+ return ks, fmt.Errorf("alta keygen: the %s role's HOME_OPERATOR_HTTP header has no JSON after it", pending)
+ }
+ for _, role := range []string{"credential", "directory"} {
+ if _, ok := ks.pins[role]; !ok {
+ return ks, fmt.Errorf("alta keygen: no HOME_OPERATOR_HTTP for the %s role", role)
+ }
+ }
+ return ks, nil
+}
+
+// validateAltaPins refuses pins Home would refuse, pins the two roles
+// disagree on, and placeholders already filled with something else. Home's
+// loaders check the filled result again before anything is printed.
+func validateAltaPins(ks altaKeyset, origins Origins, subject string) error {
+ cred, dir := ks.pins["credential"], ks.pins["directory"]
+ for role, c := range map[string]operatorHTTPConfig{"credential": cred, "directory": dir} {
+ want := origins.Directory
+ if role == "credential" {
+ want = origins.Credential
+ }
+ switch {
+ case c.Version != 1 || c.Role != role:
+ return fmt.Errorf("alta pins: the %s role's line is not a version-1 config for that role", role)
+ case c.Origin != want:
+ return fmt.Errorf("alta pins: the %s origin is %q; this Home's is %q", role, c.Origin, want)
+ case c.OperatorSubject != altaSubjectPlaceholder && c.OperatorSubject != subject:
+ return fmt.Errorf("alta pins: the %s operator_subject is already set, and not to -subject", role)
+ case role == "credential" && c.DirectoryProvisioningPublicKey != altaProvisioningPlaceholder && c.DirectoryProvisioningPublicKey != "":
+ return errors.New("alta pins: the credential directory_provisioning_public_key is already filled; team-keygen generates that key")
+ case role == "directory" && c.DirectoryProvisioningPublicKey != "":
+ return errors.New("alta pins: the directory role takes no directory_provisioning_public_key")
+ }
+ pub, err := operatorPublic(c.PublicKey)
+ if err != nil {
+ return fmt.Errorf("alta pins: the %s public_key is not a canonical P-256 point", role)
+ }
+ if sum := sha256.Sum256(pub); c.KeyID != hex.EncodeToString(sum[:]) {
+ return fmt.Errorf("alta pins: the %s key_id is not sha256(public_key)", role)
+ }
+ if p, err := hex.DecodeString(c.PrefilterSHA256); err != nil || len(p) != 32 || hex.EncodeToString(p) != c.PrefilterSHA256 {
+ return fmt.Errorf("alta pins: the %s prefilter_token_sha256 is not 64 lowercase hex", role)
+ }
+ if !slices.Contains(c.Actions, role+".inspect") {
+ return fmt.Errorf("alta pins: the %s actions lack %s.inspect", role, role)
+ }
+ 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 {
+ return fmt.Errorf("alta pins: Home's verifier refuses the %s pins (installation, registry, device or actions)", role)
+ }
+ }
+ 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 {
+ return errors.New("alta pins: the two roles' lines are from different alta keygen runs")
+ }
+ for name, pin := range map[string]string{"ALTA_OPERATOR_INSTALLATION": cred.Installation, "ALTA_OPERATOR_REGISTRY": cred.Registry, "ALTA_OPERATOR_DEVICE": cred.Device} {
+ if v, ok := ks.vars[name]; ok && v != pin {
+ return fmt.Errorf("alta pins: %s is not the value pinned in HOME_OPERATOR_HTTP", name)
+ }
+ }
+ if v, ok := ks.vars["ALTA_OPERATOR_PREFILTER"]; ok {
+ raw, err := base64.RawURLEncoding.Strict().DecodeString(v)
+ sum := sha256.Sum256(raw)
+ if err != nil || hex.EncodeToString(sum[:]) != cred.PrefilterSHA256 {
+ return errors.New("alta pins: sha256(ALTA_OPERATOR_PREFILTER) is not prefilter_token_sha256")
+ }
+ }
+ if v, ok := ks.vars["ALTA_OPERATOR_KEY"]; ok {
+ k, err := decodeHomeKeypair(v)
+ if err != nil || rawURL(k.SignPub()) != cred.PublicKey {
+ return errors.New("alta pins: ALTA_OPERATOR_KEY's public half is not public_key")
+ }
+ }
+ return nil
+}
+
+// parseTeamAssertionKeys reads the directory's HOME_ASSERTION_KEYS as
+// LoadRuntime does: its JSON, or the _BASE64 form's value.
+func parseTeamAssertionKeys(raw string, origins Origins) (map[string][]byte, error) {
+ raw = strings.TrimSpace(raw)
+ if !strings.HasPrefix(raw, "{") {
+ b, err := base64.StdEncoding.Strict().DecodeString(raw)
+ if err != nil || base64.StdEncoding.EncodeToString(b) != raw {
+ return nil, errors.New("-assertion-keys is neither HOME_ASSERTION_KEYS's JSON nor its _BASE64 value")
+ }
+ raw = string(b)
+ }
+ var encoded map[string]string
+ if len(raw) > 4096 || json.Unmarshal([]byte(raw), &encoded) != nil || len(encoded) == 0 || len(encoded) > 8 {
+ return nil, errors.New("-assertion-keys: not a HOME_ASSERTION_KEYS manifest (1 to 8 entries)")
+ }
+ keys := make(map[string][]byte, len(encoded))
+ for kid, value := range encoded {
+ key, err := base64.StdEncoding.DecodeString(value)
+ if err != nil {
+ return nil, errors.New("-assertion-keys: a value is not standard base64")
+ }
+ if _, err := operatorPublic(rawURL(key)); err != nil {
+ return nil, errors.New("-assertion-keys: a value is not a P-256 public key")
+ }
+ keys[kid] = key
+ }
+ // The directory's own check (LoadRuntime), so a manifest Home would
+ // refuse is refused here rather than reported as a key problem.
+ if _, err := assertionverifier.NewVerifier(origins.Credential, origins.Directory, keys); err != nil {
+ return nil, errors.New("-assertion-keys: Home's assertion verifier refuses this manifest for these origins")
+ }
+ return keys, nil
+}
+
+// teamKey is a public key and the name an error may print for it.
+type teamKey struct {
+ name string
+ key []byte
+}
+
+// distinctTeamKeys is every inequality Home checks at boot, over the
+// union of both roles' keys: loadOperatorHTTP's distinctOperatorKeys on
+// each role, rosterRuntime.valid, validResolveKeys, NewCredential's and
+// NewDirectory's own refusals and the native command's are each a subset
+// of "all distinct".
+func distinctTeamKeys(keys []teamKey) error {
+ seen := map[string]string{}
+ for _, k := range keys {
+ if len(k.key) == 0 {
+ return fmt.Errorf("%s is empty", k.name)
+ }
+ if prev, dup := seen[string(k.key)]; dup {
+ return fmt.Errorf("%s equals %s; Home refuses to boot with equal keys", k.name, prev)
+ }
+ seen[string(k.key)] = k.name
+ }
+ return nil
+}
+
+func assertionTeamKeys(assertion map[string][]byte) []teamKey {
+ kids := make([]string, 0, len(assertion))
+ for kid := range assertion {
+ kids = append(kids, kid)
+ }
+ sort.Strings(kids)
+ var keys []teamKey
+ for _, kid := range kids {
+ name := kid
+ if len(name) > 12 {
+ name = name[:12] + "…"
+ }
+ keys = append(keys, teamKey{"assertion key " + name, assertion[kid]})
+ }
+ return keys
+}
+
+func encodeTeamKeypair(k *family.Keypair) (string, error) {
+ raw, err := family.MarshalKeypair(k)
+ if err != nil {
+ return "", err
+ }
+ return base64.StdEncoding.EncodeToString(raw), nil
+}
+
+func encodeTeamJSON(v any) (string, error) {
+ b, err := json.Marshal(v, json.Deterministic(true))
+ if err != nil {
+ return "", err
+ }
+ return base64.StdEncoding.EncodeToString(b), nil
+}
+
+// generateTeamEnv makes fresh material for both roles from alta's pins.
+func generateTeamEnv(ks altaKeyset, origins Origins, subject string, assertion map[string][]byte, src teamKeySource) (teamEnv, error) {
+ if !ValidPersonRef(subject) {
+ return nil, errors.New("-subject is not a person ref (pr_ and 26 base32)")
+ }
+ if err := validateAltaPins(ks, origins, subject); err != nil {
+ return nil, err
+ }
+ alta, _ := operatorPublic(ks.pins["credential"].PublicKey)
+ var k [4]*family.Keypair
+ for i := range k {
+ var err error
+ if k[i], err = src.keypair(); err != nil || !validRosterKey(k[i]) {
+ return nil, errors.New("could not generate a key")
+ }
+ }
+ owner, provisioning, rosterKey, resolve := k[0], k[1], k[2], k[3]
+ keys := append([]teamKey{
+ {"Alta's operator key", alta},
+ {"the owner-seed key", owner.SignPub()},
+ {"the directory provisioning key", provisioning.SignPub()},
+ {"the roster key", rosterKey.SignPub()},
+ {"the member-resolution key", resolve.SignPub()},
+ }, assertionTeamKeys(assertion)...)
+ if err := distinctTeamKeys(keys); err != nil {
+ return nil, err
+ }
+ macs := [2][]byte{make([]byte, 32), make([]byte, 32)}
+ for _, m := range macs {
+ if src.random(m) != nil {
+ return nil, errors.New("could not read random bytes")
+ }
+ }
+ if err := distinctTeamMACs(macs[0], macs[1]); err != nil {
+ return nil, err
+ }
+
+ ownerEncoded, err1 := encodeTeamKeypair(owner)
+ provisioningEncoded, err2 := encodeTeamKeypair(provisioning)
+ rosterEncoded, err3 := encodeTeamKeypair(rosterKey)
+ resolveEncoded, err4 := encodeTeamKeypair(resolve)
+ credMaterial, err5 := encodeTeamJSON(credentialOperatorMaterial{Version: 1, Role: "credential", MAC: base64.StdEncoding.EncodeToString(macs[0]), Owner: ownerEncoded})
+ dirMaterial, err6 := encodeTeamJSON(directoryOperatorMaterial{Version: 1, Role: "directory", MAC: base64.StdEncoding.EncodeToString(macs[1]), Owner: rawURL(owner.SignPub()), Provisioning: provisioningEncoded,
+ Roster: []roster.Key{{ID: rosterKeyID(rosterKey), Public: rawURL(rosterKey.SignPub())}}})
+ credHTTP, dirHTTP := ks.pins["credential"], ks.pins["directory"]
+ credHTTP.OperatorSubject, credHTTP.DirectoryProvisioningPublicKey = subject, rawURL(provisioning.SignPub())
+ dirHTTP.OperatorSubject = subject
+ credHTTPEncoded, err7 := encodeTeamJSON(credHTTP)
+ dirHTTPEncoded, err8 := encodeTeamJSON(dirHTTP)
+ if err := errors.Join(err1, err2, err3, err4, err5, err6, err7, err8); err != nil {
+ return nil, errors.New("could not encode the material")
+ }
+ env := teamEnv{
+ teamCredentialSecrets: {"HOME_OPERATOR_MATERIAL_BASE64": credMaterial, "HOME_RESOLVE_KEY": resolveEncoded},
+ teamCredentialEnv: {"HOME_OPERATOR_HTTP_BASE64": credHTTPEncoded},
+ teamDirectorySecrets: {"HOME_ROSTER_MODE": "serve", "HOME_ROSTER_KEY": rosterEncoded, "HOME_OPERATOR_MATERIAL_BASE64": dirMaterial},
+ teamDirectoryEnv: {"HOME_RESOLVE_PUBLIC_KEY": rawURL(resolve.SignPub()), "HOME_OPERATOR_HTTP_BASE64": dirHTTPEncoded},
+ teamAltaEnv: {"ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY": rawURL(provisioning.SignPub()), "ALTA_OPERATOR_SUBJECT": subject},
+ }
+ if err := checkTeamEnv(env, origins, assertion); err != nil {
+ return nil, fmt.Errorf("the generated set fails Home's own loaders: %w", err)
+ }
+ return env, nil
+}
+
+// distinctTeamMACs: Home refuses an all-zero MAC key; the two roles' keys
+// differ by construction (§5: "All must be distinct").
+func distinctTeamMACs(credential, directory []byte) error {
+ zero := make([]byte, 32)
+ if len(credential) != 32 || len(directory) != 32 || bytes.Equal(credential, zero) || bytes.Equal(directory, zero) {
+ return errors.New("a MAC key is not 32 non-zero bytes")
+ }
+ if bytes.Equal(credential, directory) {
+ return errors.New("the credential and directory MAC keys are equal")
+ }
+ return nil
+}
+
+// withTeamEnv runs f with exactly vars set among teamLoaderVars, then
+// restores the environment. The loaders read os.Getenv; this is how a
+// check reaches them unchanged. Not safe for concurrent use.
+func withTeamEnv(vars map[string]string, f func() error) error {
+ saved := map[string]string{}
+ for _, name := range teamLoaderVars {
+ if v, ok := os.LookupEnv(name); ok {
+ saved[name] = v
+ }
+ os.Unsetenv(name)
+ }
+ defer func() {
+ for _, name := range teamLoaderVars {
+ os.Unsetenv(name)
+ if v, ok := saved[name]; ok {
+ os.Setenv(name, v)
+ }
+ }
+ }()
+ for name, value := range vars {
+ if !slices.Contains(teamLoaderVars, name) {
+ return errors.New("not a variable Home's team loaders read")
+ }
+ os.Setenv(name, value)
+ }
+ return f()
+}
+
+// publicSigner is a Keypair carrying only the assertion key's public half:
+// all the loaders read of Runtime.signer is SignPub.
+func publicSigner(pub []byte) (*family.Keypair, error) {
+ x, y := elliptic.Unmarshal(elliptic.P256(), pub)
+ if x == nil {
+ return nil, errExchangeConfig
+ }
+ return &family.Keypair{SignPriv: &ecdsa.PrivateKey{PublicKey: ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y}}}, nil
+}
+
+// loadTeamRole is LoadRuntime's tail for one role, in its order, and
+// requires every team feature on. NewRuntime's re-checks of these
+// (roster.valid, validResolveKeys) are the ones the two loaders already
+// applied; the tests boot through NewRuntime itself.
+func loadTeamRole(cfg *Runtime) error {
+ var err error
+ rosterKeys := cfg.keys
+ if cfg.role != "directory" {
+ rosterKeys = nil
+ }
+ if cfg.roster, err = loadRosterRuntime(cfg.role, rosterKeys); err != nil {
+ return fmt.Errorf("%s role: Home refuses HOME_ROSTER_MODE/HOME_ROSTER_KEY", cfg.role)
+ }
+ if err = loadResolveKeys(cfg); err != nil {
+ return fmt.Errorf("%s role: Home refuses the member-resolution key", cfg.role)
+ }
+ if err = loadOperatorHTTP(cfg); err != nil {
+ return fmt.Errorf("%s role: Home refuses HOME_OPERATOR_HTTP with this HOME_OPERATOR_MATERIAL (format, pins, or two equal keys)", cfg.role)
+ }
+ if cfg.operator == nil {
+ return fmt.Errorf("%s role: the operator endpoint would be off", cfg.role)
+ }
+ if cfg.role == "credential" && cfg.resolveSigner == nil {
+ return errors.New("credential role: no member-resolution key")
+ }
+ if cfg.role == "directory" && (cfg.roster.mode != "serve" || cfg.resolvePublic == nil) {
+ return errors.New("directory role: the roster endpoint or member resolution would be off")
+ }
+ return nil
+}
+
+// checkTeamRole loads one role's variables through Home's loaders. The
+// credential role is checked once per assertion key, as its signer: the
+// check passes whichever key the credential holds.
+func checkTeamRole(role string, vars map[string]string, origins Origins, assertion map[string][]byte) (Runtime, error) {
+ var out Runtime
+ err := withTeamEnv(vars, func() error {
+ if role == "directory" {
+ out = Runtime{role: role, origins: origins, keys: assertion}
+ return loadTeamRole(&out)
+ }
+ for _, k := range assertionTeamKeys(assertion) {
+ signer, err := publicSigner(k.key)
+ if err != nil {
+ return err
+ }
+ sum := sha256.Sum256(k.key)
+ kid := hex.EncodeToString(sum[:])
+ out = Runtime{role: role, origins: origins, signer: signer, keyID: kid, keys: map[string][]byte{kid: k.key}}
+ if err := loadTeamRole(&out); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ return out, err
+}
+
+// checkTeamEnv confirms both roles boot with env, and that the roles agree
+// with each other (and with Alta's section, when present).
+func checkTeamEnv(env teamEnv, origins Origins, assertion map[string][]byte) error {
+ for _, section := range teamSectionOrder {
+ vars, ok := env[section]
+ if !ok && section == teamAltaEnv {
+ continue
+ }
+ if !ok {
+ return fmt.Errorf("no [%s] section", section)
+ }
+ for _, name := range teamSectionVars[section] {
+ if _, ok := vars[name]; !ok {
+ return fmt.Errorf("[%s] lacks %s", section, name)
+ }
+ }
+ if len(vars) != len(teamSectionVars[section]) {
+ return fmt.Errorf("[%s] holds a variable it does not take", section)
+ }
+ }
+ for section := range env {
+ if _, ok := teamSectionVars[section]; !ok {
+ return errors.New("an unknown section")
+ }
+ }
+ cred, err := checkTeamRole("credential", env.role("credential"), origins, assertion)
+ if err != nil {
+ return err
+ }
+ dir, err := checkTeamRole("directory", env.role("directory"), origins, assertion)
+ if err != nil {
+ return err
+ }
+
+ c, d := cred.operator.config, dir.operator.config
+ 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 {
+ return errors.New("the two roles pin different Alta keysets")
+ }
+ if c.OperatorSubject != d.OperatorSubject {
+ return errors.New("the two roles name different operator_subjects")
+ }
+ var dm directoryOperatorMaterial
+ raw, err := base64.StdEncoding.Strict().DecodeString(env[teamDirectorySecrets]["HOME_OPERATOR_MATERIAL_BASE64"])
+ if err != nil || json.Unmarshal(raw, &dm, json.RejectUnknownMembers(true)) != nil {
+ return errors.New("directory role: HOME_OPERATOR_MATERIAL_BASE64 is unreadable")
+ }
+ if dm.Owner != rawURL(cred.operator.owner.SignPub()) {
+ return errors.New("the directory's owner_seed_public is not the credential's owner-seed key")
+ }
+ if c.DirectoryProvisioningPublicKey != rawURL(dir.operator.provisioning.SignPub()) {
+ return errors.New("the credential's directory_provisioning_public_key is not the directory's provisioning key")
+ }
+ if !bytes.Equal(dir.resolvePublic, cred.resolveSigner.SignPub()) {
+ return errors.New("HOME_RESOLVE_PUBLIC_KEY is not HOME_RESOLVE_KEY's public half")
+ }
+ if err := distinctTeamMACs(cred.operator.mac, dir.operator.mac); err != nil {
+ return err
+ }
+ // No union check of the keys here: with the cross-checks above, the
+ // directory's own distinct set (Alta, owner-seed, provisioning, every
+ // assertion key, the roster keys, resolve) already is the union of both
+ // roles', and loadOperatorHTTP refused any equality in it.
+ if a, ok := env[teamAltaEnv]; ok {
+ if a["ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY"] != c.DirectoryProvisioningPublicKey {
+ return errors.New("[alta env] ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY is not the directory's provisioning key")
+ }
+ if a["ALTA_OPERATOR_SUBJECT"] != c.OperatorSubject {
+ return errors.New("[alta env] ALTA_OPERATOR_SUBJECT is not operator_subject")
+ }
+ }
+ return nil
+}
+
+// parseTeamEnv reads the format writeTeamEnv prints. Like the Alta parser,
+// its errors never quote a line.
+func parseTeamEnv(r io.Reader) (teamEnv, error) {
+ env := teamEnv{}
+ section := ""
+ sc := bufio.NewScanner(r)
+ sc.Buffer(make([]byte, 0, 64<<10), 64<<10)
+ for n := 1; sc.Scan(); n++ {
+ line := strings.TrimRight(sc.Text(), "\r")
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ name := line[1 : len(line)-1]
+ if _, ok := teamSectionVars[name]; !ok || env[name] != nil {
+ return nil, fmt.Errorf("line %d: an unknown or repeated section", n)
+ }
+ env[name], section = map[string]string{}, name
+ continue
+ }
+ name, value, ok := strings.Cut(line, "=")
+ if !ok || section == "" || !slices.Contains(teamSectionVars[section], name) {
+ return nil, fmt.Errorf("line %d: not a variable this section takes", n)
+ }
+ if _, dup := env[section][name]; dup {
+ return nil, fmt.Errorf("line %d: %s twice in [%s]", n, name, section)
+ }
+ env[section][name] = value
+ }
+ if sc.Err() != nil {
+ return nil, errors.New("unreadable (a line over 64 KiB?)")
+ }
+ return env, nil
+}
+
+// writeTeamEnv prints env in its section order, each section headed with
+// the one carlos call it is.
+func writeTeamEnv(w io.Writer, env teamEnv, origins Origins, keyID, subject string) error {
+ production := origins == Origins{Origin, directoryOrigin}
+ app := map[string]string{"credential": "<the credential role's app>", "directory": "<the directory role's app>", "alta": "alta"}
+ if production {
+ app["credential"], app["directory"] = "oficina-id", "oficina"
+ }
+ notes := map[string][]string{
+ teamCredentialSecrets: {
+ "Credential role, " + origins.Credential + ". Step 1, one call:",
+ " carlos secrets set --account oficina --app " + app["credential"] + " <these lines>",
+ "Inert until step 2: Home reads the material only beside HOME_OPERATOR_HTTP.",
+ },
+ teamCredentialEnv: {
+ "Step 2, one call, in which HOME_CONSUMERS_BASE64 also gains \"alta\" (not generated here):",
+ " carlos env set --account oficina --app " + app["credential"] + " <these lines> HOME_CONSUMERS_BASE64=…",
+ "Then restart the role and sign in to one app end to end.",
+ },
+ teamDirectorySecrets: {
+ "Directory role, " + origins.Directory + ". Step 3, one call (mode and key together):",
+ " carlos secrets set --account oficina --app " + app["directory"] + " <these lines>",
+ },
+ teamDirectoryEnv: {
+ "Step 4, one call, last:",
+ " carlos env set --account oficina --app " + app["directory"] + " <these lines>",
+ },
+ teamAltaEnv: {
+ "Alta, to match, in one call with ALTA_HOME_CONSUMER_ID=alta, ALTA_ORIGIN (equal to the",
+ "\"alta\" entry of the credential's HOME_CONSUMERS) and HOME_DIRECTORY_ORIGIN=" + origins.Directory + ",",
+ "beside alta keygen's own lines:",
+ " carlos env set --account oficina --app alta <these lines> ALTA_HOME_CONSUMER_ID=alta ALTA_ORIGIN=… HOME_DIRECTORY_ORIGIN=" + origins.Directory,
+ },
+ }
+ var b strings.Builder
+ b.WriteString("# home team-keygen: team-provisioning keys for both Home roles (oficina/home #101 §5).\n")
+ b.WriteString("# PRIVATE KEYS. Keep this at mode 0600 and delete it once every value is set.\n")
+ b.WriteString("# Alta key_id " + keyID + "; operator_subject " + subject + "\n")
+ b.WriteString("# Re-check before setting: home team-keygen -check -assertion-keys '<HOME_ASSERTION_KEYS>' <this file>\n")
+ for _, section := range teamSectionOrder {
+ vars, ok := env[section]
+ if !ok {
+ continue
+ }
+ b.WriteString("\n")
+ for _, note := range notes[section] {
+ b.WriteString("# " + note + "\n")
+ }
+ b.WriteString("[" + section + "]\n")
+ for _, name := range teamSectionVars[section] {
+ b.WriteString(name + "=" + vars[name] + "\n")
+ }
+ }
+ _, err := io.WriteString(w, b.String())
+ return err
+}
+
+func openTeamInput(path string, stdin io.Reader) (io.ReadCloser, error) {
+ if path == "-" {
+ return io.NopCloser(stdin), nil
+ }
+ return os.Open(path)
+}
+
+// writeTeamFile creates path (refusing one that exists) at mode 0600.
+func writeTeamFile(path string, write func(io.Writer) error) error {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return errors.New("-out: cannot create the file (it must not exist yet)")
+ }
+ if err = f.Chmod(0o600); err == nil {
+ err = write(f)
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ os.Remove(path)
+ return errors.New("-out: could not write the file; nothing was kept")
+ }
+ return nil
+}
+
+const teamKeygenUsage = `usage:
+ home team-keygen -alta FILE -subject pr_… -assertion-keys MANIFEST [-out FILE]
+ home team-keygen -check -assertion-keys MANIFEST FILE
+
+Generates fresh team-provisioning material for both Home roles from alta
+keygen's output (FILE, or - for stdin), and prints each role's env set,
+one [section] per carlos call. -assertion-keys is the directory's
+HOME_ASSERTION_KEYS (its JSON, or HOME_ASSERTION_KEYS_BASE64's value).
+Secrets go to stdout, or with -out to a new file at mode 0600.
+
+-check loads a set this command printed through Home's own loaders and
+confirms both roles would boot with it.
+
+flags:
+`
+
+// RunTeamKeygen is `home team-keygen`. 0: done; 1: refused; 2: usage.
+func RunTeamKeygen(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
+ fs := flag.NewFlagSet("home team-keygen", flag.ContinueOnError)
+ fs.SetOutput(stderr)
+ fs.Usage = func() { fmt.Fprint(stderr, teamKeygenUsage); fs.PrintDefaults() }
+ altaPath := fs.String("alta", "", "alta keygen's output: a file, or - for stdin")
+ subject := fs.String("subject", "", "operator_subject: Paul's person ref (pr_ and 26 base32); required")
+ assertionRaw := fs.String("assertion-keys", "", "the directory's HOME_ASSERTION_KEYS, JSON or its _BASE64 value; required")
+ out := fs.String("out", "", "write the env set to this new file at mode 0600, not stdout")
+ check := fs.Bool("check", false, "check the env set in the file named after the flags (or -)")
+ credentialOrigin := fs.String("credential-origin", Origin, "the credential role's origin")
+ dirOrigin := fs.String("directory-origin", directoryOrigin, "the directory role's origin")
+ if fs.Parse(args) != nil {
+ return 2
+ }
+ refuse := func(code int, err error) int {
+ fmt.Fprintln(stderr, "home team-keygen:", err)
+ return code
+ }
+ origins := Origins{*credentialOrigin, *dirOrigin}
+ if origins.validate() != nil {
+ return refuse(2, errors.New("-credential-origin/-directory-origin are not a valid pair of Home origins"))
+ }
+ if *assertionRaw == "" {
+ return refuse(2, errors.New("-assertion-keys is required"))
+ }
+ assertion, err := parseTeamAssertionKeys(*assertionRaw, origins)
+ if err != nil {
+ return refuse(1, err)
+ }
+
+ if *check {
+ if fs.NArg() != 1 || *altaPath != "" || *subject != "" || *out != "" {
+ return refuse(2, errors.New("-check takes -assertion-keys, optional origins, and one file"))
+ }
+ in, err := openTeamInput(fs.Arg(0), stdin)
+ if err != nil {
+ return refuse(1, errors.New("cannot open the env set"))
+ }
+ env, err := parseTeamEnv(in)
+ in.Close()
+ if err == nil {
+ err = checkTeamEnv(env, origins, assertion)
+ }
+ if err != nil {
+ return refuse(1, fmt.Errorf("check failed: %w", err))
+ }
+ fmt.Fprintln(stdout, "ok: both roles boot with this set (credential "+origins.Credential+", directory "+origins.Directory+"), and the roles agree")
+ return 0
+ }
+
+ if fs.NArg() != 0 || *altaPath == "" || *subject == "" {
+ return refuse(2, errors.New("-alta, -subject and -assertion-keys are required"))
+ }
+ in, err := openTeamInput(*altaPath, stdin)
+ if err != nil {
+ return refuse(1, errors.New("cannot open -alta"))
+ }
+ ks, err := parseAltaKeygen(in)
+ in.Close()
+ if err != nil {
+ return refuse(1, err)
+ }
+ env, err := generateTeamEnv(ks, origins, *subject, assertion, defaultTeamKeySource())
+ if err != nil {
+ return refuse(1, err)
+ }
+ write := func(w io.Writer) error { return writeTeamEnv(w, env, origins, ks.pins["credential"].KeyID, *subject) }
+ if *out == "" {
+ if write(stdout) != nil {
+ return refuse(1, errors.New("could not write stdout"))
+ }
+ return 0
+ }
+ if err := writeTeamFile(*out, write); err != nil {
+ return refuse(1, err)
+ }
+ fmt.Fprintln(stdout, "wrote", *out, "(mode 0600); check it with: home team-keygen -check -assertion-keys '<HOME_ASSERTION_KEYS>'", *out)
+ return 0
+}
diff --git a/internal/home/team_keygen_test.go b/internal/home/team_keygen_test.go
new file mode 100644
index 0000000..87016c2
--- /dev/null
+++ b/internal/home/team_keygen_test.go
@@ -0,0 +1,833 @@
+package home
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ stdjson "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/home/roster"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ json "github.com/go-json-experiment/json"
+)
+
+const teamSubject = "pr_abcdefghijklmnopqrstuvwxyz"
+
+// altaKeygen is what `alta keygen` prints (oficina/alta cmd/alta/main.go,
+// keygen at f78d993), reproduced line for line: Alta is its own module and
+// imports this one, so the test cannot call it. The fixture
+// testdata/alta-keygen-f78d993.txt is the real command's output.
+type altaKeygen struct {
+ key *family.Keypair
+ prefilter string
+ text string
+}
+
+func newAltaKeygen(t *testing.T) altaKeygen {
+ t.Helper()
+ k, err := family.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ token := func() string {
+ b := make([]byte, 32)
+ rand.Read(b)
+ return base64.RawURLEncoding.EncodeToString(b)
+ }
+ prefilter := token()
+ pre, _ := base64.RawURLEncoding.DecodeString(prefilter)
+ sum := sha256.Sum256(pre)
+ pub := base64.RawURLEncoding.EncodeToString(k.SignPub())
+ inst, reg, dev := token(), token(), token()
+ var w strings.Builder
+ fmt.Fprintln(&w, "# Alta's secrets (carlos secrets set --app alta):")
+ fmt.Fprintf(&w, "ALTA_OPERATOR_KEY=%s\nALTA_OPERATOR_PREFILTER=%s\nALTA_DEK=%s\n", encodedKeypair(t, k), prefilter, base64.StdEncoding.EncodeToString(pre))
+ fmt.Fprintln(&w, "# Alta's pins (carlos env set --app alta):")
+ fmt.Fprintf(&w, "ALTA_OPERATOR_INSTALLATION=%s\nALTA_OPERATOR_REGISTRY=%s\nALTA_OPERATOR_DEVICE=%s\n", inst, reg, dev)
+ for _, role := range []struct{ name, origin string }{{"directory", "https://oficina.works"}, {"credential", "https://id.oficina.works"}} {
+ actions := []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"}
+ if role.name == "credential" {
+ actions = []string{"credential.inspect", "credential.owner-seed", "credential.register-consumer", "credential.retire-consumer"}
+ }
+ cfg := map[string]any{"version": 1, "role": role.name, "origin": role.origin, "installation": inst, "registry": reg, "device": dev,
+ "public_key": pub, "key_id": hexID(k), "actions": actions, "operator_subject": "<Paul's person ref>",
+ "prefilter_token_sha256": hex.EncodeToString(sum[:])}
+ if role.name == "credential" {
+ cfg["directory_provisioning_public_key"] = "<the directory's provisioning public key>"
+ }
+ b, _ := stdjson.Marshal(cfg)
+ fmt.Fprintf(&w, "# HOME_OPERATOR_HTTP for the %s role:\n%s\n", role.name, b)
+ }
+ return altaKeygen{key: k, prefilter: prefilter, text: w.String()}
+}
+
+// teamWorld is one Home's existing assertion key, as runtimeEnv sets it up.
+type teamWorld struct {
+ assertionPrivate string // HOME_ASSERTION_KEY
+ manifest string // HOME_ASSERTION_KEYS
+ assertion map[string][]byte
+ assertionKey *family.Keypair
+}
+
+func newTeamWorld(t *testing.T) teamWorld {
+ t.Helper()
+ private, manifest := runtimeEnv(t)
+ clearTeamVars(t)
+ keys, err := parseTeamAssertionKeys(manifest, Origins{Origin, directoryOrigin})
+ if err != nil {
+ t.Fatal(err)
+ }
+ k, err := decodeHomeKeypair(private)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return teamWorld{private, manifest, keys, k}
+}
+
+// clearTeamVars unsets (not merely empties: the roster loader reads
+// presence) every variable the team loaders read, for this test.
+func clearTeamVars(t *testing.T) {
+ t.Helper()
+ for _, k := range append([]string{"HOME_DASHBOARD_TEAMS", "HOME_DASHBOARD_TEAMS_BASE64"}, teamLoaderVars...) {
+ t.Setenv(k, "")
+ os.Unsetenv(k)
+ }
+}
+
+func runTeamKeygen(t *testing.T, stdin string, args ...string) (string, string, int) {
+ t.Helper()
+ var out, errOut bytes.Buffer
+ code := RunTeamKeygen(args, strings.NewReader(stdin), &out, &errOut)
+ return out.String(), errOut.String(), code
+}
+
+func (w teamWorld) generate(t *testing.T, alta string, extra ...string) teamEnv {
+ t.Helper()
+ out, errOut, code := runTeamKeygen(t, alta, append([]string{"-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest}, extra...)...)
+ if code != 0 || errOut != "" {
+ t.Fatalf("team-keygen refused: %d %s", code, errOut)
+ }
+ env, err := parseTeamEnv(strings.NewReader(out))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return env
+}
+
+// boot is the real thing: LoadRuntime from the environment, the serving
+// schema on a fresh database, NewRuntime, for one role, with that role's
+// generated variables set exactly as carlos would set them.
+func (w teamWorld) boot(t *testing.T, role string, env teamEnv) *App {
+ t.Helper()
+ clearTeamVars(t)
+ t.Setenv("HOME_ROLE", role)
+ if role == "credential" {
+ t.Setenv("HOME_ASSERTION_KEY", w.assertionPrivate)
+ t.Setenv("HOME_ASSERTION_KEYS", "")
+ t.Setenv("HOME_CONSUMERS", `{"directory":"`+os.Getenv("HOME_DIRECTORY_ORIGIN")+`","docs":"https://docs.oficina.works","alta":"https://alta.bds.oncarlos.com"}`)
+ } else {
+ t.Setenv("HOME_ASSERTION_KEY", "")
+ t.Setenv("HOME_ASSERTION_KEYS", w.manifest)
+ t.Setenv("HOME_CONSUMERS", "")
+ }
+ for name, value := range env.role(role) {
+ t.Setenv(name, value)
+ }
+ path := filepath.Join(t.TempDir(), role+".db")
+ cfg, err := LoadRuntime(path, quietLogger())
+ if err != nil {
+ t.Fatalf("%s: LoadRuntime refused the generated set: %v", role, err)
+ }
+ RegisterSecureDelete()
+ d, err := db.Open(path, quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ if _, err = migrate.Apply(context.Background(), d, cfg.ServingSchema()); err != nil {
+ t.Fatal(err)
+ }
+ app, err := NewRuntime(cfg, d, quietLogger())
+ if err != nil {
+ t.Fatalf("%s: NewRuntime refused the generated set: %v", role, err)
+ }
+ if app.op == nil || app.runtime == nil || app.runtime.operator == nil {
+ t.Fatalf("%s: operator endpoint not mounted", role)
+ }
+ if role == "credential" && app.runtime.resolveSigner == nil {
+ t.Fatal("credential: member resolution off")
+ }
+ if role == "directory" && (app.runtime.roster.mode != "serve" || app.runtime.resolvePublic == nil) {
+ t.Fatal("directory: roster or member resolution off")
+ }
+ return app
+}
+
+func teamPrivateValues(env teamEnv) []string {
+ var v []string
+ for _, section := range []string{teamCredentialSecrets, teamDirectorySecrets} {
+ for name, value := range env[section] {
+ if name != "HOME_ROSTER_MODE" {
+ v = append(v, value)
+ }
+ }
+ }
+ return v
+}
+
+func TestTeamKeygenOutputBootsBothRoles(t *testing.T) {
+ w := newTeamWorld(t)
+ alta := newAltaKeygen(t)
+ out, errOut, code := runTeamKeygen(t, alta.text, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest)
+ if code != 0 || errOut != "" {
+ t.Fatal("refused", code, errOut)
+ }
+ env, err := parseTeamEnv(strings.NewReader(out))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // One [section] per carlos call, in the order §5 applies them.
+ var order []string
+ for _, m := range regexp.MustCompile(`(?m)^\[(.+)\]$`).FindAllStringSubmatch(out, -1) {
+ order = append(order, m[1])
+ }
+ if strings.Join(order, ",") != strings.Join(teamSectionOrder, ",") {
+ t.Fatal("section order", order)
+ }
+ if !strings.Contains(out, "carlos secrets set --account oficina --app oficina-id") || !strings.Contains(out, "carlos env set --account oficina --app oficina ") {
+ t.Fatal("production app names missing")
+ }
+ cred := w.boot(t, "credential", env)
+ dir := w.boot(t, "directory", env)
+
+ // The roles agree, and Alta's pins came through untouched.
+ c, d := cred.runtime.operator.config, dir.runtime.operator.config
+ if c.PublicKey != rawURLPub(alta.key) || d.PublicKey != c.PublicKey || c.OperatorSubject != teamSubject || d.OperatorSubject != teamSubject {
+ t.Fatal("alta pins or subject")
+ }
+ if c.DirectoryProvisioningPublicKey != rawURLPub(dir.runtime.operator.provisioning) || env[teamAltaEnv]["ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY"] != c.DirectoryProvisioningPublicKey {
+ t.Fatal("provisioning key not pinned on the credential and Alta")
+ }
+ if !bytes.Equal(dir.runtime.resolvePublic, cred.runtime.resolveSigner.SignPub()) {
+ t.Fatal("resolve pair")
+ }
+ if len(dir.runtime.operator.rosterKeys) != 1 || dir.runtime.operator.rosterKeys[0].ID != dir.runtime.roster.keyID {
+ t.Fatal("roster_keys does not hold HOME_ROSTER_KEY")
+ }
+ if bytes.Equal(cred.runtime.operator.mac, dir.runtime.operator.mac) {
+ t.Fatal("the roles share a MAC key")
+ }
+
+ // -check accepts what it printed, on stdin and from a file.
+ if o, e, code := runTeamKeygen(t, out, "-check", "-assertion-keys", w.manifest, "-"); code != 0 || e != "" || !strings.HasPrefix(o, "ok: ") {
+ t.Fatal("check refused the generated set", code, e)
+ }
+ path := filepath.Join(t.TempDir(), "set.env")
+ os.WriteFile(path, []byte(out), 0o600)
+ if _, e, code := runTeamKeygen(t, "", "-check", "-assertion-keys", base64.StdEncoding.EncodeToString([]byte(w.manifest)), path); code != 0 {
+ t.Fatal("check refused the _BASE64 manifest form", e)
+ }
+ // Two runs never share a key.
+ again := w.generate(t, alta.text)
+ for _, v := range teamPrivateValues(env) {
+ for _, u := range teamPrivateValues(again) {
+ if v == u {
+ t.Fatal("a private value repeated across runs")
+ }
+ }
+ }
+}
+
+func TestTeamKeygenRoundTripsTheRealAltaKeygen(t *testing.T) {
+ w := newTeamWorld(t)
+ fixture, err := os.ReadFile("testdata/alta-keygen-f78d993.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ks, err := parseAltaKeygen(bytes.NewReader(fixture))
+ if err != nil {
+ t.Fatal(err)
+ }
+ env := w.generate(t, string(fixture))
+ cred := w.boot(t, "credential", env)
+ dir := w.boot(t, "directory", env)
+ for role, app := range map[string]*App{"credential": cred, "directory": dir} {
+ got, want := app.runtime.operator.config, ks.pins[role]
+ want.OperatorSubject = teamSubject
+ if role == "credential" {
+ want.DirectoryProvisioningPublicKey = rawURLPub(dir.runtime.operator.provisioning)
+ }
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Fatalf("%s: HOME_OPERATOR_HTTP is not alta keygen's line, filled in:\n got %v\nwant %v", role, got, want)
+ }
+ }
+ if ks.pins["credential"].PublicKey != "BPWEusn8TdzIQYri5RHHXVldAfLM-hPOPGJwY4A44Ay0PYEghbDdwH45X55hE5v0c1_EZ9RLrFgPskj5C2iurbM" {
+ t.Fatal("fixture changed")
+ }
+}
+
+// editAlta rewrites one role's HOME_OPERATOR_HTTP line in alta keygen output.
+func editAlta(t *testing.T, text, role string, edit func(map[string]any)) string {
+ t.Helper()
+ lines := strings.Split(text, "\n")
+ for i, l := range lines {
+ if l == "# HOME_OPERATOR_HTTP for the "+role+" role:" {
+ var m map[string]any
+ if err := stdjson.Unmarshal([]byte(lines[i+1]), &m); err != nil {
+ t.Fatal(err)
+ }
+ edit(m)
+ b, _ := stdjson.Marshal(m)
+ lines[i+1] = string(b)
+ return strings.Join(lines, "\n")
+ }
+ }
+ t.Fatal("no line for", role)
+ return ""
+}
+
+func replaceVar(text, name, value string) string {
+ return regexp.MustCompile(`(?m)^`+name+`=.*$`).ReplaceAllString(text, name+"="+value)
+}
+
+func TestTeamKeygenRefusesBadAltaPins(t *testing.T) {
+ w := newTeamWorld(t)
+ alta := newAltaKeygen(t)
+ other := newAltaKeygen(t)
+ both := func(edit func(map[string]any)) string {
+ return editAlta(t, editAlta(t, alta.text, "credential", edit), "directory", edit)
+ }
+ assertionPub := base64.RawURLEncoding.EncodeToString(w.assertionKey.SignPub())
+ sum := sha256.Sum256(w.assertionKey.SignPub())
+ notOnCurve := base64.RawURLEncoding.EncodeToString(append([]byte{4}, bytes.Repeat([]byte{1}, 64)...))
+ cases := map[string]string{
+ "key_id": both(func(m map[string]any) { m["key_id"] = strings.Repeat("0", 64) }),
+ "public_key off curve": both(func(m map[string]any) { m["public_key"] = notOnCurve }),
+ "public_key padded": both(func(m map[string]any) { m["public_key"] = m["public_key"].(string) + "=" }),
+ "alta is assertion key": replaceVar(both(func(m map[string]any) { m["public_key"], m["key_id"] = assertionPub, hex.EncodeToString(sum[:]) }), "ALTA_OPERATOR_KEY", w.assertionPrivate),
+ "prefilter not hex": both(func(m map[string]any) { m["prefilter_token_sha256"] = strings.Repeat("Z", 64) }),
+ "prefilter short": both(func(m map[string]any) { m["prefilter_token_sha256"] = "abcd" }),
+ "credential origin": editAlta(t, alta.text, "credential", func(m map[string]any) { m["origin"] = "https://id.example.com" }),
+ "directory origin": editAlta(t, alta.text, "directory", func(m map[string]any) { m["origin"] = Origin }),
+ "role swapped": editAlta(t, alta.text, "credential", func(m map[string]any) { m["role"] = "directory" }),
+ "version": both(func(m map[string]any) { m["version"] = 2 }),
+ "unknown field": both(func(m map[string]any) { m["extra"] = 1 }),
+ "no inspect": editAlta(t, alta.text, "credential", func(m map[string]any) { m["actions"] = []string{"credential.owner-seed"} }),
+ "foreign verb": editAlta(t, alta.text, "credential", func(m map[string]any) { m["actions"] = []string{"credential.inspect", "directory.seed-team"} }),
+ "repeated verb": editAlta(t, alta.text, "directory", func(m map[string]any) { m["actions"] = []string{"directory.inspect", "directory.inspect"} }),
+ "installation not token": both(func(m map[string]any) { m["installation"] = "short" }),
+ "roles from two runs": editAlta(t, alta.text, "directory", func(m map[string]any) {
+ m["device"] = strings.Split(strings.Split(other.text, "ALTA_OPERATOR_DEVICE=")[1], "\n")[0]
+ }),
+ "subject prefilled": both(func(m map[string]any) { m["operator_subject"] = "pr_zzzzzzzzzzzzzzzzzzzzzzzzzz" }),
+ "provisioning prefilled": editAlta(t, alta.text, "credential", func(m map[string]any) { m["directory_provisioning_public_key"] = rawURLPub(other.key) }),
+ "directory provisioning": editAlta(t, alta.text, "directory", func(m map[string]any) {
+ m["directory_provisioning_public_key"] = "<the directory's provisioning public key>"
+ }),
+ "ALTA_OPERATOR_KEY other": replaceVar(alta.text, "ALTA_OPERATOR_KEY", encodedKeypair(t, other.key)),
+ "ALTA_OPERATOR_PREFILTER": replaceVar(alta.text, "ALTA_OPERATOR_PREFILTER", other.prefilter),
+ "ALTA_OPERATOR_DEVICE": replaceVar(alta.text, "ALTA_OPERATOR_DEVICE", fixtureToken(9)),
+ "no credential line": strings.Split(alta.text, "# HOME_OPERATOR_HTTP for the credential role:")[0],
+ "header without JSON": strings.Split(alta.text, "# HOME_OPERATOR_HTTP for the credential role:")[0] + "# HOME_OPERATOR_HTTP for the credential role:\n",
+ "stray line": alta.text + "something else\n",
+ "repeated var": alta.text + "ALTA_OPERATOR_DEVICE=" + fixtureToken(9) + "\n",
+ "empty": "",
+ }
+ // Each pin both roles share, differing on one role alone.
+ otherCredential := ks(t, other.text).pins["credential"]
+ for field, value := range map[string]string{"installation": otherCredential.Installation, "registry": otherCredential.Registry, "device": otherCredential.Device, "prefilter_token_sha256": otherCredential.PrefilterSHA256} {
+ cases["two runs: "+field] = editAlta(t, alta.text, "directory", func(m map[string]any) { m[field] = value })
+ }
+ cases["two runs: public_key"] = editAlta(t, alta.text, "directory", func(m map[string]any) {
+ m["public_key"], m["key_id"] = otherCredential.PublicKey, otherCredential.KeyID
+ })
+ // Why each is refused: the rule that fires, not merely some rule.
+ want := map[string]string{
+ "key_id": "key_id is not sha256(public_key)", "public_key off curve": "not a canonical P-256 point", "public_key padded": "not a canonical P-256 point",
+ "alta is assertion key": "equals Alta's operator key", "prefilter not hex": "not 64 lowercase hex", "prefilter short": "not 64 lowercase hex",
+ "credential origin": "the credential origin is", "directory origin": "the directory origin is", "role swapped": "not a version-1 config",
+ "version": "not a version-1 config", "unknown field": "is not its closed JSON", "no inspect": "lack credential.inspect",
+ "foreign verb": "verifier refuses the credential pins", "repeated verb": "verifier refuses the directory pins", "installation not token": "verifier refuses",
+ "roles from two runs": "different alta keygen runs", "subject prefilled": "operator_subject is already set", "provisioning prefilled": "already filled",
+ "directory provisioning": "takes no directory_provisioning_public_key", "ALTA_OPERATOR_KEY other": "ALTA_OPERATOR_KEY's public half",
+ "ALTA_OPERATOR_PREFILTER": "sha256(ALTA_OPERATOR_PREFILTER)", "ALTA_OPERATOR_DEVICE": "ALTA_OPERATOR_DEVICE is not the value pinned",
+ "no credential line": "no HOME_OPERATOR_HTTP for the credential role", "header without JSON": "has no JSON after it", "stray line": "not a line alta keygen prints",
+ "repeated var": "ALTA_OPERATOR_DEVICE twice", "empty": "no HOME_OPERATOR_HTTP",
+ "two runs: installation": "different alta keygen runs", "two runs: registry": "different alta keygen runs", "two runs: device": "different alta keygen runs",
+ "two runs: prefilter_token_sha256": "different alta keygen runs", "two runs: public_key": "different alta keygen runs",
+ }
+ for name, text := range cases {
+ out, errOut, code := runTeamKeygen(t, text, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest)
+ if code != 1 || out != "" || want[name] == "" || !strings.Contains(errOut, want[name]) {
+ t.Errorf("%s: accepted (%d), printed something, or refused for another reason: %q", name, code, errOut)
+ }
+ for _, secret := range []string{encodedKeypair(t, alta.key), alta.prefilter, encodedKeypair(t, other.key), w.assertionPrivate} {
+ if strings.Contains(errOut, secret) {
+ t.Errorf("%s: stderr carries a secret", name)
+ }
+ }
+ }
+ // The same pins, unedited, pass: the cases above fail for their edit.
+ if _, e, code := runTeamKeygen(t, alta.text, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest); code != 0 {
+ t.Fatal("baseline refused", e)
+ }
+ // Placeholders already filled with exactly what team-keygen writes are
+ // accepted (a re-run on edited output).
+ same := both(func(m map[string]any) { m["operator_subject"] = teamSubject })
+ if _, e, code := runTeamKeygen(t, same, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest); code != 0 {
+ t.Fatal("subject already set to -subject refused", e)
+ }
+ // Usage: each required input, and its form.
+ for name, args := range map[string][]string{
+ "no subject": {"-alta", "-", "-assertion-keys", w.manifest},
+ "no alta": {"-subject", teamSubject, "-assertion-keys", w.manifest},
+ "no manifest": {"-alta", "-", "-subject", teamSubject},
+ "bad origins": {"-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest, "-directory-origin", "http://x.example"},
+ "stray argument": {"-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest, "extra"},
+ } {
+ if out, _, code := runTeamKeygen(t, alta.text, args...); code != 2 || out != "" {
+ t.Errorf("%s: %d", name, code)
+ }
+ }
+ for name, args := range map[string][]string{
+ "bad subject": {"-alta", "-", "-subject", "paul", "-assertion-keys", w.manifest},
+ "manifest garbage": {"-alta", "-", "-subject", teamSubject, "-assertion-keys", "{nope"},
+ "manifest not key": {"-alta", "-", "-subject", teamSubject, "-assertion-keys", `{"k":"AAAA"}`},
+ "manifest base64ed": {"-alta", "-", "-subject", teamSubject, "-assertion-keys", "!!"},
+ } {
+ if out, _, code := runTeamKeygen(t, alta.text, args...); code != 1 || out != "" {
+ t.Errorf("%s: %d", name, code)
+ }
+ }
+}
+
+// namesPair: err is distinctTeamKeys's refusal naming a and b, either way round.
+func namesPair(err error, a, b string) bool {
+ const tail = "; Home refuses to boot with equal keys"
+ return err != nil && (err.Error() == a+" equals "+b+tail || err.Error() == b+" equals "+a+tail)
+}
+
+func ks(t *testing.T, text string) altaKeyset {
+ t.Helper()
+ k, err := parseAltaKeygen(strings.NewReader(text))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return k
+}
+
+// fixedKeys hands out the given keypairs in order, then fresh ones.
+func fixedKeys(keys ...*family.Keypair) func() (*family.Keypair, error) {
+ return func() (*family.Keypair, error) {
+ if len(keys) == 0 {
+ return family.Generate()
+ }
+ k := keys[0]
+ keys = keys[1:]
+ return k, nil
+ }
+}
+
+func TestTeamKeygenRefusesEveryEqualKeyPair(t *testing.T) {
+ w := newTeamWorld(t)
+ alta := newAltaKeygen(t)
+ ks, err := parseAltaKeygen(strings.NewReader(alta.text))
+ if err != nil {
+ t.Fatal(err)
+ }
+ origins := Origins{Origin, directoryOrigin}
+ fresh := func() *family.Keypair { k, _ := family.Generate(); return k }
+ names := []string{"the owner-seed key", "the directory provisioning key", "the roster key", "the member-resolution key"}
+ external := map[string]*family.Keypair{"Alta's operator key": alta.key, "assertion key " + hexID(w.assertionKey)[:12] + "…": w.assertionKey}
+ run := func(keys []*family.Keypair) error {
+ _, err := generateTeamEnv(ks, origins, teamSubject, w.assertion, teamKeySource{keypair: fixedKeys(keys...), random: defaultTeamKeySource().random})
+ return err
+ }
+ // Each generated key equal to Alta's key and to the assertion key.
+ for i, name := range names {
+ for other, k := range external {
+ keys := []*family.Keypair{fresh(), fresh(), fresh(), fresh()}
+ keys[i] = k
+ if err := run(keys); !namesPair(err, name, other) {
+ t.Errorf("%s = %s: not refused by name", name, other)
+ }
+ }
+ }
+ // Each pair of generated keys.
+ for i := range names {
+ for j := i + 1; j < len(names); j++ {
+ keys := []*family.Keypair{fresh(), fresh(), fresh(), fresh()}
+ keys[j] = keys[i]
+ if err := run(keys); !namesPair(err, names[i], names[j]) {
+ t.Errorf("%s = %s: %v", names[j], names[i], err)
+ }
+ }
+ }
+ // Two assertion keys, equal to each other under two ids: the directory
+ // refuses that too.
+ twice := map[string][]byte{"a": w.assertionKey.SignPub(), "b": w.assertionKey.SignPub()}
+ if _, err := generateTeamEnv(ks, origins, teamSubject, twice, defaultTeamKeySource()); err == nil || !strings.Contains(err.Error(), "equals assertion key") {
+ t.Error("duplicate assertion keys accepted", err)
+ }
+ // The MAC keys: equal, or all zero.
+ same := func(b []byte) error { copy(b, bytes.Repeat([]byte{5}, 32)); return nil }
+ calls := 0
+ firstZero := func(b []byte) error { // the credential's zero, the directory's not
+ calls++
+ if calls == 1 {
+ clear(b)
+ return nil
+ }
+ return defaultTeamKeySource().random(b)
+ }
+ for name, c := range map[string]struct {
+ random func([]byte) error
+ want string
+ }{"equal MACs": {same, "MAC keys are equal"}, "zero MAC": {firstZero, "not 32 non-zero bytes"}} {
+ _, err := generateTeamEnv(ks, origins, teamSubject, w.assertion, teamKeySource{keypair: family.Generate, random: c.random})
+ if err == nil || !strings.Contains(err.Error(), c.want) {
+ t.Error(name, "accepted, or refused for another reason:", err)
+ }
+ }
+ // A key the loaders refuse (not a valid keypair) never reaches output.
+ bad := fresh()
+ bad.SignPriv.D.SetInt64(0)
+ if err := run([]*family.Keypair{bad}); err == nil {
+ t.Error("an invalid generated key accepted")
+ }
+ // distinctTeamKeys on its own.
+ a, b := fresh().SignPub(), fresh().SignPub()
+ if distinctTeamKeys([]teamKey{{"a", a}, {"b", b}}) != nil || distinctTeamKeys([]teamKey{{"a", a}, {"b", a}}) == nil || distinctTeamKeys([]teamKey{{"a", nil}}) == nil {
+ t.Error("distinctTeamKeys")
+ }
+ if distinctTeamMACs(bytes.Repeat([]byte{1}, 32), bytes.Repeat([]byte{2}, 32)) != nil || distinctTeamMACs(bytes.Repeat([]byte{1}, 32), bytes.Repeat([]byte{1}, 32)) == nil {
+ t.Error("distinctTeamMACs")
+ }
+}
+
+// reencode edits a _BASE64 JSON value.
+func reencode(t *testing.T, value string, v any, edit func()) string {
+ t.Helper()
+ raw, err := base64.StdEncoding.DecodeString(value)
+ if err != nil || json.Unmarshal(raw, v) != nil {
+ t.Fatal("decode", err)
+ }
+ edit()
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return base64.StdEncoding.EncodeToString(b)
+}
+
+func cloneTeamEnv(env teamEnv) teamEnv {
+ c := teamEnv{}
+ for s, vars := range env {
+ c[s] = map[string]string{}
+ for k, v := range vars {
+ c[s][k] = v
+ }
+ }
+ return c
+}
+
+func TestTeamKeygenCheckRefusesSetsThatWouldNotBoot(t *testing.T) {
+ w := newTeamWorld(t)
+ alta := newAltaKeygen(t)
+ env := w.generate(t, alta.text)
+ second := w.generate(t, alta.text)
+ other := w.generate(t, newAltaKeygen(t).text)
+ cs, ce, ds, de, ae := teamCredentialSecrets, teamCredentialEnv, teamDirectorySecrets, teamDirectoryEnv, teamAltaEnv
+ keypair := func(section, name string, e teamEnv) *family.Keypair {
+ k, err := decodeHomeKeypair(e[section][name])
+ if err != nil {
+ t.Fatal(err)
+ }
+ return k
+ }
+ resolve := keypair(cs, "HOME_RESOLVE_KEY", env)
+ rosterKey := keypair(ds, "HOME_ROSTER_KEY", env)
+ edits := map[string]func(e teamEnv){
+ "owner-seed from another run": func(e teamEnv) { e[cs]["HOME_OPERATOR_MATERIAL_BASE64"] = second[cs]["HOME_OPERATOR_MATERIAL_BASE64"] },
+ "provisioning from another run": func(e teamEnv) { e[ds] = second[ds] },
+ "provisioning swapped alone": func(e teamEnv) {
+ var dm directoryOperatorMaterial
+ e[ds]["HOME_OPERATOR_MATERIAL_BASE64"] = reencode(t, e[ds]["HOME_OPERATOR_MATERIAL_BASE64"], &dm, func() {
+ k, _ := family.Generate()
+ dm.Provisioning = encodedKeypair(t, k)
+ })
+ },
+ "resolve key from another run": func(e teamEnv) { e[cs]["HOME_RESOLVE_KEY"] = second[cs]["HOME_RESOLVE_KEY"] },
+ "another Alta on one role": func(e teamEnv) { e[de]["HOME_OPERATOR_HTTP_BASE64"] = other[de]["HOME_OPERATOR_HTTP_BASE64"] },
+ "alta section from another run": func(e teamEnv) { e[ae] = second[ae] },
+ "alta subject": func(e teamEnv) { e[ae]["ALTA_OPERATOR_SUBJECT"] = "pr_zzzzzzzzzzzzzzzzzzzzzzzzzz" },
+ "roster mode disabled": func(e teamEnv) { e[ds]["HOME_ROSTER_MODE"] = "disabled" },
+ "roster key not in roster_keys": func(e teamEnv) { e[ds]["HOME_ROSTER_KEY"] = second[ds]["HOME_ROSTER_KEY"] },
+ "resolve public not a key": func(e teamEnv) { e[de]["HOME_RESOLVE_PUBLIC_KEY"] = "AAAA" },
+ "subject differs": func(e teamEnv) {
+ var c operatorHTTPConfig
+ e[de]["HOME_OPERATOR_HTTP_BASE64"] = reencode(t, e[de]["HOME_OPERATOR_HTTP_BASE64"], &c, func() { c.OperatorSubject = "pr_zzzzzzzzzzzzzzzzzzzzzzzzzz" })
+ },
+ "MAC keys equal": func(e teamEnv) {
+ var cm credentialOperatorMaterial
+ var dm directoryOperatorMaterial
+ raw, _ := base64.StdEncoding.DecodeString(e[cs]["HOME_OPERATOR_MATERIAL_BASE64"])
+ json.Unmarshal(raw, &cm)
+ e[ds]["HOME_OPERATOR_MATERIAL_BASE64"] = reencode(t, e[ds]["HOME_OPERATOR_MATERIAL_BASE64"], &dm, func() { dm.MAC = cm.MAC })
+ },
+ "roster key = resolve key": func(e teamEnv) {
+ var dm directoryOperatorMaterial
+ e[ds]["HOME_ROSTER_KEY"] = e[cs]["HOME_RESOLVE_KEY"]
+ e[ds]["HOME_OPERATOR_MATERIAL_BASE64"] = reencode(t, e[ds]["HOME_OPERATOR_MATERIAL_BASE64"], &dm, func() {
+ dm.Roster = []roster.Key{{ID: hexID(resolve), Public: rawURLPub(resolve)}}
+ })
+ },
+ "resolve key = roster key": func(e teamEnv) {
+ e[cs]["HOME_RESOLVE_KEY"] = e[ds]["HOME_ROSTER_KEY"]
+ e[de]["HOME_RESOLVE_PUBLIC_KEY"] = rawURLPub(rosterKey)
+ },
+ "resolve key = assertion key": func(e teamEnv) {
+ e[cs]["HOME_RESOLVE_KEY"] = w.assertionPrivate
+ e[de]["HOME_RESOLVE_PUBLIC_KEY"] = rawURLPub(w.assertionKey)
+ },
+ "roster key = assertion key": func(e teamEnv) {
+ var dm directoryOperatorMaterial
+ e[ds]["HOME_ROSTER_KEY"] = w.assertionPrivate
+ e[ds]["HOME_OPERATOR_MATERIAL_BASE64"] = reencode(t, e[ds]["HOME_OPERATOR_MATERIAL_BASE64"], &dm, func() {
+ dm.Roster = []roster.Key{{ID: hexID(w.assertionKey), Public: rawURLPub(w.assertionKey)}}
+ })
+ },
+ "owner-seed = provisioning": func(e teamEnv) {
+ var cm credentialOperatorMaterial
+ var dm directoryOperatorMaterial
+ e[ds]["HOME_OPERATOR_MATERIAL_BASE64"] = reencode(t, e[ds]["HOME_OPERATOR_MATERIAL_BASE64"], &dm, func() {})
+ e[cs]["HOME_OPERATOR_MATERIAL_BASE64"] = reencode(t, e[cs]["HOME_OPERATOR_MATERIAL_BASE64"], &cm, func() { cm.Owner = dm.Provisioning })
+ e[ds]["HOME_OPERATOR_MATERIAL_BASE64"] = reencode(t, e[ds]["HOME_OPERATOR_MATERIAL_BASE64"], &dm, func() {
+ k, _ := decodeHomeKeypair(dm.Provisioning)
+ dm.Owner = rawURLPub(k)
+ })
+ },
+ "missing variable": func(e teamEnv) { delete(e[cs], "HOME_RESOLVE_KEY") },
+ "operator HTTP empty": func(e teamEnv) { e[ce]["HOME_OPERATOR_HTTP_BASE64"] = "" },
+ "resolve key empty": func(e teamEnv) { e[cs]["HOME_RESOLVE_KEY"] = "" },
+ "roster mode empty": func(e teamEnv) { e[ds]["HOME_ROSTER_MODE"] = "" },
+ "missing section": func(e teamEnv) { delete(e, ce) },
+ "extra variable": func(e teamEnv) { e[de]["HOME_ROSTER_KEY"] = e[ds]["HOME_ROSTER_KEY"] },
+ }
+ otherHTTP := ks(t, newAltaKeygen(t).text).pins["directory"]
+ for field, set := range map[string]func(*operatorHTTPConfig){
+ "installation": func(c *operatorHTTPConfig) { c.Installation = otherHTTP.Installation },
+ "registry": func(c *operatorHTTPConfig) { c.Registry = otherHTTP.Registry },
+ "device": func(c *operatorHTTPConfig) { c.Device = otherHTTP.Device },
+ "prefilter": func(c *operatorHTTPConfig) { c.PrefilterSHA256 = otherHTTP.PrefilterSHA256 },
+ "public_key": func(c *operatorHTTPConfig) { c.PublicKey, c.KeyID = otherHTTP.PublicKey, otherHTTP.KeyID },
+ } {
+ edits["directory pins another "+field] = func(e teamEnv) {
+ var c operatorHTTPConfig
+ e[de]["HOME_OPERATOR_HTTP_BASE64"] = reencode(t, e[de]["HOME_OPERATOR_HTTP_BASE64"], &c, func() { set(&c) })
+ }
+ }
+ // Why each is refused: the rule that fires, not merely some rule.
+ want := map[string]string{
+ "owner-seed from another run": "owner_seed_public is not the credential's", "provisioning from another run": "owner_seed_public is not the credential's",
+ "provisioning swapped alone": "directory_provisioning_public_key is not the directory's provisioning key", "resolve key from another run": "HOME_RESOLVE_PUBLIC_KEY is not HOME_RESOLVE_KEY's public half",
+ "another Alta on one role": "pin different Alta keysets", "alta section from another run": "ALTA_DIRECTORY_PROVISIONING_PUBLIC_KEY is not",
+ "alta subject": "ALTA_OPERATOR_SUBJECT is not", "roster mode disabled": "directory role: Home refuses HOME_ROSTER_MODE/HOME_ROSTER_KEY",
+ "roster key not in roster_keys": "directory role: Home refuses HOME_OPERATOR_HTTP", "resolve public not a key": "directory role: Home refuses the member-resolution key",
+ "subject differs": "different operator_subjects", "MAC keys equal": "MAC keys are equal",
+ "roster key = resolve key": "directory role: Home refuses the member-resolution key", "resolve key = roster key": "directory role: Home refuses the member-resolution key",
+ "resolve key = assertion key": "credential role: Home refuses the member-resolution key", "roster key = assertion key": "directory role: Home refuses HOME_ROSTER_MODE/HOME_ROSTER_KEY",
+ "owner-seed = provisioning": "credential role: Home refuses HOME_OPERATOR_HTTP", "missing variable": "lacks HOME_RESOLVE_KEY",
+ "missing section": "no [credential env] section", "operator HTTP empty": "credential role: the operator endpoint would be off",
+ "resolve key empty": "credential role: Home refuses the member-resolution key", "roster mode empty": "directory role: Home refuses HOME_ROSTER_MODE/HOME_ROSTER_KEY", "extra variable": "holds a variable it does not take",
+ }
+ for _, field := range []string{"installation", "registry", "device", "prefilter", "public_key"} {
+ want["directory pins another "+field] = "pin different Alta keysets"
+ }
+ for name, edit := range edits {
+ e := cloneTeamEnv(env)
+ edit(e)
+ err := checkTeamEnv(e, Origins{Origin, directoryOrigin}, w.assertion)
+ if err == nil || want[name] == "" || !strings.Contains(err.Error(), want[name]) {
+ t.Errorf("%s: check accepted, or refused for another reason: %v", name, err)
+ }
+ }
+ if err := checkTeamEnv(cloneTeamEnv(env), Origins{Origin, directoryOrigin}, w.assertion); err != nil {
+ t.Fatal("baseline refused", err)
+ }
+ // Without Alta's section the Home roles still check.
+ e := cloneTeamEnv(env)
+ delete(e, ae)
+ if err := checkTeamEnv(e, Origins{Origin, directoryOrigin}, w.assertion); err != nil {
+ t.Fatal("alta section is optional", err)
+ }
+ // Against a different Home (another assertion key), a set is refused only
+ // where it must be; against these origins' strangers it fails.
+ if err := checkTeamEnv(cloneTeamEnv(env), Origins{"https://id.example.com", "https://example.com"}, w.assertion); err == nil {
+ t.Error("checked against the wrong origins")
+ }
+
+ // The text format is closed, and its errors quote nothing.
+ var buf bytes.Buffer
+ if err := writeTeamEnv(&buf, env, Origins{Origin, directoryOrigin}, "kid", teamSubject); err != nil {
+ t.Fatal(err)
+ }
+ text := buf.String()
+ for name, bad := range map[string]string{
+ "secret in an env section": strings.Replace(text, "[credential env]\n", "[credential env]\nHOME_RESOLVE_KEY="+env[cs]["HOME_RESOLVE_KEY"]+"\n", 1),
+ "unknown section": text + "[credential extras]\n",
+ "repeated section": text + "[alta env]\n",
+ "before any section": "HOME_ROSTER_MODE=serve\n" + text,
+ "no equals": text + env[cs]["HOME_RESOLVE_KEY"] + "\n",
+ "repeated variable": strings.Replace(text, "HOME_ROSTER_MODE=serve\n", "HOME_ROSTER_MODE=serve\nHOME_ROSTER_MODE=serve\n", 1),
+ } {
+ o, errOut, code := runTeamKeygen(t, bad, "-check", "-assertion-keys", w.manifest, "-")
+ if code != 1 || o != "" {
+ t.Errorf("%s: %d", name, code)
+ }
+ for _, secret := range teamPrivateValues(env) {
+ if strings.Contains(errOut, secret) {
+ t.Errorf("%s: stderr quotes a secret", name)
+ }
+ }
+ }
+ if _, _, code := runTeamKeygen(t, text, "-check", "-assertion-keys", w.manifest, "-subject", teamSubject, "-"); code != 2 {
+ t.Error("-check with generate flags", code)
+ }
+}
+
+func TestTeamKeygenWritesSecretsOnlyToStdoutOrA0600File(t *testing.T) {
+ w := newTeamWorld(t)
+ alta := newAltaKeygen(t)
+ path := filepath.Join(t.TempDir(), "team.env")
+ out, errOut, code := runTeamKeygen(t, alta.text, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest, "-out", path)
+ if code != 0 || errOut != "" {
+ t.Fatal(code, errOut)
+ }
+ info, err := os.Stat(path)
+ if err != nil || info.Mode().Perm() != 0o600 {
+ t.Fatal("file mode", info.Mode(), err)
+ }
+ body, _ := os.ReadFile(path)
+ env, err := parseTeamEnv(bytes.NewReader(body))
+ if err != nil || checkTeamEnv(env, Origins{Origin, directoryOrigin}, w.assertion) != nil {
+ t.Fatal("written set does not check", err)
+ }
+ for _, secret := range teamPrivateValues(env) {
+ if strings.Contains(out, secret) || strings.Contains(errOut, secret) {
+ t.Fatal("a secret left the file")
+ }
+ }
+ if strings.Contains(out, "HOME_OPERATOR") || strings.Contains(out, "HOME_RESOLVE") || strings.Contains(out, "HOME_ROSTER") {
+ t.Fatal("-out still printed the set")
+ }
+ // An existing file is never overwritten or widened.
+ _, errOut, code = runTeamKeygen(t, alta.text, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest, "-out", path)
+ if again, _ := os.ReadFile(path); code != 1 || !bytes.Equal(again, body) || errOut == "" {
+ t.Fatal("overwrote an existing file", code)
+ }
+ // A path that cannot be created leaves nothing behind.
+ missing := filepath.Join(t.TempDir(), "no-such-dir", "team.env")
+ if _, _, code = runTeamKeygen(t, alta.text, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest, "-out", missing); code != 1 {
+ t.Fatal("wrote under a missing directory")
+ }
+ // The command has no logger: nothing in it calls slog or log.
+ src, _ := os.ReadFile("team_keygen.go")
+ if regexp.MustCompile(`\b(slog|log)\.`).Match(src) {
+ t.Fatal("team_keygen.go logs")
+ }
+}
+
+func TestTeamKeygenCheckLeavesTheEnvironmentAlone(t *testing.T) {
+ w := newTeamWorld(t)
+ env := w.generate(t, newAltaKeygen(t).text)
+ t.Setenv("HOME_ROSTER_MODE", "disabled")
+ t.Setenv("HOME_OPERATOR_HTTP", "{}")
+ if err := checkTeamEnv(env, Origins{Origin, directoryOrigin}, w.assertion); err != nil {
+ t.Fatal("the caller's environment leaked into the check", err)
+ }
+ if os.Getenv("HOME_ROSTER_MODE") != "disabled" || os.Getenv("HOME_OPERATOR_HTTP") != "{}" {
+ t.Fatal("not restored")
+ }
+ if _, ok := os.LookupEnv("HOME_RESOLVE_KEY"); ok {
+ t.Fatal("a checked secret stayed in the environment")
+ }
+}
+
+// A manifest mid-rotation holds two assertion keys, and the credential may
+// sign with either: the set must boot the credential under each, and a key
+// equal to either one is refused on the credential role itself (the
+// per-key loop in checkTeamRole), not left for the directory to catch.
+func TestTeamKeygenTwoAssertionKeys(t *testing.T) {
+ w := newTeamWorld(t)
+ second, err := family.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ manifest, _ := stdjson.Marshal(map[string]string{
+ hexID(w.assertionKey): base64.StdEncoding.EncodeToString(w.assertionKey.SignPub()),
+ hexID(second): base64.StdEncoding.EncodeToString(second.SignPub()),
+ })
+ two := w
+ two.manifest = string(manifest)
+ if two.assertion, err = parseTeamAssertionKeys(two.manifest, Origins{Origin, directoryOrigin}); err != nil || len(two.assertion) != 2 {
+ t.Fatal("two-key manifest", err)
+ }
+ env := two.generate(t, newAltaKeygen(t).text)
+ two.boot(t, "directory", env)
+ for _, signer := range []*family.Keypair{w.assertionKey, second} {
+ as := two
+ as.assertionPrivate, as.assertionKey = encodedKeypair(t, signer), signer
+ as.boot(t, "credential", env)
+ }
+ // The resolve key equal to each assertion key in turn, the later-sorted
+ // one included: the credential role refuses it, by its own loop.
+ for _, k := range []*family.Keypair{w.assertionKey, second} {
+ e := cloneTeamEnv(env)
+ e[teamCredentialSecrets]["HOME_RESOLVE_KEY"] = encodedKeypair(t, k)
+ e[teamDirectoryEnv]["HOME_RESOLVE_PUBLIC_KEY"] = rawURLPub(k)
+ err := checkTeamEnv(e, Origins{Origin, directoryOrigin}, two.assertion)
+ if err == nil || !strings.Contains(err.Error(), "credential role: Home refuses the member-resolution key") {
+ t.Errorf("resolve key = assertion key %s…: %v", hexID(k)[:12], err)
+ }
+ }
+ // And generation refuses a fresh key equal to the second assertion key.
+ ks := ks(t, newAltaKeygen(t).text)
+ name := "assertion key " + hexID(second)[:12] + "…"
+ _, err = generateTeamEnv(ks, Origins{Origin, directoryOrigin}, teamSubject, two.assertion, teamKeySource{keypair: fixedKeys(second), random: defaultTeamKeySource().random})
+ if !namesPair(err, "the owner-seed key", name) {
+ t.Error("owner-seed = second assertion key:", err)
+ }
+}
+
+// The origins flags reach every check: a preview pair generates and boots.
+func TestTeamKeygenPreviewOrigins(t *testing.T) {
+ w := newTeamWorld(t)
+ const cred, dir = "https://overnight-home-id.bds.oncarlos.com", "https://overnight-home.bds.oncarlos.com"
+ t.Setenv("HOME_CREDENTIAL_ORIGIN", cred)
+ t.Setenv("HOME_DIRECTORY_ORIGIN", dir)
+ alta := newAltaKeygen(t)
+ text := editAlta(t, editAlta(t, alta.text, "credential", func(m map[string]any) { m["origin"] = cred }), "directory", func(m map[string]any) { m["origin"] = dir })
+ if _, _, code := runTeamKeygen(t, text, "-alta", "-", "-subject", teamSubject, "-assertion-keys", w.manifest); code != 1 {
+ t.Fatal("preview pins accepted against production origins")
+ }
+ env := w.generate(t, text, "-credential-origin", cred, "-directory-origin", dir)
+ var buf bytes.Buffer
+ writeTeamEnv(&buf, env, Origins{cred, dir}, "kid", teamSubject)
+ if strings.Contains(buf.String(), "oficina-id") {
+ t.Fatal("named production apps for a preview pair")
+ }
+ w.boot(t, "credential", env)
+ w.boot(t, "directory", env)
+}
diff --git a/internal/home/testdata/alta-keygen-f78d993.txt b/internal/home/testdata/alta-keygen-f78d993.txt
new file mode 100644
index 0000000..99194e5
--- /dev/null
+++ b/internal/home/testdata/alta-keygen-f78d993.txt
@@ -0,0 +1,10 @@
+# alta keygen at oficina/alta f78d993 (a throwaway keyset, never deployed). Alta's three secret lines are removed; every other line is verbatim.
+# Alta's secrets (carlos secrets set --app alta):
+# Alta's pins (carlos env set --app alta):
+ALTA_OPERATOR_INSTALLATION=9RdlSbLFjuP5uWBf0j05zFrwwIRDN00DCJtu0LEFFFk
+ALTA_OPERATOR_REGISTRY=kaeovYOBnNXNH_TYBticCo7pY4EqZ1lZ__st3QLWY6Y
+ALTA_OPERATOR_DEVICE=g5YRjRMWPtxLVg7Scwk9heXvRYUzgpknbP8-kFXwEn8
+# HOME_OPERATOR_HTTP for the directory role:
+{"actions":["directory.inspect","directory.initialize","directory.seed-team","directory.provision-consumer","directory.verify-consumer","directory.activate-consumer","directory.disable-consumer"],"device":"g5YRjRMWPtxLVg7Scwk9heXvRYUzgpknbP8-kFXwEn8","installation":"9RdlSbLFjuP5uWBf0j05zFrwwIRDN00DCJtu0LEFFFk","key_id":"4df7f85452fe0114c6e0237c8888fa566e8b0e7f33addd46530cb5429f35d719","operator_subject":"\u003cPaul's person ref\u003e","origin":"https://oficina.works","prefilter_token_sha256":"98a5a3699b00ebf43e59c631dcc610ea2615a8f61000e05163feefb31a4383d5","public_key":"BPWEusn8TdzIQYri5RHHXVldAfLM-hPOPGJwY4A44Ay0PYEghbDdwH45X55hE5v0c1_EZ9RLrFgPskj5C2iurbM","registry":"kaeovYOBnNXNH_TYBticCo7pY4EqZ1lZ__st3QLWY6Y","role":"directory","version":1}
+# HOME_OPERATOR_HTTP for the credential role:
+{"actions":["credential.inspect","credential.owner-seed","credential.register-consumer","credential.retire-consumer"],"device":"g5YRjRMWPtxLVg7Scwk9heXvRYUzgpknbP8-kFXwEn8","directory_provisioning_public_key":"\u003cthe directory's provisioning public key\u003e","installation":"9RdlSbLFjuP5uWBf0j05zFrwwIRDN00DCJtu0LEFFFk","key_id":"4df7f85452fe0114c6e0237c8888fa566e8b0e7f33addd46530cb5429f35d719","operator_subject":"\u003cPaul's person ref\u003e","origin":"https://id.oficina.works","prefilter_token_sha256":"98a5a3699b00ebf43e59c631dcc610ea2615a8f61000e05163feefb31a4383d5","public_key":"BPWEusn8TdzIQYri5RHHXVldAfLM-hPOPGJwY4A44Ay0PYEghbDdwH45X55hE5v0c1_EZ9RLrFgPskj5C2iurbM","registry":"kaeovYOBnNXNH_TYBticCo7pY4EqZ1lZ__st3QLWY6Y","role":"credential","version":1}