carlos / platform Public

plans 6c: Astra round 1 fixes (secret file, read-back, cutoff runbook)

P1 secret handling: the webhook signing secret never goes to stdout or
stderr. --apply requires --secret-out <file>, checked before any Stripe
call; the file must not exist, is created with noclobber under umask 077
and chmod 600, and only its path is printed.

P1 replacement idempotency: every create's idempotency key names the
book version, and every create is read back by id. The run stops unless
the object is active, in the run's mode and the one asked for (lookup
key, amount, metadata, URL). A replayed archived object stops it with
"replacing an object within one book version is not supported: write a
new price book version". The runbook's "clear the lookup key and run
again" advice is gone. The fake stripe CLI now replays the first
response per idempotency key and answers GET by id.

P1 launch sponsorship coverage (runbook): cutoff set to the next whole
second, restart once it has passed, then list accounts created in
[cutoff, start] read-only from console.db and sponsor each with
deploy/billing/sponsored-unlimited.json, which a test pins to the
console's own launch limits and checks against the plan door.

P2: the house Checkout uses a fresh account created after the cutoff.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev d18318bee4b26ef8aa0aa8585c465d88f89803a8 parent 95fbbb7
5 files changed, +293 −40
  • cmd/console/stripesetup_script_test.go +106 −6
  • deploy/billing/sponsored-unlimited.json +19 −0
  • docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md +46 −15
  • internal/console/plansponsor_file_test.go +41 −0
  • scripts/stripe-setup.sh +81 −19

CI cancelled — superseded by a newer push — run details

