oficina / alta Public

alta-adopt: the local adoption command

cmd/alta-adopt runs every phase of the existing-team adoption: Home
preflights, initialize, Plans A to C, configure, witness, the live
checks, rollback and disable. Nothing is written anywhere without
--apply. The CARLOS token is read from a descriptor into memory only
and zeroed on exit; the config file must be mode 0600 and the user's.
make adopt builds it. A test keeps cmd/alta free of adopt, carlosop
and agent-access. The command's words are drafts in adopt/words.go,
pending copy review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 60332fa1bd0a9a67c8105972507d686c1fb4a29f parent 1ae9ae1
7 files changed, +2,231 −6
  • Makefile +11 −1
  • adopt/words.go +220 −5
  • cmd/alta-adopt/config.go +186 −0
  • cmd/alta-adopt/main.go +970 −0
  • cmd/alta-adopt/main_test.go +803 −0
  • cmd/alta/imports_test.go +30 −0
  • homeop/fakehome/fakehome.go +11 −0
diff --git a/Makefile b/Makefile
index 5ef907d..cb4d41d 100644
--- a/Makefile
+++ b/Makefile
@@ -13,7 +13,7 @@ RELEASE_BIN := releases/$(APP)-$(RELEASE_GOOS)-$(RELEASE_GOARCH)
# forever, and the deploy check can then never fail.
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null)
-.PHONY: build release version-check deps test vet fmt-check compat ci check compat-check
+.PHONY: build release adopt version-check deps test vet fmt-check compat ci check compat-check
build:
CGO_ENABLED=0 go build ./...
@@ -25,6 +25,16 @@ release: version-check
-o $(RELEASE_BIN) ./cmd/$(APP)
@echo "built $(RELEASE_BIN) reporting version $(VERSION)"
+# adopt builds the local adoption runner for this machine (it is run here,
+# never shipped), stamped like a release: alta-adopt version prints it.
+ADOPT_BIN := releases/alta-adopt
+adopt: version-check
+ @mkdir -p releases
+ CGO_ENABLED=0 go build -trimpath \
+ -ldflags "-s -w -X main.version=$(VERSION)" \
+ -o $(ADOPT_BIN) ./cmd/alta-adopt
+ @echo "built $(ADOPT_BIN) reporting version $(VERSION)"
+
version-check:
@test -n "$(VERSION)" || { echo "make release: no version to stamp; commit, or name it: make release VERSION=v0.1.0"; exit 1; }
@case "$(VERSION)" in *-dirty) echo "make release: the tree is dirty, so $(VERSION) does not name what you would ship"; exit 1;; esac
diff --git a/adopt/words.go b/adopt/words.go
index 612f58e..26e79fa 100644
--- a/adopt/words.go
+++ b/adopt/words.go
@@ -2,13 +2,19 @@
// go through the copy-review skill before merge (plan Task 14, step 5);
// a change here is a change of copy.
//
-// PENDING COPY REVIEW: WitnessSentence, WriteSummary and the live
-// checks' words (LiveSteps, the LiveSay lines, the four sentences and
-// the LiveNeed refusals) are drafts, not yet reviewed with Paul. They are reviewed in Task 14
-// step 5 with the runner's other strings.
+// PENDING COPY REVIEW: WitnessSentence, WriteSummary, the live checks'
+// words (LiveSteps, the LiveSay lines, the four sentences and the
+// LiveNeed refusals) and the command's words (Usage and every Say and
+// Hint below) are drafts, not yet reviewed with Paul. They are reviewed
+// in Task 14 step 5, all together.
package adopt
-import "amadan.net/oficina/alta/provision"
+import (
+ "fmt"
+ "strings"
+
+ "amadan.net/oficina/alta/provision"
+)
// WitnessSentence is what Paul types to witness app after its restart,
// once he has signed in at its canonical host in his own browser. It
@@ -61,3 +67,212 @@ const (
LiveNeedEvent = "the foreign event is not an event id"
LiveNeedRunners = "the live checks need the journal, a prompter and a browser"
)
+
+// ---- the alta-adopt command ----
+
+// Usage is alta-adopt's help: what it prints with no command, with help,
+// or with a command it does not know.
+const Usage = `alta-adopt adopts the six Oficina apps into the Oficina team at Home.
+
+Usage:
+ alta-adopt <command> --config <file> [flags]
+
+Without --apply, a command shows what it would do and writes nothing,
+anywhere.
+
+Commands, in the order of a run:
+ home-preflight --phase pre-initialize|pre-plan-a
+ check Home before initialize or before Plan A
+ preflight [--app <app>] check each app's CARLOS configuration (never writes)
+ initialize open Home's initialize plan on the directory
+ plan-a open Plan A: seed the team, then provision and
+ register the six apps
+ advance --run <id> take a run as far as it can go now
+ configure --app <app> write the app's two agent keys, restart it and
+ check it
+ witness --app <app> record that you checked the app yourself
+ activate --apps <list> open Plan B (calendar) or Plan C (the other five)
+ live --event <id> run the live checks against connect
+ rollback-config --app <app>
+ remove the app's two agent keys and restart it
+ disable --app <app> disable the app's team binding at Home
+ status show where the adoption is (never writes)
+ version print the version
+
+Flags:
+ --config <file> the configuration file: mode 0600, owned by you
+ --carlos-token-fd <n> read the CARLOS Admin token from file
+ descriptor n (3 or above); configure, witness,
+ activate, rollback-config, preflight and the
+ advance of Plans B and C need it
+ --apply do it
+`
+
+// What the command says. Values are app slugs, hosts, run ids, states
+// and fixed codes, never a secret, a value or an address.
+const (
+ SayDryRun = "Dry run: nothing was written. Run it again with --apply to do it."
+ SayDone = "Done."
+
+ SayHomeQueries = "Run each query against Home with carlos db query (it only reads), and type the count it answers."
+ SayHomeReady = "Home is as this phase needs it."
+
+ SayInitializeWould = "This opens Home's initialize plan on the directory. With --apply you will be asked to type this sentence:"
+ SayInitializeType = "Type this sentence, exactly, if it is true:"
+
+ SayPlanAWould = "This opens Plan A on both roles: the Oficina team, then each app's provision and register. With --apply you will be asked for the owner's address."
+ SayPlanAOwner = "Type the owner's address, as they sign in at Home:"
+
+ SayAdvanceWould = "With --apply this takes the run as far as it can go now."
+
+ SayWitnessObserved = "The app is serving as configured."
+ SayWitnessWould = "With --apply you will be asked to type this sentence:"
+ SayWitnessRecorded = "Witness recorded."
+
+ SayLiveOpen = "Open this address in your browser:"
+ SayLiveType = "Type this sentence, exactly, once it is true:"
+
+ SayDisableAsk = "With --apply you will be asked to type the team's label."
+)
+
+// SayHomeQuery asks for one count.
+func SayHomeQuery(query string) string { return query + "\ncount: " }
+
+// SayHomeRefused lists what the Home preflight found wrong.
+func SayHomeRefused(codes []string) string {
+ return "Home is not as this phase needs it: " + strings.Join(codes, ", ")
+}
+
+// SayPlanAContinue is plan-a once the team is seeded.
+func SayPlanAContinue(apps []string) string {
+ return "The team is seeded. This continues Plan A for the apps not yet registered: " + strings.Join(apps, ", ") + "."
+}
+
+// SayPlanAResubmit is plan-a when Plan A's plan lapsed before the seed.
+const SayPlanAResubmit = "Plan A's plan lapsed before the team was seeded. This signs it again."
+
+// SayRun is a run's state.
+func SayRun(id int64, state, code string) string {
+ return strings.TrimSpace(fmt.Sprintf("Run %d: %s %s", id, state, code))
+}
+
+// SayConfirm is what Paul does after a plan is opened: confirm it on
+// Home's pages for roles, then advance the run.
+func SayConfirm(id int64, roles []string) string {
+ pages := "directory"
+ if len(roles) > 1 {
+ pages = "directory and credential"
+ }
+ return fmt.Sprintf("Run %d opened. Confirm it on Home's %s confirm pages, then run:\n alta-adopt advance --run %d --apply", id, pages, id)
+}
+
+// SayConfigureWould is configure's dry run after the write's summary.
+func SayConfigureWould(host string) string {
+ return "Then it restarts " + host + " alone and waits for it to serve the new configuration."
+}
+
+// SayConfigured is a finished configure.
+func SayConfigured(host, app string) string {
+ return host + " restarted on the new configuration, and nothing else changed. Sign in to it yourself, then run:\n alta-adopt witness --app " + app + " --apply"
+}
+
+// SayWitnessAsk is the witness prompt.
+func SayWitnessAsk(host string) string {
+ return "Sign in to https://" + host + " in your own browser and check it works as before. Then type this sentence:"
+}
+
+// SayActivateApp is one app's readiness for activation.
+func SayActivateApp(app string, codes []string) string {
+ if len(codes) == 0 {
+ return app + ": ready"
+ }
+ return app + ": refused: " + strings.Join(codes, ", ")
+}
+
+// SayActivateWould is activate's dry run.
+func SayActivateWould(apps []string) string {
+ return "With --apply this opens an add-apps plan on both roles for: " + strings.Join(apps, ", ") + "."
+}
+
+// SayRolledBack is a finished rollback.
+func SayRolledBack(host string) string {
+ return host + ": both agent keys removed, and the app restarted on its previous configuration."
+}
+
+// SayDisableType is disable's prompt.
+func SayDisableType(app string) string {
+ return "This disables " + app + "'s team binding at Home. Type the team's label to go on:"
+}
+
+// SayDisableWould is disable's dry run.
+func SayDisableWould(app string) string {
+ return "This opens a plan on the directory to disable " + app + "'s team binding at Home."
+}
+
+// SayStatusTeam is the team's state.
+func SayStatusTeam(seeded bool) string {
+ if seeded {
+ return "Team: seeded"
+ }
+ return "Team: not seeded"
+}
+
+// SayStatusPreflight is one Home preflight's state.
+func SayStatusPreflight(phase string, recorded bool) string {
+ if recorded {
+ return "Home preflight " + phase + ": recorded"
+ }
+ return "Home preflight " + phase + ": not recorded"
+}
+
+// SayStatusApp is one app's line: its Home steps and its journal.
+func SayStatusApp(app string, parts []string) string {
+ return app + ": " + strings.Join(parts, ", ")
+}
+
+// SayStatusNothing is an app with no step and no journal yet.
+const SayStatusNothing = "not started"
+
+// SayStatusLive is the live-check gate's state.
+func SayStatusLive(open bool) string {
+ if open {
+ return "Live checks: passed"
+ }
+ return "Live checks: not passed"
+}
+
+// The command's refusals before it reaches anything: its flags, its
+// config file and the token's descriptor. They name fields and flags,
+// never a value.
+const (
+ RefuseFlag = "not a flag this command takes"
+ RefuseConfigMissing = "--config is required"
+ RefuseConfigOpen = "the config file does not open"
+ RefuseConfigRegular = "the config file is not a regular file"
+ RefuseConfigMode = "the config file must be mode 0600"
+ RefuseConfigOwner = "the config file must be owned by you"
+ RefuseConfigRead = "the config file does not read"
+ RefuseConfigJSON = "the config file is not the expected JSON"
+ RefuseTokenFD = "--carlos-token-fd must name a descriptor of 3 or above"
+ RefuseTokenFDClosed = "--carlos-token-fd does not name an open descriptor"
+ RefuseTokenFDRead = "--carlos-token-fd does not read"
+ RefuseTokenLong = "the CARLOS token is too long"
+ RefuseTokenEmpty = "the CARLOS token is empty"
+ RefuseStateOpen = "the state database does not open"
+ RefuseNoJournalBase = "the journal has a write and no baseline"
+ RefuseConsoleReached = "an adoption run reached for the console"
+)
+
+// RefuseConfigField is a config field that is missing or malformed.
+func RefuseConfigField(field string) string {
+ return "the config's " + field + " is missing or malformed"
+}
+
+// Hints that follow a refusal, telling Paul what comes first.
+const (
+ HintPreInitialize = "Run alta-adopt home-preflight --phase pre-initialize --apply first."
+ HintPrePlanA = "Run alta-adopt home-preflight --phase pre-plan-a --apply first."
+ HintToken = "This command reads CARLOS: pass the Admin token with --carlos-token-fd."
+ HintCanary = "Activate calendar first: alta-adopt activate --apps calendar --apply."
+ HintLive = "Run the live checks first: alta-adopt live --event <id> --apply."
+)
diff --git a/cmd/alta-adopt/config.go b/cmd/alta-adopt/config.go
new file mode 100644
index 0000000..46ebd3e
--- /dev/null
+++ b/cmd/alta-adopt/config.go
@@ -0,0 +1,186 @@
+package main
+
+// alta-adopt's configuration: one JSON file, mode 0600 and owned by the
+// user who runs the command. It holds Alta's operator material, so
+// nothing here ever names a value: errors name fields.
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "syscall"
+
+ "amadan.net/oficina/alta/adopt"
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/provision"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+// fileConfig is the file as written.
+type fileConfig struct {
+ AltaDEK string `json:"alta_dek"`
+ OperatorKey string `json:"operator_key"`
+ OperatorPrefilter string `json:"operator_prefilter"`
+ Pins struct {
+ Installation string `json:"installation"`
+ Registry string `json:"registry"`
+ Device string `json:"device"`
+ } `json:"pins"`
+ Provisioner string `json:"directory_provisioning_public_key"`
+ HomeIssuer string `json:"home_issuer"`
+ HomeDirectory string `json:"home_directory"`
+ CarlosConsole string `json:"carlos_console"`
+ CarlosAccount string `json:"carlos_account"`
+ State string `json:"state"`
+ Artifacts map[string]string `json:"artifacts"`
+}
+
+// config is the file, checked and decoded.
+type config struct {
+ dek []byte
+ key *family.Keypair
+ prefilter string
+ installation, registry, dev string
+ provisioner string
+ issuer, directory string
+ console, account string
+ state string
+ artifacts map[string]string
+}
+
+// artifactHex is a reviewed artifact SHA-256, as the Observer takes it.
+var artifactHex = regexp.MustCompile(`^[0-9a-f]{64}$`)
+
+// configLimit bounds the file: it is a few hundred bytes.
+const configLimit = 64 << 10
+
+// owned is a file's owner, as the platform reports it.
+type owned interface{ Owner() (uint32, bool) }
+
+type statOwner struct{ fi os.FileInfo }
+
+func (s statOwner) Owner() (uint32, bool) {
+ st, ok := s.fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, false
+ }
+ return st.Uid, true
+}
+
+// ownedByUser refuses a file another user owns, or whose owner the
+// platform does not say.
+func ownedByUser(fi owned) error {
+ uid, ok := fi.Owner()
+ if !ok || uid != uint32(os.Getuid()) {
+ return errors.New(adopt.RefuseConfigOwner)
+ }
+ return nil
+}
+
+// loadConfig opens path and checks it before reading a byte of it: a
+// regular file, mode 0600, owned by the user. The checks are on the
+// opened file, so what is checked is what is read.
+func loadConfig(path string) (*config, error) {
+ if path == "" {
+ return nil, errors.New(adopt.RefuseConfigMissing)
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, errors.New(adopt.RefuseConfigOpen)
+ }
+ defer f.Close()
+ fi, err := f.Stat()
+ if err != nil {
+ return nil, errors.New(adopt.RefuseConfigOpen)
+ }
+ if !fi.Mode().IsRegular() {
+ return nil, errors.New(adopt.RefuseConfigRegular)
+ }
+ if fi.Mode().Perm() != 0o600 {
+ return nil, errors.New(adopt.RefuseConfigMode)
+ }
+ if err := ownedByUser(statOwner{fi}); err != nil {
+ return nil, err
+ }
+ raw, err := io.ReadAll(io.LimitReader(f, configLimit+1))
+ if err != nil || len(raw) > configLimit {
+ return nil, errors.New(adopt.RefuseConfigRead)
+ }
+ defer clear(raw)
+ var fc fileConfig
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(&fc); err != nil {
+ // The decoder's message can quote the file: it is not repeated.
+ return nil, errors.New(adopt.RefuseConfigJSON)
+ }
+ c, err := fc.check()
+ if err != nil {
+ return nil, err
+ }
+ if !filepath.IsAbs(c.state) {
+ c.state = filepath.Join(filepath.Dir(path), c.state)
+ }
+ return c, nil
+}
+
+func (fc *fileConfig) check() (*config, error) {
+ bad := func(field string) error { return errors.New(adopt.RefuseConfigField(field)) }
+ c := &config{prefilter: fc.OperatorPrefilter, installation: fc.Pins.Installation, registry: fc.Pins.Registry, dev: fc.Pins.Device,
+ provisioner: fc.Provisioner, issuer: fc.HomeIssuer, directory: fc.HomeDirectory, console: fc.CarlosConsole,
+ account: fc.CarlosAccount, state: fc.State, artifacts: map[string]string{}}
+ dek, err := base64.StdEncoding.Strict().DecodeString(fc.AltaDEK)
+ if err != nil || len(dek) != 32 {
+ return nil, bad("alta_dek")
+ }
+ c.dek = dek
+ raw, err := base64.StdEncoding.Strict().DecodeString(fc.OperatorKey)
+ if err != nil {
+ return nil, bad("operator_key")
+ }
+ if c.key, err = family.UnmarshalKeypair(raw); err != nil {
+ clear(raw)
+ return nil, bad("operator_key")
+ }
+ clear(raw)
+ for field, v := range map[string]string{"operator_prefilter": c.prefilter, "pins.installation": c.installation, "pins.registry": c.registry, "pins.device": c.dev} {
+ if !homeop.CanonicalToken(v) {
+ return nil, bad(field)
+ }
+ }
+ if b, err := base64.RawURLEncoding.Strict().DecodeString(c.provisioner); err != nil || len(b) != 65 {
+ return nil, bad("directory_provisioning_public_key")
+ }
+ // The apps trust exactly this issuer; a run against any other Home
+ // would adopt them into a team they do not answer to.
+ if c.issuer != adopt.HomeIssuerOrigin {
+ return nil, bad("home_issuer")
+ }
+ if !homeop.Origin(c.directory) {
+ return nil, bad("home_directory")
+ }
+ if c.console == "" {
+ return nil, bad("carlos_console")
+ }
+ if c.account == "" {
+ return nil, bad("carlos_account")
+ }
+ if c.state == "" {
+ return nil, bad("state")
+ }
+ for app, sum := range fc.Artifacts {
+ if _, ok := provision.AppBySlug(app); !ok {
+ return nil, bad("artifacts")
+ }
+ if !artifactHex.MatchString(sum) {
+ return nil, bad("artifacts." + app)
+ }
+ c.artifacts[app] = sum
+ }
+ return c, nil
+}
diff --git a/cmd/alta-adopt/main.go b/cmd/alta-adopt/main.go
new file mode 100644
index 0000000..6174b14
--- /dev/null
+++ b/cmd/alta-adopt/main.go
@@ -0,0 +1,970 @@
+// Command alta-adopt is the existing-team adoption runner (Home
+// implementation/existing-team-adoption.md): a local operator command
+// that adopts the six canonical Oficina apps into the Home directory team
+// labelled oficina. It is never built into or deployed with alta.
+//
+// Home's half runs in Alta's own engine, on Alta's one operator signer,
+// stream and journal; CARLOS's half is package adopt, over an Admin
+// credential that lives in this process's memory only. Without --apply,
+// every command shows what it would do and writes nothing anywhere: not
+// Home, not CARLOS, not connect, not the adoption journal.
+package main
+
+import (
+ "bufio"
+ "context"
+ "database/sql"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/alta/adopt"
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/console"
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// version is stamped by make adopt.
+var version = "dev"
+
+// env is what a run reaches beyond its arguments. main fills the first
+// three; tests fill the rest, to reach fakes.
+type env struct {
+ stdin io.Reader
+ stdout, stderr io.Writer
+ // now is the clock (Home's windows and plans are measured by it).
+ now func() time.Time
+ // public reaches the apps' own origins (the delivery probes).
+ public *http.Client
+ // homeURL is where each Home role is reached, when not its origin.
+ homeURL map[string]string
+ // tokenRead sees the buffer the CARLOS token was read into, so a
+ // test can check it was zeroed.
+ tokenRead func([]byte)
+}
+
+func main() {
+ os.Exit(run(context.Background(), os.Args[1:], env{stdin: os.Stdin, stdout: os.Stdout, stderr: os.Stderr}))
+}
+
+// command is one subcommand: its flags, and whether it writes (and so
+// takes --apply).
+type command struct {
+ writes bool
+ flags func(fs *flag.FlagSet, o *opts)
+ do func(r *runner, ctx context.Context) error
+}
+
+// opts are every command's flags.
+type opts struct {
+ config string
+ tokenFD int
+ apply bool
+ phase string
+ app string
+ apps string
+ run int64
+ event string
+ connect string
+}
+
+var commands = map[string]command{
+ "home-preflight": {writes: true, flags: func(fs *flag.FlagSet, o *opts) {
+ fs.StringVar(&o.phase, "phase", "", "")
+ }, do: (*runner).homePreflight},
+ "preflight": {flags: func(fs *flag.FlagSet, o *opts) {
+ fs.StringVar(&o.app, "app", "", "")
+ }, do: (*runner).preflight},
+ "initialize": {writes: true, do: (*runner).initialize},
+ "plan-a": {writes: true, do: (*runner).planA},
+ "advance": {writes: true, flags: func(fs *flag.FlagSet, o *opts) {
+ fs.Int64Var(&o.run, "run", 0, "")
+ }, do: (*runner).advance},
+ "configure": {writes: true, flags: appFlag, do: (*runner).configure},
+ "witness": {writes: true, flags: appFlag, do: (*runner).witness},
+ "activate": {writes: true, flags: func(fs *flag.FlagSet, o *opts) {
+ fs.StringVar(&o.apps, "apps", "", "")
+ }, do: (*runner).activate},
+ "live": {writes: true, flags: func(fs *flag.FlagSet, o *opts) {
+ fs.StringVar(&o.event, "event", "", "")
+ fs.StringVar(&o.connect, "connect", adopt.Issuer, "")
+ }, do: (*runner).live},
+ "rollback-config": {writes: true, flags: appFlag, do: (*runner).rollback},
+ "disable": {writes: true, flags: appFlag, do: (*runner).disable},
+ "status": {do: (*runner).status},
+}
+
+func appFlag(fs *flag.FlagSet, o *opts) { fs.StringVar(&o.app, "app", "", "") }
+
+// run is the command. It answers the exit code: 0 done, 1 refused or
+// failed, 2 a usage error.
+func run(ctx context.Context, args []string, e env) int {
+ if e.now == nil {
+ e.now = time.Now
+ }
+ if len(args) == 0 || args[0] == "help" || args[0] == "-h" || args[0] == "--help" {
+ fmt.Fprint(e.stdout, adopt.Usage)
+ return 2
+ }
+ if args[0] == "version" {
+ fmt.Fprintln(e.stdout, version)
+ return 0
+ }
+ cmd, ok := commands[args[0]]
+ if !ok {
+ fmt.Fprint(e.stderr, adopt.Usage)
+ return 2
+ }
+ o := &opts{tokenFD: -1}
+ fs := flag.NewFlagSet("alta-adopt "+args[0], flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ fs.StringVar(&o.config, "config", "", "")
+ fs.IntVar(&o.tokenFD, "carlos-token-fd", -1, "")
+ if cmd.writes {
+ fs.BoolVar(&o.apply, "apply", false, "")
+ }
+ if cmd.flags != nil {
+ cmd.flags(fs, o)
+ }
+ if err := fs.Parse(args[1:]); err != nil || fs.NArg() > 0 {
+ // The flag package's message can quote an argument: only the
+ // usage is printed.
+ fmt.Fprintln(e.stderr, "alta-adopt: "+args[0]+": "+adopt.RefuseFlag)
+ fmt.Fprint(e.stderr, adopt.Usage)
+ return 2
+ }
+ r := &runner{e: e, o: o, in: bufio.NewReader(e.stdin)}
+ defer r.close()
+ if err := r.open(ctx); err != nil {
+ fmt.Fprintln(e.stderr, "alta-adopt: "+err.Error())
+ return 1
+ }
+ if err := cmd.do(r, ctx); err != nil {
+ fmt.Fprintln(e.stderr, "alta-adopt: "+err.Error())
+ if h := hintFor(err); h != "" {
+ fmt.Fprintln(e.stderr, h)
+ }
+ return 1
+ }
+ return 0
+}
+
+// refusal is a fixed code the command refuses with, and what comes first.
+type refusal struct{ code, hint string }
+
+func (r *refusal) Error() string { return "refused: " + r.code }
+
+func refuse(code, hint string) error { return &refusal{code, hint} }
+
+func hintFor(err error) string {
+ var r *refusal
+ if errors.As(err, &r) {
+ return r.hint
+ }
+ if errors.Is(err, adopt.ErrLiveChecksMissing) {
+ return adopt.HintLive
+ }
+ return ""
+}
+
+// runner is one command's process: its config, stores and clients. The
+// CARLOS token is in memory only, and zeroed by close.
+type runner struct {
+ e env
+ o *opts
+ in *bufio.Reader
+ cfg *config
+
+ db *sql.DB
+ ps *provision.Store
+ js *adopt.Store
+ home *homeop.Client
+
+ buf []byte // the whole buffer the token was read into
+ token []byte // the token: a slice of buf, never a copy
+ carlos *carlosop.Client
+ public *http.Client
+}
+
+// open reads the token first, so its descriptor is closed whatever
+// follows, then the config, then the state.
+func (r *runner) open(ctx context.Context) error {
+ if r.o.tokenFD != -1 {
+ if err := r.readToken(r.o.tokenFD); err != nil {
+ return err
+ }
+ }
+ cfg, err := loadConfig(r.o.config)
+ if err != nil {
+ return err
+ }
+ r.cfg = cfg
+ path := cfg.state
+ if !r.o.apply {
+ // A dry run creates nothing: with no state yet, it reads an
+ // empty one in memory.
+ if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
+ path = ":memory:"
+ }
+ }
+ if r.db, err = provision.OpenDB(path); err != nil {
+ return errors.New(adopt.RefuseStateOpen)
+ }
+ if r.ps, err = provision.NewStore(ctx, r.db, cfg.dek, r.e.now, adopt.Schema); err != nil {
+ return err
+ }
+ if r.js, err = adopt.NewStore(r.ps); err != nil {
+ return err
+ }
+ httpc := &http.Client{Timeout: 30 * time.Second}
+ roles := map[string]homeop.Role{}
+ for name, origin := range map[string]string{homeop.Credential: cfg.issuer, homeop.Directory: cfg.directory} {
+ roles[name] = homeop.Role{Name: name, Origin: origin, URL: r.e.homeURL[name], Installation: cfg.installation, Registry: cfg.registry, Device: cfg.dev}
+ }
+ r.home = &homeop.Client{HTTP: httpc, Key: cfg.key, Prefilter: cfg.prefilter, Roles: roles, Now: r.e.now}
+ r.public = r.e.public
+ if r.public == nil {
+ r.public = &http.Client{Timeout: 15 * time.Second}
+ }
+ if r.token != nil {
+ r.carlos = carlosop.New(cfg.console, cfg.account, r.token)
+ }
+ return nil
+}
+
+// tokenLimit bounds the token: a CARLOS Admin token is under 100 bytes.
+const tokenLimit = 4096
+
+// readToken reads the CARLOS token from descriptor fd into one buffer,
+// never copied: carlosop takes a slice of it, and close zeroes it all.
+// The standard streams are refused: the terminal answers prompts.
+func (r *runner) readToken(fd int) error {
+ if fd < 3 {
+ return errors.New(adopt.RefuseTokenFD)
+ }
+ f := os.NewFile(uintptr(fd), "carlos-token")
+ if f == nil {
+ return errors.New(adopt.RefuseTokenFDClosed)
+ }
+ defer f.Close()
+ r.buf = make([]byte, tokenLimit)
+ if r.e.tokenRead != nil {
+ r.e.tokenRead(r.buf)
+ }
+ n := 0
+ for n < len(r.buf) {
+ m, err := f.Read(r.buf[n:])
+ n += m
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ return errors.New(adopt.RefuseTokenFDRead)
+ }
+ }
+ if n == len(r.buf) {
+ return errors.New(adopt.RefuseTokenLong)
+ }
+ r.token = trimSpace(r.buf[:n:n])
+ if len(r.token) == 0 {
+ return errors.New(adopt.RefuseTokenEmpty)
+ }
+ return nil
+}
+
+// trimSpace is bytes.TrimSpace for ASCII space, as a subslice: the token
+// is never copied.
+func trimSpace(b []byte) []byte {
+ for len(b) > 0 && strings.ContainsRune(" \t\r\n", rune(b[0])) {
+ b = b[1:]
+ }
+ for len(b) > 0 && strings.ContainsRune(" \t\r\n", rune(b[len(b)-1])) {
+ b = b[:len(b)-1]
+ }
+ return b
+}
+
+// close zeroes the token and closes everything open.
+func (r *runner) close() {
+ if r.carlos != nil {
+ r.carlos.Close()
+ }
+ clear(r.buf)
+ if r.db != nil {
+ r.db.Close()
+ }
+}
+
+func (r *runner) say(lines ...string) {
+ for _, l := range lines {
+ fmt.Fprintln(r.e.stdout, l)
+ }
+}
+
+// ask prints prompt and reads one line from the terminal, without its
+// line ending.
+func (r *runner) ask(prompt string) (string, error) {
+ fmt.Fprint(r.e.stdout, prompt)
+ line, err := r.in.ReadString('\n')
+ if err != nil && (!errors.Is(err, io.EOF) || line == "") {
+ return "", refuse("no-answer", "")
+ }
+ return strings.TrimRight(line, "\r\n"), nil
+}
+
+// needCarlos is the console client, or a refusal naming the flag.
+func (r *runner) needCarlos() (*carlosop.Client, error) {
+ if r.carlos == nil {
+ return nil, refuse("carlos-token-needed", adopt.HintToken)
+ }
+ return r.carlos, nil
+}
+
+// offline answers nothing: the console and the apps as Alta's engine
+// meets them in an adoption, which never touches either.
+type offline struct{}
+
+func (offline) RoundTrip(*http.Request) (*http.Response, error) {
+ return nil, errors.New("alta-adopt: " + adopt.RefuseConsoleReached)
+}
+
+// engine is Alta's engine as alta-adopt runs it: Alta's one signer and
+// stream, no console credential and no network beyond Home, and obs as
+// the activation gate (nil for none).
+func (r *runner) engine(obs provision.Observer) *provision.Engine {
+ none := &http.Client{Transport: offline{}}
+ cfg := provision.Config{
+ Store: r.ps,
+ Home: r.home,
+ Console: &console.Client{HTTP: none, Base: "https://console.invalid", Account: r.cfg.account, Tokens: map[string]string{}},
+ Public: none,
+ HomeCfg: provision.HomeConfig{Issuer: r.cfg.issuer, Directory: r.cfg.directory, Provisioner: r.cfg.provisioner},
+ Account: r.cfg.account,
+ Now: r.e.now,
+ Logger: slog.New(slog.NewTextHandler(r.e.stderr, nil)),
+ }
+ if obs != nil {
+ cfg.Observer = obs
+ }
+ return provision.New(cfg)
+}
+
+// observer is the activation gate over the console client.
+func (r *runner) observer() (*adopt.Observer, error) {
+ c, err := r.needCarlos()
+ if err != nil {
+ return nil, err
+ }
+ return &adopt.Observer{C: c, H: r.public, S: r.js, Artifacts: r.cfg.artifacts, Now: r.e.now}, nil
+}
+
+func (r *runner) app() (provision.App, error) {
+ a, ok := provision.AppBySlug(r.o.app)
+ if !ok {
+ return provision.App{}, refuse("unknown-app", "")
+ }
+ return a, nil
+}
+
+// team is the adoption team's SQID, once seeded.
+func (r *runner) team(ctx context.Context) (string, error) {
+ used, err := r.ps.LabelUsed(ctx, provision.AdoptionLabel)
+ if err != nil {
+ return "", err
+ }
+ if !used {
+ return "", refuse("team-not-seeded", "")
+ }
+ t, err := r.ps.Team(ctx, provision.AdoptionLabel)
+ if err != nil {
+ return "", err
+ }
+ if t.TeamSQID == "" {
+ return "", refuse("team-not-seeded", "")
+ }
+ return t.TeamSQID, nil
+}
+
+func (r *runner) needPreflight(ctx context.Context, phase, hint string) error {
+ _, ok, err := r.js.HomePreflight(ctx, phase)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return refuse("home-preflight-missing", hint)
+ }
+ return nil
+}
+
+// ---- the commands ----
+
+// homePreflight prints Home's read-only queries, takes the counts Paul
+// pastes back, inspects both roles and checks it all against the phase.
+// Only with --apply, and only when nothing is refused, is it recorded.
+func (r *runner) homePreflight(ctx context.Context) error {
+ phase := r.o.phase
+ if phase != adopt.PhasePreInitialize && phase != adopt.PhasePrePlanA {
+ return refuse("unknown-phase", "")
+ }
+ r.say(adopt.SayHomeQueries)
+ counts := map[string]int64{}
+ for _, q := range adopt.HomeQueries() {
+ line, err := r.ask(adopt.SayHomeQuery(q))
+ if err != nil {
+ return err
+ }
+ n, err := strconv.ParseInt(strings.TrimSpace(line), 10, 64)
+ if err != nil || n < 0 {
+ return refuse("count-not-a-number", "")
+ }
+ counts[q[strings.LastIndex(q, " ")+1:]] = n
+ }
+ rec, codes, err := adopt.CheckHome(ctx, r.home, r.ps, counts, phase)
+ if err != nil {
+ return err
+ }
+ if len(codes) > 0 {
+ r.say(adopt.SayHomeRefused(codes))
+ return refuse("home-preflight-refused", "")
+ }
+ r.say(adopt.SayHomeReady)
+ if !r.o.apply {
+ r.say(adopt.SayDryRun)
+ return nil
+ }
+ if err := r.js.SaveHomePreflight(ctx, rec); err != nil {
+ return err
+ }
+ r.say(adopt.SayDone)
+ return nil
+}
+
+// preflight is CARLOS preflight for each app (or one), read-only.
+func (r *runner) preflight(ctx context.Context) error {
+ c, err := r.needCarlos()
+ if err != nil {
+ return err
+ }
+ apps := provision.Apps
+ if r.o.app != "" {
+ a, err := r.app()
+ if err != nil {
+ return err
+ }
+ apps = []provision.App{a}
+ }
+ refused := false
+ for _, a := range apps {
+ var mine map[string]string
+ if w, ok, err := r.js.Write(ctx, a.Slug); err != nil {
+ return err
+ } else if ok {
+ mine = w.Sent
+ }
+ _, codes, err := adopt.Preflight(ctx, c, r.public, a, mine)
+ if err != nil {
+ return err
+ }
+ refused = refused || len(codes) > 0
+ r.say(adopt.SayActivateApp(a.Slug, codes))
+ }
+ if refused {
+ return refuse("preflight-refused", "")
+ }
+ return nil
+}
+
+// initialize opens Home's directory initialize plan, once the
+// pre-initialize Home preflight is recorded.
+func (r *runner) initialize(ctx context.Context) error {
+ if err := r.needPreflight(ctx, adopt.PhasePreInitialize, adopt.HintPreInitialize); err != nil {
+ return err
+ }
+ if !r.o.apply {
+ r.say(adopt.SayInitializeWould, provision.InitializeAttestation, adopt.SayDryRun)
+ return nil
+ }
+ r.say(adopt.SayInitializeType, provision.InitializeAttestation)
+ typed, err := r.ask("> ")
+ if err != nil {
+ return err
+ }
+ id, err := r.engine(nil).StartInitialize(ctx, typed)
+ if err != nil {
+ return err
+ }
+ r.say(adopt.SayConfirm(id, []string{homeop.Directory}))
+ return nil
+}
+
+// planA opens Plan A, once the pre-plan-a Home preflight is recorded. A
+// Plan A whose window closed after the seed continues under add-apps
+// (ContinueAdoption); one whose plan lapsed before the seed is signed
+// again (Resubmit).
+func (r *runner) planA(ctx context.Context) error {
+ if err := r.needPreflight(ctx, adopt.PhasePrePlanA, adopt.HintPrePlanA); err != nil {
+ return err
+ }
+ used, err := r.ps.LabelUsed(ctx, provision.AdoptionLabel)
+ if err != nil {
+ return err
+ }
+ both := []string{homeop.Directory, homeop.Credential}
+ e := r.engine(nil)
+ if !used {
+ if !r.o.apply {
+ r.say(adopt.SayPlanAWould, adopt.SayDryRun)
+ return nil
+ }
+ owner, err := r.ask(adopt.SayPlanAOwner + " ")
+ if err != nil {
+ return err
+ }
+ id, err := e.StartAdoption(ctx, "Oficina", strings.TrimSpace(owner))
+ if err != nil {
+ return err
+ }
+ r.say(adopt.SayConfirm(id, both))
+ return nil
+ }
+ t, err := r.ps.Team(ctx, provision.AdoptionLabel)
+ if err != nil {
+ return err
+ }
+ if t.TeamSQID != "" {
+ var missing []string
+ for _, a := range provision.Slugs() {
+ if _, ok, err := r.ps.Done(ctx, provision.AdoptionLabel, a, provision.StepRegister); err != nil {
+ return err
+ } else if !ok {
+ missing = append(missing, a)
+ }
+ }
+ if len(missing) == 0 {
+ return refuse("plan-a-complete", "")
+ }
+ r.say(adopt.SayPlanAContinue(missing))
+ if !r.o.apply {
+ r.say(adopt.SayDryRun)
+ return nil
+ }
+ id, err := e.ContinueAdoption(ctx)
+ if err != nil {
+ return err
+ }
+ r.say(adopt.SayConfirm(id, both))
+ return nil
+ }
+ runs, err := r.ps.Runs(ctx, provision.AdoptionLabel)
+ if err != nil {
+ return err
+ }
+ for _, run := range runs {
+ if run.Adoption && run.Kind == homeop.KindCreateTeam {
+ r.say(adopt.SayPlanAResubmit)
+ if !r.o.apply {
+ r.say(adopt.SayDryRun)
+ return nil
+ }
+ if err := e.Resubmit(ctx, run.ID); err != nil {
+ return err
+ }
+ r.say(adopt.SayConfirm(run.ID, both))
+ return nil
+ }
+ }
+ return refuse("no-plan-a", "")
+}
+
+// advancePasses bounds one advance: each pass goes as far as Home allows
+// now, so a run that stops moving is left for the next advance.
+const advancePasses = 10
+
+// advance takes an initialize or adoption run as far as it can go now.
+// Plans B and C need the console: their activation re-observes each app.
+func (r *runner) advance(ctx context.Context) error {
+ run, err := r.ps.Run(ctx, r.o.run)
+ if err != nil {
+ return refuse("no-such-run", "")
+ }
+ if !run.Adoption && run.Kind != homeop.KindInitialize {
+ return refuse("not-an-adoption-run", "")
+ }
+ var obs provision.Observer
+ if run.Adoption && run.Kind == homeop.KindAddApps {
+ o, err := r.observer()
+ if err != nil {
+ return err
+ }
+ obs = o
+ }
+ r.say(adopt.SayRun(run.ID, run.State, run.Code))
+ if !r.o.apply {
+ r.say(adopt.SayAdvanceWould, adopt.SayDryRun)
+ return nil
+ }
+ e := r.engine(obs)
+ for range advancePasses {
+ if err := e.Advance(ctx, run.ID); err != nil {
+ var fl *provision.Fail
+ if !errors.As(err, &fl) {
+ return err
+ }
+ }
+ next, err := r.ps.Run(ctx, run.ID)
+ if err != nil {
+ return err
+ }
+ moved := next.State != run.State || next.Code != run.Code
+ run = next
+ if run.State == "done" || run.State == "failed" || !moved {
+ break
+ }
+ }
+ r.say(adopt.SayRun(run.ID, run.State, run.Code))
+ if run.State == "failed" {
+ return refuse(run.Code, "")
+ }
+ return nil
+}
+
+// configure writes app's two agent keys, restarts its canonical host
+// until it serves them, and captures the after snapshot (Task 9's order).
+// A resume continues from the journal; an app already captured is not
+// restarted again.
+func (r *runner) configure(ctx context.Context) error {
+ a, err := r.app()
+ if err != nil {
+ return err
+ }
+ c, err := r.needCarlos()
+ if err != nil {
+ return err
+ }
+ sqid, err := r.team(ctx)
+ if err != nil {
+ return err
+ }
+ summary, err := adopt.WriteAgentKeys(ctx, c, r.public, r.js, a, sqid, r.o.apply)
+ if err != nil {
+ return err
+ }
+ r.say(summary)
+ host := adopt.CanonicalHost(a)
+ if !r.o.apply {
+ // The restart's dry run: the scoped door must resolve the
+ // canonical host alone.
+ id, err := r.identity(ctx, c, a)
+ if err != nil {
+ return err
+ }
+ if _, err := adopt.RestartAndWait(ctx, c, r.public, a, id, func(adopt.Delivery) error { return nil }, false); err != nil {
+ return err
+ }
+ r.say(adopt.SayConfigureWould(host), adopt.SayDryRun)
+ return nil
+ }
+ if _, ok, err := r.js.After(ctx, a.Slug); err != nil {
+ return err
+ } else if !ok {
+ base, ok, err := r.js.Baseline(ctx, a.Slug)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return errors.New("adopt: " + adopt.RefuseNoJournalBase)
+ }
+ until := func(d adopt.Delivery) error { return adopt.Delivered(base.Delivery, d) }
+ if _, err := adopt.RestartAndWait(ctx, c, r.public, a, base.Identity, until, true); err != nil {
+ return err
+ }
+ if _, err := adopt.CaptureAfter(ctx, c, r.public, r.js, a); err != nil {
+ return err
+ }
+ }
+ r.say(adopt.SayConfigured(host, a.Slug))
+ return nil
+}
+
+// identity is the canonical record's identity: the baseline's once there
+// is one, otherwise a fresh read's.
+func (r *runner) identity(ctx context.Context, c *carlosop.Client, a provision.App) (adopt.Identity, error) {
+ if base, ok, err := r.js.Baseline(ctx, a.Slug); err != nil || ok {
+ return base.Identity, err
+ }
+ snap, err := adopt.Observe(ctx, c, r.public, a)
+ return snap.Identity, err
+}
+
+// witness records Paul's witnessed check. It observes first, so he is
+// asked to sign in only to an app that is serving as configured; without
+// --apply it asks for nothing.
+func (r *runner) witness(ctx context.Context) error {
+ a, err := r.app()
+ if err != nil {
+ return err
+ }
+ c, err := r.needCarlos()
+ if err != nil {
+ return err
+ }
+ if err := adopt.RecordWitness(ctx, r.js, c, r.public, a, "", false); err != nil {
+ return err
+ }
+ r.say(adopt.SayWitnessObserved)
+ sentence := adopt.WitnessSentence(a)
+ if !r.o.apply {
+ r.say(adopt.SayWitnessWould, sentence, adopt.SayDryRun)
+ return nil
+ }
+ r.say(adopt.SayWitnessAsk(adopt.CanonicalHost(a)), sentence)
+ typed, err := r.ask("> ")
+ if err != nil {
+ return err
+ }
+ if err := adopt.RecordWitness(ctx, r.js, c, r.public, a, typed, true); err != nil {
+ return err
+ }
+ r.say(adopt.SayWitnessRecorded)
+ return nil
+}
+
+// activate opens Plan B or C. Every app but the canary must pass the
+// live-check gate (Store.LiveGate, the Observer's own rule), and every
+// app must pass the Observer now, before a window is asked for; the
+// engine observes again, at activation.
+func (r *runner) activate(ctx context.Context) error {
+ var apps []string
+ for _, a := range strings.Split(r.o.apps, ",") {
+ if a = strings.TrimSpace(a); a != "" {
+ apps = append(apps, a)
+ }
+ }
+ sorted := provision.SortApps(apps)
+ if len(apps) == 0 || len(sorted) != len(apps) {
+ return refuse("unknown-app", "")
+ }
+ for _, a := range sorted {
+ if err := r.js.LiveGate(ctx, a); err != nil {
+ return refuse(adopt.ErrLiveChecksMissing.Error(), adopt.HintLive)
+ }
+ }
+ obs, err := r.observer()
+ if err != nil {
+ return err
+ }
+ sqid, err := r.team(ctx)
+ if err != nil {
+ return err
+ }
+ refused := false
+ for _, a := range sorted {
+ var codes []string
+ if _, err := obs.Observe(ctx, a, sqid); err != nil {
+ var rf *adopt.Refusal
+ if !errors.As(err, &rf) {
+ return err
+ }
+ codes = rf.Codes
+ }
+ refused = refused || len(codes) > 0
+ r.say(adopt.SayActivateApp(a, codes))
+ }
+ if refused {
+ return refuse("activate-refused", "")
+ }
+ if !r.o.apply {
+ r.say(adopt.SayActivateWould(sorted), adopt.SayDryRun)
+ return nil
+ }
+ id, err := r.engine(obs).ActivateAdopted(ctx, sorted)
+ if err != nil {
+ return err
+ }
+ r.say(adopt.SayConfirm(id, []string{homeop.Directory, homeop.Credential}))
+ return nil
+}
+
+// prompter asks Paul, on the terminal, to type a live check's sentence.
+type prompter struct{ r *runner }
+
+func (p prompter) Ask(_ context.Context, sentence string) error {
+ p.r.say(adopt.SayLiveType, sentence)
+ typed, err := p.r.ask("> ")
+ if err != nil {
+ return err
+ }
+ if strings.TrimSpace(typed) != sentence {
+ return refuse("sentence-mismatch", "")
+ }
+ return nil
+}
+
+// live runs the live checks against connect, once the canary is active:
+// a check run against an app Home has not activated would fail, and a
+// failure keeps Plan C refused for good.
+func (r *runner) live(ctx context.Context) error {
+ sqid, err := r.team(ctx)
+ if err != nil {
+ return err
+ }
+ if _, ok, err := r.ps.Done(ctx, provision.AdoptionLabel, adopt.CanaryApp, provision.StepActivate); err != nil {
+ return err
+ } else if !ok {
+ return refuse("canary-not-active", adopt.HintCanary)
+ }
+ open := func(u string) error {
+ r.say(adopt.SayLiveOpen, u)
+ return nil
+ }
+ if err := adopt.RunLive(ctx, r.o.connect, sqid, prompter{r}, r.js, open, r.o.event, r.o.apply); err != nil {
+ return err
+ }
+ if !r.o.apply {
+ r.say(adopt.SayDryRun)
+ return nil
+ }
+ r.say(adopt.SayDone)
+ return nil
+}
+
+// rollback removes the two agent keys configure wrote and restarts the
+// app on its baseline.
+func (r *runner) rollback(ctx context.Context) error {
+ a, err := r.app()
+ if err != nil {
+ return err
+ }
+ c, err := r.needCarlos()
+ if err != nil {
+ return err
+ }
+ if err := adopt.RollbackAgentKeys(ctx, c, r.public, r.js, a, r.o.apply); err != nil {
+ return err
+ }
+ if !r.o.apply {
+ r.say(adopt.SayDryRun)
+ return nil
+ }
+ r.say(adopt.SayRolledBack(adopt.CanonicalHost(a)))
+ return nil
+}
+
+// disable opens a directory-only plan disabling app's team binding. The
+// label is typed on the terminal.
+func (r *runner) disable(ctx context.Context) error {
+ a, err := r.app()
+ if err != nil {
+ return err
+ }
+ if _, err := r.team(ctx); err != nil {
+ return err
+ }
+ if !r.o.apply {
+ r.say(adopt.SayDisableWould(a.Slug), adopt.SayDisableAsk, adopt.SayDryRun)
+ return nil
+ }
+ typed, err := r.ask(adopt.SayDisableType(a.Slug) + " ")
+ if err != nil {
+ return err
+ }
+ id, err := r.engine(nil).DisableAdopted(ctx, a.Slug, strings.TrimSpace(typed))
+ if err != nil {
+ return err
+ }
+ r.say(adopt.SayConfirm(id, []string{homeop.Directory}))
+ return nil
+}
+
+// status shows where the adoption is: Home's preflights, the team, the
+// runs, each app's Home steps and journal, and the live-check gate.
+func (r *runner) status(ctx context.Context) error {
+ for _, phase := range []string{adopt.PhasePreInitialize, adopt.PhasePrePlanA} {
+ _, ok, err := r.js.HomePreflight(ctx, phase)
+ if err != nil {
+ return err
+ }
+ r.say(adopt.SayStatusPreflight(phase, ok))
+ }
+ _, err := r.team(ctx)
+ var rf *refusal
+ if err != nil && !errors.As(err, &rf) {
+ return err
+ }
+ r.say(adopt.SayStatusTeam(err == nil))
+ var runs []provision.Run
+ for _, label := range []string{"", provision.AdoptionLabel} {
+ rs, err := r.ps.Runs(ctx, label)
+ if err != nil {
+ return err
+ }
+ runs = append(runs, rs...)
+ }
+ slices.SortFunc(runs, func(a, b provision.Run) int { return int(a.ID - b.ID) })
+ for _, run := range runs {
+ r.say(adopt.SayRun(run.ID, run.Kind+" "+run.State, run.Code))
+ }
+ steps, err := r.ps.Steps(ctx, provision.AdoptionLabel)
+ if err != nil {
+ return err
+ }
+ for _, a := range provision.Slugs() {
+ var parts []string
+ for _, st := range steps {
+ if st.App == a {
+ parts = append(parts, strings.TrimSpace(st.Name+" "+st.State+" "+st.Code))
+ }
+ }
+ journal, err := r.journal(ctx, a)
+ if err != nil {
+ return err
+ }
+ parts = append(parts, journal...)
+ if len(parts) == 0 {
+ parts = []string{adopt.SayStatusNothing}
+ }
+ r.say(adopt.SayStatusApp(a, parts))
+ }
+ r.say(adopt.SayStatusLive(r.js.LiveGate(ctx, "docs") == nil))
+ return nil
+}
+
+// journal is app's adoption journal as states and codes.
+func (r *runner) journal(ctx context.Context, app string) ([]string, error) {
+ var out []string
+ if _, ok, err := r.js.Baseline(ctx, app); err != nil {
+ return nil, err
+ } else if ok {
+ out = append(out, "baseline")
+ }
+ if w, ok, err := r.js.Write(ctx, app); err != nil {
+ return nil, err
+ } else if ok {
+ out = append(out, strings.TrimSpace("write "+w.State+" "+w.Code))
+ }
+ if _, ok, err := r.js.After(ctx, app); err != nil {
+ return nil, err
+ } else if ok {
+ out = append(out, "after")
+ }
+ if _, ok, err := r.js.Witness(ctx, app); err != nil {
+ return nil, err
+ } else if ok {
+ out = append(out, "witness")
+ }
+ if rb, ok, err := r.js.Rollback(ctx, app); err != nil {
+ return nil, err
+ } else if ok {
+ out = append(out, strings.TrimSpace("rollback "+rb.State+" "+rb.Code))
+ }
+ return out, nil
+}
diff --git a/cmd/alta-adopt/main_test.go b/cmd/alta-adopt/main_test.go
new file mode 100644
index 0000000..8a7579b
--- /dev/null
+++ b/cmd/alta-adopt/main_test.go
@@ -0,0 +1,803 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/adopt"
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/carlosop/fakecarlos"
+ "amadan.net/oficina/alta/homeop"
+ "amadan.net/oficina/alta/homeop/fakehome"
+ "amadan.net/oficina/alta/provision"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+const (
+ dirOrigin = "https://oficina.works"
+ account = "bds"
+ owner = "adopt-owner-canary@oficina.test"
+ served = "v1.4.0"
+ // plainCanary prefixes every plain value seeded into the fake
+ // console: none may appear in any output.
+ plainCanary = "plain-value-canary-"
+)
+
+// rig is everything alta-adopt reaches, faked: Home's two roles, the
+// CARLOS console, the six apps' origins and connect.
+type rig struct {
+ t *testing.T
+
+ mu sync.Mutex
+ now time.Time
+
+ home *fakehome.Home
+ plans atomic.Int64 // POST /operator/v1/plan on either role
+ homeURL map[string]string
+ carlos *fakecarlos.Fake
+ public *http.Client
+ connect *httptest.Server
+ connectHit atomic.Int64
+
+ siteMu sync.Mutex
+ seen map[string]int
+ loaded map[string]bool
+
+ dir, cfgPath, state string
+ dek, opKey, pre string
+ tokens [][]byte // every token buffer the command read
+ out bytes.Buffer
+}
+
+func newRig(t *testing.T) *rig {
+ t.Helper()
+ r := &rig{t: t, now: time.Unix(2_000_000_000, 0), seen: map[string]int{}, loaded: map[string]bool{}}
+ key, err := family.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.pre = homeop.Token()
+ r.home = fakehome.New(key.SignPub(), r.pre, adopt.HomeIssuerOrigin, dirOrigin, r.clock)
+ pins := r.home.SharePins()
+ r.home.AddPerson(owner)
+ for _, a := range provision.Slugs() {
+ r.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a))
+ }
+ r.homeURL = map[string]string{}
+ for _, role := range []string{homeop.Credential, homeop.Directory} {
+ h := r.home.Handler(role)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if req.URL.Path == "/operator/v1/plan" {
+ r.plans.Add(1)
+ }
+ h.ServeHTTP(w, req)
+ }))
+ t.Cleanup(srv.Close)
+ r.homeURL[role] = srv.URL
+ }
+
+ r.carlos = fakecarlos.New(account)
+ t.Cleanup(r.carlos.Close)
+ for _, a := range provision.Apps {
+ p := a.Prefix
+ r.carlos.SetVar(a.Slug, "", p+"_HOME_ISSUER", adopt.HomeIssuerOrigin)
+ r.carlos.SetVar(a.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, a.Slug))
+ r.carlos.SetVar(a.Slug, "", p+"_ORIGIN", plainCanary+a.Slug)
+ r.carlos.SetSecret(a.Slug, "", p+"_INSTANCE_KEY")
+ r.carlos.AddInstance(carlosop.Instance{
+ Host: adopt.CanonicalHost(a), App: a.Slug, Slug: "s-" + a.Slug, Channel: "stable", Region: "eu",
+ CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4,
+ ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`),
+ })
+ }
+
+ site := httptest.NewTLSServer(http.HandlerFunc(r.site))
+ t.Cleanup(site.Close)
+ tr := site.Client().Transport.(*http.Transport).Clone()
+ addr := site.Listener.Addr().String()
+ // Every app origin the probe names lands on the fake site.
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+ }
+ tr.TLSClientConfig.ServerName = "example.com"
+ r.public = &http.Client{Transport: tr, Timeout: 10 * time.Second}
+
+ r.connect = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ r.connectHit.Add(1)
+ w.WriteHeader(http.StatusTeapot)
+ }))
+ t.Cleanup(r.connect.Close)
+
+ raw, err := family.MarshalKeypair(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.opKey = base64.StdEncoding.EncodeToString(raw)
+ dek := make([]byte, 32)
+ for i := range dek {
+ dek[i] = byte(7 + i)
+ }
+ r.dek = base64.StdEncoding.EncodeToString(dek)
+ r.dir = t.TempDir()
+ r.state = filepath.Join(r.dir, "adopt.db")
+ r.cfgPath = filepath.Join(r.dir, "adopt.json")
+ artifacts := map[string]string{}
+ sum := sha256.Sum256([]byte(served))
+ for _, a := range provision.Slugs() {
+ artifacts[a] = hex.EncodeToString(sum[:])
+ }
+ cfg := map[string]any{
+ "alta_dek": r.dek,
+ "operator_key": r.opKey,
+ "operator_prefilter": r.pre,
+ "pins": map[string]string{"installation": pins.Installation, "registry": pins.Registry, "device": pins.Device},
+ "directory_provisioning_public_key": r.home.ProvisioningPublic(),
+ "home_issuer": adopt.HomeIssuerOrigin,
+ "home_directory": dirOrigin,
+ "carlos_console": r.carlos.URL(),
+ "carlos_account": account,
+ "state": "adopt.db",
+ "artifacts": artifacts,
+ }
+ b, err := json.Marshal(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(r.cfgPath, b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+func (r *rig) clock() time.Time {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.now
+}
+
+func (r *rig) tick(d time.Duration) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.now = r.now.Add(d)
+}
+
+// site is the six apps' origins. An app answers agent-access's challenge
+// only once a restart has loaded both of its agent keys.
+func (r *rig) site(w http.ResponseWriter, req *http.Request) {
+ host, _, err := net.SplitHostPort(req.Host)
+ if err != nil {
+ host = req.Host
+ }
+ slug := strings.TrimSuffix(host, ".oficina.works")
+ switch req.URL.Path {
+ case "/api/version":
+ w.Header().Set("X-Carlos-Version", served)
+ _, _ = io.WriteString(w, served)
+ case "/healthz":
+ w.WriteHeader(http.StatusOK)
+ case "/api/v1/operations":
+ if !r.serving(slug) {
+ http.NotFound(w, req)
+ return
+ }
+ w.Header().Set("WWW-Authenticate", `Bearer realm="oficina"`)
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = io.WriteString(w, `{"error":{"code":"unauthenticated","message":"x"}}`)
+ default:
+ http.NotFound(w, req)
+ }
+}
+
+func (r *rig) serving(slug string) bool {
+ r.siteMu.Lock()
+ defer r.siteMu.Unlock()
+ a, ok := provision.AppBySlug(slug)
+ if !ok {
+ return false
+ }
+ if n := r.carlos.RestartCount(adopt.CanonicalHost(a)); n != r.seen[slug] {
+ vars, _, _ := r.carlos.Layer(slug, "")
+ keys := adopt.AgentKeys(a)
+ _, i := vars[keys[0]]
+ _, t := vars[keys[1]]
+ r.seen[slug], r.loaded[slug] = n, i && t
+ }
+ return r.loaded[slug]
+}
+
+// tokenFD is a fresh descriptor holding the CARLOS token, as Paul's shell
+// hands one over: alta-adopt reads and closes it.
+func (r *rig) tokenFD() string {
+ r.t.Helper()
+ pr, pw, err := os.Pipe()
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ if _, err := pw.Write(r.carlos.Token()); err != nil {
+ r.t.Fatal(err)
+ }
+ pw.Close()
+ fd, err := syscall.Dup(int(pr.Fd()))
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ pr.Close()
+ return strconv.Itoa(fd)
+}
+
+// cli runs alta-adopt with --config and, when token, a token descriptor.
+func (r *rig) cli(stdin string, token bool, args ...string) (int, string) {
+ r.t.Helper()
+ args = append(args, "--config", r.cfgPath)
+ if token {
+ args = append(args, "--carlos-token-fd", r.tokenFD())
+ }
+ var out bytes.Buffer
+ code := run(context.Background(), args, env{
+ stdin: strings.NewReader(stdin), stdout: &out, stderr: &out,
+ now: r.clock, public: r.public, homeURL: r.homeURL,
+ tokenRead: func(b []byte) { r.tokens = append(r.tokens, b) },
+ })
+ r.out.Write(out.Bytes())
+ return code, out.String()
+}
+
+// ok runs a command that must succeed.
+func (r *rig) ok(stdin string, token bool, args ...string) string {
+ r.t.Helper()
+ code, out := r.cli(stdin, token, args...)
+ if code != 0 {
+ r.t.Fatalf("alta-adopt %s: exit %d\n%s", strings.Join(args, " "), code, out)
+ }
+ return out
+}
+
+// refused runs a command that must fail, naming code.
+func (r *rig) refused(code string, stdin string, token bool, args ...string) string {
+ r.t.Helper()
+ exit, out := r.cli(stdin, token, args...)
+ if exit == 0 || !strings.Contains(out, code) {
+ r.t.Fatalf("alta-adopt %s: exit %d, want a refusal naming %s\n%s", strings.Join(args, " "), exit, code, out)
+ }
+ return out
+}
+
+// writes is everything a dry run must leave alone: Home's plans and
+// committed operations, the console's writes and restarts, connect, and
+// every row in the state database.
+type writes struct {
+ plans, ops, puts, restarts, appWide, connect, rows int64
+ exists bool
+}
+
+func (r *rig) writes() writes {
+ r.t.Helper()
+ w := writes{plans: r.plans.Load(), ops: int64(len(r.home.Requests())), appWide: int64(r.carlos.AppWideRestarts()), connect: r.connectHit.Load()}
+ for _, q := range r.carlos.Requests() {
+ if strings.HasPrefix(q, "PUT ") {
+ w.puts++
+ }
+ }
+ for _, a := range provision.Apps {
+ w.restarts += int64(r.carlos.RestartCount(adopt.CanonicalHost(a)))
+ }
+ w.rows, w.exists = r.rows()
+ return w
+}
+
+// rows counts every row of every table in the state database, without
+// creating it.
+func (r *rig) rows() (int64, bool) {
+ r.t.Helper()
+ if _, err := os.Stat(r.state); err != nil {
+ return 0, false
+ }
+ db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ defer db.Close()
+ rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ var tables []string
+ for rows.Next() {
+ var n string
+ if err := rows.Scan(&n); err != nil {
+ r.t.Fatal(err)
+ }
+ tables = append(tables, n)
+ }
+ rows.Close()
+ var total int64
+ for _, tb := range tables {
+ var n int64
+ if err := db.QueryRow(`SELECT count(*) FROM "` + tb + `"`).Scan(&n); err != nil {
+ r.t.Fatal(err)
+ }
+ total += n
+ }
+ return total, true
+}
+
+// dry runs a command without --apply and asserts it wrote nothing.
+func (r *rig) dry(stdin string, token bool, args ...string) string {
+ r.t.Helper()
+ before := r.writes()
+ out := r.ok(stdin, token, args...)
+ if after := r.writes(); after != before {
+ r.t.Fatalf("alta-adopt %s without --apply wrote: before %+v after %+v", strings.Join(args, " "), before, after)
+ }
+ return out
+}
+
+// applied runs a command with --apply and asserts it wrote something.
+func (r *rig) applied(stdin string, token bool, args ...string) string {
+ r.t.Helper()
+ before := r.writes()
+ out := r.ok(stdin, token, append(args, "--apply")...)
+ if after := r.writes(); after == before {
+ r.t.Fatalf("alta-adopt %s --apply wrote nothing\n%s", strings.Join(args, " "), out)
+ }
+ return out
+}
+
+func counts(phase string) string {
+ var b strings.Builder
+ for _, q := range adopt.HomeQueries() {
+ n := 0
+ if phase == adopt.PhasePrePlanA && (strings.HasSuffix(q, " roster_generation") || strings.HasSuffix(q, " roster_operator_receipts")) {
+ n = 1
+ }
+ fmt.Fprintf(&b, "%d\n", n)
+ }
+ return b.String()
+}
+
+func (r *rig) latestRun() string {
+ r.t.Helper()
+ db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ defer db.Close()
+ var id int64
+ if err := db.QueryRow("SELECT max(id) FROM runs").Scan(&id); err != nil {
+ r.t.Fatal(err)
+ }
+ return strconv.FormatInt(id, 10)
+}
+
+func (r *rig) runCount() int {
+ r.t.Helper()
+ db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ defer db.Close()
+ var n int
+ if err := db.QueryRow("SELECT count(*) FROM runs").Scan(&n); err != nil {
+ r.t.Fatal(err)
+ }
+ return n
+}
+
+func (r *rig) confirm(kind string) {
+ r.t.Helper()
+ if err := r.home.Confirm(homeop.Directory, ""); err != nil {
+ r.t.Fatal(err)
+ }
+ if kind == homeop.KindInitialize || kind == homeop.KindRetireApps {
+ return
+ }
+ who := ""
+ if kind == homeop.KindCreateTeam {
+ who = owner
+ }
+ if err := r.home.Confirm(homeop.Credential, who); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func (r *rig) runState(want string) {
+ r.t.Helper()
+ db, err := sql.Open("sqlite", "file:"+r.state+"?mode=ro&_pragma=busy_timeout(5000)")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ defer db.Close()
+ var state, code string
+ if err := db.QueryRow("SELECT state,code FROM runs ORDER BY id DESC LIMIT 1").Scan(&state, &code); err != nil {
+ r.t.Fatal(err)
+ }
+ if got := strings.TrimSuffix(state+" "+code, " "); got != want {
+ r.t.Fatalf("latest run %q, want %q", got, want)
+ }
+}
+
+// throughPlanA records both Home preflights, initializes the directory
+// and runs Plan A to awaiting-configuration, all through the command.
+func (r *rig) throughPlanA() {
+ r.t.Helper()
+ r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply")
+ r.ok(provision.InitializeAttestation+"\n", false, "initialize", "--apply")
+ r.confirm(homeop.KindInitialize)
+ r.ok("", false, "advance", "--run", r.latestRun(), "--apply")
+ r.runState("done")
+ r.tick(homeop.WindowLifetime * time.Second)
+ r.ok(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA, "--apply")
+ r.ok(owner+"\n", false, "plan-a", "--apply")
+ r.confirm(homeop.KindCreateTeam)
+ r.ok("", false, "advance", "--run", r.latestRun(), "--apply")
+ r.runState("done awaiting-configuration")
+ r.tick(homeop.WindowLifetime * time.Second)
+}
+
+// configured writes app's keys and records Paul's witness.
+func (r *rig) configured(app string) {
+ r.t.Helper()
+ a, _ := provision.AppBySlug(app)
+ r.ok("", true, "configure", "--app", app, "--apply")
+ r.ok(adopt.WitnessSentence(a)+"\n", true, "witness", "--app", app, "--apply")
+}
+
+// rehearse walks every subcommand of the table in order. Each runs first
+// without --apply, which must write nothing anywhere; then, where it
+// writes, with --apply, which must write.
+func rehearse(t *testing.T) *rig {
+ r := newRig(t)
+ cal, _ := provision.AppBySlug(adopt.CanaryApp)
+
+ // Nothing exists yet: a dry run does not even create the state.
+ r.dry(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize)
+ if _, exists := r.rows(); exists {
+ t.Fatal("a dry run created the state database")
+ }
+ r.dry("", true, "preflight")
+ r.dry("", false, "status")
+ r.applied(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize)
+
+ r.dry("", false, "initialize")
+ r.applied(provision.InitializeAttestation+"\n", false, "initialize")
+ r.confirm(homeop.KindInitialize)
+ run := r.latestRun()
+ r.dry("", false, "advance", "--run", run)
+ r.applied("", false, "advance", "--run", run)
+ r.runState("done")
+ r.tick(homeop.WindowLifetime * time.Second)
+
+ r.dry(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA)
+ r.applied(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA)
+ r.dry("", false, "plan-a")
+ r.applied(owner+"\n", false, "plan-a")
+ r.confirm(homeop.KindCreateTeam)
+ run = r.latestRun()
+ r.dry("", false, "advance", "--run", run)
+ r.applied("", false, "advance", "--run", run)
+ r.runState("done awaiting-configuration")
+ r.tick(homeop.WindowLifetime * time.Second)
+
+ r.dry("", true, "configure", "--app", adopt.CanaryApp)
+ r.applied("", true, "configure", "--app", adopt.CanaryApp)
+ r.dry("", true, "witness", "--app", adopt.CanaryApp)
+ r.applied(adopt.WitnessSentence(cal)+"\n", true, "witness", "--app", adopt.CanaryApp)
+
+ r.dry("", true, "activate", "--apps", adopt.CanaryApp)
+ r.applied("", true, "activate", "--apps", adopt.CanaryApp)
+ r.confirm(homeop.KindAddApps)
+ run = r.latestRun()
+ r.dry("", true, "advance", "--run", run)
+ r.applied("", true, "advance", "--run", run)
+ r.runState("done")
+ r.tick(homeop.WindowLifetime * time.Second)
+
+ r.dry("", false, "live", "--event", "7", "--connect", r.connect.URL)
+
+ r.dry("", true, "rollback-config", "--app", adopt.CanaryApp)
+ r.applied("", true, "rollback-config", "--app", adopt.CanaryApp)
+
+ r.dry("", false, "disable", "--app", adopt.CanaryApp)
+ r.applied(provision.AdoptionLabel+"\n", false, "disable", "--app", adopt.CanaryApp)
+
+ r.dry("", true, "preflight")
+ r.dry("", false, "status")
+ return r
+}
+
+func TestWritesNeedApply(t *testing.T) {
+ t.Parallel()
+ r := rehearse(t)
+ if r.carlos.AppWideRestarts() != 0 {
+ t.Fatal("the app-wide restart was called")
+ }
+ for _, a := range provision.Apps {
+ if a.Slug != adopt.CanaryApp && r.carlos.RestartCount(adopt.CanonicalHost(a)) != 0 {
+ t.Fatalf("%s restarted", a.Slug)
+ }
+ }
+ if r.connectHit.Load() != 0 {
+ t.Fatal("connect was called")
+ }
+}
+
+func TestInitializeRefusedWithoutHomePreflight(t *testing.T) {
+ t.Parallel()
+ r := newRig(t)
+ r.refused("home-preflight-missing", provision.InitializeAttestation+"\n", false, "initialize", "--apply")
+ if r.plans.Load() != 0 || len(r.home.Requests()) != 0 || r.runCount() != 0 {
+ t.Fatal("a refused initialize reached Home or opened a run")
+ }
+ // The same command, once the attestation is recorded, opens the plan.
+ r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply")
+ r.applied(provision.InitializeAttestation+"\n", false, "initialize")
+ if r.plans.Load() != 1 {
+ t.Fatalf("plans %d", r.plans.Load())
+ }
+}
+
+func TestPlanARefusedWithoutHomePreflight(t *testing.T) {
+ t.Parallel()
+ r := newRig(t)
+ r.ok(counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply")
+ r.ok(provision.InitializeAttestation+"\n", false, "initialize", "--apply")
+ r.confirm(homeop.KindInitialize)
+ r.ok("", false, "advance", "--run", r.latestRun(), "--apply")
+ r.tick(homeop.WindowLifetime * time.Second)
+ before := r.writes()
+ r.refused("home-preflight-missing", owner+"\n", false, "plan-a", "--apply")
+ if after := r.writes(); after != before {
+ t.Fatalf("a refused plan-a wrote: %+v %+v", before, after)
+ }
+ r.ok(counts(adopt.PhasePrePlanA), false, "home-preflight", "--phase", adopt.PhasePrePlanA, "--apply")
+ r.applied(owner+"\n", false, "plan-a")
+}
+
+// saveChecks records every live check as passed, as a run of live would.
+func (r *rig) saveChecks() {
+ r.t.Helper()
+ db, err := provision.OpenDB(r.state)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ defer db.Close()
+ dek, _ := base64.StdEncoding.DecodeString(r.dek)
+ ps, err := provision.NewStore(context.Background(), db, dek, r.clock, adopt.Schema)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ js, err := adopt.NewStore(ps)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ for _, c := range adopt.RequiredLiveChecks {
+ if err := js.SaveCheck(context.Background(), c, "passed"); err != nil {
+ r.t.Fatal(err)
+ }
+ }
+}
+
+func TestActivateNonCanaryRefusedWithoutLive(t *testing.T) {
+ t.Parallel()
+ r := newRig(t)
+ r.throughPlanA()
+ r.configured("docs")
+ before, reads := r.writes(), len(r.carlos.Requests())
+ // Store.LiveGate refuses first, and says what comes first.
+ for _, args := range [][]string{{"--apps", "docs", "--apply"}, {"--apps", "docs"}, {"--apps", "calendar,docs", "--apply"}} {
+ out := r.refused("refused: live-checks-missing", "", true, append([]string{"activate"}, args...)...)
+ if !strings.Contains(out, adopt.HintLive) {
+ t.Fatalf("activate %v: no hint\n%s", args, out)
+ }
+ }
+ if after := r.writes(); after != before {
+ t.Fatalf("a refused activate wrote: %+v %+v", before, after)
+ }
+ // The gate is the journal's: it refuses before CARLOS is read.
+ if n := len(r.carlos.Requests()); n != reads {
+ t.Fatalf("a refused activate read CARLOS %d times", n-reads)
+ }
+ // With every live check passed, the same command opens Plan C.
+ r.saveChecks()
+ r.applied("", true, "activate", "--apps", "docs")
+}
+
+func TestLiveRefusedBeforeCanaryActive(t *testing.T) {
+ t.Parallel()
+ r := newRig(t)
+ r.throughPlanA()
+ before := r.writes()
+ r.refused("canary-not-active", "", false, "live", "--event", "7", "--connect", r.connect.URL, "--apply")
+ if after := r.writes(); after != before {
+ t.Fatalf("a refused live wrote: %+v %+v", before, after)
+ }
+}
+
+func TestConfigFileModeRefused(t *testing.T) {
+ t.Parallel()
+ r := newRig(t)
+ for _, mode := range []os.FileMode{0o644, 0o640, 0o604, 0o660, 0o700} {
+ if err := os.Chmod(r.cfgPath, mode); err != nil {
+ t.Fatal(err)
+ }
+ r.refused(adopt.RefuseConfigMode, "", true, "status")
+ r.refused(adopt.RefuseConfigMode, counts(adopt.PhasePreInitialize), false, "home-preflight", "--phase", adopt.PhasePreInitialize, "--apply")
+ }
+ if _, exists := r.rows(); exists || r.plans.Load() != 0 || len(r.carlos.Requests()) != 0 {
+ t.Fatal("a refused config reached something")
+ }
+ if err := os.Chmod(r.cfgPath, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ r.ok("", false, "status")
+}
+
+func TestConfigFileOtherOwnerRefused(t *testing.T) {
+ t.Parallel()
+ if err := ownedByUser(fakeStat{uid: uint32(os.Getuid()) + 1}); err == nil {
+ t.Fatal("a file another user owns was accepted")
+ }
+ if err := ownedByUser(fakeStat{uid: uint32(os.Getuid())}); err != nil {
+ t.Fatalf("own file refused: %v", err)
+ }
+}
+
+func TestTokenFDRefusesStandardStreams(t *testing.T) {
+ t.Parallel()
+ r := newRig(t)
+ for _, fd := range []string{"0", "1", "2"} {
+ code, out := r.cli("", false, "preflight", "--carlos-token-fd", fd)
+ if code == 0 || !strings.Contains(out, adopt.RefuseTokenFD) {
+ t.Fatalf("fd %s: exit %d\n%s", fd, code, out)
+ }
+ }
+ if len(r.carlos.Requests()) != 0 {
+ t.Fatal("the console was reached")
+ }
+}
+
+// secrets are every value no output may carry.
+func (r *rig) secrets() map[string]string {
+ r.t.Helper()
+ s := map[string]string{
+ "token": string(r.carlos.Token()), "dek": r.dek, "operator key": r.opKey, "prefilter": r.pre,
+ "owner": owner, "vd1 digest": "vd1:", "cv1 version": "cv1:", "plain value": plainCanary,
+ "agent issuer value": adopt.Issuer, "home issuer value": adopt.HomeIssuerOrigin,
+ }
+ if _, sqid, ok := r.home.Team(provision.AdoptionLabel); ok {
+ s["team sqid"] = sqid
+ }
+ return s
+}
+
+// binding reads the environment_binding the activation sent, from the
+// held request.
+func (r *rig) binding(app string) string {
+ r.t.Helper()
+ db, err := provision.OpenDB(r.state)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ defer db.Close()
+ dek, _ := base64.StdEncoding.DecodeString(r.dek)
+ ps, err := provision.NewStore(context.Background(), db, dek, r.clock, adopt.Schema)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ req, ok, err := ps.LastRequest(context.Background(), provision.AdoptionLabel, app, "activate")
+ if err != nil || !ok {
+ r.t.Fatalf("no activation request: %v", err)
+ }
+ var w struct {
+ Input struct {
+ Evidence struct {
+ Binding string `json:"environment_binding"`
+ } `json:"evidence"`
+ } `json:"operation_input"`
+ }
+ if err := json.Unmarshal(req.Bytes, &w); err != nil || w.Input.Evidence.Binding == "" {
+ r.t.Fatalf("activation request: %v", err)
+ }
+ return w.Input.Evidence.Binding
+}
+
+func TestOutputScrub(t *testing.T) {
+ t.Parallel()
+ r := rehearse(t)
+ secrets := r.secrets()
+ secrets["environment binding"] = r.binding(adopt.CanaryApp)
+ // Refusals and help print too.
+ r.cli("", false)
+ r.cli("", false, "help")
+ r.cli("not-an-oficina-app\n", false, "disable", "--app", adopt.CanaryApp, "--apply")
+ r.cli("", true, "configure", "--app", "nope")
+ out := r.out.String()
+ if out == "" {
+ t.Fatal("no output captured")
+ }
+ for name, v := range secrets {
+ if v != "" && strings.Contains(out, v) {
+ t.Errorf("output carries the %s", name)
+ }
+ }
+}
+
+func TestTokenNeverInEnvOrDisk(t *testing.T) {
+ t.Parallel()
+ r := newRig(t)
+ token := r.carlos.Token()
+ // A token read for a run that stops before reaching CARLOS is zeroed
+ // too.
+ if err := os.Chmod(r.cfgPath, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ r.refused(adopt.RefuseConfigMode, "", true, "preflight")
+ if err := os.Chmod(r.cfgPath, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ r.throughPlanA()
+ r.ok("", true, "preflight")
+ r.configured("docs")
+ r.ok("", true, "status")
+ if n := len(r.carlos.Requests()); n == 0 {
+ t.Fatal("the token was never used")
+ }
+ for _, kv := range os.Environ() {
+ if strings.Contains(kv, string(token)) {
+ t.Fatal("the token is in the environment")
+ }
+ }
+ err := filepath.WalkDir(r.dir, func(path string, d os.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ return err
+ }
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ if bytes.Contains(b, token) {
+ t.Errorf("the token is on disk in %s", filepath.Base(path))
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(r.out.String(), string(token)) {
+ t.Fatal("the token was printed")
+ }
+ if len(r.tokens) == 0 {
+ t.Fatal("no token was read")
+ }
+ for i, b := range r.tokens {
+ if len(b) == 0 || !bytes.Equal(b, make([]byte, len(b))) {
+ t.Fatalf("token buffer %d was not zeroed", i)
+ }
+ }
+}
+
+type fakeStat struct{ uid uint32 }
+
+func (f fakeStat) Owner() (uint32, bool) { return f.uid, true }
diff --git a/cmd/alta/imports_test.go b/cmd/alta/imports_test.go
new file mode 100644
index 0000000..e63feb9
--- /dev/null
+++ b/cmd/alta/imports_test.go
@@ -0,0 +1,30 @@
+package main
+
+import (
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+// The served binary stays clean (Paul, 2026-11-16, Q1): the adoption
+// runner's CARLOS half, its Admin client and agent-access's client are
+// alta-adopt's alone. None of them may reach cmd/alta, directly or
+// through anything it imports.
+func TestServedAltaImportsNoAdoptionCode(t *testing.T) {
+ out, err := exec.Command("go", "list", "-deps", "amadan.net/oficina/alta/cmd/alta").CombinedOutput()
+ if err != nil {
+ t.Fatalf("go list: %v\n%s", err, out)
+ }
+ deps := strings.Fields(string(out))
+ if len(deps) < 10 {
+ t.Fatalf("go list found %d packages", len(deps))
+ }
+ for _, p := range deps {
+ switch {
+ case p == "amadan.net/oficina/alta/adopt" || strings.HasPrefix(p, "amadan.net/oficina/alta/adopt/"),
+ p == "amadan.net/oficina/alta/carlosop" || strings.HasPrefix(p, "amadan.net/oficina/alta/carlosop/"),
+ strings.HasPrefix(p, "amadan.net/oficina/agent-access"):
+ t.Errorf("cmd/alta imports %s", p)
+ }
+ }
+}
diff --git a/homeop/fakehome/fakehome.go b/homeop/fakehome/fakehome.go
index 902e548..b1e2fce 100644
--- a/homeop/fakehome/fakehome.go
+++ b/homeop/fakehome/fakehome.go
@@ -164,6 +164,17 @@ func (h *Home) Pins(r string) Pins {
return Pins{x.installation, x.registry, x.device}
}
+// SharePins gives both roles the credential role's pins, as production
+// holds them: Alta has one installation, registry and device on both
+// roles (one configuration, as alta-adopt's config file carries it).
+func (h *Home) SharePins() Pins {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ c, d := h.roles[homeop.Credential], h.roles[homeop.Directory]
+ d.installation, d.registry, d.device = c.installation, c.registry, c.device
+ return Pins{c.installation, c.registry, c.device}
+}
+
// ProvisioningPublic is the directory's provisioning key, base64url.
func (h *Home) ProvisioningPublic() string {
return base64.RawURLEncoding.EncodeToString(h.provisioning.SignPub())