Repository Public
1// mccctl is the out-of-band administration tool. It runs ON THE HOST, with2// direct database access, and is the only way to create the first owner or3// to recover an account whose passkeys are all lost. Every operation is4// recorded in the audit log with actor_kind=cli.5package main67import (8 "context"9 "encoding/hex"10 "flag"11 "fmt"12 "os"13 "time"1415 "github.com/google/uuid"16 "github.com/jackc/pgx/v5/pgxpool"1718 "clustr.spboucher.ai/mcc/internal/audit"19 "clustr.spboucher.ai/mcc/internal/config"20 "clustr.spboucher.ai/mcc/internal/db"21 "clustr.spboucher.ai/mcc/internal/identity"22)2324const usage = `mccctl — MacLustr Command Center, host-side administration2526 mccctl migrate apply database migrations27 mccctl bootstrap-owner --handle H --name N create the FIRST owner invitation (refused if an owner exists)28 mccctl recovery-invite --handle H recovery invitation: new passkey, old passkeys and sessions revoked29 mccctl audit-verify recompute the audit hash chain30 mccctl audit-verify-export [--pubkey K] FILE check a signed audit export offline (no database needed)31 mccctl freeze | unfreeze emergency stop: the orchestrator issues no command while frozen32 mccctl status users, sessions, agents, backend heartbeats33 mccctl backup --dir D [--keep 14] [--copy-to host:dir] encrypted database backup (+ optional off-host copy)34 mccctl backup-verify --file F authenticate a backup and read its catalogue35 mccctl restore --file F --to URL restore into an EMPTY database36 mccctl restore-test [--file F | --dir D] restore the latest backup into a scratch database and compare3738Options: --ttl 15m (invitations; max 24h)39The setup link is printed once. Open it on the device that will hold the passkey.40`4142func main() {43 if len(os.Args) < 2 {44 fmt.Fprint(os.Stderr, usage)45 os.Exit(2)46 }47 if os.Args[1] == "audit-verify-export" { // offline: needs neither configuration nor database48 if err := verifyExport(os.Args[2:], os.Stdout); err != nil {49 fmt.Fprintln(os.Stderr, "error:", err)50 os.Exit(1)51 }52 return53 }54 if err := run(os.Args[1], os.Args[2:]); err != nil {55 fmt.Fprintln(os.Stderr, "error:", err)56 os.Exit(1)57 }58}5960func run(cmd string, args []string) error {61 fs := flag.NewFlagSet(cmd, flag.ExitOnError)62 handle := fs.String("handle", "", "account handle")63 name := fs.String("name", "", "display name")64 ttl := fs.Duration("ttl", 15*time.Minute, "invitation lifetime")65 if _, extra := extraCommands[cmd]; !extra { // extra commands parse their own flags66 fs.Parse(args)67 }6869 cfg, err := config.Load()70 if err != nil {71 return err72 }73 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)74 defer cancel()75 pool, err := db.Open(ctx, cfg.DatabaseURL)76 if err != nil {77 return err78 }79 defer pool.Close()8081 cliAudit := func(action string, params map[string]any) error {82 _, err := audit.Append(ctx, pool, audit.Entry{ActorKind: "cli", ActorLabel: "mccctl:" + os.Getenv("USER"), Action: action,83 Outcome: audit.Success, Params: params, CorrelationID: uuid.New()})84 return err85 }8687 switch cmd {88 case "migrate":89 applied, err := db.Migrate(ctx, pool)90 fmt.Println("applied:", applied)91 return err92 case "bootstrap-owner", "recovery-invite":93 if _, err := db.Migrate(ctx, pool); err != nil {94 return err95 }96 ident, err := identity.New(pool, cfg)97 if err != nil {98 return err99 }100 var inv identity.Invitation101 var token string102 if cmd == "bootstrap-owner" {103 if *handle == "" || *name == "" {104 return fmt.Errorf("--handle and --name are required")105 }106 inv, token, err = ident.BootstrapOwner(ctx, *handle, *name, *ttl)107 } else {108 if *handle == "" {109 return fmt.Errorf("--handle is required")110 }111 inv, token, err = ident.RecoveryInvitation(ctx, *handle, *ttl)112 }113 if err != nil {114 return err115 }116 fmt.Printf("Invitation %s (%s, role %s), valid until %s UTC, single use.\n\n %s/setup#%s\n\n", inv.ID, inv.Purpose, inv.Role,117 inv.ExpiresAt.Format("2006-01-02 15:04:05"), cfg.PublicOrigin, token)118 fmt.Println("This link is shown once and is not stored. Do not paste it into chats or tickets.")119 return nil120 case "audit-verify":121 res, err := audit.Verify(ctx, pool)122 if err != nil {123 return err124 }125 fmt.Printf("entries=%d first=%d last=%d head=%s ok=%v\n", res.Entries, res.FirstSeq, res.LastSeq, hex.EncodeToString(res.HeadHash), res.OK)126 if !res.OK {127 return fmt.Errorf("chain broken at seq %d: %s", res.BrokenSeq, res.Reason)128 }129 return nil130 case "freeze", "unfreeze":131 frozen := cmd == "freeze"132 if _, err := pool.Exec(ctx, `insert into settings(key, value) values ('orchestrator.frozen', to_jsonb($1::boolean))133 on conflict (key) do update set value=excluded.value, updated_at=now(), updated_by=null`, frozen); err != nil {134 return err135 }136 fmt.Println("orchestrator.frozen =", frozen)137 return cliAudit("orchestrator."+cmd, nil)138 case "status":139 var users, owners, sessions, agents, nodes int140 pool.QueryRow(ctx, `select (select count(*) from users where disabled_at is null),141 (select count(*) from users where role='owner' and disabled_at is null),142 (select count(*) from sessions where revoked_at is null and idle_expires_at>now() and absolute_expires_at>now()),143 (select count(*) from agents where revoked_at is null), (select count(*) from nodes where retired_at is null)`).144 Scan(&users, &owners, &sessions, &agents, &nodes)145 fmt.Printf("env=%s origin=%s\nusers=%d (owners=%d) live_sessions=%d nodes=%d agents=%d\n", cfg.Env, cfg.PublicOrigin, users, owners, sessions, nodes, agents)146 rows, err := pool.Query(ctx, `select service, version, extract(epoch from now()-beat_at)::int from service_heartbeats order by service`)147 if err != nil {148 return err149 }150 defer rows.Close()151 for rows.Next() {152 var s, v string153 var age int154 rows.Scan(&s, &v, &age)155 fmt.Printf(" %-20s %-10s last beat %ds ago\n", s, v, age)156 }157 return rows.Err()158 }159 if fn, ok := extraCommands[cmd]; ok {160 return fn(ctx, cfg, pool, args)161 }162 fmt.Fprint(os.Stderr, usage)163 return fmt.Errorf("unknown command %q", cmd)164}165166// extraCommands are registered by the other files of this package.167var extraCommands = map[string]func(ctx context.Context, cfg *config.Config, pool *pgxpool.Pool, args []string) error{}168