: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): scope gateway billing to selected project (#80720)
Adam Bowkerb2afb598327a
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.tsindex 6cae27301a7a..1e3dad18786e 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts@@ -34,6 +34,7 @@ describe("DesktopPiRpcClientFactory", () => {expires: 1,region: "eu" as const,})),+ getState: vi.fn(() => ({ currentProjectId: 1 })),} as unknown as AgentAuth;const authProxy = {start: vi.fn(async () => "http://127.0.0.1:1234"),@@ -76,6 +77,7 @@ describe("DesktopPiRpcClientFactory", () => {).resolves.toBe(client);expect(authProxy.start).toHaveBeenCalledWith(getLlmGatewayUrl(getCloudUrlFromRegion("eu")),+ { "X-PostHog-Project-Id": "1" },);expect(createPiRpcClient).toHaveBeenCalledWith({cwd: "/workspace",diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.tsindex 073198af8b57..3cf1bccd9f37 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts@@ -5,6 +5,7 @@ import {} from "@posthog/agent/pi/rpc-client";import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";import { type CloudRegion, getCloudUrlFromRegion } from "@posthog/shared";+import { buildPosthogProjectHeaderRecord } from "@posthog/shared/posthog-property-headers";import {AGENT_AUTH,MCP_SERVER_CONNECTION_SOURCE,@@ -22,9 +23,6 @@ const PROXY_API_KEY = "posthog-code-auth-proxy";@injectable()export class DesktopPiRpcClientFactory implements PiRpcClientFactory {- private proxyRegion?: CloudRegion;- private proxyUrlPromise?: Promise<string>;-constructor(@inject(AGENT_AUTH) private readonly auth: AgentAuth,@inject(AUTH_PROXY_SERVICE)@@ -41,7 +39,11 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {throw new Error("Pi requires PostHog authentication");}- const baseUrl = await this.getProxyUrl(credentials.region);+ const projectId = this.auth.getState().currentProjectId;+ if (!projectId) {+ throw new Error("Pi requires a selected PostHog project");+ }+ const baseUrl = await this.getProxyUrl(credentials.region, projectId);const mcpConfiguration =await this.mcpServerSource.getMcpRuntimeConfiguration();@@ -62,13 +64,11 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {});}- private getProxyUrl(region: CloudRegion): Promise<string> {- if (this.proxyRegion !== region || !this.proxyUrlPromise) {- this.proxyRegion = region;- const gatewayUrl = getLlmGatewayUrl(getCloudUrlFromRegion(region));- this.proxyUrlPromise = this.authProxy.start(gatewayUrl);- }-- return this.proxyUrlPromise;+ private getProxyUrl(region: CloudRegion, projectId: number): Promise<string> {+ const gatewayUrl = getLlmGatewayUrl(getCloudUrlFromRegion(region));+ return this.authProxy.start(+ gatewayUrl,+ buildPosthogProjectHeaderRecord(projectId),+ );}}diff --git a/products/desktop/apps/web/src/web-host-router.ts b/products/desktop/apps/web/src/web-host-router.tsindex 26bee1cde7e3..f531ccc9085c 100644--- a/products/desktop/apps/web/src/web-host-router.ts+++ b/products/desktop/apps/web/src/web-host-router.ts@@ -151,6 +151,7 @@ const agentStubRouter = router({getLlmGatewayUrl(input.apiHost),input.region,accessToken,+ auth.getState().currentProjectId ?? undefined,);}),// Model/mode/effort options for the task-input preview + cloud run creationdiff --git a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts b/products/desktop/packages/agent/src/adapters/base-acp-agent.tsindex 3ca7eed11219..48db07fcba1d 100644--- a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts+++ b/products/desktop/packages/agent/src/adapters/base-acp-agent.ts@@ -143,6 +143,7 @@ export abstract class BaseAcpAgent implements Agent {currentModelOverride?: string,gatewayUrl?: string,gatewayAuthToken?: string,+ projectId?: number,): Promise<{currentModelId: string;options: SessionConfigSelectOption[];@@ -150,7 +151,9 @@ export abstract class BaseAcpAgent implements Agent {// Authenticated so the gateway can mark plan-restricted models —// anonymous fetches see everything allowed.this.gatewayModels = await fetchGatewayModels(- gatewayUrl ? { gatewayUrl, authToken: gatewayAuthToken } : undefined,+ gatewayUrl+ ? { gatewayUrl, authToken: gatewayAuthToken, projectId }+ : undefined,);const adapterModels = this.gatewayModelsdiff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex f6ceff8d6b80..62e58cc57b7e 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -2208,6 +2208,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {requestedModel,this.options?.gatewayEnv?.anthropicBaseUrl,this.options?.gatewayEnv?.anthropicAuthToken,+ Number(this.options?.gatewayEnv?.posthogProjectId) || undefined,),...(meta?.taskRunId? [diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.tsindex 242eb8628ed2..00a0da670a9d 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts@@ -12,9 +12,9 @@ import type {SpawnedProcess,SpawnOptions,} from "@anthropic-ai/claude-agent-sdk";+import { buildPosthogPropertyHeaderLines } from "@posthog/shared/posthog-property-headers";import type { FileEnrichmentDeps } from "../../../enrichment/file-enricher";import { IS_ROOT } from "../../../utils/common";-import { buildGatewayPropertyHeaders } from "../../../utils/gateway";import type { Logger } from "../../../utils/logger";import type { TaskState } from "../conversion/task-state";import {@@ -177,11 +177,11 @@ function buildEnvironment(// get_llm_client(team_id=...).const projectId = gateway?.posthogProjectId ?? process.env.POSTHOG_PROJECT_ID;if (projectId) {- headerLines.push(buildGatewayPropertyHeaders({ team_id: projectId }));+ headerLines.push(buildPosthogPropertyHeaderLines({ team_id: projectId }));}if (sessionId) {headerLines.push(- buildGatewayPropertyHeaders({ $ai_session_id: sessionId }),+ buildPosthogPropertyHeaderLines({ $ai_session_id: sessionId }),);}// Route to AWS Bedrock as a fallback when Anthropic returns 5xxdiff --git a/products/desktop/packages/agent/src/agent.test.ts b/products/desktop/packages/agent/src/agent.test.tsindex 79f815509e39..d25dab794a80 100644--- a/products/desktop/packages/agent/src/agent.test.ts+++ b/products/desktop/packages/agent/src/agent.test.ts@@ -60,7 +60,10 @@ describe("Agent", () => {expect(fetchMock).toHaveBeenCalledWith(expect.any(String),expect.objectContaining({- headers: { Authorization: "Bearer token" },+ headers: {+ Authorization: "Bearer token",+ "X-PostHog-Project-Id": "1",+ },}),);});diff --git a/products/desktop/packages/agent/src/agent.ts b/products/desktop/packages/agent/src/agent.tsindex b7ea903d8d2c..49324130f8d0 100644--- a/products/desktop/packages/agent/src/agent.ts+++ b/products/desktop/packages/agent/src/agent.ts@@ -1,4 +1,5 @@import { buildPrOutput, mergePrUrls, readPrUrls } from "@posthog/shared";+import { buildPosthogPropertyHeaderRecord } from "@posthog/shared/posthog-property-headers";import {createAcpConnection,type InProcessAcpConnection,@@ -14,7 +15,6 @@ import {import { PostHogAPIClient, type TaskRunUpdate } from "./posthog-api";import { SessionLogWriter } from "./session-log-writer";import type { AgentConfig, TaskExecutionOptions } from "./types";-import { buildGatewayPropertyHeaderRecord } from "./utils/gateway";import { Logger } from "./utils/logger";export class Agent {@@ -89,6 +89,7 @@ export class Agent {const models = await fetchModelsList({gatewayUrl: gatewayConfig.gatewayUrl,authToken: gatewayConfig.apiKey,+ projectId: this.posthogApiConfig?.projectId,});const gatewayCodexModels = models.filter((model) => {if (isBlockedModelId(model.id)) return false;@@ -150,7 +151,7 @@ export class Agent {reasoningEffort: options.reasoningEffort,developerInstructions: options.developerInstructions,httpHeaders: taskId- ? buildGatewayPropertyHeaderRecord({ $ai_session_id: taskId })+ ? buildPosthogPropertyHeaderRecord({ $ai_session_id: taskId }): undefined,additionalDirectories: options.additionalDirectories,}diff --git a/products/desktop/packages/agent/src/gateway-models.test.ts b/products/desktop/packages/agent/src/gateway-models.test.tsindex 8c988ec1e97d..e243cf025308 100644--- a/products/desktop/packages/agent/src/gateway-models.test.ts+++ b/products/desktop/packages/agent/src/gateway-models.test.ts@@ -72,6 +72,28 @@ describe("gateway models cache", () => {expect(second[0]?.allowed).toBe(true);});+ it("does not serve one project's marks to another project using the same token", async () => {+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(modelsResponse(false))+ .mockResolvedValueOnce(modelsResponse(true));+ const gatewayUrl = "https://gateway.project-key-test";++ await fetchGatewayModels({ gatewayUrl, authToken: "tok-a", projectId: 1 });+ const second = await fetchGatewayModels({+ gatewayUrl,+ authToken: "tok-a",+ projectId: 2,+ });++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls[1]?.[1]?.headers).toMatchObject({+ Authorization: "Bearer tok-a",+ "X-PostHog-Project-Id": "2",+ });+ expect(second[0]?.allowed).toBe(true);+ });+it("serves the cached list to the same token without refetching", async () => {const fetchMock = vi.spyOn(globalThis, "fetch")diff --git a/products/desktop/packages/agent/src/gateway-models.ts b/products/desktop/packages/agent/src/gateway-models.tsindex 1ec28dc001e0..007c15feeaa9 100644--- a/products/desktop/packages/agent/src/gateway-models.ts+++ b/products/desktop/packages/agent/src/gateway-models.ts@@ -2,6 +2,7 @@ import {type GatewayModel,normalizeGatewayModelsResponse,} from "@posthog/shared";+import { buildPosthogProjectHeaderRecord } from "@posthog/shared/posthog-property-headers";export {BLOCKED_GATEWAY_MODEL_IDS,@@ -32,6 +33,7 @@ export interface FetchGatewayModelsOptions {gatewayUrl: string;/** Bearer token; required for accurate free-tier marks. */authToken?: string;+ projectId?: number;}const CACHE_TTL = 10 * 60 * 1000; // 10 minutes@@ -51,19 +53,34 @@ interface ModelsCache<T> {expiry: number;url: string;token: string | null;+ projectId: number | null;}function readModelsCache<T>(cache: ModelsCache<T> | null,url: string,token: string | null,+ projectId: number | null,): T[] | null {- if (!cache || cache.url !== url || cache.token !== token) return null;+ if (+ !cache ||+ cache.url !== url ||+ cache.token !== token ||+ cache.projectId !== projectId+ )+ return null;return Date.now() < cache.expiry ? cache.models : null;}-function authHeaders(authToken?: string): Record<string, string> | undefined {- return authToken ? { Authorization: `Bearer ${authToken}` } : undefined;+function authHeaders(+ authToken?: string,+ projectId?: number,+): Record<string, string> | undefined {+ if (!authToken && !projectId) return undefined;+ return {+ ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),+ ...buildPosthogProjectHeaderRecord(projectId),+ };}let gatewayModelsCache: ModelsCache<GatewayModel> | null = null;@@ -77,14 +94,20 @@ export async function fetchGatewayModels(}const token = options?.authToken ?? null;- const cached = readModelsCache(gatewayModelsCache, gatewayUrl, token);+ const projectId = options?.projectId ?? null;+ const cached = readModelsCache(+ gatewayModelsCache,+ gatewayUrl,+ token,+ projectId,+ );if (cached) return cached;const modelsUrl = `${gatewayUrl}/v1/models`;try {const response = await fetch(modelsUrl, {- headers: authHeaders(options?.authToken),+ headers: authHeaders(options?.authToken, options?.projectId),signal: AbortSignal.timeout(GATEWAY_FETCH_TIMEOUT_MS),});@@ -98,6 +121,7 @@ export async function fetchGatewayModels(expiry: Date.now() + CACHE_TTL,url: gatewayUrl,token,+ projectId,};return models;} catch {@@ -123,13 +147,14 @@ export async function fetchModelsList(}const token = options?.authToken ?? null;- const cached = readModelsCache(modelsListCache, gatewayUrl, token);+ const projectId = options?.projectId ?? null;+ const cached = readModelsCache(modelsListCache, gatewayUrl, token, projectId);if (cached) return cached;try {const modelsUrl = `${gatewayUrl}/v1/models`;const response = await fetch(modelsUrl, {- headers: authHeaders(options?.authToken),+ headers: authHeaders(options?.authToken, options?.projectId),signal: AbortSignal.timeout(GATEWAY_FETCH_TIMEOUT_MS),});if (!response.ok) {@@ -148,6 +173,7 @@ export async function fetchModelsList(expiry: Date.now() + CACHE_TTL,url: gatewayUrl,token,+ projectId,};return results;} catch {diff --git a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.tsindex 6b18e64f2236..55709a006e05 100644--- a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts@@ -224,6 +224,7 @@ describe("AgentServer.configureEnvironment", () => {"x-posthog-property-task_title": "Fix the bug","x-posthog-property-team_id": "1","x-posthog-property-$ai_session_id": "task-abc",+ "X-PostHog-Project-Id": "1",});});@@ -249,6 +250,7 @@ describe("AgentServer.configureEnvironment", () => {"x-posthog-property-task_run_id: run-xyz","x-posthog-property-task_user_id: 42","x-posthog-property-task_title: Fix the bug",+ "X-PostHog-Project-Id: 1",].join("\n"),);});@@ -290,7 +292,7 @@ describe("AgentServer.configureEnvironment", () => {});expect(env.anthropicCustomHeaders).toBe(- "x-posthog-property-task_internal: false",+ "x-posthog-property-task_internal: false\nX-PostHog-Project-Id: 1",);});diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex f3a8b4c817c8..6ab0f5f821eb 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -27,6 +27,12 @@ import {readMcpToolDescriptor,readPrUrls,} from "@posthog/shared";+import {+ buildPosthogPropertiesHeaderLines,+ buildPosthogPropertiesHeaderRecord,+ buildPosthogScopedPropertyHeaderLines,+ buildPosthogScopedPropertyHeaderRecord,+} from "@posthog/shared/posthog-property-headers";import { unzipSync } from "fflate";import { Hono } from "hono";import { z } from "zod";@@ -91,14 +97,7 @@ import type {} from "../types";import { resourceLink } from "../utils/acp-content";import { AsyncMutex } from "../utils/async-mutex";-import {- buildGatewayPropertiesHeader,- buildGatewayPropertiesHeaderRecord,- buildGatewayPropertyHeaderRecord,- buildGatewayPropertyHeaders,- resolveGatewayProduct,- resolveGatewayTarget,-} from "../utils/gateway";+import { resolveGatewayProduct, resolveGatewayTarget } from "../utils/gateway";import { resolveGithubToken } from "../utils/github-token";import { Logger } from "../utils/logger";import { logAgentshRuntimeInfo } from "./agentsh-runtime";@@ -1622,6 +1621,7 @@ export class AgentServer {void fetchGatewayModels({gatewayUrl: gatewayEnv.anthropicBaseUrl,authToken: gatewayEnv.anthropicAuthToken,+ projectId: Number(gatewayEnv.posthogProjectId) || undefined,}).catch(() => {});}@@ -4071,17 +4071,23 @@ ${commonInstructions}ai_product: aiProduct,team_id: projectId,};- customHeaders = buildGatewayPropertiesHeader(properties);- openaiCustomHeaders = buildGatewayPropertiesHeaderRecord(properties);+ customHeaders = buildPosthogPropertiesHeaderLines(properties);+ openaiCustomHeaders = buildPosthogPropertiesHeaderRecord(properties);} else {- customHeaders = buildGatewayPropertyHeaders(gatewayProperties);+ customHeaders = buildPosthogScopedPropertyHeaderLines(+ gatewayProperties,+ projectId,+ );// No $ai_session_id on the Go-gateway path above: it strips $-prefixed// blob keys, so the session id would be silently dropped there.- openaiCustomHeaders = buildGatewayPropertyHeaderRecord({- ...gatewayProperties,- team_id: projectId,- $ai_session_id: taskId,- });+ openaiCustomHeaders = buildPosthogScopedPropertyHeaderRecord(+ {+ ...gatewayProperties,+ team_id: projectId,+ $ai_session_id: taskId,+ },+ projectId,+ );}// Server-level constants that don't vary per task — safe to keep indiff --git a/products/desktop/packages/agent/src/utils/gateway.ts b/products/desktop/packages/agent/src/utils/gateway.tsindex 5ba218a4f000..984160498f87 100644--- a/products/desktop/packages/agent/src/utils/gateway.ts+++ b/products/desktop/packages/agent/src/utils/gateway.ts@@ -35,13 +35,6 @@ export function resolveGatewayProduct({return "posthog_code";}-export {- buildPosthogPropertiesHeaderLines as buildGatewayPropertiesHeader,- buildPosthogPropertiesHeaderRecord as buildGatewayPropertiesHeaderRecord,- buildPosthogPropertyHeaderLines as buildGatewayPropertyHeaders,- buildPosthogPropertyHeaderRecord as buildGatewayPropertyHeaderRecord,-} from "@posthog/shared/posthog-property-headers";-function getGatewayBaseUrl(posthogHost: string): string {return getCloudTaskGatewayUrl(posthogHost).replace(/\/posthog_code$/, "");}diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 2a379b9544a9..4a0e4c2109ee 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -210,8 +210,13 @@ describe("PostHogAPIClient", () => {expect(fetch).toHaveBeenCalledWith(new URL("https://gateway.eu.posthog.com/posthog_code/v1/models"),- expect.objectContaining({ method: "GET" }),+ expect.objectContaining({+ method: "GET",+ headers: expect.any(Headers),+ }),);+ const requestHeaders = fetch.mock.calls[0]?.[1]?.headers as Headers;+ expect(requestHeaders.get("X-PostHog-Project-Id")).toBe("123");expect(options.find((option) => option.category === "model")).toMatchObject({currentValue: "claude-opus-4-8",diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 69c7c632339e..f683e6b87fc9 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -110,6 +110,7 @@ import type {TaskThreadMessage,UserBasic,} from "@posthog/shared/domain-types";+import { buildPosthogProjectHeaderRecord } from "@posthog/shared/posthog-property-headers";import {buildAgentAnalyticsQueries,type HogQLGrid,@@ -1592,11 +1593,15 @@ export class PostHogAPIClient {async getCloudTaskConfigOptions(adapter: Adapter = "claude",): Promise<CloudTaskConfigOption[]> {+ const teamId = await this.getTeamId();const url = new URL(`${getCloudTaskGatewayUrl(this.apiHost)}/v1/models`);const response = await this.api.fetcher.fetch({method: "get",url,path: url.pathname,+ parameters: {+ header: buildPosthogProjectHeaderRecord(teamId),+ },});return buildCloudTaskConfigOptions(normalizeGatewayModelsResponse(await response.json()),diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.tsindex b65d8b6fcee3..737dc2638376 100644--- a/products/desktop/packages/core/src/auth/auth.test.ts+++ b/products/desktop/packages/core/src/auth/auth.test.ts@@ -910,6 +910,42 @@ describe("AuthService", () => {});});+ it("restores the saved project and its organization after an external organization switch", async () => {+ seedStoredSession({ selectedProjectId: 11 });+ oauthFlow.refreshToken.mockResolvedValue(+ mockTokenResponse({ scopedOrgs: ["org-1", "org-2"] }),+ );+ stubAuthFetch({+ currentOrgId: "org-2",+ orgs: {+ "org-1": {+ name: "Org 1",+ projects: [{ id: 11, name: "Project 11" }],+ },+ "org-2": {+ name: "Org 2",+ projects: [{ id: 22, name: "Project 22" }],+ },+ },+ });++ const fetchSpy = vi.spyOn(globalThis, "fetch");++ await service.initialize();++ expect(service.getState()).toMatchObject({+ status: "authenticated",+ currentOrgId: "org-1",+ currentProjectId: 11,+ });+ expect(sessionPort.getCurrent()?.selectedProjectId).toBe(11);++ const patchCall = fetchSpy.mock.calls.find(+ ([, init]) => (init as RequestInit | undefined)?.method === "PATCH",+ );+ expect(patchCall).toBeUndefined();+ });+describe("lifecycle: connectivity recovery", () => {it("recovers session when connectivity changes to online", async () => {seedStoredSession({ selectedProjectId: 42 });diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.tsindex d325c0d80816..3cd63cafea34 100644--- a/products/desktop/packages/core/src/auth/auth.ts+++ b/products/desktop/packages/core/src/auth/auth.ts@@ -428,6 +428,27 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {throw new Error(`Failed to switch organization: ${response.statusText}`);}}+ private reconcileInitialSelection(input: {+ orgProjectsMap: OrgProjectsMap;+ currentOrgId: string | null;+ preferredProjectId: number | null;+ lastSelectedOrgId: string | null;+ }): {+ currentOrgId: string | null;+ currentProjectId: number | null;+ } {+ const currentProjectId = pickInitialProjectId(input);+ const projectOrgId = currentProjectId+ ? findOrgForProject(+ input.orgProjectsMap,+ currentProjectId,+ input.currentOrgId,+ )+ : null;+ const currentOrgId = projectOrgId ?? input.currentOrgId;++ return { currentOrgId, currentProjectId };+ }async logout(): Promise<AuthState> {const { cloudRegion, currentProjectId } = this.state;@@ -712,7 +733,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {const lastPrefs = accountKey? this.authPreference.get(accountKey, options.cloudRegion): null;- const currentProjectId = pickInitialProjectId({+ const selection = this.reconcileInitialSelection({orgProjectsMap,currentOrgId,preferredProjectId:@@ -730,8 +751,8 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {sessionType: refreshToken ? "persistent" : "impersonated",cloudRegion: options.cloudRegion,orgProjectsMap,- currentOrgId,- currentProjectId,+ currentOrgId: selection.currentOrgId,+ currentProjectId: selection.currentProjectId,orgProjectsIncomplete,};@@ -1284,7 +1305,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {: null;const storedSelected =this.authSession.getCurrent()?.selectedProjectId ?? null;- const currentProjectId = pickInitialProjectId({+ const selection = this.reconcileInitialSelection({orgProjectsMap: map,currentOrgId: session.currentOrgId,preferredProjectId:@@ -1296,8 +1317,8 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {});await this.commitSessionState(session, {orgProjectsMap: map,- currentOrgId: session.currentOrgId,- currentProjectId,+ currentOrgId: selection.currentOrgId,+ currentProjectId: selection.currentProjectId,});this.logger.info("Recovered organizations/projects after incomplete sync",diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.tsindex c16378f6a0b4..67a6760cfb1b 100644--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts@@ -46,7 +46,7 @@ function createService(const orgListeners: Array<(state: { currentOrgId: string | null }) => void> =[];const authService = {- getState: () => ({ currentOrgId: "org-1" }),+ getState: () => ({ currentOrgId: "org-1", currentProjectId: 42 }),on: (_event: string,listener: (state: { currentOrgId: string | null }) => void,@@ -109,6 +109,7 @@ describe("LlmGatewayService.prompt", () => {const [url, init] = fetchMock.mock.calls[0];expect(url).toBe(`${API_HOST}/gateway/v1/messages`);expect(init.method).toBe("POST");+ expect(init.headers).toMatchObject({ "X-PostHog-Project-Id": "42" });const body = JSON.parse(init.body);expect(body.model).toBe("claude-default");expect(body.system).toBe("be terse");@@ -351,6 +352,9 @@ describe("LlmGatewayService.fetchUsage", () => {expect(usage.product).toBe("code");expect(usage.is_pro).toBe(true);expect(usage.sustained.used_percent).toBe(10);+ expect(fetchMock).toHaveBeenCalledWith(`${API_HOST}/gateway/usage`, {+ headers: { "X-PostHog-Project-Id": "42" },+ });});it("throws a usage_error LlmGatewayError on non-ok response", async () => {diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.tsindex 9cc90c6585e5..af01082b2385 100644--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts@@ -1,6 +1,7 @@import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";import { classifyGatewayLimitError } from "@posthog/shared";import {+ buildPosthogProjectHeaderRecord,buildPosthogPropertyHeaderRecord,type PosthogProperties,} from "@posthog/shared/posthog-property-headers";@@ -56,6 +57,7 @@ export class LlmGatewayService {this.auth = host;this.endpoints = host;this.log = logger.scope("llm-gateway");+ this.authService = authService;let orgId = authService.getState().currentOrgId;authService.on(AuthServiceEvent.StateChanged, (state) => {if (state.currentOrgId === orgId) return;@@ -67,6 +69,7 @@ export class LlmGatewayService {private readonly auth: LlmGatewayAuth;private readonly endpoints: LlmGatewayEndpoints;private readonly log: LlmGatewayLogger;+ private readonly authService: AuthService;private lastKnownCodeUsageSubscribed: boolean | null = null;@@ -167,6 +170,7 @@ export class LlmGatewayService {const headers: Record<string, string> = {"Content-Type": "application/json",+ ...this.projectScopeHeaders(),...(posthogProperties? buildPosthogPropertyHeaderRecord(posthogProperties): {}),@@ -260,7 +264,9 @@ export class LlmGatewayService {let response: Response;try {- response = await this.auth.authenticatedFetch(usageUrl);+ response = await this.auth.authenticatedFetch(usageUrl, {+ headers: this.projectScopeHeaders(),+ });} catch (err) {this.log.warn("Usage fetch network error", {error: err instanceof Error ? err.message : String(err),@@ -284,4 +290,10 @@ export class LlmGatewayService {}return usage;}++ private projectScopeHeaders(): Record<string, string> {+ return buildPosthogProjectHeaderRecord(+ this.authService.getState().currentProjectId,+ );+ }}diff --git a/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.ts b/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.tsindex 8f487f0fa051..fbf885711fe3 100644--- a/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.ts@@ -75,10 +75,11 @@ export async function fetchPosthogPiModelCatalog(gatewayUrl: string,region: CloudRegion,apiKey?: string,+ projectId?: number,): Promise<PiModelCatalogEntry[]> {const models =process.env.PI_OFFLINE || process.env.HARNESS_STATIC_MODELS? []- : await fetchPosthogGatewayModels(gatewayUrl, apiKey);+ : await fetchPosthogGatewayModels(gatewayUrl, apiKey, projectId);return resolvePosthogPiModelCatalog(models, region);}diff --git a/products/desktop/packages/harness/src/extensions/posthog-provider/models.ts b/products/desktop/packages/harness/src/extensions/posthog-provider/models.tsindex 100b6daf07b3..b64a70558368 100644--- a/products/desktop/packages/harness/src/extensions/posthog-provider/models.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-provider/models.ts@@ -1,6 +1,7 @@import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";import type { CloudRegion } from "@posthog/shared";+import { buildPosthogProjectHeaderRecord } from "@posthog/shared/posthog-property-headers";import { getLlmGatewayUrl } from "./gateway";export const DEFAULT_MODEL = "claude-opus-4-8";@@ -231,10 +232,17 @@ export function fallbackModelConfigs(export async function fetchPosthogGatewayModels(baseUrl: string,apiKey?: string,+ projectId?: number,): Promise<GatewayModel[]> {try {const response = await fetch(`${baseUrl.replace(/\/$/, "")}/v1/models`, {- headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : undefined,+ headers:+ apiKey || projectId+ ? {+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),+ ...buildPosthogProjectHeaderRecord(projectId),+ }+ : undefined,signal: AbortSignal.timeout(MODELS_FETCH_TIMEOUT_MS),});if (!response.ok) {@@ -266,6 +274,7 @@ export async function resolveModelConfigs(region: CloudRegion,baseUrl?: string,apiKey?: string,+ projectId?: number,): Promise<ProviderModelConfig[]> {if (process.env.PI_OFFLINE || process.env.HARNESS_STATIC_MODELS) {return fallbackModelConfigs(region);@@ -274,6 +283,7 @@ export async function resolveModelConfigs(const models = await fetchPosthogGatewayModels(baseUrl ?? getLlmGatewayUrl(region),apiKey,+ projectId,);return resolveModelConfigsFromGatewayModels(models, region);}diff --git a/products/desktop/packages/shared/src/posthog-property-headers.test.ts b/products/desktop/packages/shared/src/posthog-property-headers.test.tsindex 099151a553a4..d716f0028abc 100644--- a/products/desktop/packages/shared/src/posthog-property-headers.test.ts+++ b/products/desktop/packages/shared/src/posthog-property-headers.test.ts@@ -1,12 +1,37 @@import { describe, expect, it } from "vitest";import {+ buildPosthogProjectHeaderLines,+ buildPosthogProjectHeaderRecord,buildPosthogPropertiesBlob,buildPosthogPropertiesHeaderLines,buildPosthogPropertiesHeaderRecord,buildPosthogPropertyHeaderLines,buildPosthogPropertyHeaderRecord,+ buildPosthogScopedPropertyHeaderLines,+ buildPosthogScopedPropertyHeaderRecord,} from "./posthog-property-headers";+describe("PostHog project headers", () => {+ it("builds record and line forms from the same header contract", () => {+ expect(buildPosthogProjectHeaderRecord(42)).toEqual({+ "X-PostHog-Project-Id": "42",+ });+ expect(buildPosthogProjectHeaderLines(42)).toBe("X-PostHog-Project-Id: 42");+ });++ it("combines the project scope with per-property headers", () => {+ expect(+ buildPosthogScopedPropertyHeaderRecord({ task_id: "task-1" }, 42),+ ).toEqual({+ "x-posthog-property-task_id": "task-1",+ "X-PostHog-Project-Id": "42",+ });+ expect(+ buildPosthogScopedPropertyHeaderLines({ task_id: "task-1" }, 42),+ ).toBe("x-posthog-property-task_id: task-1\nX-PostHog-Project-Id: 42");+ });+});+describe("buildPosthogPropertyHeaderRecord", () => {it("returns each property as an x-posthog-property-<key> entry", () => {expect(diff --git a/products/desktop/packages/shared/src/posthog-property-headers.ts b/products/desktop/packages/shared/src/posthog-property-headers.tsindex 475852cf3b28..d54e129fdec9 100644--- a/products/desktop/packages/shared/src/posthog-property-headers.ts+++ b/products/desktop/packages/shared/src/posthog-property-headers.ts@@ -2,6 +2,8 @@ export type PosthogPropertyValue = string | number | boolean | null | undefined;export type PosthogProperties = Record<string, PosthogPropertyValue>;+export const POSTHOG_PROJECT_ID_HEADER = "X-PostHog-Project-Id";+/*** Make a value safe to embed in an HTTP header value. Only printable ASCII* survives: latin1 is valid per RFC 9110 and undici accepts it, but Bun's@@ -59,6 +61,40 @@ export function buildPosthogPropertyHeaderLines(.join("\n");}+export function buildPosthogProjectHeaderRecord(+ projectId: number | null | undefined,+): Record<string, string> {+ return projectId ? { [POSTHOG_PROJECT_ID_HEADER]: String(projectId) } : {};+}++export function buildPosthogProjectHeaderLines(+ projectId: number | null | undefined,+): string {+ return projectId ? `${POSTHOG_PROJECT_ID_HEADER}: ${projectId}` : "";+}++export function buildPosthogScopedPropertyHeaderRecord(+ properties: PosthogProperties,+ projectId: number | null | undefined,+): Record<string, string> {+ return {+ ...buildPosthogPropertyHeaderRecord(properties),+ ...buildPosthogProjectHeaderRecord(projectId),+ };+}++export function buildPosthogScopedPropertyHeaderLines(+ properties: PosthogProperties,+ projectId: number | null | undefined,+): string {+ return [+ buildPosthogPropertyHeaderLines(properties),+ buildPosthogProjectHeaderLines(projectId),+ ]+ .filter(Boolean)+ .join("\n");+}+/** Header carrying the whole property set as one JSON object. */export const POSTHOG_PROPERTIES_HEADER = "X-PostHog-Properties";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 abf5ed2f52ed..e30eed1ea00d 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@@ -190,6 +190,7 @@ function createMockDependencies() {agentAuthAdapter: {getCurrentCredentials: vi.fn().mockResolvedValue(null),gatewayAuthToken: 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),createPosthogConfig: vi.fn((credentials) => ({@@ -324,6 +325,9 @@ describe("AgentService", () => {"claude",);+ expect(fetchGatewayModels).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: 1 }),+ );const modelOption = options.find((option) => option.id === "model");expect(modelOption).toMatchObject({type: "select",diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex 79ee1336867a..9264b8bbaa98 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -2345,6 +2345,7 @@ For git operations while detached:gatewayUrl,region,(await this.agentAuthAdapter.gatewayAuthToken()) ?? undefined,+ this.agentAuthAdapter.gatewayProjectId() ?? undefined,);}@@ -2356,6 +2357,7 @@ For git operations while detached:const gatewayModels = await fetchGatewayModels({gatewayUrl,authToken: (await this.agentAuthAdapter.gatewayAuthToken()) ?? undefined,+ projectId: this.agentAuthAdapter.gatewayProjectId() ?? undefined,});const configOptions = buildCloudTaskConfigOptions(gatewayModels,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 3357f202f305..b3f7e190c69e 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@@ -5,6 +5,7 @@ import {} from "@posthog/agent/adapters/claude/mcp/tool-metadata";import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";import type { McpServerConnection, McpToolPolicy } from "@posthog/shared";+import { POSTHOG_PROJECT_ID_HEADER } from "@posthog/shared/posthog-property-headers";import { inject, injectable } from "inversify";import type { AuthProxyService } from "../auth-proxy/auth-proxy";import { AUTH_PROXY_SERVICE } from "../auth-proxy/identifiers";@@ -134,7 +135,7 @@ export class AgentAuthAdapter {url: proxiedPosthogUrl,headers: [{- name: "x-posthog-project-id",+ name: POSTHOG_PROJECT_ID_HEADER,value: String(credentials.projectId),},{ name: "x-posthog-mcp-version", value: "2" },@@ -200,6 +201,10 @@ export class AgentAuthAdapter {}}+ gatewayProjectId(): number | null {+ return this.authService.getState().currentProjectId;+ }+async configureProcessEnv({credentials,proxyUrl,diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.tsindex 635505e97fc9..c2c14071a000 100644--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts@@ -56,6 +56,21 @@ describe("AuthProxyService", () => {expect(url).toBe("https://gateway.example/v1/messages");});+ it("forwards trusted headers instead of client-supplied values", async () => {+ authMock.authenticatedFetch.mockResolvedValue(new Response("ok"));++ const proxyUrl = await service.start("https://gateway.example", {+ "X-PostHog-Project-Id": "1",+ });+ await fetch(`${proxyUrl}/v1/messages`, {+ headers: { "X-PostHog-Project-Id": "999" },+ });++ const [, options] = authMock.authenticatedFetch.mock.calls[0];+ const headers = new Headers(options.headers);+ expect(headers.get("X-PostHog-Project-Id")).toBe("1");+ });+it("rejects requests that do not include the generated access token", async () => {const proxyUrl = await service.start("https://gateway.example");const proxyOrigin = new URL(proxyUrl).origin;diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.tsindex 06a6ee740cb6..0de28ca01f32 100644--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts@@ -19,8 +19,11 @@ export class AuthProxyService {private server: http.Server | null = null;private port: number | null = null;private listenPromise: Promise<void> | null = null;- private readonly gatewayUrlByToken = new Map<string, string>();- private readonly tokenByGatewayUrl = new Map<string, string>();+ private readonly targetByToken = new Map<+ string,+ { gatewayUrl: string; headers: Record<string, string> }+ >();+ private readonly tokenByTarget = new Map<string, string>();private readonly log: ScopedLogger;constructor(@@ -32,12 +35,21 @@ export class AuthProxyService {this.log = rootLogger.scope("auth-proxy");}- async start(gatewayUrl: string): Promise<string> {- let token = this.tokenByGatewayUrl.get(gatewayUrl);+ async start(+ gatewayUrl: string,+ headers: Record<string, string> = {},+ ): Promise<string> {+ const targetKey = JSON.stringify([+ gatewayUrl,+ Object.entries(headers).sort(([left], [right]) =>+ left.localeCompare(right),+ ),+ ]);+ let token = this.tokenByTarget.get(targetKey);if (!token) {token = randomBytes(32).toString("base64url");- this.tokenByGatewayUrl.set(gatewayUrl, token);- this.gatewayUrlByToken.set(token, gatewayUrl);+ this.tokenByTarget.set(targetKey, token);+ this.targetByToken.set(token, { gatewayUrl, headers: { ...headers } });}await this.ensureListening();@@ -95,8 +107,8 @@ export class AuthProxyService {this.server = null;this.port = null;this.listenPromise = null;- this.gatewayUrlByToken.clear();- this.tokenByGatewayUrl.clear();+ this.targetByToken.clear();+ this.tokenByTarget.clear();resolve();});});@@ -109,14 +121,16 @@ export class AuthProxyService {const incomingUrl = new URL(req.url ?? "/", "http://127.0.0.1");const match = incomingUrl.pathname.match(/^\/([^/]+)(\/.*)?$/);const token = match?.[1];- const gatewayUrl = token ? this.gatewayUrlByToken.get(token) : undefined;- if (!gatewayUrl) {+ const target = token ? this.targetByToken.get(token) : undefined;+ if (!target) {res.writeHead(401);res.end("Unauthorized");return;}- const base = gatewayUrl.endsWith("/") ? gatewayUrl : `${gatewayUrl}/`;+ const base = target.gatewayUrl.endsWith("/")+ ? target.gatewayUrl+ : `${target.gatewayUrl}/`;const targetPath = `${match?.[2] ?? "/"}${incomingUrl.search}`;const targetUrl = new URL(targetPath.replace(/^\//, ""), base);@@ -172,6 +186,14 @@ export class AuthProxyService {headers[key] = value;}}+ const trustedHeaderNames = new Set(+ Object.keys(target.headers).map((key) => key.toLowerCase()),+ );+ for (const key of Object.keys(headers)) {+ if (trustedHeaderNames.has(key.toLowerCase())) {+ delete headers[key];+ }+ }// The client connection governs the request lifetime. An explicit signal// also opts out of authenticatedFetch's default timeout, which would// abort streaming LLM responses that outlive it.@@ -184,7 +206,7 @@ export class AuthProxyService {const fetchOptions: RequestInit = {method: req.method ?? "GET",- headers,+ headers: { ...headers, ...target.headers },signal: abort.signal,};diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex 94c9bb291be0..b754f046fa82 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -35,14 +35,14 @@ Existing Django callers should use `build_openai_client`, `build_async_openai_cl### ⛔ Stay on the Python gateway for now-| Use case | Blocking contract |-| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| PostHog Desktop, PostHog Code, cloud agents, onboarding, Wizard, and similar first-party products | Trusted product identity, OAuth application allowlists, OAuth user attribution, server-minted credential requirements, per-product model policy, and product billing or unbilled policy are not available together in Go. An `ai_product` event property is not an authorization or billing boundary. |-| Product or user budget enforcement | Python supports product and user cost limits, plan checks, quota buckets, and requests that debit no wallet. Go currently admits against the credential owner's team wallet and does not branch settlement on credential billing mode. |-| OpenRouter, Fireworks, Cloudflare Workers AI, or Baseten | These provider paths are not available in Go. |-| OpenAI audio transcription | Go has no transcription endpoint. |-| OpenAI models through Anthropic Messages | Go does not provide this reverse translation. |-| Python product usage status | The Python product usage and quota API is different from Go request usage and wallet APIs. |+| Use case | Blocking contract |+| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| PostHog Desktop, PostHog Code, cloud agents, onboarding, Wizard, and similar first-party products | Trusted product identity, OAuth application allowlists, OAuth user attribution, server-minted credential requirements, per-product model policy, and product billing or unbilled policy are not available together in Go. Desktop also requires a request-selected project validated against OAuth scope, live organization membership, and project-level access control. An `ai_product` event property is not an authorization or billing boundary. |+| Product or user budget enforcement | Python supports product and user cost limits, plan checks, quota buckets, and requests that debit no wallet. Go currently admits against the credential owner's team wallet and does not branch settlement on credential billing mode. |+| OpenRouter, Fireworks, Cloudflare Workers AI, or Baseten | These provider paths are not available in Go. |+| OpenAI audio transcription | Go has no transcription endpoint. |+| OpenAI models through Anthropic Messages | Go does not provide this reverse translation. |+| Python product usage status | The Python product usage and quota API is different from Go request usage and wallet APIs. |### 🔎 Verify before switching@@ -59,19 +59,19 @@ These are compatibility checks, not automatic blockers:## Parity map-| Contract | Go gateway today | Python-only behavior that can block migration |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, and product-specific API key or OAuth application rules. |-| Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, and model policy. |-| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, body-derived OpenAI or Anthropic end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |-| Billing and limits | Wallet reservation and settlement, idempotency, balance read, request usage read, and front-line rate limiting. | Product and user cost windows, plans, quota buckets, free tiers, unbilled products, and product usage status. |-| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |-| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |-| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and selected Modal models. | OpenRouter, Fireworks, Cloudflare Workers AI, and Baseten. |-| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, and router categories. | Broader LiteLLM model acceptance and Python product allowlists. |-| Routing and failure behavior | Health-based host choice, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |-| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |-| Session attribution | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |+| Contract | Go gateway today | Python-only behavior that can block migration |+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves a fixed team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |+| Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, and model policy. |+| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, body-derived OpenAI or Anthropic end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |+| Billing and limits | Wallet reservation and settlement, idempotency, balance read, request usage read, and front-line rate limiting. | Product and user cost windows, plans, quota buckets, free tiers, unbilled products, and product usage status. |+| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |+| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |+| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and selected Modal models. | OpenRouter, Fireworks, Cloudflare Workers AI, and Baseten. |+| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, and router categories. | Broader LiteLLM model acceptance and Python product allowlists. |+| Routing and failure behavior | Health-based host choice, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |+| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |+| Session attribution | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |## Migration checklist@@ -87,10 +87,10 @@ Run `/migrating-llm-gateway-callers` to inventory and convert a caller.Run `/auditing-llm-gateway-parity` after either gateway changes auth, attribution, billing, endpoints, providers, models, routing, or event metadata. The skill audits implementation sources in both repositories and updates this file without migrating callers.-Last verified on 2026-08-06 against:+Last verified on 2026-08-10 against:-- `PostHog/posthog` master at `64bcdbd983585d754d6a8e5c975f0a0122eb6510`-- `PostHog/ai-gateway` main at `e2e28a738e701d107e57d12c6ed244a50af2b2ac`+- `PostHog/posthog` master at `5b663afc7882e4e13de4cbe8aad921d09b1e8c04`+- `PostHog/ai-gateway` main at `de0094020b615f5afc207a71e1c54d3e1df95374`## Referencesdiff --git a/services/llm-gateway/src/llm_gateway/api/models.py b/services/llm-gateway/src/llm_gateway/api/models.pyindex 286b98cf7ad7..76798e17a87d 100644--- a/services/llm-gateway/src/llm_gateway/api/models.py+++ b/services/llm-gateway/src/llm_gateway/api/models.py@@ -1,10 +1,11 @@from typing import Literalimport structlog-from fastapi import APIRouter, Request+from fastapi import APIRouter, HTTPException, Request, statusfrom pydantic import BaseModel-from llm_gateway.auth.service import get_auth_service+from llm_gateway.auth.models import AuthenticatedUser+from llm_gateway.auth.service import InvalidProjectScopeError, UnauthorizedProjectScopeError, get_auth_servicefrom llm_gateway.config import get_settingsfrom llm_gateway.products.config import (FREE_TIER_RESTRICTION_REASON,@@ -80,29 +81,46 @@ def _build_response(product: str) -> ModelsResponse:return ModelsResponse(data=model_objects, models=model_objects)-async def _caller_confirmed_free_tier(request: Request) -> bool:+async def _authenticated_caller(request: Request) -> AuthenticatedUser | None:+ """Resolve the caller when credentials are present, translating+ project-scope errors into responses. Runs on every product listing,+ independent of the model gate: a caller that selected a project it cannot+ use must get an error, never a list it could read as valid for that+ project. Anonymous callers and auth failures resolve to None."""+ try:+ return await get_auth_service().authenticate_request(request, request.app.state.db_pool)+ except InvalidProjectScopeError as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid project scope") from exc+ except UnauthorizedProjectScopeError as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Project access denied") from exc+ except Exception:+ logger.warning("models_caller_resolution_failed", exc_info=True)+ return None+++async def _caller_confirmed_free_tier(request: Request, user: AuthenticatedUser | None) -> bool:"""Caller is authenticated, non-staff, and their org isn't billed for Codeusage. Unidentifiable callers (anonymous, auth failure) are never marked;quota-fetch failures read the same last-known billing bit as enforcement,so marks match what requests would do. Enforcement stays the gate."""+ if user is None:+ return False+ if is_usage_unlimited(user):+ return False+ if user.team_id is None:+ # no team to bill: enforcement reads this caller as unbilled too+ return Truetry:- user = await get_auth_service().authenticate_request(request, request.app.state.db_pool)- if user is None:- return False- if is_usage_unlimited(user):- return False- if user.team_id is None:- # no team to bill: enforcement reads this caller as unbilled too- return Truequota_status = await resolve_quota_status(request, user.team_id, CreditBucket.POSTHOG_CODE_CREDITS.value)- return not quota_status.code_usage_billing_activeexcept Exception:logger.warning("models_free_tier_resolution_failed", exc_info=True)return False+ return not quota_status.code_usage_billing_active@models_router.get("/v1/models")-async def list_models() -> ModelsResponse:+async def list_models(request: Request) -> ModelsResponse:+ await _authenticated_caller(request)return _build_response("llm_gateway")@@ -111,9 +129,11 @@ async def list_models_for_product(product: str, request: Request) -> ModelsResporesolved = validate_product(product)response = _build_response(product)+ user = await _authenticated_caller(request)+if resolved != "posthog_code" or not get_settings().posthog_code_model_gate_enabled:return response- if not await _caller_confirmed_free_tier(request):+ if not await _caller_confirmed_free_tier(request, user):return responsefree_ids = set(filter_to_free_tier_models([m.id for m in response.data]))diff --git a/services/llm-gateway/src/llm_gateway/auth/authenticators.py b/services/llm-gateway/src/llm_gateway/auth/authenticators.pyindex 815879e97000..98e0b36d014b 100644--- a/services/llm-gateway/src/llm_gateway/auth/authenticators.py+++ b/services/llm-gateway/src/llm_gateway/auth/authenticators.py@@ -109,7 +109,8 @@ class OAuthAccessTokenAuthenticator(Authenticator):row = await conn.fetchrow("""SELECT oat.id, oat.user_id, oat.scope, oat.expires,- oat.application_id, u.current_team_id, u.distinct_id, u.is_staff+ oat.application_id, oat.scoped_teams, oat.scoped_organizations,+ u.current_team_id, u.distinct_id, u.is_staffFROM posthog_oauthaccesstoken oatJOIN posthog_user u ON oat.user_id = u.idWHERE oat.token_checksum = $1 AND u.is_active = true@@ -140,4 +141,6 @@ class OAuthAccessTokenAuthenticator(Authenticator):token_expires_at=expires,application_id=str(row["application_id"]),is_staff=row["is_staff"],+ scoped_teams=row.get("scoped_teams"),+ scoped_organizations=row.get("scoped_organizations"),)diff --git a/services/llm-gateway/src/llm_gateway/auth/models.py b/services/llm-gateway/src/llm_gateway/auth/models.pyindex d83956bb1d04..a34fc477a5e7 100644--- a/services/llm-gateway/src/llm_gateway/auth/models.py+++ b/services/llm-gateway/src/llm_gateway/auth/models.py@@ -12,6 +12,8 @@ class AuthenticatedUser:token_expires_at: datetime | None = Noneapplication_id: str | None = Noneis_staff: bool = False+ scoped_teams: list[int] | None = None+ scoped_organizations: list[str] | None = Nonedef resolve_distinct_id(auth_user: AuthenticatedUser, end_user_id: str | None) -> str:diff --git a/services/llm-gateway/src/llm_gateway/auth/service.py b/services/llm-gateway/src/llm_gateway/auth/service.pyindex 9c2441245618..a876a9beadd0 100644--- a/services/llm-gateway/src/llm_gateway/auth/service.py+++ b/services/llm-gateway/src/llm_gateway/auth/service.py@@ -1,4 +1,6 @@+import jsonimport re+from dataclasses import replacefrom functools import lru_cacheimport asyncpg@@ -7,9 +9,44 @@ from fastapi import Requestfrom llm_gateway.auth.authenticators import Authenticator, OAuthAccessTokenAuthenticator, PersonalApiKeyAuthenticatorfrom llm_gateway.auth.cache import AuthCache, get_auth_cachefrom llm_gateway.auth.models import AuthenticatedUser+from llm_gateway.config import get_settings+from llm_gateway.db.postgres import acquire_connectionfrom llm_gateway.metrics.prometheus import AUTH_CACHE_HITS, AUTH_CACHE_MISSES, AUTH_INVALIDBEARER_PATTERN = re.compile(r"^Bearer\s+(\S+)$", re.IGNORECASE)+PROJECT_SCOPE_HEADER = "x-posthog-project-id"+MAX_PROJECT_ID = 2_147_483_647+# Denials expire fast so access granted moments after a failed attempt becomes+# usable within a minute, while the short window still absorbs repeated denied+# requests. Allows keep the full OAuth auth TTL.+PROJECT_SCOPE_DENIAL_TTL_SECONDS = 60+ORG_ADMIN_MEMBERSHIP_LEVEL = 8 # OrganizationMembership.Level.ADMIN+_PROJECT_ACCESS_LEVEL_RANK = {"none": 0, "member": 1, "admin": 2}+++def _feature_keys(raw: object) -> set[str]:+ """Feature keys from posthog_organization.available_product_features —+ a jsonb[] column, so asyncpg yields each element as a JSON string."""+ if not isinstance(raw, list | tuple):+ return set()+ keys: set[str] = set()+ for item in raw:+ if isinstance(item, str):+ try:+ item = json.loads(item)+ except ValueError:+ continue+ if isinstance(item, dict) and isinstance(item.get("key"), str):+ keys.add(item["key"])+ return keys+++class InvalidProjectScopeError(Exception):+ pass+++class UnauthorizedProjectScopeError(Exception):+ passdef extract_token(request: Request) -> str | None:@@ -83,7 +120,142 @@ class AuthService:token = extract_token(request)if not token:return None- return await self.authenticate(token, pool)+ user = await self.authenticate(token, pool)+ if user is None or user.auth_method != "oauth_access_token":+ return user++ raw_project_id = request.headers.get(PROJECT_SCOPE_HEADER)+ if raw_project_id is None:+ return user+ try:+ project_id = int(raw_project_id)+ except ValueError as exc:+ raise InvalidProjectScopeError from exc+ if project_id <= 0 or project_id > MAX_PROJECT_ID:+ raise InvalidProjectScopeError++ return await self._resolve_project_scope(user, project_id, token, pool)++ async def _resolve_project_scope(+ self, user: AuthenticatedUser, project_id: int, token: str, pool: asyncpg.Pool+ ) -> AuthenticatedUser:+ """Rebind the user to the selected project when the token's scope+ ceilings, live org membership, and project-level access control allow it.++ Only the allow/deny decision is cached per token-and-project (allows for+ the OAuth auth TTL, denials for PROJECT_SCOPE_DENIAL_TTL_SECONDS so newly+ granted access becomes usable within a minute); the returned user is+ rebuilt from this request's authentication, never the cached snapshot.+ """+ token_hash = next(auth.hash_token(token) for auth in self._authenticators if auth.matches(token))+ cache_key = f"{token_hash}:project:{project_id}"++ hit, cached = self._cache.get(cache_key)+ if hit:+ AUTH_CACHE_HITS.labels(auth_type="oauth_project_scope").inc()+ if cached is None:+ raise UnauthorizedProjectScopeError+ return replace(user, team_id=project_id)+ AUTH_CACHE_MISSES.labels(auth_type="oauth_project_scope").inc()++ if not await self._project_scope_allowed(user, project_id, pool):+ self._cache.set(cache_key, None, ttl=PROJECT_SCOPE_DENIAL_TTL_SECONDS)+ raise UnauthorizedProjectScopeError++ # Stored as a user object so token expiry evicts the entry; reads above+ # use it only as the allow marker.+ self._cache.set(cache_key, replace(user, team_id=project_id), ttl=get_settings().auth_cache_ttl_oauth)+ return replace(user, team_id=project_id)++ async def _project_scope_allowed(self, user: AuthenticatedUser, project_id: int, pool: asyncpg.Pool) -> bool:+ """Mirror of the Django checks a project-nested request passes.++ Scope ceilings follow APIScopePermission.check_team_and_org_permissions:+ scoped_teams and scoped_organizations are independent ceilings, each+ enforced whenever non-empty. Project access follows+ UserAccessControl.get_user_access_level for resource="project": org+ admins bypass, rows apply only when the organization has the+ access_control feature, and no rows means the open project default.+ Rows resolve most-specific-first (_object_access_level_from_rows):+ explicit member and role rows for this user take the highest level+ among themselves and the default row is consulted only when no+ explicit row names the user. Role rows count only when the+ organization also has the role_based_access feature and the user+ holds the role in the project's organization+ (UserAccessControl._user_role_ids).+ """+ async with acquire_connection(pool) as conn:+ project = await conn.fetchrow(+ """+ SELECT t.organization_id, om.id AS membership_id, om.level AS membership_level,+ o.available_product_features+ FROM posthog_team t+ JOIN posthog_organizationmembership om ON om.organization_id = t.organization_id+ JOIN posthog_organization o ON o.id = t.organization_id+ WHERE t.id = $1 AND om.user_id = $2+ """,+ project_id,+ user.user_id,+ )+ if project is None:+ return False++ scoped_teams = user.scoped_teams or []+ scoped_organizations = user.scoped_organizations or []+ if scoped_teams and project_id not in scoped_teams:+ return False+ if scoped_organizations and str(project["organization_id"]) not in scoped_organizations:+ return False++ if project["membership_level"] >= ORG_ADMIN_MEMBERSHIP_LEVEL:+ return True+ features = _feature_keys(project["available_product_features"])+ if "access_control" not in features:+ return True++ rows = await conn.fetch(+ """+ SELECT access_level, organization_member_id, role_id+ FROM ee_accesscontrol+ WHERE team_id = $1 AND resource = 'project' AND resource_id = $2+ """,+ project_id,+ str(project_id),+ )+ if not rows:+ return True++ default_levels: list[str] = []+ explicit_levels: list[str] = []+ role_grants: dict[str, str] = {}+ for row in rows:+ if row["organization_member_id"] is None and row["role_id"] is None:+ default_levels.append(row["access_level"])+ elif row["organization_member_id"] is not None:+ if str(row["organization_member_id"]) == str(project["membership_id"]):+ explicit_levels.append(row["access_level"])+ elif row["role_id"] is not None:+ role_grants[str(row["role_id"])] = row["access_level"]++ if role_grants and "role_based_access" in features:+ user_roles = await conn.fetch(+ """+ SELECT rm.role_id+ FROM ee_rolemembership rm+ JOIN ee_role r ON r.id = rm.role_id+ WHERE rm.user_id = $1 AND r.organization_id = $2+ """,+ user.user_id,+ project["organization_id"],+ )+ explicit_levels.extend(+ role_grants[str(row["role_id"])] for row in user_roles if str(row["role_id"]) in role_grants+ )++ levels = explicit_levels or default_levels+ if not levels:+ return True+ return any(_PROJECT_ACCESS_LEVEL_RANK.get(level, 0) > 0 for level in levels)@lru_cachediff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.pyindex 3f52b1d61cde..1ec4b555e270 100644--- a/services/llm-gateway/src/llm_gateway/dependencies.py+++ b/services/llm-gateway/src/llm_gateway/dependencies.py@@ -9,7 +9,12 @@ import structlogfrom fastapi import Depends, HTTPException, Request, statusfrom llm_gateway.auth.models import AuthenticatedUser-from llm_gateway.auth.service import AuthService, get_auth_service+from llm_gateway.auth.service import (+ AuthService,+ InvalidProjectScopeError,+ UnauthorizedProjectScopeError,+ get_auth_service,+)from llm_gateway.circuit_breaker import AnthropicCircuitBreakerfrom llm_gateway.products.config import (ALLOWED_PRODUCTS,@@ -50,7 +55,12 @@ async def get_authenticated_user(db_pool: Annotated[asyncpg.Pool, Depends(get_db_pool)],auth_service: Annotated[AuthService, Depends(get_auth_service)],) -> AuthenticatedUser:- user = await auth_service.authenticate_request(request, db_pool)+ try:+ user = await auth_service.authenticate_request(request, db_pool)+ except InvalidProjectScopeError as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid project scope") from exc+ except UnauthorizedProjectScopeError as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Project access denied") from excif not user:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required")return userdiff --git a/services/llm-gateway/tests/test_auth.py b/services/llm-gateway/tests/test_auth.pyindex c68827fe1340..a2525f2f5865 100644--- a/services/llm-gateway/tests/test_auth.py+++ b/services/llm-gateway/tests/test_auth.py@@ -1,6 +1,7 @@from collections.abc import Generator+from dataclasses import replacefrom datetime import UTC, datetime, timedelta-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi import Request@@ -10,7 +11,13 @@ from llm_gateway.auth.authenticators import (PersonalApiKeyAuthenticator,)from llm_gateway.auth.cache import AuthCache, reset_auth_cache-from llm_gateway.auth.service import AuthService, extract_token+from llm_gateway.auth.service import (+ PROJECT_SCOPE_DENIAL_TTL_SECONDS,+ AuthService,+ InvalidProjectScopeError,+ UnauthorizedProjectScopeError,+ extract_token,+)@pytest.fixture(autouse=True)@@ -82,6 +89,33 @@ class TestExtractToken:assert extract_token(request) is None+def _token_row(**overrides) -> dict:+ row = {+ "id": 1,+ "user_id": 123,+ "scope": "llm_gateway:read",+ "expires": datetime.now(UTC) + timedelta(hours=1),+ "current_team_id": 456,+ "application_id": 789,+ "distinct_id": "test-distinct-id",+ "is_staff": False,+ "scoped_teams": None,+ "scoped_organizations": None,+ }+ row.update(overrides)+ return row+++def _project_row(project_id: int, membership_level: int = 1, features: list[str] | None = None) -> dict:+ return {+ "id": project_id,+ "organization_id": "org-2",+ "membership_id": "mem-1",+ "membership_level": membership_level,+ "available_product_features": features,+ }++class TestAuthService:@pytest.mark.asyncioasync def test_missing_token_returns_none(self, auth_service: AuthService, mock_pool: MagicMock) -> None:@@ -154,6 +188,441 @@ class TestAuthService:result = await auth_service.authenticate_request(request, mock_pool)assert result is None+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "scoped_teams,scoped_organizations",+ [+ pytest.param([789], [], id="team_scope"),+ pytest.param([], ["org-2"], id="organization_scope"),+ pytest.param([], [], id="unrestricted_empty_scope"),+ pytest.param(None, None, id="unrestricted_null_scope"),+ ],+ )+ async def test_oauth_project_scope_overrides_current_team_when_authorized(+ self,+ auth_service: AuthService,+ mock_pool: MagicMock,+ scoped_teams: list[int] | None,+ scoped_organizations: list[str] | None,+ ) -> None:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": "789",+ }+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ side_effect=[+ {+ "id": 1,+ "user_id": 123,+ "scope": "llm_gateway:read",+ "expires": datetime.now(UTC) + timedelta(hours=1),+ "current_team_id": 456,+ "application_id": 789,+ "distinct_id": "test-distinct-id",+ "is_staff": False,+ "scoped_teams": scoped_teams,+ "scoped_organizations": scoped_organizations,+ },+ {+ "id": 789,+ "organization_id": "org-2",+ "membership_id": "mem-1",+ "membership_level": 1,+ "available_product_features": None,+ },+ ]+ )++ result = await auth_service.authenticate_request(request, mock_pool)++ assert result is not None+ assert result.team_id == 789++ @pytest.mark.asyncio+ async def test_oauth_project_scope_rejects_project_outside_token_scope(+ self, auth_service: AuthService, mock_pool: MagicMock+ ) -> None:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": "789",+ }+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ side_effect=[+ {+ "id": 1,+ "user_id": 123,+ "scope": "llm_gateway:read",+ "expires": datetime.now(UTC) + timedelta(hours=1),+ "current_team_id": 456,+ "application_id": 789,+ "distinct_id": "test-distinct-id",+ "is_staff": False,+ "scoped_teams": [],+ "scoped_organizations": ["org-1"],+ },+ {+ "id": 789,+ "organization_id": "org-2",+ "membership_id": "mem-1",+ "membership_level": 1,+ "available_product_features": None,+ },+ ]+ )++ with pytest.raises(UnauthorizedProjectScopeError):+ await auth_service.authenticate_request(request, mock_pool)++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "project_id",+ [+ pytest.param("not-a-project", id="not_an_integer"),+ pytest.param("2147483648", id="above_postgres_integer_range"),+ ],+ )+ async def test_oauth_project_scope_rejects_malformed_project_id(+ self, auth_service: AuthService, mock_pool: MagicMock, project_id: str+ ) -> None:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": project_id,+ }+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ return_value={+ "id": 1,+ "user_id": 123,+ "scope": "llm_gateway:read",+ "expires": datetime.now(UTC) + timedelta(hours=1),+ "current_team_id": 456,+ "application_id": 789,+ "distinct_id": "test-distinct-id",+ "is_staff": False,+ "scoped_teams": [456],+ "scoped_organizations": ["org-1"],+ }+ )++ with pytest.raises(InvalidProjectScopeError):+ await auth_service.authenticate_request(request, mock_pool)++ @pytest.mark.asyncio+ async def test_oauth_project_scope_decision_is_cached_per_project(+ self, auth_service: AuthService, mock_pool: MagicMock+ ) -> None:+ def request_for(project_id: str) -> MagicMock:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": project_id,+ }+ return request++ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ side_effect=[+ {+ "id": 1,+ "user_id": 123,+ "scope": "llm_gateway:read",+ "expires": datetime.now(UTC) + timedelta(hours=1),+ "current_team_id": 456,+ "application_id": 789,+ "distinct_id": "test-distinct-id",+ "is_staff": False,+ "scoped_teams": None,+ "scoped_organizations": None,+ },+ {+ "id": 789,+ "organization_id": "org-2",+ "membership_id": "mem-1",+ "membership_level": 1,+ "available_product_features": None,+ },+ {+ "id": 790,+ "organization_id": "org-2",+ "membership_id": "mem-1",+ "membership_level": 1,+ "available_product_features": None,+ },+ ]+ )++ first = await auth_service.authenticate_request(request_for("789"), mock_pool)+ repeat = await auth_service.authenticate_request(request_for("789"), mock_pool)+ other_project = await auth_service.authenticate_request(request_for("790"), mock_pool)++ assert first is not None and first.team_id == 789+ assert repeat is not None and repeat.team_id == 789+ assert other_project is not None and other_project.team_id == 790+ assert conn.fetchrow.await_count == 3++ @pytest.mark.asyncio+ async def test_oauth_project_scope_denial_is_cached(self, auth_service: AuthService, mock_pool: MagicMock) -> None:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": "999",+ }+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ side_effect=[+ {+ "id": 1,+ "user_id": 123,+ "scope": "llm_gateway:read",+ "expires": datetime.now(UTC) + timedelta(hours=1),+ "current_team_id": 456,+ "application_id": 789,+ "distinct_id": "test-distinct-id",+ "is_staff": False,+ "scoped_teams": None,+ "scoped_organizations": None,+ },+ None,+ {+ "id": 999,+ "organization_id": "org-2",+ "membership_id": "mem-1",+ "membership_level": 1,+ "available_product_features": None,+ },+ ]+ )++ clock = {"now": 1000.0}+ with patch("llm_gateway.auth.cache.time.monotonic", side_effect=lambda: clock["now"]):+ with pytest.raises(UnauthorizedProjectScopeError):+ await auth_service.authenticate_request(request, mock_pool)+ with pytest.raises(UnauthorizedProjectScopeError):+ await auth_service.authenticate_request(request, mock_pool)+ assert conn.fetchrow.await_count == 2++ clock["now"] += PROJECT_SCOPE_DENIAL_TTL_SECONDS + 1+ granted = await auth_service.authenticate_request(request, mock_pool)++ assert granted is not None+ assert granted.team_id == 999+ assert conn.fetchrow.await_count == 3++ @pytest.mark.asyncio+ async def test_oauth_project_scope_enforces_both_ceilings_when_both_set(+ self, auth_service: AuthService, mock_pool: MagicMock+ ) -> None:+ def request_for(project_id: str) -> MagicMock:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": project_id,+ }+ return request++ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ side_effect=[+ _token_row(scoped_teams=[789], scoped_organizations=["org-2"]),+ _project_row(790),+ _project_row(789),+ ]+ )++ with pytest.raises(UnauthorizedProjectScopeError):+ await auth_service.authenticate_request(request_for("790"), mock_pool)++ allowed = await auth_service.authenticate_request(request_for("789"), mock_pool)+ assert allowed is not None+ assert allowed.team_id == 789++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "access_rows,role_rows,features,expected_team",+ [+ pytest.param(+ [{"access_level": "none", "organization_member_id": None, "role_id": None}],+ None,+ ['{"key": "access_control"}'],+ None,+ id="restricted_default_denies",+ ),+ pytest.param(+ [+ {"access_level": "none", "organization_member_id": None, "role_id": None},+ {"access_level": "member", "organization_member_id": "mem-1", "role_id": None},+ ],+ None,+ ['{"key": "access_control"}'],+ 789,+ id="member_grant_allows",+ ),+ pytest.param(+ [+ {"access_level": "none", "organization_member_id": None, "role_id": None},+ {"access_level": "member", "organization_member_id": "mem-other", "role_id": None},+ ],+ None,+ ['{"key": "access_control"}'],+ None,+ id="other_members_grant_does_not_allow",+ ),+ pytest.param(+ [+ {"access_level": "none", "organization_member_id": None, "role_id": None},+ {"access_level": "member", "organization_member_id": None, "role_id": "role-1"},+ ],+ [{"role_id": "role-1"}],+ ['{"key": "access_control"}', '{"key": "role_based_access"}'],+ 789,+ id="role_grant_allows",+ ),+ pytest.param(+ [+ {"access_level": "none", "organization_member_id": None, "role_id": None},+ {"access_level": "member", "organization_member_id": None, "role_id": "role-1"},+ ],+ [{"role_id": "role-other"}],+ ['{"key": "access_control"}', '{"key": "role_based_access"}'],+ None,+ id="unheld_role_grant_does_not_allow",+ ),+ pytest.param(+ [+ {"access_level": "none", "organization_member_id": None, "role_id": None},+ {"access_level": "member", "organization_member_id": None, "role_id": "role-1"},+ ],+ None,+ ['{"key": "access_control"}'],+ None,+ id="role_grant_inert_without_rbac_feature",+ ),+ pytest.param(+ [+ {"access_level": "member", "organization_member_id": None, "role_id": None},+ {"access_level": "none", "organization_member_id": "mem-1", "role_id": None},+ ],+ None,+ ['{"key": "access_control"}'],+ None,+ id="explicit_member_denial_overrides_open_default",+ ),+ pytest.param(+ [{"access_level": "none", "organization_member_id": "mem-1", "role_id": None}],+ None,+ ['{"key": "access_control"}'],+ None,+ id="explicit_member_denial_without_default",+ ),+ pytest.param(+ [+ {"access_level": "none", "organization_member_id": "mem-1", "role_id": None},+ {"access_level": "member", "organization_member_id": None, "role_id": "role-1"},+ ],+ [{"role_id": "role-1"}],+ ['{"key": "access_control"}', '{"key": "role_based_access"}'],+ 789,+ id="role_grant_outranks_member_denial",+ ),+ ],+ )+ async def test_oauth_project_scope_applies_project_access_control(+ self,+ auth_service: AuthService,+ mock_pool: MagicMock,+ access_rows: list[dict],+ role_rows: list[dict] | None,+ features: list[str],+ expected_team: int | None,+ ) -> None:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": "789",+ }+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ side_effect=[+ _token_row(),+ _project_row(789, features=features),+ ]+ )+ conn.fetch = AsyncMock(side_effect=[access_rows] + ([role_rows] if role_rows is not None else []))++ if expected_team is None:+ with pytest.raises(UnauthorizedProjectScopeError):+ await auth_service.authenticate_request(request, mock_pool)+ else:+ result = await auth_service.authenticate_request(request, mock_pool)+ assert result is not None+ assert result.team_id == expected_team++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "membership_level,features",+ [+ pytest.param(8, ['{"key": "access_control"}'], id="org_admin_bypasses_rbac"),+ pytest.param(1, None, id="rbac_rows_ignored_without_entitlement"),+ ],+ )+ async def test_oauth_project_scope_skips_access_control_rows(+ self,+ auth_service: AuthService,+ mock_pool: MagicMock,+ membership_level: int,+ features: list[str] | None,+ ) -> None:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": "789",+ }+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ side_effect=[+ _token_row(),+ _project_row(789, membership_level=membership_level, features=features),+ ]+ )+ conn.fetch = AsyncMock()++ result = await auth_service.authenticate_request(request, mock_pool)++ assert result is not None+ assert result.team_id == 789+ conn.fetch.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_oauth_project_scope_cache_hit_rebinds_current_user(+ self, auth_service: AuthService, mock_pool: MagicMock+ ) -> None:+ request = MagicMock(spec=Request)+ request.headers = {+ "authorization": "Bearer pha_valid_token",+ "x-posthog-project-id": "789",+ }+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(side_effect=[_token_row(), _project_row(789)])++ first = await auth_service.authenticate_request(request, mock_pool)+ assert first is not None+ assert first.is_staff is False++ token_hash = OAuthAccessTokenAuthenticator().hash_token("pha_valid_token")+ auth_service._cache.set(token_hash, replace(first, team_id=456, is_staff=True), ttl=60)++ second = await auth_service.authenticate_request(request, mock_pool)++ assert second is not None+ assert second.is_staff is True+ assert second.team_id == 789+ assert conn.fetchrow.await_count == 2+class TestPersonalApiKeyAuthenticator:@pytest.fixture@@ -245,7 +714,10 @@ class TestPersonalApiKeyAuthenticator:],)async def test_invalid_keys_return_none(- self, authenticator: PersonalApiKeyAuthenticator, mock_pool: MagicMock, db_result: dict | None+ self,+ authenticator: PersonalApiKeyAuthenticator,+ mock_pool: MagicMock,+ db_result: dict[str, object] | None,) -> None:conn = mock_pool.acquire.return_valueconn.fetchrow = AsyncMock(return_value=db_result)diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.pyindex 1f3bdcf737e8..6f62a534a315 100644--- a/services/llm-gateway/tests/test_dependencies.py+++ b/services/llm-gateway/tests/test_dependencies.py@@ -6,10 +6,12 @@ from fastapi import HTTPException, Requestfrom starlette.datastructures import Headersfrom llm_gateway.auth.models import AuthenticatedUser+from llm_gateway.auth.service import InvalidProjectScopeError, UnauthorizedProjectScopeErrorfrom llm_gateway.dependencies import (_extract_end_user_id_from_body,enforce_product_access,enforce_throttles,+ get_authenticated_user,get_model_from_request,get_provider_from_request,get_request_json,@@ -78,6 +80,25 @@ def _make_user(auth_method: str = "personal_api_key", user_id: int = 1) -> Authe)+class TestGetAuthenticatedUser:+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "error,expected_status",+ [+ pytest.param(InvalidProjectScopeError(), 400, id="invalid_project"),+ pytest.param(UnauthorizedProjectScopeError(), 403, id="unauthorized_project"),+ ],+ )+ async def test_rejects_invalid_oauth_project_scope(self, error: Exception, expected_status: int) -> None:+ auth_service = MagicMock()+ auth_service.authenticate_request = AsyncMock(side_effect=error)++ with pytest.raises(HTTPException) as exc_info:+ await get_authenticated_user(_make_request(), MagicMock(), auth_service)++ assert exc_info.value.status_code == expected_status++class TestExtractEndUserIdFromBody:@pytest.mark.asyncioasync def test_returns_openai_user_field(self) -> None:diff --git a/services/llm-gateway/tests/test_models_api.py b/services/llm-gateway/tests/test_models_api.pyindex 8de13d7d9130..dac795458b6a 100644--- a/services/llm-gateway/tests/test_models_api.py+++ b/services/llm-gateway/tests/test_models_api.py@@ -1,8 +1,9 @@-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi.testclient import TestClient+from llm_gateway.auth.service import InvalidProjectScopeError, UnauthorizedProjectScopeErrorfrom llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostServicefrom llm_gateway.services.model_registry import ModelRegistryService@@ -279,6 +280,66 @@ class TestFreeTierModelListing:assert "claude-opus-4-5" in {m["id"] for m in models}assert all(m["allowed"] for m in models)+ @pytest.mark.parametrize("gate_flag", ["true", "false"], ids=["gate_on", "gate_off"])+ @pytest.mark.parametrize(+ "error,expected_status",+ [+ pytest.param(InvalidProjectScopeError(), 400, id="invalid_project"),+ pytest.param(UnauthorizedProjectScopeError(), 403, id="unauthorized_project"),+ ],+ )+ def test_project_scope_errors_are_returned(+ self,+ app,+ monkeypatch: pytest.MonkeyPatch,+ error: Exception,+ expected_status: int,+ gate_flag: str,+ ):+ from llm_gateway.config import get_settings++ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", gate_flag)+ get_settings.cache_clear()+ auth_service = MagicMock()+ auth_service.authenticate_request = AsyncMock(side_effect=error)++ with patch("llm_gateway.api.models.get_auth_service", return_value=auth_service), TestClient(app) as client:+ response = client.get(+ "/posthog_code/v1/models",+ headers={"Authorization": "Bearer pha_scoped_models", "X-PostHog-Project-Id": "123"},+ )++ assert response.status_code == expected_status++ def test_project_scope_errors_are_returned_on_bare_models_route(self, app):+ auth_service = MagicMock()+ auth_service.authenticate_request = AsyncMock(side_effect=UnauthorizedProjectScopeError())++ with patch("llm_gateway.api.models.get_auth_service", return_value=auth_service), TestClient(app) as client:+ response = client.get(+ "/v1/models",+ headers={"Authorization": "Bearer pha_scoped_models", "X-PostHog-Project-Id": "123"},+ )++ assert response.status_code == 403++ def test_gate_off_valid_project_scope_returns_unrestricted_list(self, app, monkeypatch: pytest.MonkeyPatch):+ from llm_gateway.config import get_settings++ monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "false")+ get_settings.cache_clear()+ auth_service = MagicMock()+ auth_service.authenticate_request = AsyncMock(return_value=MagicMock(team_id=123, is_staff=False))++ with patch("llm_gateway.api.models.get_auth_service", return_value=auth_service), TestClient(app) as client:+ response = client.get(+ "/posthog_code/v1/models",+ headers={"Authorization": "Bearer pha_scoped_models", "X-PostHog-Project-Id": "123"},+ )++ assert response.status_code == 200+ assert all(m["allowed"] for m in response.json()["data"])+def test_unbilled_org_gets_full_list_with_premium_models_marked(self, app, mock_db_pool):from unittest.mock import AsyncMock