diff --git a/doc/observability.md b/doc/observability.md index 501b095e44..15b0266ef9 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -317,6 +317,22 @@ event. These pages run signed out: session response arrives is not captured. The gate opens only after the session query resolves. +### Environment attribution + +Set `SENTRY_ENVIRONMENT` to the deployment environment, such as `staging` +or `production`. The server SDK reads this value from its process environment. +The authenticated session sends the same value in `sentryEnvironment`, and +`SentryGate` passes it to the browser SDK. This is runtime configuration, so the +same built image can report correctly in different environments. It does not +infer an environment from the page URL or include a tenant identifier. + +When the variable is absent or empty, the session sends `null` and the browser +keeps the SDK's default environment. The field is optional in the session +schema so a newer browser can still read a response from an older server. +A session refetch that changes the environment closes and restarts monitoring; +signing out still closes it. The browser release continues to identify the +loaded bundle, even if the server has since deployed another version. + ### Privacy settings The feature uses built-in Sentry options only. diff --git a/packages/shared/src/validators/access.test.ts b/packages/shared/src/validators/access.test.ts index 32ae79444f..e2d7ec3d99 100644 --- a/packages/shared/src/validators/access.test.ts +++ b/packages/shared/src/validators/access.test.ts @@ -160,6 +160,19 @@ describe("authSessionSchema", () => { expect(result.success && result.data.sentryDsn).toBe(null); }); + it.each([undefined, null, "staging", "production"])( + "preserves the optional Sentry environment (%s)", + (environment) => { + const result = authSessionSchema.parse({ + session: { id: "s1", userId: "u1" }, + user: { id: "u1", email: "a@b.com", name: "Jane", image: null }, + sentryDsn: null, + ...(environment === undefined ? {} : { sentryEnvironment: environment }), + }); + expect(result.sentryEnvironment).toBe(environment); + }, + ); + it("accepts a real sentryDsn value", () => { const result = authSessionSchema.safeParse({ session: { id: "s1", userId: "u1" }, diff --git a/packages/shared/src/validators/access.ts b/packages/shared/src/validators/access.ts index a5eddd48e5..c046b84d56 100644 --- a/packages/shared/src/validators/access.ts +++ b/packages/shared/src/validators/access.ts @@ -205,6 +205,8 @@ export const authSessionSchema = z.object({ // monitoring. The browser reads this value to open its own Sentry gate — // see `ui/src/lib/sentry.ts`. sentryDsn: z.string().min(1).nullable(), + // Optional for browser/server version skew; null leaves the SDK default. + sentryEnvironment: z.string().nullable().optional(), }); export type AuthSession = z.infer; diff --git a/server/src/__tests__/auth-routes.test.ts b/server/src/__tests__/auth-routes.test.ts index 3cb3cf6fb0..7b3588ae07 100644 --- a/server/src/__tests__/auth-routes.test.ts +++ b/server/src/__tests__/auth-routes.test.ts @@ -1,6 +1,6 @@ import express from "express"; import request from "supertest"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { errorHandler } from "../middleware/index.js"; import { authRoutes } from "../routes/auth.js"; @@ -63,6 +63,7 @@ describe.sequential("auth routes", () => { const originalSentryDsnBackend = process.env.SENTRY_DSN_BACKEND; afterEach(() => { + vi.unstubAllEnvs(); if (originalSentryDsn === undefined) delete process.env.SENTRY_DSN; else process.env.SENTRY_DSN = originalSentryDsn; if (originalSentryDsnFrontend === undefined) delete process.env.SENTRY_DSN_FRONTEND; @@ -72,6 +73,7 @@ describe.sequential("auth routes", () => { }); it("returns the persisted user profile in the session payload", async () => { + vi.stubEnv("SENTRY_ENVIRONMENT", undefined); delete process.env.SENTRY_DSN; const app = await createApp( { @@ -92,6 +94,7 @@ describe.sequential("auth routes", () => { }, user: baseUser, sentryDsn: null, + sentryEnvironment: null, }); }); @@ -203,6 +206,44 @@ describe.sequential("auth routes", () => { expect(res.body.sentryDsn).toBeUndefined(); }); + it.each(["staging", "production", "preview"])( + "sends the configured Sentry environment %s to board actors", + async (environment) => { + vi.stubEnv("SENTRY_ENVIRONMENT", environment); + const app = createApp({ type: "board", userId: "user-1", source: "session" }, baseUser); + + const res = await request(app).get("/api/auth/get-session"); + + expect(res.status).toBe(200); + expect(res.body.sentryEnvironment).toBe(environment); + }, + ); + + it.each([undefined, ""])("sends null for an unset Sentry environment (%s)", async (environment) => { + vi.stubEnv("SENTRY_ENVIRONMENT", environment); + const app = createApp({ type: "board", userId: "user-1", source: "session" }, baseUser); + + const res = await request(app).get("/api/auth/get-session"); + + expect(res.status).toBe(200); + expect(res.body.sentryEnvironment).toBeNull(); + }); + + it.each([ + { type: "none", source: "none" }, + { type: "agent", agentId: "agent-1", companyId: "company-1", source: "agent_key" }, + ] satisfies Express.Request["actor"][])("withholds Sentry settings from a $type actor", async (actor) => { + vi.stubEnv("SENTRY_ENVIRONMENT", "staging"); + vi.stubEnv("SENTRY_DSN_FRONTEND", "https://public@o0.ingest.sentry.io/1"); + const app = createApp(actor, baseUser); + + const res = await request(app).get("/api/auth/get-session"); + + expect(res.status).toBe(401); + expect(res.body.sentryDsn).toBeUndefined(); + expect(res.body.sentryEnvironment).toBeUndefined(); + }); + it("updates the signed-in profile", async () => { const app = await createApp( { diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts index 6455636f82..cfa65e033c 100644 --- a/server/src/routes/auth.ts +++ b/server/src/routes/auth.ts @@ -55,6 +55,8 @@ export function authRoutes(db: Db) { // handler, so no second authorization check runs here. This field // carries the front-end DSN only; it never carries the backend DSN. sentryDsn: resolveSentryDsns().frontend, + // Match the server SDK's runtime environment, including in reused images. + sentryEnvironment: process.env.SENTRY_ENVIRONMENT || null, })); }); diff --git a/ui/src/components/SentryGate.test.tsx b/ui/src/components/SentryGate.test.tsx index 30702bdba0..e10ad420ee 100644 --- a/ui/src/components/SentryGate.test.tsx +++ b/ui/src/components/SentryGate.test.tsx @@ -8,7 +8,7 @@ import { queryKeys } from "@/lib/queryKeys"; import { SentryGate } from "./SentryGate"; const getSessionMock = vi.hoisted(() => vi.fn()); -const initBrowserErrorMonitoringMock = vi.hoisted(() => vi.fn(async (_dsn: string) => {})); +const initBrowserErrorMonitoringMock = vi.hoisted(() => vi.fn(async (_dsn: string, _environment?: string) => {})); const teardownBrowserErrorMonitoringMock = vi.hoisted(() => vi.fn(async () => {})); vi.mock("@/api/auth", () => ({ @@ -16,7 +16,7 @@ vi.mock("@/api/auth", () => ({ })); vi.mock("@/lib/sentry", () => ({ - initBrowserErrorMonitoring: (dsn: string) => initBrowserErrorMonitoringMock(dsn), + initBrowserErrorMonitoring: (dsn: string, environment?: string) => initBrowserErrorMonitoringMock(dsn, environment), teardownBrowserErrorMonitoring: () => teardownBrowserErrorMonitoringMock(), })); @@ -93,7 +93,7 @@ describe("SentryGate", () => { const root = await renderGate(); expect(initBrowserErrorMonitoringMock).toHaveBeenCalledTimes(1); - expect(initBrowserErrorMonitoringMock).toHaveBeenCalledWith("https://public@o0.ingest.sentry.io/1"); + expect(initBrowserErrorMonitoringMock).toHaveBeenCalledWith("https://public@o0.ingest.sentry.io/1", undefined); root.unmount(); }); @@ -113,10 +113,43 @@ describe("SentryGate", () => { await flushReact(); expect(initBrowserErrorMonitoringMock).toHaveBeenCalledTimes(1); - expect(initBrowserErrorMonitoringMock).toHaveBeenCalledWith("https://public@o0.ingest.sentry.io/1"); + expect(initBrowserErrorMonitoringMock).toHaveBeenCalledWith("https://public@o0.ingest.sentry.io/1", undefined); root.unmount(); }); + it("restarts monitoring when the session environment changes with the same DSN", async () => { + const session = { + session: { id: "s1", userId: "u1" }, + user: { id: "u1", email: "a@b.com", name: "Jane", image: null }, + sentryDsn: "https://public@o0.ingest.sentry.io/1", + sentryEnvironment: "staging", + }; + getSessionMock.mockResolvedValue(session); + const root = await renderGate(); + try { + expect(initBrowserErrorMonitoringMock).toHaveBeenLastCalledWith(session.sentryDsn, "staging"); + await act(async () => { + await queryClient.refetchQueries({ queryKey: queryKeys.auth.session }); + }); + await flushReact(); + expect(initBrowserErrorMonitoringMock).toHaveBeenCalledTimes(1); + expect(teardownBrowserErrorMonitoringMock).not.toHaveBeenCalled(); + + getSessionMock.mockResolvedValue({ ...session, sentryEnvironment: "production" }); + await act(async () => { + await queryClient.refetchQueries({ queryKey: queryKeys.auth.session }); + }); + await flushReact(); + expect(teardownBrowserErrorMonitoringMock).toHaveBeenCalledTimes(1); + expect(initBrowserErrorMonitoringMock).toHaveBeenCalledTimes(2); + expect(initBrowserErrorMonitoringMock).toHaveBeenLastCalledWith(session.sentryDsn, "production"); + expect(teardownBrowserErrorMonitoringMock.mock.invocationCallOrder[0]) + .toBeLessThan(initBrowserErrorMonitoringMock.mock.invocationCallOrder[1]); + } finally { + root.unmount(); + } + }); + it("closes browser monitoring when sign-out clears the session's DSN", async () => { getSessionMock.mockResolvedValue({ session: { id: "s1", userId: "u1" }, diff --git a/ui/src/components/SentryGate.tsx b/ui/src/components/SentryGate.tsx index 0fa0d80e1f..3d99695cc1 100644 --- a/ui/src/components/SentryGate.tsx +++ b/ui/src/components/SentryGate.tsx @@ -26,14 +26,15 @@ export function SentryGate() { }); const dsn = session?.sentryDsn; + const environment = session?.sentryEnvironment ?? undefined; useEffect(() => { if (!dsn) return; - void initBrowserErrorMonitoring(dsn); + void initBrowserErrorMonitoring(dsn, environment); return () => { void teardownBrowserErrorMonitoring(); }; - }, [dsn]); + }, [dsn, environment]); return null; } diff --git a/ui/src/lib/sentry.test.ts b/ui/src/lib/sentry.test.ts index e1612a197e..a887cff096 100644 --- a/ui/src/lib/sentry.test.ts +++ b/ui/src/lib/sentry.test.ts @@ -111,11 +111,10 @@ describe("initBrowserErrorMonitoring", () => { const mocks = mockSentryPackage(); const { initBrowserErrorMonitoring } = await importFreshSentry(); - await initBrowserErrorMonitoring(DSN); + await initBrowserErrorMonitoring(DSN, "staging"); expect(mocks.init).toHaveBeenCalledTimes(1); - const initOptions = mocks.init.mock.calls[0][0] as { dsn: string }; - expect(initOptions.dsn).toBe(DSN); + expect(mocks.init.mock.calls[0][0]).toMatchObject({ dsn: DSN, environment: "staging" }); }); it("a second call starts no second client", async () => { @@ -376,11 +375,14 @@ describe("captured event shape against the real @sentry/browser SDK", () => { * adds no `beforeSend` of its own (see the "holds no beforeSend hook" * test above). */ - async function initRealSentryForTest(onEvent: (event: Record) => void) { + async function initRealSentryForTest( + onEvent: (event: Record) => void, + environment?: string | null, + ) { const { buildBrowserSentryInitOptions } = await importFreshSentry(); const Sentry = await import("@sentry/browser"); Sentry.init({ - ...buildBrowserSentryInitOptions(DSN), + ...buildBrowserSentryInitOptions(DSN, environment), transport: () => ({ send: async () => ({}), flush: async () => true }), beforeSend: (event) => { onEvent(event as unknown as Record); @@ -390,6 +392,25 @@ describe("captured event shape against the real @sentry/browser SDK", () => { return Sentry; } + it.each([ + ["staging", "staging"], + ["production", "production"], + [null, "production"], + [undefined, "production"], + ])("emits environment %s as %s without page context", async (environment, expected) => { + let captured: Record | null = null; + const Sentry = await initRealSentryForTest((event) => { captured = event; }, environment); + try { + Sentry.captureException(new Error("environment attribution check")); + await Sentry.flush(2000); + expect(captured).toMatchObject({ environment: expected }); + expect(captured).not.toHaveProperty("request"); + expect((captured as unknown as Record).breadcrumbs).toBeUndefined(); + } finally { + await Sentry.close(); + } + }); + it("attaches the bundle release to an emitted event without page context", async () => { const commit = "0123456789abcdef0123456789abcdef01234567"; vi.stubGlobal("__PAPERCLIP_BUILD_COMMIT__", commit); diff --git a/ui/src/lib/sentry.ts b/ui/src/lib/sentry.ts index bb433c5d2f..0c3a8e6c63 100644 --- a/ui/src/lib/sentry.ts +++ b/ui/src/lib/sentry.ts @@ -65,12 +65,12 @@ let sentry: SentryBrowserModule | null = null; * — the session query can refetch and call this again, and a second call is * a no-op because a client is already started. */ -export function initBrowserErrorMonitoring(dsn: string): Promise { +export function initBrowserErrorMonitoring(dsn: string, environment?: string | null): Promise { return enqueue(async () => { if (sentry) return; try { const Sentry = await import("@sentry/browser"); - Sentry.init(buildBrowserSentryInitOptions(dsn)); + Sentry.init(buildBrowserSentryInitOptions(dsn, environment)); sentry = Sentry; } catch (err) { // The dynamic import or the init call failed. Fall through with a @@ -152,9 +152,13 @@ export function captureBrowserException(error: unknown): void { * `@sentry/browser` module and assert the resolved integration list and the * captured-event shape against the true SDK, not a stand-in. */ -export function buildBrowserSentryInitOptions(dsn: string): BrowserSentryInitOptions { +export function buildBrowserSentryInitOptions( + dsn: string, + environment?: string | null, +): BrowserSentryInitOptions { return { dsn, + environment: environment ?? undefined, // Use the loaded bundle's build, even when the server has since deployed. release: typeof __PAPERCLIP_BUILD_COMMIT__ === "string"