Skip to content

fix(api): validate customer usage attribution subject keys - #3526

Merged
tothandras merged 2 commits into
mainfrom
fix/customer-validation
Oct 21, 2025
Merged

tothandras merged 2 commits into
mainfrom
fix/customer-validation

Conversation

@tothandras

@tothandras tothandras commented Oct 21, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Batch operations: support multiple identifiers in a single request for subjects, customers, entitlements, and grants.
    • Added a dedicated upsert schema for subjects to formalize create/update payloads.
  • Improvements

    • Stronger validation and minimum-length constraints for subject keys and identifiers.
    • New optional fields for entitlements/grants (metadata, timing, recurrence, expiration) for finer control.
  • Bug Fixes

    • Server-side request validation now enforces per-field validators and returns clearer validation errors.

@tothandras
tothandras requested a review from a team as a code owner October 21, 2025 09:46
@coderabbitai

coderabbitai Bot commented Oct 21, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Schema 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

Cohort / File(s) Change Summary
OpenAPI schemas
api/openapi.yaml, api/openapi.cloud.yaml
Added/updated subject/subjectKey constraints (minLength, description, example); added type and other properties to Subject; introduced SubjectUpsert; made some identifier/key properties array-valued and added validation metadata.
JS client Zod schemas
api/client/javascript/src/zod/index.ts
Replaced singular identifier fields with array types; added regex/min-length validations for ULID/key formats; added optional fields (metadata, effectiveAt, recurrence, expiration) and defaults for pagination/ordering.
TypeSpec (customer)
api/spec/src/customer/customer.tsp
Added scalar SubjectKey extends string @minLength(1) and changed CustomerUsageAttribution.subjectKeys from string[] → SubjectKey[].
Go models & validation
openmeter/customer/customer.go
Added MinSubjectKeyLength constant; implemented CustomerUsageAttribution.Validate() aggregating per-key validation errors; registered type as models.Validator; updated CustomerMutate.Validate() to call usage attribution validation.
DB layer invoice checks
openmeter/ent/db/billinginvoice_create.go, openmeter/ent/db/billinginvoice_update.go
Invoke CustomerUsageAttribution.Validate() during create/update checks and return field-specific ValidationError when validation fails.
Other (related Zod/OpenAPI clients & schemas)
... (implicit many affected schema locations)
Widespread schema adjustments to accept multi-value identifiers and enforce regex/min-length across entitlement, grant, usage, and customer-related request/response models.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "fix(api): validate customer usage attribution subject keys" accurately and directly reflects the primary changes in the changeset. The raw summary confirms that the core changes involve adding validation logic for CustomerUsageAttribution through a new Validate() method that enforces minimum length constraints on subject keys, introducing a MinSubjectKeyLength constant, and integrating these validations into BillingInvoice create and update operations. The title is concise, specific, and clearly indicates the nature of the fix without vague terminology or unnecessary details. A teammate reviewing the git history would immediately understand that this PR addresses validation concerns for subject keys in customer usage attribution.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/customer-validation

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@tothandras tothandras added the release-note/bug-fix Release note: Bug Fixes label Oct 21, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 929c685 and bc12556.

📒 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 SubjectKey scalar 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[] to SubjectKey[] correctly applies the @minLength(1) constraint defined on the scalar. The backend already includes matching validation in openmeter/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: 1 and maxItems: 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: 1 intentional (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:

  1. Is maxItems: 1 intentional to enforce a single subject key per customer?
  2. Does this change align with the broader multi-valued identifiers goal mentioned in the PR title?
  3. Are there breaking implications for existing API consumers?

Comment on lines +6682 to 6692
.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.'),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 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/zod

Length 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 -50

Length 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.ts

Length 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.

Suggested change
.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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 with models.NewNillableGenericValidationError (line 180). This creates unnecessary double-wrapping. Following the pattern from models.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 MinSubjectKeyLength is 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

📥 Commits

Reviewing files that changed from the base of the PR and between bc12556 and 4f669ca.

📒 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 fmt import is necessary for the error formatting in the new validation method.


160-167: LGTM!

The compile-time assertion ensures CustomerUsageAttribution implements the models.Validator interface, and the MinSubjectKeyLength constant 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 the Validate() method.

@chrisgacsal
chrisgacsal force-pushed the fix/customer-validation branch from 4f669ca to 1f31a6d Compare October 21, 2025 10:52

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4f669ca and 1f31a6d.

📒 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)

Comment on lines +835 to +839
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)}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

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.

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants