carlos / platform Public

billingstripe: 401/403 errors carry Stripe's message, keys redacted

A restricted key missing a permission got only "api_error status=403
stripe_type=invalid_request_error" in the log, so nobody could tell which
permission to grant. On a 401 or 403 the error now carries Stripe's
message (which names the permission) and its code and param, with any
rk_/sk_/pk_/whsec_ token redacted, control characters dropped and the
length capped. Other statuses still drop the message: there it can echo
request parameters (emails, card last four).

Error() also prints stripe_param when set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6b641f4c99fc05aafc8073f0afa8f6446779b988 parent 32a59ad
2 files changed, +147 −9
  • internal/billingstripe/client.go +78 −9
  • internal/billingstripe/client_test.go +69 −0
diff --git a/internal/billingstripe/client.go b/internal/billingstripe/client.go
index 55521e8d5..190370de8 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,58 @@ 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 anything shaped like a Stripe key or signing secret,
+// masked or not: Stripe masks keys in its messages, but redact anyway.
+var keyToken = regexp.MustCompile(`(?i)\b(?:rk|sk|pk|whsec)_[A-Za-z0-9_*.\-]*`)
+
+// stripeKeyMessage is a 401 or 403 message made safe to log: key-shaped
+// tokens redacted, control characters dropped, capped at maxStripeMessage
+// bytes on a rune boundary.
+func stripeKeyMessage(msg string) string {
+ msg = keyToken.ReplaceAllString(msg, "[redacted]")
+ 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 = 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 +367,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 +375,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..68d73ab1a 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,74 @@ 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 and desk_top stay", "chunk_size and desk_top stay"},
+ } {
+ 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": "", "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) {