diff --git a/cmd/console/stripesetup_script_test.go b/cmd/console/stripesetup_script_test.go
index e07f94972..0b017f177 100644
--- a/cmd/console/stripesetup_script_test.go
+++ b/cmd/console/stripesetup_script_test.go
@@ -36,6 +36,10 @@ type fakeStripeWorld struct {
Live bool `json:"live"`
Objects map[string][]map[string]any `json:"objects"`
Next int `json:"next"`
+ // Idem is every create's first response by idempotency key. As Stripe
+ // does, a create under a key it has seen gets that response again,
+ // whatever has happened to the object since.
+ Idem map[string]json.RawMessage `json:"idem"`
}
var stripeIDPrefix = map[string]string{
@@ -62,11 +66,15 @@ func fakeStripe(args []string) int {
}
verb, path := args[0], args[1]
var data [][2]string
+ idem := ""
for i := 2; i < len(args); i++ {
switch args[i] {
case "--confirm", "--live":
- case "--stripe-version", "--project-name", "-i":
+ case "--stripe-version", "--project-name":
i++
+ case "-i":
+ i++
+ idem = args[i]
case "-d":
i++
k, v, _ := strings.Cut(args[i], "=")
@@ -90,6 +98,23 @@ func fakeStripe(args []string) int {
return ""
}
kind := strings.TrimPrefix(path, "/v1/")
+ for k := range stripeIDPrefix {
+ id, ok := strings.CutPrefix(kind, k+"/")
+ if !ok || verb != "get" {
+ continue
+ }
+ for _, o := range w.Objects[k] {
+ if o["id"] == id {
+ return reply(o)
+ }
+ }
+ fmt.Println(`{"error":{"type":"invalid_request_error","message":"No such object"}}`)
+ return 1
+ }
+ if raw, ok := w.Idem[idem]; ok && verb == "post" && idem != "" {
+ fmt.Println(string(raw))
+ return 0
+ }
switch {
case verb == "get" && kind == "account":
return reply(map[string]any{"id": w.Account, "object": "account"})
@@ -140,6 +165,12 @@ func fakeStripe(args []string) int {
w.Objects = map[string][]map[string]any{}
}
w.Objects[kind] = append(w.Objects[kind], stored)
+ if idem != "" {
+ if w.Idem == nil {
+ w.Idem = map[string]json.RawMessage{}
+ }
+ w.Idem[idem], _ = json.Marshal(o)
+ }
b, _ := json.Marshal(w)
if err := os.WriteFile(worldPath, b, 0o600); err != nil {
return 99
@@ -295,7 +326,8 @@ func (w *stripeWorld) run(env []string, args ...string) (string, string, int) {
func TestStripeSetupLiveApply(t *testing.T) {
w := newStripeWorld(t, liveAccount, true)
env := []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}
- stdout, stderr, code := w.run(env, "--live", "--apply")
+ secretFile := filepath.Join(w.dir, "webhook-secret")
+ stdout, stderr, code := w.run(env, "--live", "--apply", "--secret-out", secretFile)
if code != 0 {
t.Fatalf("live --apply failed (%d):\n%s\n%s", code, stdout, stderr)
}
@@ -333,8 +365,22 @@ func TestStripeSetupLiveApply(t *testing.T) {
t.Errorf("stdout lacks %q:\n%s", want, stdout)
}
}
- if !strings.Contains(stderr, "CARLOS_STRIPE_WEBHOOK_SECRET=whsec_FakeSecret") || strings.Contains(stdout, "whsec_FakeSecret") {
- t.Errorf("the signing secret must go to stderr only")
+ // The signing secret is in the file alone, never on either stream.
+ if strings.Contains(stdout+stderr, "FakeSecret") {
+ t.Errorf("the signing secret reached the output")
+ }
+ if !strings.Contains(stdout, secretFile) {
+ t.Errorf("stdout does not name the secret file")
+ }
+ fi, err := os.Stat(secretFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fi.Mode().Perm() != 0o600 {
+ t.Errorf("secret file mode %v, want 0600", fi.Mode().Perm())
+ }
+ if b, _ := os.ReadFile(secretFile); string(b) != "CARLOS_STRIPE_WEBHOOK_SECRET=whsec_FakeSecret\n" {
+ t.Errorf("secret file holds %q", b)
}
before := len(calls)
@@ -349,7 +395,7 @@ func TestStripeSetupLiveApply(t *testing.T) {
// A sandbox --apply still never passes --live and makes test-mode objects.
func TestStripeSetupSandboxApply(t *testing.T) {
w := newStripeWorld(t, sandboxAccount, false)
- if stdout, stderr, code := w.run(nil, "--apply"); code != 0 {
+ if stdout, stderr, code := w.run(nil, "--apply", "--secret-out", filepath.Join(w.dir, "secret")); code != 0 {
t.Fatalf("sandbox --apply failed (%d):\n%s\n%s", code, stdout, stderr)
}
for _, c := range w.calls() {
@@ -428,6 +474,10 @@ func TestStripeSetupLiveRefusals(t *testing.T) {
args: []string{"--live", "--apply"}, env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, want: "not in live mode"},
{name: "a sandbox run against live", account: sandboxAccount, live: true, args: []string{"--apply"},
want: "balance is not in test mode"},
+ {name: "apply without --secret-out", account: liveAccount, live: true, args: []string{"--live", "--apply", "--no-secret-out"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, want: "needs --secret-out", noCallsAt: true},
+ {name: "secret file already there", account: liveAccount, live: true, args: []string{"--live", "--apply", "--secret-exists"},
+ env: []string{"STRIPE_LIVE_ACCOUNT=" + liveAccount}, want: "already exists", noCallsAt: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -436,7 +486,21 @@ func TestStripeSetupLiveRefusals(t *testing.T) {
w.save(fakeStripeWorld{Account: tc.account, Live: tc.live,
Objects: map[string][]map[string]any{"products": tc.seed}})
}
- stdout, stderr, code := w.run(tc.env, tc.args...)
+ // An apply names a new secret file unless the case is about it.
+ args := slices.Clone(tc.args)
+ switch {
+ case slices.Contains(args, "--no-secret-out"):
+ args = slices.DeleteFunc(args, func(a string) bool { return a == "--no-secret-out" })
+ case slices.Contains(args, "--secret-exists"):
+ f := filepath.Join(w.dir, "secret")
+ if err := os.WriteFile(f, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ args = append(slices.DeleteFunc(args, func(a string) bool { return a == "--secret-exists" }), "--secret-out", f)
+ case slices.Contains(args, "--apply"):
+ args = append(args, "--secret-out", filepath.Join(w.dir, "secret"))
+ }
+ stdout, stderr, code := w.run(tc.env, args...)
if code == 0 {
t.Fatalf("not refused:\n%s", stdout)
}
@@ -454,6 +518,42 @@ func TestStripeSetupLiveRefusals(t *testing.T) {
}
}
+// A price archived (lookup key cleared) after it was made is not made again
+// under the same book version: Stripe answers the create by replaying the
+// first response, which still says active, so the script reads the price
+// back and stops, naming the way out (a new book version).
+func TestStripeSetupReplayedArchivedPriceStops(t *testing.T) {
+ w := newStripeWorld(t, sandboxAccount, false)
+ if stdout, stderr, code := w.run(nil, "--apply", "--secret-out", filepath.Join(w.dir, "secret-1")); code != 0 {
+ t.Fatalf("first apply failed (%d):\n%s\n%s", code, stdout, stderr)
+ }
+ fw := w.load()
+ archived := ""
+ for _, p := range fw.Objects["prices"] {
+ if p["lookup_key"] == "2026-11-01-v1/personal/usd" {
+ p["active"], p["lookup_key"] = false, nil
+ archived = p["id"].(string)
+ }
+ }
+ if archived == "" {
+ t.Fatal("no personal/usd price was made")
+ }
+ w.save(fw)
+ stdout, stderr, code := w.run(nil, "--apply", "--secret-out", filepath.Join(w.dir, "secret-2"))
+ if code == 0 {
+ t.Fatalf("a replayed archived price was accepted:\n%s", stdout)
+ }
+ if !strings.Contains(stderr, archived) || !strings.Contains(stderr, "new price book version") {
+ t.Fatalf("refusal does not name the price and the way out: %s", stderr)
+ }
+ if strings.Contains(stdout, "CARLOS_BILLING_PRICES=") {
+ t.Fatalf("the environment block was printed after the refusal")
+ }
+ if n := len(w.load().Objects["prices"]); n != 24 {
+ t.Fatalf("%d prices, want the first run's 24", n)
+ }
+}
+
// Every book in deploy/billing loads against the example catalog (the one
// dev runs), and the newest one is approved for live.
func TestRepoPriceBooksLoad(t *testing.T) {
diff --git a/deploy/billing/sponsored-unlimited.json b/deploy/billing/sponsored-unlimited.json
new file mode 100644
index 000000000..ead502d73
--- /dev/null
+++ b/deploy/billing/sponsored-unlimited.json
@@ -0,0 +1,19 @@
+{
+ "running_things": 2305843009213693951,
+ "sidecars_per_app": 2305843009213693951,
+ "idle_seconds": 9223372036,
+ "memory_tier": "default",
+ "awake_hours_month": 2305843009213693951,
+ "disk_bytes": 2305843009213693951,
+ "storage_bytes": 2305843009213693951,
+ "storage_self_serve": true,
+ "email_per_day": 2305843009213693951,
+ "bandwidth_bytes_month": 2305843009213693951,
+ "custom_domains": true,
+ "fleets": true,
+ "min_schedule_seconds": 1,
+ "history_days": 106751,
+ "rate_client_share": 1000000,
+ "rate_per_second": 1000000,
+ "rate_burst": 1000000
+}
diff --git a/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md b/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
index 2e6e66ead..263b96190 100644
--- a/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
+++ b/docs/superpowers/plans/2026-10-27-plans-6c-stripe-setup.md
@@ -183,7 +183,8 @@ export CONSOLE_URL=https://platform.dev.carlosframework.com
export STRIPE_TAX_CODE=txcd_10103000 # the default; see 6.2
scripts/stripe-setup.sh # dry run: sends nothing, prints every command
scripts/stripe-setup.sh --check # reads only: what exists, what is wrong, what is missing
-scripts/stripe-setup.sh --apply # makes what is missing
+secrets="$(mktemp -d)" # a new 0700 directory for the signing secret
+scripts/stripe-setup.sh --apply --secret-out "$secrets/webhook-secret" # makes what is missing
scripts/stripe-setup.sh --check # again: everything exists and nothing is wrong
```
@@ -194,8 +195,9 @@ What the script does:
- It checks that the CLI is on the expected account (`STRIPE_ACCOUNT`, default `acct_1UVFkoIiAD0xflDQ`) and in test mode: `GET /v1/balance` must say `livemode: false`. Every object it reads or makes must say `livemode: false`. Without `--live` it never passes `--live`, and it refuses a live `STRIPE_API_KEY` or a set `STRIPE_LIVE_ACCOUNT`.
- It finds existing objects first: products by `metadata[carlos_product]`, prices by `lookup_key` or `metadata[price_key]` on their product, the portal configuration by `metadata[carlos_portal]=locked`, the coupon by `metadata[carlos_coupon]=house` and the endpoint by its URL. It looks only at live objects: active products, prices and portal configurations, valid coupons and enabled endpoints. It makes only what is missing, so running it twice makes nothing the second time.
- It never deletes, archives or edits anything. If something exists but breaks a rule in section 2, it stops, names the object and the rule, and leaves the fix to you in the Dashboard.
-- Each create carries an idempotency key (`stripe-setup:<kind>:<name>`). If a response gets lost, running again within 24 hours returns the same object instead of a second one.
-- When it makes the webhook endpoint, it prints the signing secret once, to stderr, and writes it nowhere. Copy it straight into the console's EnvironmentFile (4.4). If you lose it, roll the secret in the Dashboard.
+- Each create carries an idempotency key naming the book version (`stripe-setup:<book>:<kind>:<name>`). If a response gets lost, running again within 24 hours returns the same object instead of a second one.
+- After every create it reads the object back by id. It stops unless the object is active, in the run's mode, and the one it asked for (key, amount, metadata). A create Stripe answers by replaying an earlier response, for an object archived since, therefore stops the run (section 7).
+- `--apply` needs `--secret-out <file>`, a file that does not exist yet. If it makes the webhook endpoint, it writes `CARLOS_STRIPE_WEBHOOK_SECRET=whsec_...` there, mode 0600, and prints only the path. The secret never goes to stdout or stderr, so it stays out of logs and transcripts. Move it into 1Password and the console's EnvironmentFile (4.4), then delete the file and its directory. If you lose it, roll the secret in the Dashboard.
- At the end it prints the console's non-secret variables, ready to paste.
Two questions only the sandbox can answer:
@@ -247,7 +249,7 @@ The dev console's systemd unit, `/etc/systemd/system/console.service`, exists on
3. Write `/etc/carlos/billing.env`, root:root, mode 0600, holding:
- the block the script printed (`CARLOS_BILLING=test`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES` in single quotes, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, `CARLOS_STRIPE_HOUSE_COUPON`);
- `CARLOS_STRIPE_SECRET_KEY=rk_test_...`, the key from 4.3;
- - `CARLOS_STRIPE_WEBHOOK_SECRET=whsec_...`, the secret the script printed on stderr.
+ - `CARLOS_STRIPE_WEBHOOK_SECRET=whsec_...`, the line in the script's `--secret-out` file.
Keep the secrets off any command line, and out of SSM send-command output. Either put them in SSM Parameter Store as SecureStrings and have the box read them (the pattern in `2026-10-05-scanner-host-rollout.md`, Task 9, steps 3 and 5), or type them in an interactive session on the box.
4. Add `/etc/systemd/system/console.service.d/billing.conf`:
@@ -324,6 +326,7 @@ The product tax code is `txcd_10103000`, "Software as a service (SaaS), personal
- Every call carries `--live`. `GET /v1/account` must report `STRIPE_LIVE_ACCOUNT`, `GET /v1/balance` must say `livemode: true`, and every object it lists or makes must say `livemode: true`. A test object in a live list stops the run.
- `STRIPE_API_KEY`, if set, overrides the CLI's login. With `--live` it must be an `sk_live_` or `rk_live_` key. Without `--live` a live key is refused.
- The dry run sends nothing, and `--check` only reads, exactly as in the sandbox.
+- As in the sandbox, every create is read back by id before it is used, and the webhook signing secret goes only to the `--secret-out` file (4.2).
- The printed block says `CARLOS_BILLING=live`.
`cmd/console/stripesetup_script_test.go` runs every one of these against a fake stripe CLI.
@@ -354,24 +357,52 @@ Then us:
export STRIPE_LIVE_ACCOUNT=acct_... # from step 3
scripts/stripe-setup.sh --live # dry run: sends nothing
scripts/stripe-setup.sh --live --check # reads only
- scripts/stripe-setup.sh --live --apply # makes the 8 products, 24 prices, portal, coupon, endpoint
+ secrets="$(mktemp -d)" # a new 0700 directory
+ scripts/stripe-setup.sh --live --apply --secret-out "$secrets/webhook-secret"
+ # makes the 8 products, 24 prices, portal, coupon, endpoint
scripts/stripe-setup.sh --live --check # everything exists, nothing wrong
```
- The webhook signing secret is printed once, on stderr. Save it in 1Password straight away. Whatever the sandbox run learnt about the portal (4.2) applies here too.
+ The webhook signing secret is only in `$secrets/webhook-secret`. Move it into 1Password, and from there into the flagship's `billing.env` (step 6). Then delete the file and the directory: `rm "$secrets/webhook-secret" && rmdir "$secrets"`. Whatever the sandbox run learnt about the portal (4.2) applies here too.
6. **The flagship console's files,** shaped as in 4.4, on a console running v0.33.1 or later:
- - `/etc/carlos/plans.json`: the example catalog, version `2026-10-20-v1`, plus `"sponsor_accounts_before": "<UTC time>"` in whole seconds, no later than the restart in step 7 (the time you write the file will do). Keep the version: the book prices `2026-10-20-v1`, and a new catalog version would need a new book.
+ - `/etc/carlos/plans.json`: the example catalog, version `2026-10-20-v1`, plus `"sponsor_accounts_before"`, written last (step 7). Keep the version: the book prices `2026-10-20-v1`, and a new catalog version would need a new book.
- `/etc/carlos/pricebook-2026-11-01-v1.json`, root:root 0644, never edited afterwards.
- `/etc/carlos/billing.env`, root:root 0600: the block step 5 printed (`CARLOS_BILLING=live`, `CARLOS_PLAN_CATALOG`, `CARLOS_PRICE_BOOK`, `CARLOS_BILLING_PRICES` in single quotes, `CARLOS_STRIPE_ACCOUNT`, `CARLOS_STRIPE_PORTAL_CONFIGURATION`, `CARLOS_STRIPE_HOUSE_COUPON`), plus `CARLOS_STRIPE_SECRET_KEY` from step 4 and `CARLOS_STRIPE_WEBHOOK_SECRET` from step 5. The secrets reach the box through SSM SecureStrings or an interactive session, never a command line.
- `console.service.d/billing.conf` with `EnvironmentFile=/etc/carlos/billing.env`, no leading `-`.
With the catalog in `billing.env`, plans and billing go on together.
-7. **One restart:** `systemctl daemon-reload && systemctl restart console.service`. In the log:
- - `console: sponsored N existing accounts with no limits (created before ...)`. N is every account but the ops one. `PLANS ARE OFF` instead means sponsoring failed: plans and billing both stay off, and the log says why.
- - `console: billing is ready`. `billing not ready:` names the object and the rule. `scripts/stripe-setup.sh --live --check` shows the same from Stripe's side.
- - `https://console.carloku.com/billing/webhook` no longer answers 503.
-8. **A first house-account Checkout at zero:** mark an account of ours as house, never `bab`, which has no billing: `carlos billing house -account <sqid> -on -note "first live checkout"`. Buy Personal from its billing page. Checkout shows a total of 0, the webhook delivery succeeds in the Dashboard, and the account's billing page shows Personal.
-9. Then publish `https://console.carloku.com/upgrade?plan=<plan>&currency=<cur>` and the pricing page (Plan 7).
+7. **The cutoff, then one restart.** The console refuses a cutoff later than its start, so the cutoff comes before the restart. Accounts created between the two are not sponsored by the console, and are sponsored by hand in step 8.
+ 1. With every other file in place, set `sponsor_accounts_before` in `/etc/carlos/plans.json` to the next whole second, for example the output of `date -u -d '+1 second' +%Y-%m-%dT%H:%M:%SZ`.
+ 2. Once that second has passed, `systemctl daemon-reload && systemctl restart console.service`.
+ 3. In the log:
+ - `console: sponsored N existing accounts with no limits (created before ...)`. N is every account created before the cutoff but the ops one. `PLANS ARE OFF` instead means sponsoring failed: plans and billing both stay off, and the log says why.
+ - `console: billing is ready`. `billing not ready:` names the object and the rule. `scripts/stripe-setup.sh --live --check` shows the same from Stripe's side.
+ - `https://console.carloku.com/billing/webhook` no longer answers 503.
+8. **Accounts created between the cutoff and the start,** straight after the start. No `carlos` command lists accounts by creation time, so read the console's database, read-only, on the console box (`CONSOLE_DB`, `/data/console/console.db` by default):
+
+ ```sh
+ cutoff=$(date -u -d '<the cutoff from step 7>' +%s)
+ start=$(date -d "$(systemctl show console.service -p ExecMainStartTimestamp --value)" +%s)
+ python3 -c 'import sqlite3, sys; db = sqlite3.connect("file:/data/console/console.db?mode=ro", uri=True); [print(*r) for r in db.execute("SELECT sqid, name, created_at FROM accounts WHERE created_at >= ? AND created_at <= ? ORDER BY created_at", (int(sys.argv[1]), int(sys.argv[2])))]' "$cutoff" "$start"
+ ```
+
+ The window includes the start's own second, because the old console may have created an account in it. The cost is that an account made in the new console's first second is sponsored too. Sponsor each account listed, with the launch sponsorship's own limits:
+
+ ```sh
+ carlos accounts plan --console https://console.carloku.com --account <sqid> --set free \
+ --sponsored deploy/billing/sponsored-unlimited.json --reason "existing account at plan launch"
+ ```
+
+ `free` is the catalog's `default_plan`. `deploy/billing/sponsored-unlimited.json` is exactly what the console gives an account it sponsors at start. `TestSponsoredUnlimitedFileIsTheLaunchSponsorship` keeps it so, and checks that the plan door accepts it. An empty list means nothing to do.
+9. **A first house-account Checkout at zero,** on a new account. Billing refuses Checkout for a sponsored account, and every account from before the cutoff is sponsored now, so make a fresh one. Never use `bab`, which has no billing:
+
+ ```sh
+ carlos accounts create --console https://console.carloku.com --name house-checkout
+ carlos billing house -account <its sqid> -on -note "first live checkout"
+ ```
+
+ Buy Personal from its billing page. Checkout shows a total of 0, the webhook delivery succeeds in the Dashboard, and the account's billing page shows Personal.
+10. Then publish `https://console.carloku.com/upgrade?plan=<plan>&currency=<cur>` and the pricing page (Plan 7).
To turn billing off again, set `CARLOS_BILLING=off` and restart. Nothing at Stripe changes. Plans stay on, and the existing accounts stay sponsored.
@@ -379,5 +410,5 @@ To turn billing off again, set `CARLOS_BILLING=off` and restart. Nothing at Stri
- **The console refuses to start.** The log names the variable. Fix `/etc/carlos/billing.env`, run `systemctl reset-failed console.service` and start it again. Or set `CARLOS_BILLING=off`.
- **The readiness check fails.** The log names the price key or the object, and the rule it broke. Run `scripts/stripe-setup.sh --check` to see the same thing from the Stripe side.
-- **A wrong object was made.** Archive it in the Dashboard (deactivate a portal configuration, delete a coupon, disable an endpoint), then run the script again. The script ignores archived objects, so it makes a new one. Prices and products that have been used cannot be deleted, only archived.
-- **Stripe refuses a new price because its lookup key is taken.** An older price still holds the key: archiving a product does not archive its prices, and an archived price may keep its key. Clear that price's lookup key in the Dashboard, then run again. The script never moves a lookup key itself.
+- **A wrong object was made.** Replacing an object within one book version is not supported. Archive the wrong object in the Dashboard (archive a price or product, deactivate a portal configuration, delete a coupon, disable an endpoint). Then write a new book version: a new file and version, with the same or corrected amounts, which gives every price a new key and every create a new idempotency key. Run the script with `PRICE_BOOK` set to the new book, and point `CARLOS_PRICE_BOOK` and `CARLOS_BILLING_PRICES` at it. Prices and products that have been used cannot be deleted, only archived.
+- **The script stops with "Stripe replayed an earlier create".** That is the same case: it asked for an object under a key it used before, and Stripe answered with the earlier object, which has since been archived or changed. The script will not use it. Write a new book version, as above.
diff --git a/internal/console/plansponsor_file_test.go b/internal/console/plansponsor_file_test.go
new file mode 100644
index 000000000..f6d16d83c
--- /dev/null
+++ b/internal/console/plansponsor_file_test.go
@@ -0,0 +1,41 @@
+package console
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "reflect"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// deploy/billing/sponsored-unlimited.json is the limits file the plans 6c
+// runbook hands `carlos accounts plan --sponsored` for an account created
+// between the launch cutoff and the console's start. It must be exactly the
+// launch sponsorship's own limits, and the plan door must accept it.
+func TestSponsoredUnlimitedFileIsTheLaunchSponsorship(t *testing.T) {
+ b, err := os.ReadFile("../../deploy/billing/sponsored-unlimited.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ dec := json.NewDecoder(bytes.NewReader(b))
+ dec.DisallowUnknownFields()
+ var got plans.Limits
+ if err := dec.Decode(&got); err != nil {
+ t.Fatal(err)
+ }
+ if want := sponsorUnlimited(); !reflect.DeepEqual(got, want) {
+ t.Fatalf("the file holds %+v, the launch sponsorship %+v", got, want)
+ }
+ cat, err := plans.LoadCatalog("../plans/testdata/example-catalog.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if msg := planRequestProblem(cat, setAccountPlanRequest{Plan: cat.DefaultPlan, Sponsored: &got}); msg != "" {
+ t.Fatal(msg)
+ }
+ if _, err := cat.Effective(cat.DefaultPlan, nil, &got, 1); err != nil {
+ t.Fatalf("the plan door would refuse it: %v", err)
+ }
+}
diff --git a/scripts/stripe-setup.sh b/scripts/stripe-setup.sh
index 057dae654..cd8fa1326 100755
--- a/scripts/stripe-setup.sh
+++ b/scripts/stripe-setup.sh
@@ -21,8 +21,10 @@
# Read only. Checks the account and its mode, finds what exists,
# checks it the way the console's readiness check does, and prints
# what --apply would create.
-# CONSOLE_URL=... scripts/stripe-setup.sh --apply
-# As --check, then creates whatever is missing.
+# CONSOLE_URL=... scripts/stripe-setup.sh --apply --secret-out <file>
+# As --check, then creates whatever is missing. If it makes the
+# webhook endpoint, it writes the endpoint's signing secret to <file>,
+# mode 0600, and prints only the path. <file> must not exist yet.
# Add --live to any of the three for the live account. Live needs
# STRIPE_LIVE_ACCOUNT=acct_... naming the live account, and an approved
# price book. Start with a live dry run, then a live --check.
@@ -71,8 +73,14 @@
# Lookups see only live objects: active products, prices and portal
# configurations, valid coupons, enabled endpoints. So once a wrong
# object is archived in the Dashboard, the next run makes a new one.
-# - The webhook signing secret is printed once, to stderr, and is written
-# to no file.
+# - The webhook signing secret never goes to stdout or stderr. It goes
+# only to the --secret-out file, which --apply requires up front.
+# - After every create it reads the object back by id, and stops unless
+# it is active, in the run's mode and the object it asked for. Each
+# create's idempotency key names the book version, so a create Stripe
+# answers with an earlier object (one since archived) stops the run:
+# replacing an object within one book version is not supported. Write
+# a new book version, with new price keys, instead.
#
# Needs bash, jq and the stripe CLI.
set -euo pipefail
@@ -96,16 +104,29 @@ usage() { sed -n '4,/^set -euo/p' "${BASH_SOURCE[0]}" | sed -e '/^set -euo/d' -e
mode="dry-run"
live=false
+secret_out=""
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help) usage; exit 0 ;;
--apply) mode="apply"; shift ;;
--check) mode="check"; shift ;;
--live) live=true; shift ;;
+ --secret-out)
+ [[ $# -ge 2 && -n "$2" ]] || die "--secret-out needs a file path"
+ secret_out="$2"; shift 2 ;;
*) die "unknown argument: $1 (try --help)" ;;
esac
done
if [[ "$live" == true ]]; then mode_word="live"; else mode_word="test"; fi
+# The webhook signing secret goes to a file and never to a terminal or a log,
+# so an apply, which may make the endpoint, needs that file named up front.
+if [[ "$mode" == apply ]]; then
+ [[ -n "$secret_out" ]] || die "--apply needs --secret-out <file>: where the new webhook endpoint's signing secret goes (mode 0600)"
+fi
+if [[ -n "$secret_out" ]]; then
+ [[ ! -e "$secret_out" && ! -L "$secret_out" ]] || die "--secret-out $secret_out already exists. Name a new file"
+ [[ -d "$(dirname "$secret_out")" ]] || die "--secret-out $secret_out: its directory does not exist"
+fi
command -v jq >/dev/null || die "jq is needed"
if [[ "$mode" != "dry-run" ]]; then
@@ -297,6 +318,24 @@ made_object() {
id="$(jq -r .id <<<"$out")"
}
+# read_back reads the object just made, $id, again by id into $out, and
+# stops unless <problem> (a jq program over it, with the given jq args)
+# comes back empty. A create Stripe answers by replaying an earlier response
+# under the same idempotency key carries that object's old state; only a
+# fresh read shows whether it has since been archived or changed.
+read_back() { # <what> <path> <problem> [jq args...] -- [read args...]
+ local what="$1" path="$2" prog="$3" problem
+ shift 3
+ local jqargs=()
+ while [[ $# -gt 0 && "$1" != -- ]]; do jqargs+=("$1"); shift; done
+ [[ $# -gt 0 ]] && shift
+ read_call get "$path/$id" "$@"
+ jq -e --arg id "$id" '.id == $id' >/dev/null <<<"$out" || die "reading $what $id back returned another object. Stopping"
+ problem="$(jq -r "${jqargs[@]}" "$prog" <<<"$out")"
+ [[ -z "$problem" ]] ||
+ die "the create for $what was answered with $id, which is $problem. Stripe replayed an earlier create under the same idempotency key, for an object since archived or changed. Replacing an object within one book version is not supported: write a new price book version (new file, new version, new price keys) and run with it"
+}
+
ids='{}' # what the env block prints
prices='{}' # price key -> price id
remember() { ids="$(jq -c --arg k "$1" --arg v "$2" '. + {($k): $v}' <<<"$ids")"; }
@@ -329,6 +368,12 @@ readonly PRICE_PROBLEM='
elif (.metadata.price_key // "") != $key then "its metadata price_key is not its key"
else "" end'
+readonly PRODUCT_PROBLEM='
+ if .active != true then "not active"
+ elif .livemode != '"$live"' then "not in '"$mode_word"' mode"
+ elif (.metadata.carlos_product // "") != $meta then "not the product for \($meta)"
+ else "" end'
+
readonly PORTAL_PROBLEM='
.features as $f
| if .active != true then "not active"
@@ -436,9 +481,10 @@ setup_product() { # <metadata value> <book section> <book name>
else
echo "# none yet; this creates it:"
product_name "$meta"
- if write_call post /v1/products -i "stripe-setup:product:$meta" \
+ if write_call post /v1/products -i "stripe-setup:$book_version:product:$meta" \
-d "name=$pname" -d "tax_code=$tax_code" -d "metadata[carlos_product]=$meta"; then
made_object prod_
+ read_back "product $meta" /v1/products "$PRODUCT_PROBLEM" --arg meta "$meta"
pid="$id"
made=1
echo "# created: $pid"
@@ -469,7 +515,7 @@ setup_product() { # <metadata value> <book section> <book name>
[[ -z "$problem" ]] || die "price $key ($prid): $problem. The console would refuse it. Archive it in the Dashboard and run again"
[[ "$(jq -r '.[0].lookup_key // ""' <<<"$found")" == "$key" ]] || warn "price $key ($prid) has no lookup_key $key. The console does not read it"
echo "# exists: $prid"
- elif write_call post /v1/prices -i "stripe-setup:price:$key" \
+ elif write_call post /v1/prices -i "stripe-setup:$book_version:price:$key" \
-d "product=$pid" -d "currency=$cur" -d "unit_amount=$amount" \
-d "recurring[interval]=year" -d "recurring[interval_count]=1" -d "recurring[usage_type]=licensed" \
-d billing_scheme=per_unit -d tax_behavior=exclusive \
@@ -478,6 +524,10 @@ setup_product() { # <metadata value> <book section> <book name>
prid="$id"
problem="$(jq -r --arg key "$key" --arg currency "$cur" --argjson amount "$amount" --arg product "$pid" "$PRICE_PROBLEM" <<<"$out")"
[[ -z "$problem" ]] || die "the price just made for $key ($prid): $problem. Stopping"
+ read_back "price $key" /v1/prices \
+ "($PRICE_PROBLEM) as \$p | if \$p == \"\" and (.lookup_key // \"\") != \$key then \"without lookup key \\(\$key)\" else \$p end" \
+ --arg key "$key" --arg currency "$cur" --argjson amount "$amount" --arg product "$pid" \
+ -- -d "expand[]=currency_options"
echo "# created: $prid"
else
prid="$(placeholder "price $key")"
@@ -518,11 +568,13 @@ else
[[ -z "$privacy_url" ]] || args+=(-d "business_profile[privacy_policy_url]=$privacy_url")
[[ -z "$terms_url" ]] || args+=(-d "business_profile[terms_of_service_url]=$terms_url")
args+=(-d "metadata[carlos_portal]=locked")
- if write_call post /v1/billing_portal/configurations -i "stripe-setup:portal:locked" "${args[@]}"; then
+ if write_call post /v1/billing_portal/configurations -i "stripe-setup:$book_version:portal:locked" "${args[@]}"; then
made_object bpc_
portal="$id"
problem="$(jq -r "$PORTAL_PROBLEM" <<<"$out")"
[[ -z "$problem" ]] || die "the portal configuration just made ($portal): $problem. Stopping"
+ read_back "the locked portal configuration" /v1/billing_portal/configurations \
+ "($PORTAL_PROBLEM) as \$p | if \$p == \"\" and .metadata.carlos_portal != \"locked\" then \"not the locked configuration\" else \$p end"
echo "# created: $portal"
else
portal="$(placeholder "portal configuration")"
@@ -548,12 +600,16 @@ else
echo "# none yet; this creates it (no promotion code):"
args=(-d percent_off=100 -d duration=forever -d "expand[]=applies_to" -d "metadata[carlos_coupon]=house")
[[ -z "$coupon_name" ]] || args+=(-d "name=$coupon_name")
- if write_call post /v1/coupons -i "stripe-setup:coupon:house" "${args[@]}"; then
+ if write_call post /v1/coupons -i "stripe-setup:$book_version:coupon:house" "${args[@]}"; then
jq -e --argjson live "$live" '.livemode == $live and (.id | type == "string" and test("^[A-Za-z0-9_-]{1,200}$"))' >/dev/null <<<"$out" ||
die "the coupon just made is not a $mode_word-mode coupon with a usable id"
coupon="$(jq -r .id <<<"$out")"
problem="$(jq -r "$COUPON_PROBLEM" <<<"$out")"
[[ -z "$problem" ]] || die "the coupon just made ($coupon): $problem. Stopping"
+ id="$coupon"
+ read_back "the house coupon" /v1/coupons \
+ "($COUPON_PROBLEM) as \$p | if \$p == \"\" and .metadata.carlos_coupon != \"house\" then \"not the house coupon\" else \$p end" \
+ -- -d "expand[]=applies_to"
echo "# created: $coupon"
else
coupon="$(placeholder "house coupon")"
@@ -575,29 +631,35 @@ if ((n == 1)); then
we="$(jq -r '.[0].id' <<<"$found")"
problem="$(jq -r --arg version "$API_VERSION" --argjson events "$events_json" ".[0] | $WEBHOOK_PROBLEM" <<<"$found")"
[[ -z "$problem" ]] || die "webhook endpoint $we: $problem. Fix its events in the Dashboard, or, for a wrong API version (fixed when an endpoint is made), disable it and run again"
- echo "# exists: $we. Its signing secret was shown when it was made."
+ echo "# exists: $we. Its signing secret went to the --secret-out file when it was made."
echo "# If you do not have it, roll it in the Dashboard (Developers, Webhooks, the endpoint, Roll secret)."
else
echo "# none yet; this creates it:"
args=(-d "url=$webhook_url")
for e in "${WEBHOOK_EVENTS[@]}"; do args+=(-d "enabled_events[]=$e"); done
args+=(-d "api_version=$API_VERSION" -d "description=console billing" -d "metadata[carlos_webhook]=billing")
- if write_call post /v1/webhook_endpoints -i "stripe-setup:webhook:$webhook_url" "${args[@]}"; then
+ if write_call post /v1/webhook_endpoints -i "stripe-setup:$book_version:webhook:$webhook_url" "${args[@]}"; then
made_object we_
problem="$(jq -r --arg version "$API_VERSION" --argjson events "$events_json" "$WEBHOOK_PROBLEM" <<<"$out")"
[[ -z "$problem" ]] || die "the webhook endpoint just made ($id): $problem. Stopping"
secret="$(jq -r '.secret // ""' <<<"$out")"
out=""
[[ "$secret" == whsec_* ]] || die "the new webhook endpoint ($id) came back without a signing secret. Roll its secret in the Dashboard"
- echo "# created: $id. Its signing secret is on stderr, once."
- {
- echo
- echo "CARLOS_STRIPE_WEBHOOK_SECRET=$secret"
- echo " ^ The webhook signing secret. It is shown once and kept nowhere else."
- echo " Put it in the console's EnvironmentFile now. Never put it in the repo, a ticket or a chat."
- echo
- } >&2
+ # Read back before the secret is kept: a replayed create carries the
+ # secret of an endpoint that may since have been disabled.
+ read_back "the webhook endpoint" /v1/webhook_endpoints \
+ "($WEBHOOK_PROBLEM) as \$p | if \$p == \"\" and .url != \$url then \"at another URL\" else \$p end" \
+ --arg version "$API_VERSION" --argjson events "$events_json" --arg url "$webhook_url"
+ out=""
+ # noclobber: the file is made new, never written through an existing one.
+ if ! (umask 077 && set -C && printf 'CARLOS_STRIPE_WEBHOOK_SECRET=%s\n' "$secret" >"$secret_out") 2>/dev/null; then
+ secret=""
+ die "could not write $secret_out. The endpoint $id exists: roll its secret in the Dashboard (Developers, Webhooks, the endpoint, Roll secret)"
+ fi
secret=""
+ chmod 600 "$secret_out"
+ echo "# created: $id. Its signing secret is in $secret_out (mode 0600), and nowhere else."
+ echo "# Move it into the password manager and the console's EnvironmentFile, then delete $secret_out."
fi
fi
echo
@@ -618,4 +680,4 @@ jq -r 'to_entries[] | "\(.key)=\(.value)"' <<<"$ids"
echo
echo "## Secrets: set them by hand in the same file. Never in the repo."
echo "# CARLOS_STRIPE_SECRET_KEY the rk_${mode_word}_ restricted key made in the Dashboard (the plans 6c runbook)"
-echo "# CARLOS_STRIPE_WEBHOOK_SECRET the whsec_ signing secret, printed on stderr when the endpoint is made"
+echo "# CARLOS_STRIPE_WEBHOOK_SECRET the whsec_ signing secret, in the --secret-out file when the endpoint is made"