Repository navigation
fix(api): validate customer usage attribution subject keys - #3526
Conversation
📝 WalkthroughWalkthroughSchema and validation updates: identifier fields (subject/key/entitlement/customer) now accept arrays with regex/min-length constraints; new SubjectUpsert schema and added optional metadata/timing fields; Go validators added for CustomerUsageAttribution and wired into invoice create/update checks. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
api/client/javascript/src/zod/index.ts (2)
6925-6935: Same tightening needed here (no coerce, trim, uniqueness).Mirror the changes from Lines 6682–6692 for update flows; keep the context-specific max (updateCustomerBodyUsageAttributionSubjectKeysMax).
12153-12163: Apply the same validation hardening for Stripe checkout.Repeat the stricter item schema and uniqueness check here; keep the Stripe-specific max.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
api/client/javascript/src/zod/index.ts(3 hunks)api/openapi.cloud.yaml(1 hunks)api/openapi.yaml(1 hunks)api/spec/src/customer/customer.tsp(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: Artifacts / Benthos Collector Container image
- GitHub Check: Artifacts / Container image
- GitHub Check: Lint
- GitHub Check: Test
- GitHub Check: Migration Checks
- GitHub Check: Code Generators
- GitHub Check: Build
- GitHub Check: SAST (semgrep)
- GitHub Check: Repository Scan
- GitHub Check: Analyze (go)
🔇 Additional comments (4)
api/spec/src/customer/customer.tsp (2)
284-288: LGTM! Good type safety with validation.The
SubjectKeyscalar type with@minLength(1)constraint prevents empty strings from being used as subject keys, which is appropriate for identifier fields.
281-281: Change is correct and properly enforces validation.The type change from
string[]toSubjectKey[]correctly applies the@minLength(1)constraint defined on the scalar. The backend already includes matching validation inopenmeter/subject/subject.go.Codebase verification found no empty subject key patterns in tests, documentation, or migrations. However, confirm that production customer records contain only non-empty subject keys before deploying.
api/openapi.cloud.yaml (1)
15260-15263: Clarify the array cardinality constraint for subject keys.The schema defines an array with
minItems: 1andmaxItems: 1, which restricts the array to exactly one item. However, the PR objective mentions supporting "multi-valued identifiers (subject keys)". This suggests the constraint should allow multiple subject keys rather than just one.Is
maxItems: 1intentional (e.g., transitional design or wrapper pattern), or should this be revised to allow multiple subject keys?api/openapi.yaml (1)
15413-15420: Verify constraint alignment with PR objectives.The PR title indicates support for "multi-valued identifiers," but this schema constrains the subject array to exactly one item (
maxItems: 1). This appears contradictory—either the constraint should be relaxed to allow multiple subject keys, or the PR objectives need clarification.Please confirm:
- Is
maxItems: 1intentional to enforce a single subject key per customer?- Does this change align with the broader multi-valued identifiers goal mentioned in the PR title?
- Are there breaking implications for existing API consumers?
| .array( | ||
| zod.coerce | ||
| .string() | ||
| .min(1) | ||
| .describe( | ||
| 'SubjectKey is a key that is used to identify a subject.', | ||
| ), | ||
| ) | ||
| .min(1) | ||
| .max(createCustomerBodyUsageAttributionSubjectKeysMax) | ||
| .describe('The subjects that are attributed to the customer.'), |
There was a problem hiding this comment.
🧩 Analysis chain
Harden subjectKeys validation: drop coerce, trim, and enforce uniqueness.
zod.coerce.string() is too permissive for identifiers (e.g., objects become "[object Object]"), .min(1) allows whitespace-only strings, and duplicates aren’t rejected. Tighten to strict strings with trimming and add an array-level uniqueness check.
Apply this diff:
- .array(
- zod.coerce
- .string()
- .min(1)
- .describe(
- 'SubjectKey is a key that is used to identify a subject.',
- ),
- )
+ .array(
+ zod
+ .string()
+ .trim()
+ .min(1, 'subjectKey cannot be empty')
+ .describe(
+ 'SubjectKey is a key that is used to identify a subject.',
+ ),
+ )
.min(1)
.max(createCustomerBodyUsageAttributionSubjectKeysMax)
+ .refine(
+ (arr) => new Set(arr).size === arr.length,
+ { message: 'subjectKeys must be unique' },
+ )
.describe('The subjects that are attributed to the customer.'),Optional: if a canonical subjectKey schema/pattern exists, reuse it here to avoid drift; otherwise consider extracting one and a helper like boundedSubjectKeys(max).
Run to confirm constants and a reusable schema exist, and to find other coerce usages to fix:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Check subjectKeys max constants are defined:"
rg -n -C2 'createCustomerBodyUsageAttributionSubjectKeysMax|updateCustomerBodyUsageAttributionSubjectKeysMax|createStripeCheckoutSessionBodyCustomerUsageAttributionSubjectKeysMax'
echo -e "\nSearch for a canonical SubjectKey schema/pattern to reuse:"
rg -n -C2 -P '\b(subjectKeySchema|SubjectKeySchema|subjectKeyPattern)\b' api/client/javascript/src/zod
echo -e "\nFind other subjectKeys arrays still using coerce:"
rg -n -C1 -P 'subjectKeys:\s*zod\s*\.\s*array\s*\(\s*zod\s*\.\s*coerce\s*\.\s*string' api/client/javascript/src/zodLength of output: 2766
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Count all coerce.string() usages in the file to assess scope:"
rg -n -c 'coerce\s*\.\s*string' api/client/javascript/src/zod/index.ts | head -1
echo -e "\nList all coerce.string() lines with context:"
rg -n 'coerce\s*\.\s*string' api/client/javascript/src/zod/index.ts | head -20
echo -e "\nConfirm the three subjectKeys array definitions and their constraints:"
rg -n -B5 -A8 'subjectKeys.*zod.*array' api/client/javascript/src/zod/index.ts | head -50Length of output: 1580
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Hunk 1: Lines around 6682-6692 ==="
sed -n '6675,6700p' api/client/javascript/src/zod/index.ts
echo -e "\n=== Hunk 2: Lines around updateCustomerBody subjectKeys (approx 6930-6940) ==="
sed -n '6920,6945p' api/client/javascript/src/zod/index.ts
echo -e "\n=== Hunk 3: Lines around createStripeCheckoutSession subjectKeys (approx 12155-12170) ==="
sed -n '12150,12175p' api/client/javascript/src/zod/index.tsLength of output: 2990
Harden subjectKeys validation: drop coerce and add trim for identifier validation.
zod.coerce.string() is too permissive for identifiers (e.g., objects become "[object Object]"), and .min(1) allows whitespace-only strings. Since these are used as metering identifiers, they must be strict strings with whitespace trimmed.
Apply this diff to all three occurrences (createCustomerBody, updateCustomerBody, and createStripeCheckoutSession):
- zod.coerce
- .string()
- .min(1)
+ zod
+ .string()
+ .trim()
+ .min(1, 'subjectKey cannot be empty')This ensures subjectKeys are strict strings, not coerced objects or whitespace-padded values.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| .array( | |
| zod.coerce | |
| .string() | |
| .min(1) | |
| .describe( | |
| 'SubjectKey is a key that is used to identify a subject.', | |
| ), | |
| ) | |
| .min(1) | |
| .max(createCustomerBodyUsageAttributionSubjectKeysMax) | |
| .describe('The subjects that are attributed to the customer.'), | |
| .array( | |
| zod | |
| .string() | |
| .trim() | |
| .min(1, 'subjectKey cannot be empty') | |
| .describe( | |
| 'SubjectKey is a key that is used to identify a subject.', | |
| ), | |
| ) | |
| .min(1) | |
| .max(createCustomerBodyUsageAttributionSubjectKeysMax) | |
| .describe('The subjects that are attributed to the customer.'), |
🤖 Prompt for AI Agents
In api/client/javascript/src/zod/index.ts around lines 6682 to 6692, the schema
uses zod.coerce.string().min(1) which allows non-string values to be coerced
(e.g., objects -> "[object Object]") and permits whitespace-only strings;
replace the coercion with zod.string().trim().min(1) to enforce strict string
types and strip whitespace, and apply the same change to the other two
occurrences of subjectKeys in createCustomerBody and createStripeCheckoutSession
so all three schemas validate identifiers as non-empty, trimmed strings.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
openmeter/customer/customer.go (2)
169-181: Consider simplifying error wrapping to avoid double-wrapping.The individual errors are wrapped with
models.NewGenericValidationError(lines 174-176), then the joined result is wrapped again withmodels.NewNillableGenericValidationError(line 180). This creates unnecessary double-wrapping. Following the pattern frommodels.Validate, only the final joined error should be wrapped.Apply this diff to simplify:
func (c CustomerUsageAttribution) Validate() error { var errs []error for _, subjectKey := range c.SubjectKeys { if len(subjectKey) < MinSubjectKeyLength { - errs = append(errs, models.NewGenericValidationError( - fmt.Errorf("subject key must be at least %d character: %q", MinSubjectKeyLength, subjectKey), - )) + errs = append(errs, fmt.Errorf("subject key must be at least %d character: %q", MinSubjectKeyLength, subjectKey)) } } return models.NewNillableGenericValidationError(errors.Join(errs...)) }
175-175: Consider future-proofing the error message grammar.The error message uses "character" (singular), which is grammatically correct since
MinSubjectKeyLengthis currently 1. However, if the constant is increased in the future, the grammar would be incorrect. Consider using "characters" (plural) for robustness, as "1 characters" is more acceptable than "2 character".Apply this diff:
- errs = append(errs, models.NewGenericValidationError( - fmt.Errorf("subject key must be at least %d character: %q", MinSubjectKeyLength, subjectKey), - )) + errs = append(errs, fmt.Errorf("subject key must be at least %d characters: %q", MinSubjectKeyLength, subjectKey))
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
openmeter/customer/customer.go(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/customer/customer.go (4)
pkg/models/validator.go (1)
Validate(16-26)api/api.gen.go (1)
CustomerUsageAttribution(2387-2390)openmeter/streaming/query_params.go (1)
CustomerUsageAttribution(81-85)pkg/models/errors.go (2)
NewGenericValidationError(138-140)NewNillableGenericValidationError(129-135)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: Artifacts / Container image
- GitHub Check: Test
- GitHub Check: Migration Checks
- GitHub Check: Lint
- GitHub Check: Code Generators
- GitHub Check: Build
- GitHub Check: Repository Scan
- GitHub Check: Analyze (go)
🔇 Additional comments (3)
openmeter/customer/customer.go (3)
5-5: LGTM!The
fmtimport is necessary for the error formatting in the new validation method.
160-167: LGTM!The compile-time assertion ensures
CustomerUsageAttributionimplements themodels.Validatorinterface, and theMinSubjectKeyLengthconstant appropriately enforces the minLength(1) constraint consistent with the schema changes.
101-104: LGTM!The integration of
UsageAttribution.Validate()is correct. The error is returned directly since it's already wrapped by theValidate()method.
4f669ca to
1f31a6d
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
openmeter/customer/customer.go(3 hunks)openmeter/ent/db/billinginvoice_create.go(1 hunks)openmeter/ent/db/billinginvoice_update.go(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
openmeter/ent/db/billinginvoice_create.go (4)
openmeter/customer/customer.go (1)
CustomerUsageAttribution(163-165)openmeter/billing/invoice.go (1)
CustomerUsageAttribution(601-601)pkg/models/validator.go (1)
Validate(16-26)openmeter/ent/db/ent.go (1)
ValidationError(260-263)
openmeter/customer/customer.go (4)
pkg/models/validator.go (1)
Validate(16-26)openmeter/billing/invoice.go (1)
CustomerUsageAttribution(601-601)openmeter/streaming/query_params.go (1)
CustomerUsageAttribution(81-85)pkg/models/errors.go (2)
NewGenericValidationError(138-140)NewNillableGenericValidationError(129-135)
openmeter/ent/db/billinginvoice_update.go (3)
openmeter/customer/customer.go (1)
CustomerUsageAttribution(163-165)openmeter/billing/invoice.go (1)
CustomerUsageAttribution(601-601)openmeter/ent/db/ent.go (1)
ValidationError(260-263)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Artifacts / Container image
- GitHub Check: Code Generators
- GitHub Check: Test
- GitHub Check: Lint
- GitHub Check: Build
- GitHub Check: Analyze (go)
| if v, ok := _c.mutation.CustomerUsageAttribution(); ok { | ||
| if err := v.Validate(); err != nil { | ||
| return &ValidationError{Name: "customer_usage_attribution", err: fmt.Errorf(`db: validator failed for field "BillingInvoice.customer_usage_attribution": %w`, err)} | ||
| } | ||
| } |
There was a problem hiding this comment.
Handle nil before validating usage attribution
Here too, a caller can set CustomerUsageAttribution to nil (even while satisfying the “required” check), which would panic when invoking Validate(). Please reject nil explicitly before calling Validate().
if v, ok := _c.mutation.CustomerUsageAttribution(); ok {
+ if v == nil {
+ return &ValidationError{Name: "customer_usage_attribution", err: errors.New(`db: validator failed for field "BillingInvoice.customer_usage_attribution": value cannot be null`)}
+ }
if err := v.Validate(); err != nil {
return &ValidationError{Name: "customer_usage_attribution", err: fmt.Errorf(`db: validator failed for field "BillingInvoice.customer_usage_attribution": %w`, err)}
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if v, ok := _c.mutation.CustomerUsageAttribution(); ok { | |
| if err := v.Validate(); err != nil { | |
| return &ValidationError{Name: "customer_usage_attribution", err: fmt.Errorf(`db: validator failed for field "BillingInvoice.customer_usage_attribution": %w`, err)} | |
| } | |
| } | |
| if v, ok := _c.mutation.CustomerUsageAttribution(); ok { | |
| if v == nil { | |
| return &ValidationError{Name: "customer_usage_attribution", err: errors.New(`db: validator failed for field "BillingInvoice.customer_usage_attribution": value cannot be null`)} | |
| } | |
| if err := v.Validate(); err != nil { | |
| return &ValidationError{Name: "customer_usage_attribution", err: fmt.Errorf(`db: validator failed for field "BillingInvoice.customer_usage_attribution": %w`, err)} | |
| } | |
| } |
🤖 Prompt for AI Agents
In openmeter/ent/db/billinginvoice_create.go around lines 835-839, the code
calls v.Validate() without checking for nil which can panic if
CustomerUsageAttribution is explicitly set to nil; update the block to first
check if v == nil and return a ValidationError for "customer_usage_attribution"
(with a descriptive fmt.Errorf indicating the field was nil), and only call
v.Validate() if v is non-nil, preserving the existing error wrapping for
validation failures.
Summary by CodeRabbit
New Features
Improvements
Bug Fixes