Skip to content

feat(web): associate Sentry errors with users#1452

Open
brendan-kellam wants to merge 2 commits into
mainfrom
brendan/associate-sentry-errors-with-users
Open

feat(web): associate Sentry errors with users#1452
brendan-kellam wants to merge 2 commits into
mainfrom
brendan/associate-sentry-errors-with-users

Conversation

@brendan-kellam

@brendan-kellam brendan-kellam commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Summary

  • associate browser-side Sentry events with the active NextAuth user
  • associate server-side Sentry events after resolving the request session
  • clear identity for unauthenticated sessions and only include email/name when PII telemetry is enabled

Testing

  • yarn workspace @sourcebot/web test (1,074 tests passed)
  • yarn workspace @sourcebot/web lint (passes with 4 pre-existing warnings)

Note

Low Risk
Observability-only change with no auth behavior changes; PII is limited to user id unless the existing telemetry PII flag is enabled.

Overview
Sentry events can now be tied to the active user on both the browser and server, using a shared setSentryUser helper that calls Sentry.setUser.

On the client, SentryUserProvider is mounted in the root layout inside SessionProvider. It waits until the NextAuth session is not loading, then sets or clears Sentry user context when auth state changes. On the server, getAuthContext in withAuth sets the same context right after the request principal is resolved (session, OAuth bearer, or API key), and clears it when there is no user.

By default only id is sent to Sentry; email and name are included only when SOURCEBOT_TELEMETRY_PII_COLLECTION_ENABLED is 'true', matching existing telemetry PII behavior. Vitest coverage was added for the helper and provider (loading, sign-in, sign-out, PII on/off).

Reviewed by Cursor Bugbot for commit 87756c8. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Added Sentry user context tracking across authenticated and unauthenticated sessions.
    • User IDs are tracked by default; email and display name are included only when telemetry PII collection is enabled.
    • User context is cleared when authentication ends.
  • Tests

    • Added coverage for loading, authentication changes, PII settings, and clearing user data.

@github-actions

Copy link
Copy Markdown
Contributor

@brendan-kellam your pull request is missing a changelog!

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Adds Sentry user context tracking across the web app. A new setSentryUser helper maps user data (optionally including PII) to Sentry, a client SentryUserProvider syncs it from the session, and withAuth middleware calls it for server-resolved authentication.

Changes

Sentry user context

Layer / File(s) Summary
Sentry user mapping
packages/web/src/lib/sentryUser.ts, packages/web/src/lib/sentryUser.test.ts
Adds SentryUser type and setSentryUser helper that sets or clears Sentry's user, including email/username only when PII collection is enabled; tested for default, PII-enabled, and unauthenticated cases.
Client session wiring
packages/web/src/app/sentryUserProvider.tsx, packages/web/src/app/sentryUserProvider.test.tsx, packages/web/src/app/layout.tsx
Adds a SentryUserProvider client component that waits for session resolution then calls setSentryUser, rendered inside RootLayout's SessionProvider with isPiiEnabled from telemetry config; includes tests for loading and auth-state transitions.
Server authentication wiring
packages/web/src/middleware/withAuth.ts
Calls setSentryUser in getAuthContext with the resolved principal (or null) and PII flag, regardless of the authentication method used.

Estimated code review effort: 2 (Simple) | ~12 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SessionProvider
  participant SentryUserProvider
  participant setSentryUser
  participant Sentry
  SessionProvider->>SentryUserProvider: provide session status and user
  SentryUserProvider->>setSentryUser: update resolved user and PII flag
  setSentryUser->>Sentry: set or clear user context
Loading
sequenceDiagram
  participant Request
  participant withAuth
  participant setSentryUser
  participant Sentry
  Request->>withAuth: getAuthContext resolves principal
  withAuth->>setSentryUser: pass user or null, PII flag
  setSentryUser->>Sentry: set or clear user context
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: associating Sentry errors with authenticated users in the web app.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch brendan/associate-sentry-errors-with-users

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.

Comment thread packages/web/src/auth.ts Outdated
Move setSentryUser out of the memoized auth() resolver and into
getAuthContext so it captures the resolved principal for all auth
sources (session, OAuth Bearer, API key) rather than clearing the
identity on API-key / Bearer requests where auth() returns null.

Co-authored-by: Brendan Kellam <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 87756c8. Configure here.

setSentryUser(
user ?? null,
env.SOURCEBOT_TELEMETRY_PII_COLLECTION_ENABLED === 'true',
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sentry user set after org lookup

Low Severity

setSentryUser runs only after the org lookup succeeds. If that query throws or returns missing, the already-resolved principal is never attached, so the resulting Sentry event lacks user identity even though auth already succeeded.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 87756c8. Configure here.

@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

🤖 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 `@packages/web/src/middleware/withAuth.ts`:
- Around line 87-94: Move the setSentryUser call in the withAuth middleware to
immediately after authResult resolves the principal and before the organization
lookup, preserving the existing PII flag and unauthenticated null behavior.
Ensure lookup failures are captured with the authenticated user context.
🪄 Autofix (Beta)

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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 69b9026b-7932-4238-b19a-aa4b1ec44c1e

📥 Commits

Reviewing files that changed from the base of the PR and between 49d0429 and 87756c8.

📒 Files selected for processing (1)
  • packages/web/src/middleware/withAuth.ts

Comment on lines +87 to +94
// Associate the resolved principal with Sentry so request-scoped errors
// carry the user's identity, regardless of how they authenticated (session,
// OAuth Bearer, or API key). Clears the identity for unauthenticated requests.
setSentryUser(
user ?? null,
env.SOURCEBOT_TELEMETRY_PII_COLLECTION_ENABLED === 'true',
);

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Associate the user before the organization lookup.

authResult has already resolved the principal at Line 73, but setSentryUser runs only after org.findUnique(). If that lookup fails, the captured server error will not include the authenticated user context.

Suggested ordering
 const authResult = await getAuthenticatedUser();
+const user = authResult?.user;
+setSentryUser(
+    user ?? null,
+    env.SOURCEBOT_TELEMETRY_PII_COLLECTION_ENABLED === "true",
+);
 
 const org = await __unsafePrisma.org.findUnique({
     // ...
 });
 
-const user = authResult?.user;
-// setSentryUser(...)
📝 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
// Associate the resolved principal with Sentry so request-scoped errors
// carry the user's identity, regardless of how they authenticated (session,
// OAuth Bearer, or API key). Clears the identity for unauthenticated requests.
setSentryUser(
user ?? null,
env.SOURCEBOT_TELEMETRY_PII_COLLECTION_ENABLED === 'true',
);
const authResult = await getAuthenticatedUser();
const user = authResult?.user;
setSentryUser(
user ?? null,
env.SOURCEBOT_TELEMETRY_PII_COLLECTION_ENABLED === 'true',
);
const org = await __unsafePrisma.org.findUnique({
// ...
});
🤖 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 `@packages/web/src/middleware/withAuth.ts` around lines 87 - 94, Move the
setSentryUser call in the withAuth middleware to immediately after authResult
resolves the principal and before the organization lookup, preserving the
existing PII flag and unauthenticated null behavior. Ensure lookup failures are
captured with the authenticated user context.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant