feat: console member tool may empty the demo holding account
The box-side console member tool may remove the last owner of the CARLOS_DEMO_ACCOUNT holding account only, once it owns its demo fleet, demo settings are valid and every account token is revoked. Every other account keeps the last-owner guard. Paul's option 1 on amadan #527. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from demo-holding-last-owner into main.
6 files changed,
+615
−1
README.md+2 −0cmd/console/member.go+31 −1cmd/console/member_demo_test.go+131 −0docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-HOLDING.md+20 −0internal/console/demo_members.go+131 −0internal/console/member_demo_test.go+300 −0
CI passed — run details
diff --git a/README.md b/README.md| index efd37ddf5..1ba228d94 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -619,6 +619,8 @@ Set these variables on the console: |
| | `CARLOS_DEMO_CREATE_GLOBAL_DAY` | Positive integer. Default `100`. | |
| | `CARLOS_DEMO_MAX_LIVE` | Positive integer. Default `20`. Failed and retiring demos keep their place until cleanup completes. | |
| +Create the holding account and its demo fleet. Revoke all of the account's CLI and service tokens through its service pages, including expired tokens. Only an owner can revoke them, so do this before removing the last owner. Then run `console member -remove <address> "$CARLOS_DEMO_ACCOUNT"` on the console box for each member, leaving the owner until last. Use the console's environment with valid demo settings. You can leave `CARLOS_DEMO_APPS` unset while preparing the account. Only the configured holding account can lose its last owner. It must own `CARLOS_DEMO_FLEET`. The command refuses to remove the last owner while any tokens remain unrevoked and lists them. It reports when no members remain. |
| + |
| Put each demo box's settings in its root-owned `/etc/carlos/host.env`. Set `CARLOS_DEMO_BOX=1` and the same `CARLOS_DEMO_ACCOUNT`, `CARLOS_DEMO_FLEET` and `CARLOS_DEMO_DOMAIN` tuple as the console. Keep the box's existing `CARLOS_FLEET`, box identity, tunnel credentials and release public key consistent with that fleet. These are per-box authority settings. Preserve them through host.env rewrites, using the same per-box mechanism as `CARLOS_FLEET`; do not deliver them through shared or regional parameters. |
| On each designated builder, also set `CARLOS_DEMO_BUILD_WORKER=1`, `CARLOS_DEMO_BUILD_CONCURRENCY=1`, `CARLOS_DEMO_TOOLCHAIN_DIR` to its absolute immutable bundle directory, and `CARLOS_DEMO_CONSOLE_URL` to the console's HTTPS origin, for example [https://console.example.com](https://console.example.com). Preserve these per-box values through rewrites too. Concurrency accepts values from `1` through `4`; each build needs a 1 GiB memory allowance, so keep `1` until the box has capacity for more. The console URL must be the console origin, not the tunnel hostname or the operator's CLI setting. |
diff --git a/cmd/console/member.go b/cmd/console/member.go| index 297c33afa..dfb7cefaf 100644 |
| --- a/cmd/console/member.go |
| +++ b/cmd/console/member.go |
| @@ -11,6 +11,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/demo" |
| ) |
| // memberUsage is spelled out rather than left to flag.PrintDefaults because |
| @@ -197,10 +198,14 @@ func memberAdd(st *console.Store, acct *console.Account, address, role string) { |
| } |
| // memberRemove is the verb the flagship needed and did not have. Removing |
| -// somebody who is not a member is a no-op that says so rather than an error: |
| +// somebody who is not a member of an ordinary account is a no-op: |
| // the operator's intent — "they must not be in this account" — is already |
| // satisfied, and failing would make a cleanup script stop halfway. |
| func memberRemove(st *console.Store, acct *console.Account, address string) { |
| + if acct.Sqid == os.Getenv("CARLOS_DEMO_ACCOUNT") { |
| + memberRemoveDemoHolding(st, acct, address) |
| + return |
| + } |
| current, err := st.Role(acct.ID, address) |
| if err != nil { |
| log.Fatal(err) |
| @@ -215,6 +220,31 @@ func memberRemove(st *console.Store, acct *console.Account, address string) { |
| fmt.Printf("removed %s (%s) from %s (%s)\n", address, current, acct.Sqid, acct.Name) |
| } |
| +// Only the box's own environment can select this exception. Ordinary accounts |
| +// and every HTTP removal retain the store's last-owner guard. |
| +func memberRemoveDemoHolding(st *console.Store, acct *console.Account, address string) { |
| + cfg, err := demo.LoadConfig(os.Getenv) |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| + cat, err := planCatalog() |
| + if err != nil { |
| + log.Fatalf("could not load plan catalog from CARLOS_PLAN_CATALOG: %v", err) |
| + } |
| + if err := st.RemoveDemoHoldingMember(acct.ID, address, cfg, envOr("CARLOS_REGISTRY", "/data/registry.db"), cat, time.Now()); err != nil { |
| + log.Fatal(err) |
| + } |
| + fmt.Printf("removed %s from %s (%s)\n", address, acct.Sqid, acct.Name) |
| + members, err := st.Members(acct.ID) |
| + if err != nil { |
| + log.Fatalf("membership removed; cannot check remaining members: %v", err) |
| + } |
| + if len(members) != 0 { |
| + return |
| + } |
| + fmt.Printf("%s (%s) has no members\n", acct.Sqid, acct.Name) |
| +} |
| + |
| // parseInterspersed parses flags that may appear AFTER positional arguments. |
| // Go's flag package stops at the first non-flag word, which would make |
| // `console member -add alice@keymail.dev bab -role owner` silently ignore the |
diff --git a/cmd/console/member_demo_test.go b/cmd/console/member_demo_test.go| new file mode 100644 |
| index 000000000..54abfc577 |
| --- /dev/null |
| +++ b/cmd/console/member_demo_test.go |
| @@ -0,0 +1,131 @@ |
| +package main_test |
| + |
| +import ( |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func TestMemberDemoHoldingLastOwner(t *testing.T) { |
| + bin := buildConsole(t) |
| + for _, tc := range []struct { |
| + name, enabled, domain, fleetOwner, target, address, want string |
| + extraMember, extraOwner, liveTokens bool |
| + }{ |
| + {name: "prepare before admission", fleetOwner: "shop", want: "has no members"}, |
| + {name: "admission enabled", enabled: "1", fleetOwner: "shop", want: "has no members"}, |
| + {name: "invalid switch", enabled: "yes", fleetOwner: "shop", want: "CARLOS_DEMO_APPS"}, |
| + {name: "invalid disabled config", domain: "bad", fleetOwner: "shop", want: "CARLOS_DEMO_DOMAIN"}, |
| + {name: "missing fleet", want: "does not own demo fleet"}, |
| + {name: "another accounts fleet", fleetOwner: "other", want: "does not own demo fleet"}, |
| + {name: "different account", fleetOwner: "shop", target: "other", want: "last owner"}, |
| + {name: "different account invalid config", enabled: "bad", target: "other", want: "last owner"}, |
| + {name: "not a member", fleetOwner: "shop", address: "absent@keymail.dev", want: "not a member"}, |
| + {name: "members remain", fleetOwner: "shop", extraMember: true, want: "removed"}, |
| + {name: "live tokens", fleetOwner: "shop", liveTokens: true, want: "console: cannot remove the last owner while CLI or service tokens remain unrevoked. revoke them first through the account's service pages (including expired tokens):"}, |
| + {name: "live tokens with member remaining", fleetOwner: "shop", extraMember: true, liveTokens: true, want: "console: cannot remove the last owner while CLI or service tokens remain unrevoked. revoke them first through the account's service pages (including expired tokens):"}, |
| + {name: "another owner can revoke", fleetOwner: "shop", extraOwner: true, liveTokens: true, want: "removed"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + dir := t.TempDir() |
| + dbPath, regPath := filepath.Join(dir, "console.db"), filepath.Join(dir, "registry.db") |
| + st, err := console.Open(dbPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer st.Close() |
| + now := time.Now() |
| + for id, sqid := range map[int64]string{42: "shop", 43: "other"} { |
| + if err := st.CreateAccount(id, sqid, sqid, "owner@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if tc.extraMember { |
| + if err := st.AddMember(42, "member@keymail.dev", console.RoleMember, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if tc.extraOwner { |
| + if err := st.AddMember(42, "second@keymail.dev", console.RoleOwner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Tokens minted by someone else must be reported too. No implicit revocation. |
| + secret, err := st.NewAppToken(42, "example", "another@keymail.dev", "demo credential", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + toks, err := st.CLITokens("another@keymail.dev") |
| + if err != nil || len(toks) != 1 { |
| + t.Fatalf("tokens: %v %v", toks, err) |
| + } |
| + if !tc.liveTokens { |
| + if err := st.RevokeAccountToken(42, toks[0].ID, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + reg, err := registry.Open(regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if tc.fleetOwner != "" { |
| + if err := reg.UpsertFleet(registry.Fleet{Name: "demo", Account: tc.fleetOwner, Bucket: "local"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + reg.Close() |
| + domain := tc.domain |
| + if domain == "" { |
| + domain = "demo.example.com" |
| + } |
| + target := tc.target |
| + if target == "" { |
| + target = "shop" |
| + } |
| + address := tc.address |
| + if address == "" { |
| + address = "owner@keymail.dev" |
| + } |
| + run := runner(t, bin, "CONSOLE_DB="+dbPath, "CARLOS_REGISTRY="+regPath, |
| + "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=", "CARLOS_HOST_CLAIM=", |
| + "CARLOS_PLAN_CATALOG=", "CARLOS_DEMO_ACCOUNT=shop", "CARLOS_DEMO_FLEET=demo", |
| + "CARLOS_DEMO_DOMAIN="+domain, "CARLOS_DEMO_APPS="+tc.enabled, |
| + "CARLOS_DEMO_BUILD_WORKER=", "CARLOS_DEMO_BUILD_CONCURRENCY=", |
| + "CARLOS_DEMO_CREATE_PER_IP_DAY=", "CARLOS_DEMO_CREATE_GLOBAL_DAY=", "CARLOS_DEMO_MAX_LIVE=") |
| + out, err := run("member", "-remove", address, target) |
| + success := tc.want == "has no members" || tc.want == "removed" |
| + if (err == nil) != success || !strings.Contains(out, tc.want) { |
| + t.Fatalf("remove: %v\n%s\nwant success=%v and %q", err, out, success, tc.want) |
| + } |
| + id := int64(42) |
| + if target == "other" { |
| + id = 43 |
| + } |
| + role, err := st.Role(id, "owner@keymail.dev") |
| + if err != nil || (role == "") != success { |
| + t.Fatalf("owner role=%q err=%v", role, err) |
| + } |
| + if !success && tc.liveTokens { |
| + for _, want := range []string{toks[0].ID, "demo credential", "another@keymail.dev", "revoke"} { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("output missing %q: %s", want, out) |
| + } |
| + } |
| + if strings.Contains(out, secret) { |
| + t.Fatal("printed token secret") |
| + } |
| + } |
| + if (tc.extraMember || tc.extraOwner || !success) && strings.Contains(out, "has no members") { |
| + t.Fatalf("false empty report: %s", out) |
| + } |
| + after, err := st.CLITokens("another@keymail.dev") |
| + if err != nil || (tc.liveTokens && (len(after) != 1 || after[0].ID != toks[0].ID)) || (!tc.liveTokens && len(after) != 0) { |
| + t.Fatalf("tokens changed: %v %v", after, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-HOLDING.md b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-HOLDING.md| new file mode 100644 |
| index 000000000..344fd0502 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-HOLDING.md |
| @@ -0,0 +1,20 @@ |
| +| where (file:line) | current | new | why | |
| +|---|---|---|---| |
| +| README.md:622 | Create the holding account and its demo fleet, then revoke all of the account's CLI and service tokens through its service pages, including expired tokens. Only a member can revoke them, so do this before removing the last owner. Then run `console member -remove <address> "$CARLOS_DEMO_ACCOUNT"` on the console box for each member, leaving the owner until last. Use the console's environment with valid demo settings; you can leave `CARLOS_DEMO_APPS` unset while preparing the account. Only the configured holding account can lose its last owner, and it must own `CARLOS_DEMO_FLEET`. The command refuses to remove the last owner while any tokens remain unrevoked and lists them. It reports when no members remain. | Create the holding account and its demo fleet. Revoke all of the account's CLI and service tokens through its service pages, including expired tokens. Only a member can revoke them, so do this before removing the last owner. Then run `console member -remove <address> "$CARLOS_DEMO_ACCOUNT"` on the console box for each member, leaving the owner until last. Use the console's environment with valid demo settings. You can leave `CARLOS_DEMO_APPS` unset while preparing the account. Only the configured holding account can lose its last owner. It must own `CARLOS_DEMO_FLEET`. The command refuses to remove the last owner while any tokens remain unrevoked and lists them. It reports when no members remain. | Splits the long paragraph into short sentences while preserving the command, flags and environment variable names. | |
| +| cmd/console/member.go:232 | `CARLOS_PLAN_CATALOG: %v` | `could not load plan catalog from CARLOS_PLAN_CATALOG: %v` | Starts with a lower-case word as required for an operator log line and keeps the environment variable name. | |
| +| cmd/console/member.go:237 | `removed %s from %s (%s)` | unchanged | unchanged | |
| +| cmd/console/member.go:240 | `membership removed; cannot check remaining members: %v` | unchanged | unchanged | |
| +| cmd/console/member.go:245 | `%s (%s) has no members` | unchanged | unchanged | |
| +| internal/console/demo_members.go:27 | `console: the ops account cannot be a demo holding account` | unchanged | unchanged | |
| +| internal/console/demo_members.go:41 | `console: cannot check demo fleet ownership: %w` | unchanged | unchanged | |
| +| internal/console/demo_members.go:46 | `console: removal committed but registry detach failed: %w` | unchanged | unchanged | |
| +| internal/console/demo_members.go:66 | `console: account %q is not the configured demo holding account` | unchanged | unchanged | |
| +| internal/console/demo_members.go:71 | `console: cannot check demo fleet ownership: %w` | unchanged | unchanged | |
| +| internal/console/demo_members.go:74 | `console: account %q does not own demo fleet %q` | unchanged | unchanged | |
| +| internal/console/demo_members.go:79 | `console: %s is not a member of %s` | unchanged | unchanged | |
| +| internal/console/demo_members.go:102 | `console: cannot remove the last owner while CLI or service tokens remain unrevoked; revoke them first through the account's service pages (including expired tokens):` | `console: cannot remove the last owner while CLI or service tokens remain unrevoked. revoke them first through the account's service pages (including expired tokens):` | Uses separate short sentences and lower-case Go error style after the full stop. | |
| +| internal/console/demo_members.go:104 | `\n%s\taddress=%q\tname=%q\tlabel=%q\tkind=%q\tapp=%q` | unchanged | unchanged | |
| + |
| +**Flags** |
| + |
| +- None. |
diff --git a/internal/console/demo_members.go b/internal/console/demo_members.go| new file mode 100644 |
| index 000000000..1b3748cc2 |
| --- /dev/null |
| +++ b/internal/console/demo_members.go |
| @@ -0,0 +1,131 @@ |
| +package console |
| + |
| +import ( |
| + "database/sql" |
| + "fmt" |
| + "net/url" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// RemoveDemoHoldingMember is only for the box-side member tool. The registry |
| +// is attached read-only so fleet ownership and membership are read in the same |
| +// transaction. Use a dedicated Store: the attachment lasts for this call. |
| +// HTTP removal continues to use removeMemberTx and its last-owner guard. |
| +func (s *Store) RemoveDemoHoldingMember(accountID int64, address string, cfg demo.Config, registryPath string, cat *plans.Catalog, now time.Time) (err error) { |
| + // Preparation works before admission is enabled, but needs the complete |
| + // admission tuple. Validate a copy without changing the operator's switch. |
| + cfg.Enabled = true |
| + if err := cfg.Validate(); err != nil { |
| + return err |
| + } |
| + if accountID == OpsAccountID { |
| + return fmt.Errorf("console: the ops account cannot be a demo holding account") |
| + } |
| + var old *AccountPlanRow |
| + if cat != nil { |
| + if old, err = s.AccountPlan(accountID); err != nil { |
| + return err |
| + } |
| + } |
| + path, err := filepath.Abs(registryPath) |
| + if err != nil { |
| + return err |
| + } |
| + uri := (&url.URL{Scheme: "file", Path: path, RawQuery: "mode=ro"}).String() |
| + if _, err := s.db.Exec(`ATTACH DATABASE ? AS demo_holding_registry`, uri); err != nil { |
| + return fmt.Errorf("console: cannot check demo fleet ownership: %w", err) |
| + } |
| + defer func() { |
| + _, detachErr := s.db.Exec(`DETACH DATABASE demo_holding_registry`) |
| + if err == nil && detachErr != nil { |
| + err = fmt.Errorf("console: removal committed but registry detach failed: %w", detachErr) |
| + } |
| + }() |
| + _, err = s.MembershipTransition(accountID, cat, old, removeDemoHoldingMemberWrite(accountID, address, cfg), now) |
| + return err |
| +} |
| + |
| +// Recheck both identities here; an earlier command-side lookup cannot grant |
| +// the exception. No token is revoked by this write. |
| +func removeDemoHoldingMemberWrite(accountID int64, address string, cfg demo.Config) func(*sql.Tx) error { |
| + return func(tx *sql.Tx) error { |
| + cfg.Enabled = true |
| + if err := cfg.Validate(); err != nil { |
| + return err |
| + } |
| + var sqid string |
| + if err := tx.QueryRow(`SELECT sqid FROM accounts WHERE id = ?`, accountID).Scan(&sqid); err != nil { |
| + return err |
| + } |
| + if sqid != cfg.Account || accountID == OpsAccountID { |
| + return fmt.Errorf("console: account %q is not the configured demo holding account", sqid) |
| + } |
| + var owner string |
| + err := tx.QueryRow(`SELECT account FROM demo_holding_registry.fleets WHERE name = ?`, cfg.Fleet).Scan(&owner) |
| + if err != nil && err != sql.ErrNoRows { |
| + return fmt.Errorf("console: cannot check demo fleet ownership: %w", err) |
| + } |
| + if err == sql.ErrNoRows || owner != sqid { |
| + return fmt.Errorf("console: account %q does not own demo fleet %q", sqid, cfg.Fleet) |
| + } |
| + var role string |
| + err = tx.QueryRow(`SELECT role FROM memberships WHERE account_id = ? AND address = ?`, accountID, address).Scan(&role) |
| + if err == sql.ErrNoRows { |
| + return fmt.Errorf("console: %s is not a member of %s", address, sqid) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if role == RoleOwner { |
| + var owners int |
| + if err := tx.QueryRow(`SELECT COUNT(*) FROM memberships WHERE account_id = ? AND role = ?`, accountID, RoleOwner).Scan(&owners); err != nil { |
| + return err |
| + } |
| + if owners == 1 { |
| + // Keep an owner who can revoke credentials through the service |
| + // pages. Count expired but unrevoked tokens, as admission does. |
| + rows, err := tx.Query(accountCLITokensSQL, accountID) |
| + if err != nil { |
| + return err |
| + } |
| + tokens, err := scanCLITokenRows(rows) |
| + if err != nil { |
| + return err |
| + } |
| + if len(tokens) != 0 { |
| + var message strings.Builder |
| + message.WriteString("console: cannot remove the last owner while CLI or service tokens remain unrevoked. revoke them first through the account's service pages (including expired tokens):") |
| + for _, tok := range tokens { |
| + fmt.Fprintf(&message, "\n%s\taddress=%q\tname=%q\tlabel=%q\tkind=%q\tapp=%q", tok.ID, tok.Address, tok.Name, tok.Label, tok.Kind, tok.App) |
| + } |
| + return fmt.Errorf("%s", message.String()) |
| + } |
| + } |
| + } |
| + if _, err := tx.Exec(`DELETE FROM app_stars WHERE account_id = ? AND address = ?`, accountID, address); err != nil { |
| + return err |
| + } |
| + _, err = tx.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`, accountID, address) |
| + return err |
| + } |
| +} |
| + |
| +// AccountCLITokens matches demo admission's credential check, including expired |
| +// but unrevoked rows and credentials minted by other people. IDs are hashes, |
| +// never bearer secrets. |
| +func (s *Store) AccountCLITokens(accountID int64) ([]CLIToken, error) { |
| + rows, err := s.db.Query(accountCLITokensSQL, accountID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return scanCLITokenRows(rows) |
| +} |
| + |
| +const accountCLITokensSQL = `SELECT token_hash, address, label, remote_addr, kind, account_id, app, |
| +role, name, created_at, expires_at, last_used, revoked_at, rotated_at, rungs, commands, scope |
| +FROM cli_tokens WHERE account_id = ? AND revoked_at = 0 ORDER BY created_at DESC, token_hash` |
diff --git a/internal/console/member_demo_test.go b/internal/console/member_demo_test.go| new file mode 100644 |
| index 000000000..27e84e86d |
| --- /dev/null |
| +++ b/internal/console/member_demo_test.go |
| @@ -0,0 +1,300 @@ |
| +package console |
| + |
| +import ( |
| + "database/sql" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func TestDemoHoldingLastOwnerHTTPStillRefused(t *testing.T) { |
| + fx, c, csrf := memberFixture(t) |
| + if err := fx.st.CreateAccount(42, "shop", "Demo", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := demoTestConfig(t) |
| + cfg.Enabled = false |
| + fx.srv.cfg.Demo = cfg |
| + t.Setenv("CARLOS_DEMO_ACCOUNT", cfg.Account) |
| + t.Setenv("CARLOS_DEMO_FLEET", cfg.Fleet) |
| + t.Setenv("CARLOS_DEMO_DOMAIN", cfg.Domain) |
| + reg, err := registry.Open(fx.srv.cfg.Registry) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.UpsertFleet(registry.Fleet{Name: cfg.Fleet, Account: cfg.Account, Bucket: "local"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg.Close() |
| + status, loc, _ := postGated(t, fx, c, fx.ts.URL+"/a/shop/members/remove", url.Values{"csrf": {csrf}, "address": {"paul@keymail.dev"}}) |
| + if status != http.StatusSeeOther { |
| + t.Fatalf("status=%d", status) |
| + } |
| + _, _, body := get(t, c, fx.ts.URL+loc) |
| + if !strings.Contains(body, "last owner") { |
| + t.Fatalf("missing last-owner refusal: %s", body) |
| + } |
| + if role, err := fx.st.Role(42, "paul@keymail.dev"); err != nil || role != RoleOwner { |
| + t.Fatalf("role=%q err=%v", role, err) |
| + } |
| +} |
| + |
| +func TestDemoHoldingMemberWriteRechecksAndRollsBack(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + edit func(*demo.Config) |
| + moveFleet, rollback bool |
| + want string |
| + }{ |
| + {name: "different account", edit: func(c *demo.Config) { c.Account = "other" }, want: "not the configured"}, |
| + {name: "invalid config", edit: func(c *demo.Config) { c.Domain = "bad" }, want: "CARLOS_DEMO_DOMAIN"}, |
| + {name: "fleet changed after write constructed", moveFleet: true, want: "does not own demo fleet"}, |
| + {name: "later transaction failure", rollback: true, want: "later failure"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + if err := st.AddMember(42, "owner@keymail.dev", RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := demoTestConfig(t) |
| + cfg.Enabled = false |
| + path := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + fleet := registry.Fleet{Name: cfg.Fleet, Account: cfg.Account, Bucket: "local"} |
| + if err := reg.UpsertFleet(fleet); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.db.Exec(`ATTACH DATABASE ? AS demo_holding_registry`, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + if tc.edit != nil { |
| + tc.edit(&cfg) |
| + } |
| + write := removeDemoHoldingMemberWrite(42, "owner@keymail.dev", cfg) |
| + if tc.moveFleet { |
| + fleet.Account = "other" |
| + if err := reg.UpsertFleet(fleet); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + _, err = st.MembershipTransition(42, nil, nil, func(tx *sql.Tx) error { |
| + if err := write(tx); err != nil { |
| + return err |
| + } |
| + if tc.rollback { |
| + return errors.New("later failure") |
| + } |
| + return nil |
| + }, time.Now()) |
| + if err == nil || !strings.Contains(err.Error(), tc.want) { |
| + t.Fatalf("err=%v want %q", err, tc.want) |
| + } |
| + if role, err := st.Role(42, "owner@keymail.dev"); err != nil || role != RoleOwner { |
| + t.Fatalf("role=%q err=%v", role, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoHoldingMemberRemovalDetachesRegistry(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + cfg := demoTestConfig(t) |
| + cfg.Enabled = false |
| + path := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.UpsertFleet(registry.Fleet{Name: cfg.Fleet, Account: cfg.Account, Bucket: "local"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg.Close() |
| + for _, address := range []string{"first@keymail.dev", "second@keymail.dev"} { |
| + if err := st.AddMember(42, address, RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.RemoveDemoHoldingMember(42, address, cfg, path, nil, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Refusal detaches too, and a missing registry is never created. |
| + missing := filepath.Join(t.TempDir(), "missing.db") |
| + if err := st.RemoveDemoHoldingMember(42, "absent@keymail.dev", cfg, missing, nil, time.Now()); err == nil { |
| + t.Fatal("missing registry accepted") |
| + } |
| + if _, err := os.Stat(missing); !os.IsNotExist(err) { |
| + t.Fatalf("missing registry was created: %v", err) |
| + } |
| + for i := 0; i < 2; i++ { |
| + err := st.RemoveDemoHoldingMember(42, "absent@keymail.dev", cfg, path, nil, time.Now()) |
| + if err == nil || !strings.Contains(err.Error(), "not a member") { |
| + t.Fatalf("repeat refusal: %v", err) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoHoldingAccountCLITokensMatchAdmission(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + // Include expired and unknown-kind rows: admission counts every unrevoked |
| + // credential on the account. Neither the minter nor kind narrows that set. |
| + for _, tok := range []struct { |
| + id string |
| + account int |
| + revoked int |
| + }{ |
| + {"live", 42, 0}, {"revoked", 42, 1}, {"other-account", 43, 0}, |
| + } { |
| + _, err := st.db.Exec(`INSERT INTO cli_tokens(token_hash,address,label,created_at,expires_at,account_id,kind,revoked_at) VALUES(?, 'another@keymail.dev','test',1,2,?,'future-kind',?)`, tok.id, tok.account, tok.revoked) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + tokens, err := st.AccountCLITokens(42) |
| + if err != nil || len(tokens) != 1 || tokens[0].ID != "live" { |
| + t.Fatalf("tokens=%v err=%v", tokens, err) |
| + } |
| +} |
| + |
| +func TestDemoHoldingOpsAccountRefused(t *testing.T) { |
| + for _, entry := range []string{"public method", "transaction callback"} { |
| + t.Run(entry, func(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + now := time.Now() |
| + if err := st.CreateAccount(OpsAccountID, "ops", "Operators", "owner@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := demoTestConfig(t) |
| + cfg.Account = "ops" |
| + path := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.UpsertFleet(registry.Fleet{Name: cfg.Fleet, Account: cfg.Account, Bucket: "local"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg.Close() |
| + want := "the ops account cannot be a demo holding account" |
| + if entry == "public method" { |
| + // An unreadable registry distinguishes the early check from the |
| + // callback check. Removing the early check must fail this case. |
| + err = st.RemoveDemoHoldingMember(OpsAccountID, "owner@keymail.dev", cfg, filepath.Join(path, "missing.db"), nil, now) |
| + } else { |
| + if _, err := st.db.Exec(`ATTACH DATABASE ? AS demo_holding_registry`, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = st.MembershipTransition(OpsAccountID, nil, nil, removeDemoHoldingMemberWrite(OpsAccountID, "owner@keymail.dev", cfg), now) |
| + want = "not the configured demo holding account" |
| + } |
| + if err == nil || !strings.Contains(err.Error(), want) { |
| + t.Fatalf("err=%v want %q", err, want) |
| + } |
| + if role, err := st.Role(OpsAccountID, "owner@keymail.dev"); err != nil || role != RoleOwner { |
| + t.Fatalf("role=%q err=%v", role, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoHoldingLastOwnerTokens(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, kind string |
| + account int64 |
| + expired bool |
| + revoked bool |
| + wantRefuse bool |
| + }{ |
| + {name: "app token", kind: "app", account: 42, wantRefuse: true}, |
| + {name: "service token", kind: "service", account: 42, wantRefuse: true}, |
| + {name: "expired token", kind: "service", account: 42, expired: true, wantRefuse: true}, |
| + {name: "unknown kind", kind: "future-kind", account: 42, wantRefuse: true}, |
| + {name: "revoked token", kind: "service", account: 42, revoked: true}, |
| + {name: "another account", kind: "service", account: 43}, |
| + {name: "personal token", kind: "terminal", account: 0}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + now := time.Now() |
| + if err := st.AddMember(42, "owner@keymail.dev", RoleOwner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := demoTestConfig(t) |
| + path := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.UpsertFleet(registry.Fleet{Name: cfg.Fleet, Account: cfg.Account, Bucket: "local"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg.Close() |
| + expires, revoked := now.Add(time.Hour).Unix(), int64(0) |
| + if tc.expired { |
| + expires = now.Add(-time.Hour).Unix() |
| + } |
| + if tc.revoked { |
| + revoked = now.Unix() |
| + } |
| + // Construct the write before minting credentials to catch a check |
| + // that moves outside the membership transaction. |
| + write := removeDemoHoldingMemberWrite(42, "owner@keymail.dev", cfg) |
| + for _, id := range []string{"first-token-id", "second-token-id"} { |
| + _, err := st.db.Exec(`INSERT INTO cli_tokens(token_hash,address,label,name,created_at,expires_at,account_id,kind,revoked_at) |
| +VALUES(?, 'another@keymail.dev', 'deploy label', ?, ?, ?, ?, ?, ?)`, id, "deploy name "+id, now.Unix(), expires, tc.account, tc.kind, revoked) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := st.db.Exec(`ATTACH DATABASE ? AS demo_holding_registry`, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = st.MembershipTransition(42, nil, nil, write, now) |
| + if (err != nil) != tc.wantRefuse { |
| + t.Fatalf("err=%v want refusal=%v", err, tc.wantRefuse) |
| + } |
| + if tc.wantRefuse { |
| + for _, want := range []string{"first-token-id", "second-token-id", "deploy label", "deploy name", "another@keymail.dev", "console: cannot remove the last owner while CLI or service tokens remain unrevoked. revoke them first through the account's service pages (including expired tokens):"} { |
| + if !strings.Contains(err.Error(), want) { |
| + t.Errorf("refusal missing %q: %v", want, err) |
| + } |
| + } |
| + } |
| + role, err := st.Role(42, "owner@keymail.dev") |
| + if err != nil || (role == RoleOwner) != tc.wantRefuse { |
| + t.Fatalf("owner role=%q err=%v", role, err) |
| + } |
| + var count int |
| + if err := st.db.QueryRow(`SELECT COUNT(*) FROM cli_tokens WHERE revoked_at = ?`, revoked).Scan(&count); err != nil || count != 2 { |
| + t.Fatalf("tokens changed: count=%d err=%v", count, err) |
| + } |
| + if _, err := st.db.Exec(`DETACH DATABASE demo_holding_registry`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if tc.wantRefuse { |
| + for _, id := range []string{"first-token-id", "second-token-id"} { |
| + if err := st.RevokeAccountToken(42, id, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := st.RemoveDemoHoldingMember(42, "owner@keymail.dev", cfg, path, nil, now); err != nil { |
| + t.Fatalf("remove after revocation: %v", err) |
| + } |
| + if role, err := st.Role(42, "owner@keymail.dev"); err != nil || role != "" { |
| + t.Fatalf("owner remains after revocation: role=%q err=%v", role, err) |
| + } |
| + } |
| + }) |
| + } |
| +} |