billing: name every Stripe key permission; log Stripe 401/403 text
The money record lists balance transactions with their sources expanded, which needs Balance Transaction Sources read; the docs never said so, and both consoles got an hourly 403 until it was added. The docs now list every permission the console key needs, and billingstripe errors on 401/403 carry Stripe's message (keys redacted) so the log names a missing permission. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from billing-stripe-perm-followups into main.
5 files changed,
+163
−14
docs/site/plans.md+1 −1docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md+1 −1docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md+6 −3internal/billingstripe/client.go+82 −9internal/billingstripe/client_test.go+73 −0
CI passed — run details
diff --git a/docs/site/plans.md b/docs/site/plans.md| index adf32abd9..26df09a02 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -157,7 +157,7 @@ Every billing setting lives in the console's EnvironmentFile. None of them is a |
| If any of them is wrong, the console refuses to start and names the variable, never its value. |
| -The restricted key also needs read access to Balance, Charges and Refunds, and the webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`, so the console can record the money it receives. |
| +So the console can record the money it receives, the restricted key also needs read access to Balance, Balance Transaction Sources, Charges and Refunds, and Invoices. The webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`. |
| Point Stripe's webhook at `https://<console>/billing/webhook`. When the console starts, it checks the account, every price in the book, the portal configuration and the house coupon (if you set one) against Stripe before it accepts a webhook. Until that check passes, the webhook answers 503 and Stripe tries again later, so a console that starts while Stripe is unreachable catches up by itself. |
diff --git a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md| index f2bbdd863..ace39f50d 100644 |
| --- a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md |
| +++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md |
| @@ -80,7 +80,7 @@ BDC-32 to BDC-34 are new lines in the section's `sh` block, after `carlos billin |
| | id | file | text | status | |
| |---|---|---|---| |
| -| BDC-37 | docs/site/plans.md | The restricted key also needs read access to Balance, Charges and Refunds, and the webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`, so the console can record the money it receives. | approved | |
| +| BDC-37 | docs/site/plans.md | So the console can record the money it receives, the restricted key also needs read access to Balance, Balance Transaction Sources, Charges and Refunds, and Invoices. The webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`. | approved | |
| BDC-37 goes straight after the paragraph that starts "If any of them is wrong", which follows the variables table. |
diff --git a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md| index ed53f6716..8b5a05ea2 100644 |
| --- a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md |
| +++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md |
| @@ -874,7 +874,8 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - `docs/site/cli.md` `### carlos billing`: one paragraph for the two verbs |
| and their example lines. |
| - `docs/site/plans.md`: one sentence after the variables table saying the |
| - key also needs read access to balance, charges and refunds, and that |
| + key also needs read access to Balance, Balance Transaction Sources, |
| + Charges and Refunds, and Invoices (corrected 2026-11-10), and that |
| Stripe's webhook also sends `charge.succeeded`, `charge.captured` and |
| `charge.refunded`. |
| - `scripts/stripe-setup.sh`: the `WEBHOOK_PROBLEM` line that says "the six". |
| @@ -977,8 +978,10 @@ and §5; Plan 3 (written separately) covers §4.5. |
| ## After the plan |
| -- Before the first roll that carries this, Paul adds Balance, Charges and |
| - Refunds read to the dev and flagship restricted keys, and the three |
| +- Before the first roll that carries this, Paul adds Balance, Balance |
| + Transaction Sources (for `expand[]=data.source` on balance transactions), |
| + Charges and Refunds, and Invoices read to the dev and flagship restricted |
| + keys (Sources corrected 2026-11-10), and the three |
| charge events to both webhook endpoints. Without them the money pass |
| fails its job and nothing else changes; once added, the next hourly pass |
| backfills everything. |
diff --git a/internal/billingstripe/client.go b/internal/billingstripe/client.go| index 55521e8d5..68dfe3d1b 100644 |
| --- a/internal/billingstripe/client.go |
| +++ b/internal/billingstripe/client.go |
| @@ -23,6 +23,7 @@ import ( |
| "strconv" |
| "strings" |
| "time" |
| + "unicode/utf8" |
| "github.com/carlosframework/platform/internal/billing" |
| ) |
| @@ -42,10 +43,13 @@ const ( |
| requestTimeout = 15 * time.Second |
| ) |
| -// Stable, sanitized error codes. Error never carries a response body, |
| -// a Stripe error "message" (which can echo request parameters back) or |
| -// any request secret — only these codes plus the HTTP status and, for a |
| -// parsed Stripe API error, Stripe's own "type" and "code" enum values. |
| +// Stable, sanitized error codes. Error never carries a response body or |
| +// any request secret: only these codes plus the HTTP status and, for a |
| +// parsed Stripe API error, Stripe's own "type", "code" and "param" values. |
| +// Stripe's "message" (which can echo request parameters back) travels only |
| +// on a 401 or 403, where it describes the key, not the request: it names |
| +// the permission a restricted key lacks. Any key-shaped token in it is |
| +// redacted. |
| const ( |
| CodeInvalidParams = "invalid_params" |
| CodeInvalidID = "invalid_id" |
| @@ -72,6 +76,10 @@ type Error struct { |
| // StripeParam is Stripe's error "param" field: the request parameter |
| // the refusal is about. Present only for CodeAPIError. |
| StripeParam string |
| + // StripeMessage is Stripe's error "message", present only for a |
| + // CodeAPIError on a 401 or 403 (see stripeKeyMessage): control |
| + // characters dropped, key-shaped tokens redacted, length capped. |
| + StripeMessage string |
| // Replayed reports that the provider answered from its memory of an |
| // earlier request under the same idempotency key (its |
| // Idempotent-Replayed header), and ran nothing now. |
| @@ -101,6 +109,12 @@ func (e *Error) Error() string { |
| if e.StripeCode != "" { |
| parts = append(parts, "stripe_code="+e.StripeCode) |
| } |
| + if e.StripeParam != "" { |
| + parts = append(parts, "stripe_param="+e.StripeParam) |
| + } |
| + if e.StripeMessage != "" { |
| + parts = append(parts, "stripe_message="+strconv.Quote(e.StripeMessage)) |
| + } |
| if e.Cause != nil { |
| parts = append(parts, "cause="+e.Cause.Error()) |
| } |
| @@ -201,13 +215,62 @@ type stripeErrorEnvelope struct { |
| Type string `json:"type"` |
| Code string `json:"code"` |
| Param string `json:"param"` |
| - // message and param are deliberately not decoded: Stripe's message |
| - // text can interpolate request parameters (card numbers' last four, |
| - // email addresses, free-text fields), and this package promises |
| - // never to surface response-body content in an error. |
| + // Message is kept only for a 401 or 403 (stripeKeyMessage): on |
| + // other statuses Stripe's text can interpolate request parameters |
| + // (card numbers' last four, email addresses, free-text fields). |
| + Message string `json:"message"` |
| } `json:"error"` |
| } |
| +// maxStripeMessage caps the message an Error carries, in bytes. |
| +const maxStripeMessage = 400 |
| + |
| +// keyToken matches a whole word holding anything shaped like a Stripe key |
| +// or signing secret, masked or not, wherever in the word it starts |
| +// ("x_rk_live_..." too): Stripe masks keys in its messages, but redact |
| +// anyway. A plain word that happens to hold "sk_" ("desk_top") is |
| +// redacted as well; over-redacting a log line is the safe side. |
| +var keyToken = regexp.MustCompile(`(?i)[A-Za-z0-9_*.\-]*(?:rk|sk|pk|whsec)_[A-Za-z0-9_*.\-]*`) |
| + |
| +// stripeKeyMessage is a 401 or 403 message made safe to log: control |
| +// characters dropped first, so dropping one cannot rejoin a key the |
| +// redaction already passed over, then key-shaped tokens redacted, then |
| +// capped at maxStripeMessage bytes on a rune boundary. |
| +func stripeKeyMessage(msg string) string { |
| + msg = strings.Map(func(r rune) rune { |
| + if r == '\n' || r == '\t' { |
| + return ' ' |
| + } |
| + if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) || r == '\u2028' || r == '\u2029' || r == utf8.RuneError { |
| + return -1 |
| + } |
| + return r |
| + }, msg) |
| + msg = keyToken.ReplaceAllString(msg, "[redacted]") |
| + msg = strings.TrimSpace(msg) |
| + if len(msg) > maxStripeMessage { |
| + cut := maxStripeMessage |
| + for cut > 0 && !utf8.RuneStart(msg[cut]) { |
| + cut-- |
| + } |
| + msg = msg[:cut] + "..." |
| + } |
| + return msg |
| +} |
| + |
| +// keyWord matches a Stripe error code or param name: a short word of |
| +// lowercase letters, digits, underscores, dots and brackets. |
| +var keyWord = regexp.MustCompile(`^[a-z0-9_.\[\]]{1,64}$`) |
| + |
| +// stripeKeyWord keeps a 401 or 403 error's code or param when it is |
| +// word-shaped and not key-shaped, and drops it otherwise. |
| +func stripeKeyWord(v string) string { |
| + if !keyWord.MatchString(v) || keyToken.MatchString(v) { |
| + return "" |
| + } |
| + return v |
| +} |
| + |
| // response is what every answer carries besides its body. |
| type response struct { |
| Status int |
| @@ -308,7 +371,7 @@ func (c *Client) exchange(ctx context.Context, method, path, query string, body |
| if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| var env stripeErrorEnvelope |
| _ = json.Unmarshal(respBody, &env) // best-effort; body itself never leaves this function |
| - return meta, &Error{ |
| + apiErr := &Error{ |
| Code: CodeAPIError, |
| HTTPStatus: resp.StatusCode, |
| StripeType: safeErrorEnum(env.Error.Type), |
| @@ -316,6 +379,16 @@ func (c *Client) exchange(ctx context.Context, method, path, query string, body |
| StripeParam: safeErrorParam(env.Error.Param), |
| Replayed: meta.Replayed, |
| } |
| + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { |
| + apiErr.StripeMessage = stripeKeyMessage(env.Error.Message) |
| + if apiErr.StripeCode == "" { |
| + apiErr.StripeCode = stripeKeyWord(env.Error.Code) |
| + } |
| + if apiErr.StripeParam == "" { |
| + apiErr.StripeParam = stripeKeyWord(env.Error.Param) |
| + } |
| + } |
| + return meta, apiErr |
| } |
| if out == nil { |
diff --git a/internal/billingstripe/client_test.go b/internal/billingstripe/client_test.go| index d9b575d32..6a8a4df0e 100644 |
| --- a/internal/billingstripe/client_test.go |
| +++ b/internal/billingstripe/client_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "strings" |
| "testing" |
| "time" |
| + "unicode/utf8" |
| ) |
| func testClient(t *testing.T, base string) *Client { |
| @@ -448,6 +449,78 @@ func TestDo_APIErrorSanitized(t *testing.T) { |
| } |
| } |
| +// A restricted key missing a permission gets a 403 whose message names |
| +// the permission. The error carries that message, so the log says what to |
| +// grant, with every key-shaped token redacted. |
| +func TestDo_PermissionErrorCarriesMessage(t *testing.T) { |
| + const message = "The provided key 'rk_live_51AbCdEfGhIjKlMnOpQrStUv' does not have the required permissions for this endpoint on account 'acct_1'. Having the 'rak_balance_transaction_source_read' permission would allow this request to continue." |
| + for _, status := range []int{http.StatusForbidden, http.StatusUnauthorized} { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "invalid_request_error", |
| + "code": "secret_key_required", |
| + "param": "expand[0]", |
| + "message": message, |
| + }, |
| + }) |
| + })) |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetSubscription(context.Background(), "sub_1") |
| + srv.Close() |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError || e.HTTPStatus != status { |
| + t.Fatalf("%d: err = %v, want CodeAPIError", status, err) |
| + } |
| + msg := e.Error() |
| + for _, want := range []string{ |
| + "stripe_type=invalid_request_error", |
| + "stripe_code=secret_key_required", |
| + "stripe_param=expand[0]", |
| + "does not have the required permissions", |
| + "Having the 'rak_balance_transaction_source_read' permission would allow this request to continue.", |
| + "'[redacted]'", |
| + } { |
| + if !strings.Contains(msg, want) { |
| + t.Errorf("%d: Error() lacks %q: %s", status, want, msg) |
| + } |
| + } |
| + if strings.Contains(msg, "rk_live") || strings.Contains(msg, "51AbCdEf") { |
| + t.Errorf("%d: Error() leaked the key: %s", status, msg) |
| + } |
| + } |
| +} |
| + |
| +func TestStripeKeyMessage(t *testing.T) { |
| + for _, tc := range []struct{ in, want string }{ |
| + {"key rk_live_abc123 bad", "key [redacted] bad"}, |
| + {"key 'sk_test_****************4242' bad", "key '[redacted]' bad"}, |
| + {"pk_live_x, RK_TEST_Y and whsec_z", "[redacted], [redacted] and [redacted]"}, |
| + {"line one\nline two\x1b[31m\u2028end", "line one line two[31mend"}, |
| + {" padded ", "padded"}, |
| + {"chunk_size stays", "chunk_size stays"}, |
| + {"key x_rk_live_abc123 glued", "key [redacted] glued"}, |
| + {"key sk\u2028_live_abc123 split", "key [redacted] split"}, |
| + {"key sk_\x00live_abc123 split", "key [redacted] split"}, |
| + {"key r\u0085k_live_abc123 split", "key [redacted] split"}, |
| + } { |
| + if got := stripeKeyMessage(tc.in); got != tc.want { |
| + t.Errorf("stripeKeyMessage(%q) = %q, want %q", tc.in, got, tc.want) |
| + } |
| + } |
| + long := strings.Repeat("é", maxStripeMessage) |
| + got := stripeKeyMessage(long) |
| + if len(got) > maxStripeMessage+len("...") || !strings.HasSuffix(got, "...") || !utf8.ValidString(got) { |
| + t.Errorf("long message not capped on a rune boundary: %d bytes", len(got)) |
| + } |
| + for in, want := range map[string]string{"secret_key_required": "secret_key_required", "expand[0]": "expand[0]", "rk_live_x": "", "x_sk_test_y": "", "has space": "", "": ""} { |
| + if got := stripeKeyWord(in); got != want { |
| + t.Errorf("stripeKeyWord(%q) = %q, want %q", in, got, want) |
| + } |
| + } |
| +} |
| + |
| // --- Strict decode: Session/Subscription reject null / missing / invalid id / missing livemode --- |
| func TestSessionUnmarshalJSON_Strictness(t *testing.T) { |