feat(observability): extend audit log, PostHog, and storage metering coverage#5269
feat(observability): extend audit log, PostHog, and storage metering coverage#5269waleedlatif1 wants to merge 29 commits into
Conversation
…coverage Instruments previously-uncaptured resources and actions across the three observability layers (audit log, PostHog product analytics, usage metering): - Exfiltration audit: file downloads (workspace/public-share/v1), table, workflow, and workspace exports. - Credential access audited at the token-issuance boundary (success-only). - Full revenue trail: invoice paid/failed, overage billed, disputes, credit fulfillment, subscription lifecycle, plan/seat changes. - Session/login lifecycle audit via Better Auth hooks (login, blocked sign-in, logout, session revoke, account delete). - v1/admin programmatic surface and copilot tool handlers instrumented. - Dead audit/PostHog constants wired (lock/unlock, table, custom tool, etc.). - Storage metering extended to KB documents and copilot files. - PostHog person identify + workspace/organization group hygiene. Audit package hardened to null the actor FK for system actors (admin-api) and adds an awaitable recordAuditNow for pre-delete hooks. All instrumentation is fire-and-forget and never blocks or breaks the primary operation.
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
PR SummaryMedium Risk Overview Audit package accepts Storage metering for knowledge-base uploads checks quota before insert and increments after commit; hard deletes decrement bytes in the same transaction via new PostHog event map grows (revenue, org/seat, credentials, schedules, etc.); Reviewed by Cursor Bugbot for commit 2afd114. Configure here. |
Greptile SummaryThis PR extends the three observability layers — audit log, PostHog analytics, and storage metering — to cover a comprehensive set of previously uninstrumented events: billing webhooks (invoices, disputes, subscriptions, enterprise), credential access, copilot tool/skill/table management, file downloads/exports, and the entire v1 admin API surface. The audit package is also hardened to null actor FKs for system actors and on user-lookup failures, with a new
Confidence Score: 5/5Safe to merge — all instrumentation is fire-and-forget, all actor-resolution helpers have internal try/catch so they cannot throw into critical billing paths, and the storage accounting changes use existing transaction boundaries. The billing-webhook instrumentation blocks that were previously identified as potentially blocking critical operations (payment-failed user-blocking, public-share actor misattribution, actor FK violations on catch paths) have all been addressed with try/catch guards, null-actor paths, and regression tests. Storage metering for KB document deletes is correctly atomic with the delete transaction via decrementStorageUsageInTx. The GET-handler credential audit is correctly placed after refreshTokenIfNeeded succeeds. No new unguarded awaits were introduced on critical webhook paths. No files require special attention — the most sensitive paths (billing webhooks, storage counters, audit FK safety) were reviewed in depth and follow the defensive patterns described in the PR. Important Files Changed
Sequence Diagram%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant Stripe as Stripe Webhook
participant Handler as Webhook Handler
participant ActorResolver as resolveBillingActorId
participant AuditLog as recordAudit (fire-and-forget)
participant PostHog as captureServerEvent (fire-and-forget)
participant DB as Database
Stripe->>Handler: event (invoice / subscription / dispute)
Handler->>Handler: run critical business logic
Handler->>ActorResolver: resolve actor (org owner lookup)
ActorResolver->>DB: "SELECT member WHERE role='owner'"
DB-->>ActorResolver: userId OR referenceId (fallback)
ActorResolver-->>Handler: actorId (never throws)
Handler->>AuditLog: "recordAudit({ actorId, action, ... })"
AuditLog->>DB: "SELECT user WHERE id=actorId"
alt user found
DB-->>AuditLog: name, email
else user not found or lookup error
AuditLog->>AuditLog: "null actorId, label=Admin API/System"
end
AuditLog->>DB: INSERT audit_log (async, non-blocking)
Handler->>PostHog: captureServerEvent(actorId, event, props)
Handler-->>Stripe: 200 OK
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant Stripe as Stripe Webhook
participant Handler as Webhook Handler
participant ActorResolver as resolveBillingActorId
participant AuditLog as recordAudit (fire-and-forget)
participant PostHog as captureServerEvent (fire-and-forget)
participant DB as Database
Stripe->>Handler: event (invoice / subscription / dispute)
Handler->>Handler: run critical business logic
Handler->>ActorResolver: resolve actor (org owner lookup)
ActorResolver->>DB: "SELECT member WHERE role='owner'"
DB-->>ActorResolver: userId OR referenceId (fallback)
ActorResolver-->>Handler: actorId (never throws)
Handler->>AuditLog: "recordAudit({ actorId, action, ... })"
AuditLog->>DB: "SELECT user WHERE id=actorId"
alt user found
DB-->>AuditLog: name, email
else user not found or lookup error
AuditLog->>AuditLog: "null actorId, label=Admin API/System"
end
AuditLog->>DB: INSERT audit_log (async, non-blocking)
Handler->>PostHog: captureServerEvent(actorId, event, props)
Handler-->>Stripe: 200 OK
Reviews (28): Last reviewed commit: "chore(observability): trim verbose inlin..." | Re-trigger Greptile |
Address Cursor Bugbot review: - GET OAuth token: emit CREDENTIAL_ACCESSED/credential_used after refreshTokenIfNeeded succeeds (matches POST), not before. - File export: audit on each actual success exit via a shared helper — including the non-markdown serve redirect (previously unaudited) and after the zip is generated (previously before asset fetch).
Address Greptile P1: setting actorId to the file owner made every anonymous external download read as a self-download, undermining the exfiltration trail. recordAudit now accepts a null actor; the public content/inline routes record actorId=null with the owner in metadata.sharedByUserId and rely on ip/user-agent for the forensic trail. The misleading owner-attributed file_downloaded PostHog event is dropped on these anonymous paths.
|
@cursor review |
- Admin workflow/workspace ZIP exports now audit only after the archive is built (via a local helper), so a zip/build failure no longer logs an export. - Remove redundant 'success-only placement' inline comments and tighten the remaining design-rationale notes (export helper now TSDoc).
|
@cursor review |
Address Cursor review: - handleDisputeClosed now records CHARGE_DISPUTE_CLOSED for every closed dispute (won/lost/warning_closed), unblocking only on favorable outcomes. dispute.status in the metadata distinguishes the outcome, so lost chargebacks are no longer missing from the trail. - Threshold overage now emits OVERAGE_BILLED + overage_billed even when credits fully cover the overage (settledVia: 'credits' vs 'stripe'), so credit-settled overages are audited instead of silently returning null.
Address Greptile P1: deleting the metadata row before the decrement meant a decrement failure left the quota permanently inflated with no record to retry from. Decrement first; only remove the metadata row once it succeeds.
|
@cursor review |
…tion - Copilot file delete now releases storage via a single transaction (releaseDeletedFileStorage): the soft-delete is the idempotency claim and the decrement shares the transaction, so neither a partial failure (inflated counter) nor a retry (double-decrement) can desync the quota. Resolves the conflicting Greptile/Cursor ordering findings. - Policy-blocked sign-ups now record USER_SIGNUP_BLOCKED instead of USER_SIGNIN_BLOCKED, so account-lifecycle events aren't mislabeled.
|
@cursor review |
Address Cursor review: addImportColumns (async createColumns import path) now threads the importing userId into auditTableColumnsAdded instead of falling back to table.createdBy, so column additions are attributed to the actual member who ran the import rather than the table creator.
|
@cursor review |
Per design decision: copilot files are working/conversational artifacts, so gating their materialization on storage quota would fail an agent operation mid-flow when a user is over limit, and metering them would inflate usage enough to block KB/workspace uploads indirectly. Remove copilot quota gates + copilot ingest metering entirely (revert copilot-file-manager, metadata, and the upload route's copilot branch to baseline) and drop the now-unused releaseDeletedFileStorage. KB document metering + quota enforcement (the deliberate, persistent storage path) is unchanged.
|
@cursor review |
Address Cursor review: gate the group-sync effect on workspace metadata being loaded (activeWorkspace present) so the workspace and organization groups always update atomically. Acting during the load window paired the new workspace group with the previous workspace's org group; until metadata loads, events stay consistently attributed to the previous workspace.
|
@cursor review |
Address Cursor review: async exports only emitted TABLE_EXPORTED when the background job reached 'ready', so an authorized export whose job later failed or was abandoned left no audit trail — inconsistent with the sync export route, which audits before streaming. Move the audit + analytics to the async route's authorization point (after the job is claimed/dispatched) and remove it from the runner. Drop the now-unused userId from TableExportPayload.
|
@cursor review |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit f5f8a00. Configure here.
…king Address Greptile P1: the payment_failed audit hoisted an unguarded isSubscriptionOrgScoped DB read (for entity_type) directly before the attempt-count user-blocking block. A transient failure of that read would throw out of the handler and skip blocking. Wrap the whole audit/analytics block in try/catch (best-effort), and let the blocking compute its own isSubscriptionOrgScoped as it did originally — instrumentation can no longer abort payment processing.
|
@cursor review |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 2afd114. Configure here.
Summary
Extends the three observability layers — audit log, PostHog product analytics, and usage metering — to cover resources and actions that were previously uninstrumented. Found via a codebase-wide coverage audit; every gap below was a real blind spot.
Audit log
CREDENTIAL_ACCESSED), success-only.v1/adminprogrammatic surface (member/role/export ops) and copilot tool handlers (skills, custom tools, tables) — both previously bypassed audit entirely.AuditActionconstants (lock/unlock, table update/delete, etc.).PostHog
Metering
Hardening
admin-api) with a readable label instead of silently FK-failing; adds an awaitablerecordAuditNowfor pre-delete hooks.Type of Change
Testing
check:api-validationpass.Checklist