Repository navigation
feat: strengthen namespace validate - #4905
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughInvoice and plan APIs now require singular namespaces. Billing, application, secret, Stripe, and product-catalog references enforce namespace ownership. Collection discovery returns customer IDs, and advancement discovery returns invoice IDs. ChangesNamespace isolation and billing workflows
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/app/stripe/types.go (1)
39-88: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winUse the required validation error contract in all changed input validators.
These validators return early raw errors or a non-nillable generic error. Collect the field errors and return
models.NewNillableGenericValidationError(errors.Join(errs...))instead.
openmeter/app/stripe/types.go#L39-L88: Aggregate app, namespace, API key, and webhook secret validation errors with field context.openmeter/secret/entity/input.go#L54-L70: Aggregate app ID, secret ID, and key validation errors with field context.openmeter/billing/gatheringinvoice.go#L1006-L1023: Wrap the joined namespace, page, and expand errors inmodels.NewNillableGenericValidationError.openmeter/billing/gatheringinvoice.go#L1038-L1043: Collect theAsOfvalidation error and return the required nillable generic validation error.As per coding guidelines,
Validate() errormust collect field errors and returnmodels.NewNillableGenericValidationError(errors.Join(errs...)).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/app/stripe/types.go` around lines 39 - 88, Update Validate() in openmeter/app/stripe/types.go (lines 39-88) to collect app, namespace, API key, and webhook secret field errors with context, then return models.NewNillableGenericValidationError(errors.Join(errs...)); update openmeter/secret/entity/input.go (lines 54-70) similarly for app ID, secret ID, and key errors; in openmeter/billing/gatheringinvoice.go (lines 1006-1023), wrap joined namespace, page, and expand errors with the required nillable generic error; and at lines 1038-1043, collect the AsOf error and return models.NewNillableGenericValidationError(errors.Join(errs...)).Source: Coding guidelines
🧹 Nitpick comments (4)
test/billing/customeroverride_test.go (2)
33-33: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSwap
context.Background()fors.T().Context()in these new tests.All four new tests have
s.T()available, so the test context is the right choice. It also cancels on test completion, which keeps the DB work tied to the test lifetime. The new tests intest/billing/adapter_test.goin this same PR already uses.T().Context(), so this also lines the two files up.♻️ Proposed change (apply at each of the four sites)
- ctx := context.Background() + ctx := s.T().Context()As per coding guidelines: "Use
t.Context()whenever atesting.Tortesting.TBis available."Also applies to: 69-69, 101-101, 129-129
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/billing/customeroverride_test.go` at line 33, Replace context.Background() with s.T().Context() at all four new test sites in the customer override tests, preserving the existing context usage otherwise and tying database work to the test lifecycle.Source: Coding guidelines
165-169: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd a nil check before reading
override.Profile.ID.
GetCustomerOverridereturnsnil, nilwhen no override exists, as the assertion at line 158 shows. If the bulk assignment silently writes nothing, line 169 panics instead of reporting a clean assertion failure.🛡️ Proposed guard
require.NoError(s.T(), err) + require.NotNil(s.T(), override) require.Equal(s.T(), targetProfile.ID, override.Profile.ID)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/billing/customeroverride_test.go` around lines 165 - 169, Before accessing override.Profile.ID in the GetCustomerOverride test flow, assert that override is non-nil after require.NoError. Keep the existing targetProfile.ID comparison, but ensure a missing override produces a clean test failure instead of a nil dereference.test/billing/adapter_test.go (1)
193-198: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNice isolation coverage — consider tightening the bare
require.Errorchecks.These three assertions pass for any error, including one caused by a setup mistake rather than by the namespace guard.
require.ErrorContains(orrequire.ErrorIswhere a sentinel exists) pins the test to the behaviour you actually want to protect. The mapper messages are stable, for example the missing-invoice message inopenmeter/billing/adapter/invoicelinesplitgroup.goline 232 and the missing-usage-config message inopenmeter/billing/adapter/stdinvoicelinemapper.goline 135.♻️ Example for the split-line-group invoice subtest
- require.Error(s.T(), err) + require.ErrorContains(s.T(), err, "billing invoice must be expanded")Also applies to: 352-352
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/billing/adapter_test.go` around lines 193 - 198, Replace the bare require.Error assertions in the relevant billing adapter tests, including the GetGatheringInvoiceById case, with require.ErrorContains or require.ErrorIs checks for the expected namespace-guard mapper messages. Assert the stable missing-invoice and missing-usage-config errors so setup failures cannot satisfy the tests.openmeter/billing/adapter/profile.go (1)
506-511: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNice guard — one small tweak to make the log easier to act on.
The
dbWC == nilcase and the namespace mismatch case take the same branch, so a workflow config edge that was simply not eager-loaded gets reported as an "isolation violation". The log also has no identifier, which makes the returned "billing workflow config not found" hard to trace. Splitting the two cases keeps the real isolation signal clean.♻️ Proposed split of the two failure modes
- if dbWC == nil || dbWC.Namespace != namespace { - a.logger.ErrorContext(ctx, "billing workflow config namespace isolation violation", - "expected_namespace", namespace, - ) - return billing.WorkflowConfig{}, models.NewGenericNotFoundError(fmt.Errorf("billing workflow config not found")) - } + if dbWC == nil { + a.logger.ErrorContext(ctx, "billing workflow config edge is not loaded", + "expected_namespace", namespace, + ) + return billing.WorkflowConfig{}, models.NewGenericNotFoundError(fmt.Errorf("billing workflow config not found")) + } + + if dbWC.Namespace != namespace { + a.logger.ErrorContext(ctx, "billing workflow config namespace isolation violation", + "workflow_config_id", dbWC.ID, + "expected_namespace", namespace, + "actual_namespace", dbWC.Namespace, + ) + return billing.WorkflowConfig{}, models.NewGenericNotFoundError(fmt.Errorf("billing workflow config not found [id=%s]", dbWC.ID)) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/adapter/profile.go` around lines 506 - 511, Split the guard in the workflow-config lookup around dbWC so a nil config logs a not-found/missing-config message, while a non-nil config with a different Namespace retains the isolation-violation log. Include the workflow config identifier in both messages, and preserve the existing not-found return behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openmeter/billing/customeroverride.go`:
- Around line 376-378: Update Validate() to accumulate profile and customer
validation failures in an errs collection instead of returning on the first
mismatch. Preserve indexed field context by wrapping each validation error,
continue checking all fields, and return
models.NewNillableGenericValidationError(errors.Join(errs...)) after validation
completes.
In `@openmeter/billing/invoice.go`:
- Around line 328-330: The Namespace checks in both validators currently append
raw errors and return errors.Join directly; update both validator methods to
return models.NewNillableGenericValidationError(errors.Join(outErr...)) while
preserving the namespace field context by wrapping the validation errors
consistently with the existing field validators.
In `@openmeter/billing/stdinvoice.go`:
- Around line 1189-1191: Update the namespace validation branch in Validate() to
wrap the “namespace is required” error with the namespace field context,
matching the existing expand: and externalIDs: validation errors before joining
them.
In `@openmeter/billing/worker/collect/collect.go`:
- Around line 33-40: Update ListCustomersToCollectInput.Validate to wrap the
joined validation errors with models.NewNillableGenericValidationError before
returning. Preserve the existing AsOf validation and collected field-error
behavior.
In `@test/billing/invoice_test.go`:
- Line 3952: Update the test setup around ctx in the affected suite test to use
s.T().Context() instead of context.Background(), preserving the test’s existing
context usage while inheriting the suite deadline and cancellation scope.
In `@test/billing/profile_test.go`:
- Line 35: Replace context.Background() with s.T().Context() in the test setup,
preserving the existing context usage while binding database calls to the suite
test lifecycle and cancellation scope.
---
Outside diff comments:
In `@openmeter/app/stripe/types.go`:
- Around line 39-88: Update Validate() in openmeter/app/stripe/types.go (lines
39-88) to collect app, namespace, API key, and webhook secret field errors with
context, then return
models.NewNillableGenericValidationError(errors.Join(errs...)); update
openmeter/secret/entity/input.go (lines 54-70) similarly for app ID, secret ID,
and key errors; in openmeter/billing/gatheringinvoice.go (lines 1006-1023), wrap
joined namespace, page, and expand errors with the required nillable generic
error; and at lines 1038-1043, collect the AsOf error and return
models.NewNillableGenericValidationError(errors.Join(errs...)).
---
Nitpick comments:
In `@openmeter/billing/adapter/profile.go`:
- Around line 506-511: Split the guard in the workflow-config lookup around dbWC
so a nil config logs a not-found/missing-config message, while a non-nil config
with a different Namespace retains the isolation-violation log. Include the
workflow config identifier in both messages, and preserve the existing not-found
return behavior.
In `@test/billing/adapter_test.go`:
- Around line 193-198: Replace the bare require.Error assertions in the relevant
billing adapter tests, including the GetGatheringInvoiceById case, with
require.ErrorContains or require.ErrorIs checks for the expected namespace-guard
mapper messages. Assert the stable missing-invoice and missing-usage-config
errors so setup failures cannot satisfy the tests.
In `@test/billing/customeroverride_test.go`:
- Line 33: Replace context.Background() with s.T().Context() at all four new
test sites in the customer override tests, preserving the existing context usage
otherwise and tying database work to the test lifecycle.
- Around line 165-169: Before accessing override.Profile.ID in the
GetCustomerOverride test flow, assert that override is non-nil after
require.NoError. Keep the existing targetProfile.ID comparison, but ensure a
missing override produces a clean test failure instead of a nil dereference.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 8838fe7f-2eee-4852-870f-30640ab49964
📒 Files selected for processing (72)
api/v3/handlers/billinginvoices/list.gocmd/jobs/billing/advance/advance.gocmd/jobs/billing/collect/collect.goopenmeter/app/adapter/app.goopenmeter/app/adapter/customer.goopenmeter/app/adapter/customer_test.goopenmeter/app/custominvoicing/adapter/customerdata.goopenmeter/app/custominvoicing/adapter/customerdata_test.goopenmeter/app/stripe/README.mdopenmeter/app/stripe/adapter/customer.goopenmeter/app/stripe/adapter/customer_test.goopenmeter/app/stripe/adapter/stripe.goopenmeter/app/stripe/service/billing.goopenmeter/app/stripe/types.goopenmeter/app/stripe/types_test.goopenmeter/billing/adapter.goopenmeter/billing/adapter/customeroverride.goopenmeter/billing/adapter/gatheringinvoice.goopenmeter/billing/adapter/gatheringlines.goopenmeter/billing/adapter/invoice.goopenmeter/billing/adapter/invoice_advancement.goopenmeter/billing/adapter/invoicelinesplitgroup.goopenmeter/billing/adapter/profile.goopenmeter/billing/adapter/stdinvoicelinediff_test.goopenmeter/billing/adapter/stdinvoicelinemapper.goopenmeter/billing/adapter/stdinvoicelines.goopenmeter/billing/charges/invoiceupdater/invoiceupdate.goopenmeter/billing/charges/service/creditpurchase_test.goopenmeter/billing/charges/service/gathering_preview_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/service/pendinglines_test.goopenmeter/billing/charges/service/taxcode_test.goopenmeter/billing/charges/service/usagebased_test.goopenmeter/billing/customeroverride.goopenmeter/billing/gatheringinvoice.goopenmeter/billing/httpdriver/invoice.goopenmeter/billing/invoice.goopenmeter/billing/invoice_test.goopenmeter/billing/service.goopenmeter/billing/service/customeroverride.goopenmeter/billing/service/gatheringinvoice.goopenmeter/billing/service/gatheringinvoicependinglines.goopenmeter/billing/service/invoice.goopenmeter/billing/service/stdinvoice.goopenmeter/billing/service/stdinvoiceline.goopenmeter/billing/stdinvoice.goopenmeter/billing/stdinvoice_test.goopenmeter/billing/validators/customer/customer.goopenmeter/billing/worker/advance/advance.goopenmeter/billing/worker/collect/collect.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/loader.goopenmeter/billing/worker/subscriptionsync/service/reconciler/invoiceupdater/invoiceupdate.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/billing/worker/subscriptionsync/service/sync_test.goopenmeter/secret/entity/input.goopenmeter/secret/entity/secret.goopenmeter/secret/entity/secret_test.goopenmeter/server/server_test.gotest/app/stripe/invoice_credits_test.gotest/billing/adapter_test.gotest/billing/collection_test.gotest/billing/customeroverride_test.gotest/billing/invoice_test.gotest/billing/lineengine_test.gotest/billing/profile_test.gotest/billing/subscription_test.gotest/credits/credit_then_invoice_test.gotest/credits/creditgrant_test.gotest/credits/sanity_test.gotest/credits/voidgrant_test.gotest/subscription/scenario_firstofmonth_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/billing/adapter/gatheringinvoice.go (1)
338-350: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake the persistence mapping explicit.
Lines 338-350 map database rows to domain identities inside local callbacks. Use a direct loop here. This keeps the namespace identity mapping visible and follows the repository rule for persistence mapping.
Proposed refactor
- nilCollectionAtInvoiceIDs := lo.FilterMap(rows, func(row customerIDRow, _ int) (string, bool) { - return row.InvoiceID, row.CollectionAt == nil - }) + nilCollectionAtInvoiceIDs := make([]string, 0) + customers := make([]customer.CustomerID, 0, len(rows)) + for _, row := range rows { + if row.CollectionAt == nil { + nilCollectionAtInvoiceIDs = append(nilCollectionAtInvoiceIDs, row.InvoiceID) + } + + customers = append(customers, customer.CustomerID{ + Namespace: row.Namespace, + ID: row.CustomerID, + }) + } + if len(nilCollectionAtInvoiceIDs) > 0 { tx.logger.WarnContext(ctx, "gathering invoices have nil next collection at; this may indicate legacy or inconsistent state", "invoice_ids", nilCollectionAtInvoiceIDs) } - customers := lo.Uniq(lo.Map(rows, func(row customerIDRow, _ int) customer.CustomerID { - return customer.CustomerID{ - Namespace: row.Namespace, - ID: row.CustomerID, - } - })) + customers = lo.Uniq(customers)As per coding guidelines: “Do not hide type switching, validation, persistence mapping, or meaningful domain translation inside local closures; use named helpers and reserve inline callbacks for obvious, tiny logic.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/adapter/gatheringinvoice.go` around lines 338 - 350, Replace the lo.FilterMap and lo.Map callbacks in the customer identity mapping section with an explicit loop over rows, preserving the nil CollectionAt warning and constructing each customer.CustomerID with row.Namespace and row.CustomerID; deduplicate the resulting customers as before, without hiding persistence mapping in local closures.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@openmeter/billing/adapter/gatheringinvoice.go`:
- Around line 338-350: Replace the lo.FilterMap and lo.Map callbacks in the
customer identity mapping section with an explicit loop over rows, preserving
the nil CollectionAt warning and constructing each customer.CustomerID with
row.Namespace and row.CustomerID; deduplicate the resulting customers as before,
without hiding persistence mapping in local closures.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 9e381268-ac17-4e7e-abb2-843deba3c85d
📒 Files selected for processing (1)
openmeter/billing/adapter/gatheringinvoice.go
This reverts commit 7c85983.
Overview
This PR makes namespace handling explicit and consistent across billing reads and writes, background invoice processing, app-customer relationships, Stripe integration data, and app-owned secrets.
High-level changes
Billing and invoice workers
Apps, Stripe, and secrets
Tests
Review guide
The billing changes are centered in
openmeter/billing/adapterand the collection/advancement workers. App relationship changes are underopenmeter/app, while Stripe credential ownership is shared betweenopenmeter/app/stripeandopenmeter/secret.Plan-specific changes were split into the stacked PR #4906.
Integration note
The collection and advancement worker interfaces now return lightweight customer and invoice identities. The corresponding
openmeterio/cloudbilling-worker consumers need to be updated before that repository advances its OpenMeter dependency.Validation
GitHub CI passes build, lint, tests, E2E, code generation, migration checks, Quickstart, dependency review, and repository/security scans.
No Jira ticket; this is a bug fix.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Greptile Summary
This PR strengthens namespace isolation across billing, invoice workers, app-customer relationships, Stripe data, and app-owned secrets.
Confidence Score: 5/5
The PR appears safe to merge.
No blocking failure remains.
Important Files Changed
Reviews (7): Last reviewed commit: "Revert "fix: strengthen plan namespace i..." | Re-trigger Greptile
Context used: