: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
feat(settings): show AI gateway spend per project secret key (#118197)
Brandon0214d173f2f7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c9c647388a40..d645c8c05bd8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -15610,6 +15610,10 @@ snapshots:hash: v1.k794b7964.5de3e955f865fa9301e3e3e7a1cd018790e74f18b3aec241c4164549eaa2ad68.rsccvu79W2TIlGdjUPSc6M0r4sz5rF5MX7rHkJOkFA4scenes-other-settings-organization-oauth-apps--with-apps--light:hash: v1.k794b7964.b205875d375c5a66196e4ad55b794f719e0f8d98e3e5f7838da6f8e846294194.d6wj83uWgchZ8z3T8PNbeKl1NaCAhZFiVOm2hF6qKsk+ scenes-other-settings-project-gateway-key-spend--with-spend--dark:+ hash: v1.k794b7964.c80a6bb6d26aeea08ba16ade17e3338f55ced40ace8197076692b1816065d580.rfUZNNvsXcBb-qHUEkLkYqOYRnRZ-5fXDWvx7Cnmp9M+ scenes-other-settings-project-gateway-key-spend--with-spend--light:+ hash: v1.k794b7964.4b25dec6b1eccb8ed6cb9b00031606d0bdbcf06bab4ce9fa5143dc9ab37d2386.wRszJ8E6zhUO_cRvzwm8KQ1shzGv-RbPxGS_q7Bet2wscenes-other-startup-program--email-domain-blocked--dark:hash: v1.k794b7964.3415b4b283c8afd8ae270ebd5640b9b526e7c91fcf0c081176a3ffb22fbd16af.Zv8TLzbKuqfD5P1FrOelwSY5EaK409zF0IpWkHPQfZ8scenes-other-startup-program--email-domain-blocked--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 40df096e607f..e261d1c70a75 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -5193,6 +5193,11 @@ export interface ProjectSecretAPIKeyApi {readonly last_rolled_at: string | null/** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */scopes: string[]+ /**+ * Value the AI gateway stamps as $ai_credential on generations made with this key, so gateway spend can be grouped by key. Derived from the key's hash, so it changes when the key is rolled.+ * @nullable+ */+ readonly ai_credential: string | null}export interface PaginatedProjectSecretAPIKeyListApi {@@ -5219,6 +5224,11 @@ export interface PatchedProjectSecretAPIKeyApi {readonly last_rolled_at?: string | null/** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */scopes?: string[]+ /**+ * Value the AI gateway stamps as $ai_credential on generations made with this key, so gateway spend can be grouped by key. Derived from the key's hash, so it changes when the key is rolled.+ * @nullable+ */+ readonly ai_credential?: string | null}/**diff --git a/frontend/src/scenes/settings/project/GatewayKeySpend.stories.tsx b/frontend/src/scenes/settings/project/GatewayKeySpend.stories.tsxnew file mode 100644index 000000000000..9d770a8afd77--- /dev/null+++ b/frontend/src/scenes/settings/project/GatewayKeySpend.stories.tsx@@ -0,0 +1,78 @@+import { Meta, StoryObj } from '@storybook/react'++import { useStorybookMocks } from '~/mocks/browser'++import { GatewayKeySpend } from './GatewayKeySpend'++const meta: Meta = {+ title: 'Scenes-Other/Settings/Project/Gateway key spend',+ component: GatewayKeySpend,+}+export default meta++type Story = StoryObj<{}>++const createdBy = { id: 1, uuid: 'test-user', first_name: 'Test', email: '[email protected]', hedgehog_config: null }++// Every row shape: a key with spend, an idle key, an unscoped key, rolled-key spend, pre-attribution spend.+export const WithSpend: Story = {+ render: () => {+ useStorybookMocks({+ get: {+ '/api/projects/:team_id/project_secret_api_keys/': {+ count: 3,+ next: null,+ previous: null,+ results: [+ {+ id: 'agent',+ label: 'Support agent',+ value: '',+ mask_value: 'phs_...a1b2',+ created_at: '2026-09-01T10:00:00Z',+ created_by: createdBy,+ last_used_at: '2026-10-14T21:45:00Z',+ last_rolled_at: null,+ scopes: ['llm_gateway:read'],+ ai_credential: '1cf0cfd88962385d39a50f24133fd919',+ },+ {+ id: 'idle',+ label: 'Staging',+ value: '',+ mask_value: 'phs_...c3d4',+ created_at: '2026-09-20T10:00:00Z',+ created_by: createdBy,+ last_used_at: null,+ last_rolled_at: null,+ scopes: ['llm_gateway:read'],+ ai_credential: '9e6a0b3f5c2d4e1f8a7b6c5d4e3f2a1b',+ },+ {+ id: 'flags',+ label: 'Flags only',+ value: '',+ mask_value: 'phs_...e5f6',+ created_at: '2026-08-01T10:00:00Z',+ created_by: createdBy,+ last_used_at: null,+ last_rolled_at: null,+ scopes: ['feature_flag:read'],+ ai_credential: '0a1b2c3d4e5f60718293a4b5c6d7e8f9',+ },+ ],+ },+ },+ post: {+ '/api/environments/:team_id/query/HogQLQuery/': {+ results: [+ ['1cf0cfd88962385d39a50f24133fd919', 3234, 116.95],+ ['fedcba9876543210fedcba9876543210', 42, 1.5],+ [null, 11, 0.25],+ ],+ },+ },+ })+ return <GatewayKeySpend />+ },+}diff --git a/frontend/src/scenes/settings/project/GatewayKeySpend.tsx b/frontend/src/scenes/settings/project/GatewayKeySpend.tsxnew file mode 100644index 000000000000..81326104dc39--- /dev/null+++ b/frontend/src/scenes/settings/project/GatewayKeySpend.tsx@@ -0,0 +1,83 @@+import { useValues } from 'kea'++import { LemonTable } from '@posthog/lemon-ui'++import { humanFriendlyCurrency, humanFriendlyNumber } from 'lib/utils/numbers'++import { GatewayKeySpendRow, gatewayKeySpendLogic } from './gatewayKeySpendLogic'+import { GATEWAY_SPEND_WINDOW_DAYS } from './gatewayKeySpendQuery'++export function GatewayKeySpend(): JSX.Element | null {+ const { hasGatewayKeys, summary, spend, spendLoading, spendFailed } = useValues(gatewayKeySpendLogic)++ if (!hasGatewayKeys) {+ return null+ }++ const loading = spendLoading || spend === null++ return (+ <div className="mt-6">+ <h3>AI gateway spend by key</h3>+ <p className="text-secondary">+ Spend on gateway generations in the last {GATEWAY_SPEND_WINDOW_DAYS} days, grouped by the key that made+ them.+ </p>+ {spendFailed ? (+ <p className="text-danger">Couldn't load gateway spend. Reload the page to try again.</p>+ ) : (+ <LemonTable<GatewayKeySpendRow>+ dataSource={summary.rows}+ loading={loading}+ rowKey="id"+ size="small"+ columns={[+ {+ title: 'Label',+ dataIndex: 'label',+ render: (_, row) => <span className="font-semibold">{row.label}</span>,+ },+ {+ title: 'Secret key',+ dataIndex: 'maskValue',+ render: (_, row) =>+ row.maskValue ? (+ <span className="font-mono">{row.maskValue}</span>+ ) : (+ <span className="text-secondary">No preview</span>+ ),+ },+ {+ title: 'Requests',+ dataIndex: 'requests',+ render: (_, row) => humanFriendlyNumber(row.requests),+ sorter: (a, b) => a.requests - b.requests,+ },+ {+ title: 'Spend',+ dataIndex: 'costUsd',+ render: (_, row) => humanFriendlyCurrency(row.costUsd, 4),+ sorter: (a, b) => a.costUsd - b.costUsd,+ },+ ]}+ />+ )}+ {!loading && !spendFailed && (summary.unmatchedCostUsd > 0 || summary.untaggedCostUsd > 0) && (+ <p className="text-secondary text-sm mt-2 mb-0 flex flex-wrap gap-x-3">+ {summary.unmatchedCostUsd > 0 && (+ <span>+ Rolled or deleted keys:{' '}+ <span translate="no">{humanFriendlyCurrency(summary.unmatchedCostUsd, 4)}</span>+ </span>+ )}+ {summary.untaggedCostUsd > 0 && (+ <span>+ Before keys were attributed:{' '}+ <span translate="no">{humanFriendlyCurrency(summary.untaggedCostUsd, 4)}</span>+ </span>+ )}+ </p>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.test.tsx b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.test.tsxindex 382ef630e7e3..1beac1c2d923 100644--- a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.test.tsx+++ b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.test.tsx@@ -30,6 +30,7 @@ const createKeys = (count: number): ProjectSecretAPIKeyApi[] =>last_used_at: null,last_rolled_at: null,scopes: ['endpoint:read'],+ ai_credential: null,}))describe('<ProjectSecretAPIKeys />', () => {diff --git a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsxindex 6f0c7af36b0e..ea59e3917ec0 100644--- a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx+++ b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx@@ -11,6 +11,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'import type { ScopeAccessLevel } from 'lib/scopes'import { APIKeyTable } from '../shared/APIKeyTable'+import { GatewayKeySpend } from './GatewayKeySpend'import { MAX_PROJECT_API_KEYS_PER_PROJECT, projectSecretAPIKeysLogic } from './projectSecretAPIKeysLogic'function EditKeyModal(): JSX.Element {@@ -170,6 +171,8 @@ export function ProjectSecretAPIKeys(): JSX.Element {showActions={!restrictionReason}/>+ <GatewayKeySpend />+<EditKeyModal /></>)diff --git a/frontend/src/scenes/settings/project/gatewayKeySpendLogic.test.ts b/frontend/src/scenes/settings/project/gatewayKeySpendLogic.test.tsnew file mode 100644index 000000000000..ca7affb9dfb1--- /dev/null+++ b/frontend/src/scenes/settings/project/gatewayKeySpendLogic.test.ts@@ -0,0 +1,77 @@+import { expectLogic } from 'kea-test-utils'++import { ProjectSecretAPIKeyApi } from '~/generated/core/api.schemas'+import { initKeaTests } from '~/test/init'++import { GATEWAY_SCOPE, gatewayKeySpendLogic } from './gatewayKeySpendLogic'+import { fetchGatewaySpendByCredential } from './gatewayKeySpendQuery'+import { projectSecretAPIKeysLogic } from './projectSecretAPIKeysLogic'++jest.mock('./gatewayKeySpendQuery', () => ({+ ...jest.requireActual('./gatewayKeySpendQuery'),+ fetchGatewaySpendByCredential: jest.fn(),+}))++const gatewayKey = (overrides: Partial<ProjectSecretAPIKeyApi>): ProjectSecretAPIKeyApi => ({+ id: 'key',+ label: 'Key',+ value: '',+ mask_value: null,+ created_at: '2026-01-01T00:00:00Z',+ created_by: { id: 1, uuid: 'test-user', first_name: 'Test', email: '[email protected]', hedgehog_config: null },+ last_used_at: null,+ last_rolled_at: null,+ scopes: [GATEWAY_SCOPE],+ ai_credential: null,+ ...overrides,+})++describe('gatewayKeySpendLogic', () => {+ let logic: ReturnType<typeof gatewayKeySpendLogic.build>++ beforeEach(() => {+ jest.clearAllMocks()+ initKeaTests()+ logic = gatewayKeySpendLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('joins spend to keys by ai_credential and tallies spend no current key can claim', async () => {+ jest.mocked(fetchGatewaySpendByCredential).mockResolvedValue([+ { credential: 'aaa', requests: 10, costUsd: 4 },+ { credential: 'ccc', requests: 1, costUsd: 0.5 },+ { credential: 'gone', requests: 2, costUsd: 1.5 },+ { credential: null, requests: 3, costUsd: 0.25 },+ ])++ projectSecretAPIKeysLogic.actions.loadKeysSuccess([+ gatewayKey({ id: 'a', label: 'Agent', mask_value: 'phs_...aaaa', ai_credential: 'aaa' }),+ gatewayKey({ id: 'b', label: 'Idle', ai_credential: 'bbb' }),+ gatewayKey({ id: 'c', label: 'Descoped', scopes: ['feature_flag:read'], ai_credential: 'ccc' }),+ gatewayKey({ id: 'd', label: 'Flags only', scopes: ['feature_flag:read'], ai_credential: 'ddd' }),+ ])+ await expectLogic(logic).toDispatchActions(['loadSpend', 'loadSpendSuccess'])++ expect(logic.values.summary).toEqual({+ rows: [+ { id: 'a', label: 'Agent', maskValue: 'phs_...aaaa', requests: 10, costUsd: 4 },+ { id: 'c', label: 'Descoped', maskValue: null, requests: 1, costUsd: 0.5 },+ { id: 'b', label: 'Idle', maskValue: null, requests: 0, costUsd: 0 },+ ],+ unmatchedCostUsd: 1.5,+ untaggedCostUsd: 0.25,+ })+ })++ it('does not query spend for a project with no gateway key', async () => {+ projectSecretAPIKeysLogic.actions.loadKeysSuccess([gatewayKey({ scopes: ['feature_flag:read'] })])+ await expectLogic(logic).toNotHaveDispatchedActions(['loadSpend'])++ expect(fetchGatewaySpendByCredential).not.toHaveBeenCalled()+ expect(logic.values.hasGatewayKeys).toBe(false)+ })+})diff --git a/frontend/src/scenes/settings/project/gatewayKeySpendLogic.ts b/frontend/src/scenes/settings/project/gatewayKeySpendLogic.tsnew file mode 100644index 000000000000..bd4512a9629a--- /dev/null+++ b/frontend/src/scenes/settings/project/gatewayKeySpendLogic.ts@@ -0,0 +1,170 @@+import { MakeLogicType, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { ProjectSecretAPIKeyApi } from '~/generated/core/api.schemas'++import { GatewayCredentialSpend, fetchGatewaySpendByCredential } from './gatewayKeySpendQuery'+import { projectSecretAPIKeysLogic } from './projectSecretAPIKeysLogic'++export const GATEWAY_SCOPE = 'llm_gateway:read'++export interface GatewayKeySpendRow {+ id: string+ label: string+ maskValue: string | null+ requests: number+ costUsd: number+}++export interface GatewayKeySpendSummary {+ rows: GatewayKeySpendRow[]+ /** Spend whose credential matches no current key: the key was rolled or deleted since. */+ unmatchedCostUsd: number+ /** Spend from generations made before the gateway attributed keys. */+ untaggedCostUsd: number+}++// A key is listed when it can call the gateway or has spend to show, so a key that lost the scope+// still accounts for what it spent while it had it.+export function buildGatewayKeySpendSummary(+ keys: ProjectSecretAPIKeyApi[],+ spend: GatewayCredentialSpend[] | null+): GatewayKeySpendSummary {+ const byCredential = new Map<string, GatewayCredentialSpend>()+ for (const entry of spend ?? []) {+ if (entry.credential) {+ byCredential.set(entry.credential, entry)+ }+ }+ const matched = new Set<string>()+ const rows: GatewayKeySpendRow[] = []+ for (const key of keys) {+ const hit = key.ai_credential ? byCredential.get(key.ai_credential) : undefined+ if (!hit && !key.scopes.includes(GATEWAY_SCOPE)) {+ continue+ }+ if (key.ai_credential) {+ matched.add(key.ai_credential)+ }+ rows.push({+ id: key.id,+ label: key.label,+ maskValue: key.mask_value,+ requests: hit?.requests ?? 0,+ costUsd: hit?.costUsd ?? 0,+ })+ }+ rows.sort((a, b) => b.costUsd - a.costUsd)++ let unmatchedCostUsd = 0+ let untaggedCostUsd = 0+ for (const entry of spend ?? []) {+ if (!entry.credential) {+ untaggedCostUsd += entry.costUsd+ } else if (!matched.has(entry.credential)) {+ unmatchedCostUsd += entry.costUsd+ }+ }+ return { rows, unmatchedCostUsd, untaggedCostUsd }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayKeySpendLogicValues {+ keys: ProjectSecretAPIKeyApi[] // projectSecretAPIKeysLogic+ hasGatewayKeys: boolean+ spend: GatewayCredentialSpend[] | null+ spendFailed: boolean+ spendLoading: boolean+ summary: GatewayKeySpendSummary+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayKeySpendLogicActions {+ loadKeysSuccess: (+ keys: ProjectSecretAPIKeyApi[],+ payload?:+ | {+ value: true+ }+ | undefined+ ) => {+ keys: ProjectSecretAPIKeyApi[]+ payload?: {+ value: true+ }+ } // projectSecretAPIKeysLogic+ loadSpend: () => any+ loadSpendFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSpendSuccess: (+ spend: GatewayCredentialSpend[],+ payload?: any+ ) => {+ spend: GatewayCredentialSpend[]+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayKeySpendLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ hasGatewayKeys: (keys: ProjectSecretAPIKeyApi[]) => boolean+ summary: (keys: ProjectSecretAPIKeyApi[], spend: GatewayCredentialSpend[] | null) => GatewayKeySpendSummary+ }+}++export type gatewayKeySpendLogicType = MakeLogicType<+ gatewayKeySpendLogicValues,+ gatewayKeySpendLogicActions,+ Record<string, any>,+ gatewayKeySpendLogicMeta+>++export const gatewayKeySpendLogic = kea<gatewayKeySpendLogicType>([+ path(['scenes', 'settings', 'project', 'gatewayKeySpendLogic']),+ connect(() => ({+ values: [projectSecretAPIKeysLogic, ['keys']],+ actions: [projectSecretAPIKeysLogic, ['loadKeysSuccess']],+ })),+ // null until the first query answers, so the table shows skeletons rather than zeros.+ loaders(() => ({+ spend: [+ null as GatewayCredentialSpend[] | null,+ {+ loadSpend: async () => await fetchGatewaySpendByCredential(),+ },+ ],+ })),+ reducers({+ spendFailed: [false, { loadSpend: () => false, loadSpendFailure: () => true }],+ }),+ selectors({+ hasGatewayKeys: [+ (s) => [s.keys],+ (keys: ProjectSecretAPIKeyApi[]): boolean => keys.some((key) => key.scopes.includes(GATEWAY_SCOPE)),+ ],+ summary: [+ (s) => [s.keys, s.spend],+ (keys: ProjectSecretAPIKeyApi[], spend: GatewayCredentialSpend[] | null): GatewayKeySpendSummary =>+ buildGatewayKeySpendSummary(keys, spend),+ ],+ }),+ // The query runs only for a project with a gateway key, so every other settings visit skips it.+ listeners(({ actions, values }) => ({+ loadKeysSuccess: () => {+ if (values.hasGatewayKeys) {+ actions.loadSpend()+ }+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.hasGatewayKeys) {+ actions.loadSpend()+ }+ }),+])diff --git a/frontend/src/scenes/settings/project/gatewayKeySpendQuery.ts b/frontend/src/scenes/settings/project/gatewayKeySpendQuery.tsnew file mode 100644index 000000000000..48c62f87d10e--- /dev/null+++ b/frontend/src/scenes/settings/project/gatewayKeySpendQuery.ts@@ -0,0 +1,37 @@+import api from 'lib/api'++import { hogql } from '~/queries/utils'++export const GATEWAY_SPEND_WINDOW_DAYS = 30++export interface GatewayCredentialSpend {+ /** The $ai_credential the gateway stamped, or null for generations made before keys were attributed. */+ credential: string | null+ requests: number+ costUsd: number+}++// The events table is team-scoped, so the query needs no project filter.+export async function fetchGatewaySpendByCredential(): Promise<GatewayCredentialSpend[]> {+ const response = await api.queryHogQL(+ hogql`+ SELECT+ properties.$ai_credential AS credential,+ count() AS requests,+ round(sum(toFloat(properties.$ai_total_cost_usd)), 4) AS cost_usd+ FROM events+ WHERE event = '$ai_generation'+ AND properties.$ai_gateway = true+ AND timestamp >= now() - INTERVAL ${GATEWAY_SPEND_WINDOW_DAYS} DAY+ GROUP BY credential+ ORDER BY cost_usd DESC+ LIMIT 200+ `,+ { scene: 'Settings', productKey: 'ai_gateway', name: 'gateway_spend_by_key' }+ )+ return (response.results ?? []).map((row: unknown[]) => ({+ credential: row[0] ? String(row[0]) : null,+ requests: Number(row[1]) || 0,+ costUsd: Number(row[2]) || 0,+ }))+}diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.pyindex cc7af3d79af4..f4b90fda0af1 100644--- a/posthog/api/project_secret_api_key.py+++ b/posthog/api/project_secret_api_key.py@@ -6,6 +6,7 @@ from django.db.models import QuerySetfrom django.utils import timezoneimport structlog+from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import response, serializers, status, viewsetsfrom rest_framework.exceptions import PermissionDenied, ValidationErrorfrom rest_framework.request import Request@@ -18,7 +19,7 @@ from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL, wizard_identity_blockedfrom posthog.models import Organization, Userfrom posthog.models.project_secret_api_key import ProjectSecretAPIKey, RevokedTeamSecretToken-from posthog.models.utils import generate_random_token_secret, hash_key_value, mask_key_value+from posthog.models.utils import ai_credential_value, generate_random_token_secret, hash_key_value, mask_key_valuefrom posthog.permissions import (TeamMemberStrictManagementPermission,TimeSensitiveActionPermission,@@ -120,6 +121,12 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):),)created_by = UserBasicSerializer(read_only=True)+ ai_credential = serializers.SerializerMethodField(+ help_text=(+ "Value the AI gateway stamps as $ai_credential on generations made with this key, so gateway "+ "spend can be grouped by key. Derived from the key's hash, so it changes when the key is rolled."+ ),+ )class Meta:model = ProjectSecretAPIKey@@ -133,6 +140,7 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):"last_used_at","last_rolled_at","scopes",+ "ai_credential",]read_only_fields = ["id",@@ -146,6 +154,10 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):def get_key_value(self, obj: ProjectSecretAPIKey) -> str:return getattr(obj, "_value", None) # type: ignore+ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_ai_credential(self, obj: ProjectSecretAPIKey) -> str | None:+ return ai_credential_value(obj.secure_value) if obj.secure_value else None+def validate_scopes(self, scopes):allowed = set(PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)# Staff grant llm_gateway:read; a key that already holds it stays saveable by any admin.diff --git a/posthog/api/test/test_project_secret_api_keys.py b/posthog/api/test/test_project_secret_api_keys.pyindex 004ec70b5567..6eed493a8c59 100644--- a/posthog/api/test/test_project_secret_api_keys.py+++ b/posthog/api/test/test_project_secret_api_keys.py@@ -7,7 +7,12 @@ from posthog.api.project_secret_api_key import MAX_PROJECT_SECRET_API_KEYS_PER_Tfrom posthog.models import Organization, OrganizationMembership, Teamfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project_secret_api_key import ProjectSecretAPIKey-from posthog.models.utils import generate_random_token_personal, generate_random_token_secret, hash_key_value+from posthog.models.utils import (+ ai_credential_value,+ generate_random_token_personal,+ generate_random_token_secret,+ hash_key_value,+)class TestProjectSecretAPIKeysAPIMember(APIBaseTest):@@ -338,6 +343,8 @@ class TestProjectSecretAPIKeysAPI(APIBaseTest):key_id = data["id"]original_mask = data["mask_value"]original_secure_value = ProjectSecretAPIKey.objects.get(id=key_id).secure_value+ assert original_secure_value is not None+ assert data["ai_credential"] == ai_credential_value(original_secure_value)response = self.client.post(f"/api/projects/{self.team.id}/project_secret_api_keys/{key_id}/roll")assert response.status_code == 200@@ -350,8 +357,12 @@ class TestProjectSecretAPIKeysAPI(APIBaseTest):assert rolled["value"] is not Noneassert rolled["value"].startswith("phs_")- key = ProjectSecretAPIKey.objects.get(id=key_id)- assert key.secure_value != original_secure_value+ rolled_secure_value = ProjectSecretAPIKey.objects.get(id=key_id).secure_value+ assert rolled_secure_value is not None+ assert rolled_secure_value != original_secure_value+ # The gateway attribution follows the secret, so a rolled key reports a new value.+ assert rolled["ai_credential"] == ai_credential_value(rolled_secure_value)+ assert rolled["ai_credential"] != data["ai_credential"]def test_list_only_current_team_keys(self):self.client.post(diff --git a/posthog/models/test/test_utils.py b/posthog/models/test/test_utils.pyindex c7623eff14a4..ac8e0c2fa812 100644--- a/posthog/models/test/test_utils.py+++ b/posthog/models/test/test_utils.py@@ -10,6 +10,7 @@ from parameterized import parameterizedfrom posthog.models.utils import (AMBIGUOUS_CHARS,BASE57,+ ai_credential_value,convert_legacy_metric,convert_legacy_metrics,generate_random_oauth_access_token,@@ -18,6 +19,7 @@ from posthog.models.utils import (generate_random_token_personal,generate_random_token_project,generate_random_token_secret,+ hash_key_value,int_to_base,mask_key_value,uuid7,@@ -63,6 +65,11 @@ def test_mask_key_value():assert mask_key_value("") == "********" # Empty string+def test_ai_credential_value_matches_gateway_vector():+ # Twin of TestCredentialNodeParityVector in PostHog/ai-gateway; both derivations must agree byte for byte.+ assert ai_credential_value(hash_key_value("phs_parity_vector")) == "1cf0cfd88962385d39a50f24133fd919"++BASE57_SET = set(BASE57)diff --git a/posthog/models/utils.py b/posthog/models/utils.pyindex 3ab832c353fa..e4da20d0ae7e 100644--- a/posthog/models/utils.py+++ b/posthog/models/utils.py@@ -226,6 +226,16 @@ def hash_key_value(return f"sha256${value}" # Following format from Django's PBKDF2PasswordHasher+# Mirrors CredentialNodeValue in PostHog/ai-gateway; a change here without its twin breaks the join silently.+AI_CREDENTIAL_HEX_LENGTH = 32+++def ai_credential_value(secure_value: str) -> str:+ """The value the AI gateway stamps as $ai_credential on a key's generations: sha256 over the+ stored sha256$<hex> hash (the gateway's credential fingerprint), first 32 hex characters."""+ return hashlib.sha256(secure_value.encode()).hexdigest()[:AI_CREDENTIAL_HEX_LENGTH]++def int_to_base(number: int, base: int, *, alphabet: Optional[str] = None) -> str:if alphabet is None:if base > 62:diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9c21264e7765..7f2bc3952a99 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -72230,6 +72230,11 @@ export namespace Schemas {readonly last_rolled_at: string | null;/** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */scopes: string[];+ /**+ * Value the AI gateway stamps as $ai_credential on generations made with this key, so gateway spend can be grouped by key. Derived from the key's hash, so it changes when the key is rolled.+ * @nullable+ */+ readonly ai_credential: string | null;}export interface PaginatedProjectSecretAPIKeyList {@@ -84375,6 +84380,11 @@ export namespace Schemas {readonly last_rolled_at?: string | null;/** Project-wide API scopes granted to this key. Project secret API keys do not honor object-level access controls, so a scope can access resources of that type even when per-resource RBAC would hide them from an individual user. */scopes?: string[];+ /**+ * Value the AI gateway stamps as $ai_credential on generations made with this key, so gateway spend can be grouped by key. Derived from the key's hash, so it changes when the key is rolled.+ * @nullable+ */+ readonly ai_credential?: string | null;}export interface PatchedProxyRecordUpdate {