:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): keep the OAuth access token out of shell environments (#97436)
Jonathan Mieloo8f1d8fe036aa
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.tsindex a63c8599dff3..8f98c837cc89 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts@@ -218,6 +218,7 @@ function createMockDependencies() {agentAuthAdapter: {getCurrentCredentials: vi.fn().mockResolvedValue(null),gatewayAuthToken: vi.fn().mockResolvedValue("gateway-token"),+ gatewayPublishToken: vi.fn().mockResolvedValue("gateway-token"),gatewayProjectId: vi.fn().mockReturnValue(1),ensureGatewayProxy: vi.fn().mockResolvedValue("http://127.0.0.1:9999"),configureProcessEnv: vi.fn().mockResolvedValue(undefined),@@ -387,7 +388,6 @@ describe("AgentService", () => {).mountContextWiki(credentials);const ENV_KEYS = [- "POSTHOG_API_KEY","POSTHOG_PERSONAL_API_KEY","POSTHOG_CONTEXT_LAYER_PATH","POSTHOG_CONTEXT_LAYER_COMMITS_PATH",@@ -405,35 +405,30 @@ describe("AgentService", () => {}});- // POSTHOG_API_KEY is what the auth sync just wrote, and it is deliberately- // absent while impersonating — so an impersonation credential must never- // reach the agent subprocess as a publish token.+ // The publish token is whatever the auth adapter hands out; it stays null+ // for impersonated sessions so that credential never reaches a subprocess.it.each([- ["the auth sync wrote one", "synced-key", "synced-key"],- ["the session is impersonated", undefined, undefined],- ])(- "exposes a publish token only when %s",- async (_label, apiKey, expected) => {- if (apiKey) {- process.env.POSTHOG_API_KEY = apiKey;- }- mockPrepareContextWiki.mockResolvedValueOnce(mount);+ ["a session the adapter covers", "gateway-token", "gateway-token"],+ ["an impersonated session", null, undefined],+ ])("exposes the publish token for %s", async (_label, token, expected) => {+ vi.mocked(+ deps.agentAuthAdapter.gatewayPublishToken,+ ).mockResolvedValueOnce(token);+ mockPrepareContextWiki.mockResolvedValueOnce(mount);- const wiki = await mountContextWiki();+ const wiki = await mountContextWiki();- expect(wiki).toEqual({- path: mount.path,- commitsPath: mount.commitsPath,- personalApiKey: expected,- });- },- );+ expect(wiki).toEqual({+ path: mount.path,+ commitsPath: mount.commitsPath,+ personalApiKey: expected,+ });+ });// The mount travels per-session precisely because the harness adapters// snapshot process.env at spawn time — a global write here would let// concurrent session starts leak one session's token into another.it("never writes the wiki vars to shared process.env", async () => {- process.env.POSTHOG_API_KEY = "synced-key";mockPrepareContextWiki.mockResolvedValueOnce(mount);await mountContextWiki();@@ -444,7 +439,6 @@ describe("AgentService", () => {});it("threads the mount into agent.run as a per-session value", async () => {- process.env.POSTHOG_API_KEY = "synced-key";mockPrepareContextWiki.mockResolvedValue(mount);await service.startSession(baseSessionParams);@@ -456,7 +450,7 @@ describe("AgentService", () => {contextWiki: {path: mount.path,commitsPath: mount.commitsPath,- personalApiKey: "synced-key",+ personalApiKey: "gateway-token",},}),);diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex 66b5a63de28c..c8f41e0792aa 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -794,14 +794,11 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {if (!mount) {return null;}- // The publish token mirrors POSTHOG_API_KEY exactly: gatewayAuthToken()- // just re-synced it, so it is absent for impersonated sessions (an- // impersonation credential must never reach agent subprocesses) and fresh- // after any token rotation or account switch.+ const publishToken = await this.agentAuthAdapter.gatewayPublishToken();return {path: mount.path,commitsPath: mount.commitsPath,- personalApiKey: process.env.POSTHOG_API_KEY || undefined,+ personalApiKey: publishToken ?? undefined,};}diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.tsindex 7faed330c940..7db91eb132f9 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts@@ -90,8 +90,6 @@ describe("AgentAuthAdapter", () => {afterEach(() => {vi.restoreAllMocks();- delete process.env.POSTHOG_API_KEY;- delete process.env.POSTHOG_AUTH_HEADER;});describe("getCurrentCredentials", () => {@@ -413,8 +411,6 @@ describe("AgentAuthAdapter", () => {claudeCliPath: "/mock/claude-cli.js",});- expect(process.env.POSTHOG_API_KEY).toBe("test-access-token");- expect(process.env.POSTHOG_AUTH_HEADER).toBe("Bearer test-access-token");expect(process.env.LLM_GATEWAY_URL).toBe("http://127.0.0.1:9999");expect(process.env.CLAUDE_CODE_EXECUTABLE).toBe("/mock/claude-cli.js");expect(process.env.POSTHOG_PROJECT_ID).toBe("1");@@ -422,23 +418,20 @@ describe("AgentAuthAdapter", () => {expect(process.env.PATH).toBe(pathBefore);});- it("does not export impersonated credentials to the process environment", async () => {- process.env.POSTHOG_API_KEY = "stale-token";- process.env.POSTHOG_AUTH_HEADER = "Bearer stale-token";- deps.authService.getState.mockReturnValue({- currentProjectId: 1,- sessionType: "impersonated",- });-- await adapter.configureProcessEnv({- credentials: baseCredentials,- proxyUrl: "http://127.0.0.1:9999",- claudeCliPath: "/mock/claude-cli.js",- });+ it.each([+ { sessionType: "impersonated" as const, expected: null },+ { sessionType: "persistent" as const, expected: "test-access-token" },+ ])(+ "returns $expected as the publish token for $sessionType sessions",+ async ({ sessionType, expected }) => {+ deps.authService.getState.mockReturnValue({+ currentProjectId: 1,+ sessionType,+ });- expect(process.env.POSTHOG_API_KEY).toBeUndefined();- expect(process.env.POSTHOG_AUTH_HEADER).toBeUndefined();- });+ await expect(adapter.gatewayPublishToken()).resolves.toBe(expected);+ },+ );it.each([{ rtkEnabled: false, expected: "0" },diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.tsindex 6461d08b66b8..24d984b71b55 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts@@ -235,6 +235,18 @@ export class AgentAuthAdapter {}}+ /**+ * Token that may reach agent subprocesses (e.g. the context wiki publish+ * token). Null for impersonated sessions: an impersonation credential must+ * never reach a subprocess.+ */+ async gatewayPublishToken(): Promise<string | null> {+ if (this.authService.getState().sessionType === "impersonated") {+ return null;+ }+ return this.gatewayAuthToken();+ }+authenticatedFetch(input: string, init?: RequestInit): Promise<Response> {return this.authService.authenticatedFetch(fetch, input, init);}@@ -265,25 +277,13 @@ export class AgentAuthAdapter {}}- private syncTokenEnvironment(token: string): void {- if (this.authService.getState().sessionType === "impersonated") {- delete process.env.POSTHOG_API_KEY;- delete process.env.POSTHOG_AUTH_HEADER;- return;- }- process.env.POSTHOG_API_KEY = token;- process.env.POSTHOG_AUTH_HEADER = `Bearer ${token}`;- }-private async getValidToken(): Promise<string> {const { accessToken } = await this.authService.getValidAccessToken();- this.syncTokenEnvironment(accessToken);return accessToken;}private async refreshToken(): Promise<string> {const { accessToken } = await this.authService.refreshAccessToken();- this.syncTokenEnvironment(accessToken);return accessToken;}