carlos / platform Public

feat: console member tool may empty the demo holding account

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 42cb3ce18378c52bdb12e6eee3e33d7dd6ca951f parent 6be0846
5 files changed, +433 −1
  • README.md +2 −0
  • cmd/console/member.go +43 −1
  • cmd/console/member_demo_test.go +118 −0
  • internal/console/demo_members.go +102 −0
  • internal/console/member_demo_test.go +168 −0

CI passed — run details

Intent

Attributed to this commit: 188 g CO₂e (18,089,823 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-holding-last-owner, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/README.md b/README.md
index efd37ddf5..cecef6f73 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. |
+After creating the holding account and its demo fleet, 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 reports when no members remain and lists any live CLI tokens. Revoke those tokens separately before enabling admission.
+
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..17eccdcbb 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,43 @@ 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("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)
+ tokens, err := st.AccountCLITokens(acct.ID)
+ if err != nil {
+ log.Fatalf("cannot list remaining CLI tokens; check and revoke them before enabling demo admission: %v", err)
+ }
+ if len(tokens) == 0 {
+ fmt.Println("No live CLI tokens remain on this account.")
+ return
+ }
+ fmt.Println("Live CLI tokens remain on this account; revoke them before enabling demo admission:")
+ for _, tok := range tokens {
+ fmt.Printf("%s\taddress=%q\tname=%q\tlabel=%q\tkind=%q\tapp=%q\n", tok.ID, tok.Address, tok.Name, tok.Label, tok.Kind, tok.App)
+ }
+}
+
// 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..52e8cde6a
--- /dev/null
+++ b/cmd/console/member_demo_test.go
@@ -0,0 +1,118 @@
+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 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"},
+ } {
+ 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)
+ }
+ }
+ // 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)
+ }
+ 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.extraMember {
+ 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 && strings.Contains(out, "has no members") {
+ t.Fatalf("false empty report: %s", out)
+ }
+ after, err := st.CLITokens("another@keymail.dev")
+ if err != nil || len(after) != 1 || after[0].ID != toks[0].ID {
+ t.Fatalf("tokens changed: %v %v", after, err)
+ }
+ })
+ }
+}
diff --git a/internal/console/demo_members.go b/internal/console/demo_members.go
new file mode 100644
index 000000000..ec2a32b00
--- /dev/null
+++ b/internal/console/demo_members.go
@@ -0,0 +1,102 @@
+package console
+
+import (
+ "database/sql"
+ "fmt"
+ "net/url"
+ "path/filepath"
+ "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 _, 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(`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`, accountID)
+ if err != nil {
+ return nil, err
+ }
+ return scanCLITokenRows(rows)
+}
diff --git a/internal/console/member_demo_test.go b/internal/console/member_demo_test.go
new file mode 100644
index 000000000..e933a4d14
--- /dev/null
+++ b/internal/console/member_demo_test.go
@@ -0,0 +1,168 @@
+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)
+ }
+}