: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(oauth): bind CIMD verification tokens to their metadata URL (#74913)
Matt Brooker12d94ca24e49
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b13891e27cbe..b75ee5a02f8f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7150,6 +7150,10 @@ snapshots:hash: v1.k794b7964.b2709895d612381724c2275aeaa291853ad3460c7a70f82f44f9b68b53d48da7.Jz5OoUecWaosBkoyKe1t79ypi05lM4inlLcCVqXXESoscenes-app-settings-organization--settings-organization-billing--light:hash: v1.k794b7964.d4b5e0030757796876fa680f389ca76201f098f3b1b65eb303ca73b5e1be6ae4.bisG2Rrhp6kgmqbOtUQGs_484Kn8TkyRsaRSBlNVVl4+ scenes-app-settings-organization--settings-organization-cimd-verification-tokens--dark:+ hash: v1.k794b7964.a0efb34409ff03a8a94d527a39101882a124357800b9ebce870c124ba665b643.H5ZBcbmWeVY9BgSRWeSYkjfOCmCRmGGsipKPFigGqUA+ scenes-app-settings-organization--settings-organization-cimd-verification-tokens--light:+ hash: v1.k794b7964.a170546647ece777290b1868dc4c9fb6b4c67d2f4d63c2aed321f3155220fb4b.H1Y1g89WwXye_1nxkBwTgMxkT6a0hqW7SV6cFKtFJtUscenes-app-settings-organization--settings-organization-danger-zone--dark:hash: v1.k794b7964.459d4562ee5b565df4810e3d27235dd302cf95293a62903e35bfef2ed1c21a77.9b4ajnjIa9Fmj4VPX98HECmrnRzyeHsjwUYdxIypN24scenes-app-settings-organization--settings-organization-danger-zone--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex fd7bbd767129..b4f07b0a8963 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -64,10 +64,20 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+/**+ * Read shape for list/retrieve/create-response. `cimd_url` is nullable here for+ * tokens issued before URL binding; the write serializers below require a value.+ */export interface CIMDVerificationTokenApi {readonly id: string- /** @maxLength 40 */- label: string+ /** Human-readable name to identify this token later, e.g. 'Production CIMD partner'. */+ readonly label: string+ /**+ * HTTPS URL of the CIMD metadata document this token verifies at. Null on tokens issued before URL binding; those no longer verify until bound via PATCH or reissued.+ * @maxLength 2048+ * @nullable+ */+ readonly cimd_url: string | null/** @nullable */readonly mask_value: string | nullreadonly created_by: UserBasicApi@@ -85,6 +95,23 @@ export interface PaginatedCIMDVerificationTokenListApi {results: CIMDVerificationTokenApi[]}+/**+ * Write shape for `create`. `cimd_url` is required and non-null: only tokens+ * issued before URL binding existed are nullable, not new ones.+ */+export interface CIMDVerificationTokenCreateApi {+ /**+ * Human-readable name to identify this token later, e.g. 'Production CIMD partner'.+ * @maxLength 40+ */+ label: string+ /**+ * HTTPS URL of the CIMD metadata document this token will be published in. The token only verifies at this URL, so a copy hosted anywhere else is rejected. Host case, an explicit :443 and a trailing slash are normalized away; the path is case-sensitive.+ * @maxLength 2048+ */+ cimd_url: string+}+/*** Create-response variant that includes the plaintext token.*@@ -93,8 +120,14 @@ export interface PaginatedCIMDVerificationTokenListApi {*/export interface CIMDVerificationTokenWithValueApi {readonly id: string- /** @maxLength 40 */- label: string+ /** Human-readable name to identify this token later, e.g. 'Production CIMD partner'. */+ readonly label: string+ /**+ * HTTPS URL of the CIMD metadata document this token verifies at. Null on tokens issued before URL binding; those no longer verify until bound via PATCH or reissued.+ * @maxLength 2048+ * @nullable+ */+ readonly cimd_url: string | null/** @nullable */readonly mask_value: string | nullreadonly created_by: UserBasicApi@@ -105,6 +138,19 @@ export interface CIMDVerificationTokenWithValueApi {readonly value: string}+/**+ * Write shape for `partial_update` (PATCH). Exposes only `cimd_url`, and only ever+ * performs a null -> value transition: `validate` rejects any instance whose `cimd_url`+ * is already set, so an existing binding can never be re-pointed through this endpoint.+ */+export interface PatchedCIMDVerificationTokenUpdateApi {+ /**+ * HTTPS URL of the CIMD metadata document to bind this token to. Only settable once, on a token with no existing binding; an already-bound token must be reissued instead.+ * @maxLength 2048+ */+ cimd_url?: string+}+export interface OrganizationDomainApi {readonly id: string/** @maxLength 128 */diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex ab143bed3658..52d7242cf0dd 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -12,6 +12,7 @@ import type {BulkUpdateTagsRequestApi,BulkUpdateTagsResponseApi,CIMDVerificationTokenApi,+ CIMDVerificationTokenCreateApi,CIMDVerificationTokenWithValueApi,CimdVerificationTokensListParams,DomainsListParams,@@ -49,6 +50,7 @@ import type {PaginatedProjectSecretAPIKeyListApi,PaginatedUserGitHubIntegrationListResponseListApi,PaginatedUserListApi,+ PatchedCIMDVerificationTokenUpdateApi,PatchedEnterprisePropertyDefinitionApi,PatchedFileSystemApi,PatchedFileSystemShortcutApi,@@ -126,6 +128,11 @@ export const getCimdVerificationTokensListUrl = (organizationId: string, params?* the metadata, matching the token links the partner app to this organization and* grants a higher default rate limit for account provisioning.*+ * Each token is scoped at creation to the one `cimd_url` it will be published at,+ * and verifies nowhere else. Two organizations may name the same URL; only the one+ * whose token is actually served there verifies, so claiming a URL cannot be used+ * to block a partner from verifying theirs.+ ** The plaintext value is only available on creation; we store a hash.*/export const cimdVerificationTokensList = async (@@ -152,18 +159,23 @@ export const getCimdVerificationTokensCreateUrl = (organizationId: string) => {* the metadata, matching the token links the partner app to this organization and* grants a higher default rate limit for account provisioning.*+ * Each token is scoped at creation to the one `cimd_url` it will be published at,+ * and verifies nowhere else. Two organizations may name the same URL; only the one+ * whose token is actually served there verifies, so claiming a URL cannot be used+ * to block a partner from verifying theirs.+ ** The plaintext value is only available on creation; we store a hash.*/export const cimdVerificationTokensCreate = async (organizationId: string,- cIMDVerificationTokenApi: NonReadonly<CIMDVerificationTokenApi>,+ cIMDVerificationTokenCreateApi: CIMDVerificationTokenCreateApi,options?: RequestInit): Promise<CIMDVerificationTokenWithValueApi> => {return apiMutator<CIMDVerificationTokenWithValueApi>(getCimdVerificationTokensCreateUrl(organizationId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(cIMDVerificationTokenApi),+ body: JSON.stringify(cIMDVerificationTokenCreateApi),})}@@ -180,6 +192,11 @@ export const getCimdVerificationTokensRetrieveUrl = (organizationId: string, id:* the metadata, matching the token links the partner app to this organization and* grants a higher default rate limit for account provisioning.*+ * Each token is scoped at creation to the one `cimd_url` it will be published at,+ * and verifies nowhere else. Two organizations may name the same URL; only the one+ * whose token is actually served there verifies, so claiming a URL cannot be used+ * to block a partner from verifying theirs.+ ** The plaintext value is only available on creation; we store a hash.*/export const cimdVerificationTokensRetrieve = async (@@ -193,6 +210,40 @@ export const cimdVerificationTokensRetrieve = async (})}+export const getCimdVerificationTokensPartialUpdateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/cimd_verification_tokens/${id}/`+}++/**+ * Manage CIMD verification tokens for an organization.+ *+ * A partner embeds the plaintext token in their CIMD metadata document as+ * `verification_token` inside the `com.posthog` object (the legacy top-level+ * `posthog_verification_token` field still works as a fallback). When PostHog fetches+ * the metadata, matching the token links the partner app to this organization and+ * grants a higher default rate limit for account provisioning.+ *+ * Each token is scoped at creation to the one `cimd_url` it will be published at,+ * and verifies nowhere else. Two organizations may name the same URL; only the one+ * whose token is actually served there verifies, so claiming a URL cannot be used+ * to block a partner from verifying theirs.+ *+ * The plaintext value is only available on creation; we store a hash.+ */+export const cimdVerificationTokensPartialUpdate = async (+ organizationId: string,+ id: string,+ patchedCIMDVerificationTokenUpdateApi?: PatchedCIMDVerificationTokenUpdateApi,+ options?: RequestInit+): Promise<CIMDVerificationTokenApi> => {+ return apiMutator<CIMDVerificationTokenApi>(getCimdVerificationTokensPartialUpdateUrl(organizationId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedCIMDVerificationTokenUpdateApi),+ })+}+export const getCimdVerificationTokensDestroyUrl = (organizationId: string, id: string) => {return `/api/organizations/${organizationId}/cimd_verification_tokens/${id}/`}@@ -206,6 +257,11 @@ export const getCimdVerificationTokensDestroyUrl = (organizationId: string, id:* the metadata, matching the token links the partner app to this organization and* grants a higher default rate limit for account provisioning.*+ * Each token is scoped at creation to the one `cimd_url` it will be published at,+ * and verifies nowhere else. Two organizations may name the same URL; only the one+ * whose token is actually served there verifies, so claiming a URL cannot be used+ * to block a partner from verifying theirs.+ ** The plaintext value is only available on creation; we store a hash.*/export const cimdVerificationTokensDestroy = async (diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex f0b0c993d3b5..b189c78e7752 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -18,13 +18,65 @@ import * as zod from 'zod'* the metadata, matching the token links the partner app to this organization and* grants a higher default rate limit for account provisioning.*+ * Each token is scoped at creation to the one `cimd_url` it will be published at,+ * and verifies nowhere else. Two organizations may name the same URL; only the one+ * whose token is actually served there verifies, so claiming a URL cannot be used+ * to block a partner from verifying theirs.+ ** The plaintext value is only available on creation; we store a hash.*/export const cimdVerificationTokensCreateBodyLabelMax = 40-export const CimdVerificationTokensCreateBody = /* @__PURE__ */ zod.object({- label: zod.string().max(cimdVerificationTokensCreateBodyLabelMax),-})+export const cimdVerificationTokensCreateBodyCimdUrlMax = 2048++export const CimdVerificationTokensCreateBody = /* @__PURE__ */ zod+ .object({+ label: zod+ .string()+ .max(cimdVerificationTokensCreateBodyLabelMax)+ .describe("Human-readable name to identify this token later, e.g. 'Production CIMD partner'."),+ cimd_url: zod+ .string()+ .max(cimdVerificationTokensCreateBodyCimdUrlMax)+ .describe(+ 'HTTPS URL of the CIMD metadata document this token will be published in. The token only verifies at this URL, so a copy hosted anywhere else is rejected. Host case, an explicit :443 and a trailing slash are normalized away; the path is case-sensitive.'+ ),+ })+ .describe(+ 'Write shape for `create`. `cimd_url` is required and non-null: only tokens\nissued before URL binding existed are nullable, not new ones.'+ )++/**+ * Manage CIMD verification tokens for an organization.+ *+ * A partner embeds the plaintext token in their CIMD metadata document as+ * `verification_token` inside the `com.posthog` object (the legacy top-level+ * `posthog_verification_token` field still works as a fallback). When PostHog fetches+ * the metadata, matching the token links the partner app to this organization and+ * grants a higher default rate limit for account provisioning.+ *+ * Each token is scoped at creation to the one `cimd_url` it will be published at,+ * and verifies nowhere else. Two organizations may name the same URL; only the one+ * whose token is actually served there verifies, so claiming a URL cannot be used+ * to block a partner from verifying theirs.+ *+ * The plaintext value is only available on creation; we store a hash.+ */+export const cimdVerificationTokensPartialUpdateBodyCimdUrlMax = 2048++export const CimdVerificationTokensPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ cimd_url: zod+ .string()+ .max(cimdVerificationTokensPartialUpdateBodyCimdUrlMax)+ .optional()+ .describe(+ 'HTTPS URL of the CIMD metadata document to bind this token to. Only settable once, on a token with no existing binding; an already-bound token must be reissued instead.'+ ),+ })+ .describe(+ 'Write shape for `partial_update` (PATCH). Exposes only `cimd_url`, and only ever\nperforms a null -> value transition: `validate` rejects any instance whose `cimd_url`\nis already set, so an existing binding can never be re-pointed through this endpoint.'+ )export const domainsCreateBodyDomainMax = 128diff --git a/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx b/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsxindex 00c159f51432..c129b4d62c8b 100644--- a/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx+++ b/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx@@ -1,20 +1,42 @@import { useActions, useValues } from 'kea'-import { IconTrash } from '@posthog/icons'-import { LemonButton, LemonDialog, LemonInput, LemonModal, LemonTable, Link } from '@posthog/lemon-ui'+import { IconPencil, IconTrash } from '@posthog/icons'+import { LemonButton, LemonDialog, LemonInput, LemonModal, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { IconKey } from 'lib/lemon-ui/icons'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'-import { cimdVerificationTokensLogic, CIMDVerificationToken } from './cimdVerificationTokensLogic'+import { cimdVerificationTokensLogic, validateCimdUrl, CIMDVerificationToken } from './cimdVerificationTokensLogic'export function CIMDVerificationTokens(): JSX.Element {- const { tokens, tokensLoading, isCreateDialogOpen, newTokenLabel, justCreatedToken } =- useValues(cimdVerificationTokensLogic)- const { showCreateDialog, hideCreateDialog, setNewTokenLabel, createToken, deleteToken, setJustCreatedToken } =- useActions(cimdVerificationTokensLogic)+ const {+ tokens,+ tokensLoading,+ isCreateDialogOpen,+ isCreatingToken,+ newTokenLabel,+ newTokenUrl,+ justCreatedToken,+ bindingToken,+ bindUrl,+ isBindingToken,+ } = useValues(cimdVerificationTokensLogic)+ const {+ showCreateDialog,+ hideCreateDialog,+ setNewTokenLabel,+ setNewTokenUrl,+ createToken,+ deleteToken,+ setJustCreatedToken,+ showBindDialog,+ hideBindDialog,+ setBindUrl,+ bindToken,+ } = useActions(cimdVerificationTokensLogic)+ const hasUnboundToken = tokens.some((token) => !token.cimd_url)return (<div className="space-y-4">@@ -22,7 +44,7 @@ export function CIMDVerificationTokens(): JSX.Element {Verification tokens link a CIMD partner application to this organization. Add the token to your CIMDmetadata document as <code>verification_token</code> inside the <code>com.posthog</code> object.Verified partners get a higher default rate limit for account provisioning and a clear identity trail.- See the{' '}+ Each token verifies only at the metadata URL you name when creating it. See the{' '}<Linkto="https://posthog.com/docs/integrate/provisioning#host-a-cimd-metadata-document"target="_blank"@@ -38,6 +60,13 @@ export function CIMDVerificationTokens(): JSX.Element {</LemonButton></div>+ {hasUnboundToken && (+ <LemonBanner type="warning">+ Some tokens were issued before URL binding and have stopped verifying. Set a metadata URL on each+ one below to restore verification.+ </LemonBanner>+ )}+{!tokensLoading && tokens.length === 0 ? (<div className="border border-dashed rounded-lg p-8 text-center"><IconKey className="text-4xl text-secondary mx-auto mb-3" />@@ -56,6 +85,16 @@ export function CIMDVerificationTokens(): JSX.Element {<span className="font-semibold">{row.label}</span>),},+ {+ title: 'Metadata URL',+ key: 'cimd_url',+ render: (_, row: CIMDVerificationToken) =>+ row.cimd_url ? (+ <span className="text-xs font-mono break-all">{row.cimd_url}</span>+ ) : (+ <LemonTag type="warning">Not verifying</LemonTag>+ ),+ },{title: 'Token',key: 'mask_value',@@ -86,25 +125,35 @@ export function CIMDVerificationTokens(): JSX.Element {key: 'actions',width: 0,render: (_, row: CIMDVerificationToken) => (- <LemonButton- icon={<IconTrash />}- size="small"- status="danger"- tooltip="Revoke token"- onClick={() =>- LemonDialog.open({- title: `Revoke token "${row.label}"?`,- description:- 'Partners using this token in their CIMD metadata will no longer be recognized and will fall back to the anonymous rate limit tier.',- primaryButton: {- children: 'Revoke',- status: 'danger',- onClick: () => deleteToken(row),- },- secondaryButton: { children: 'Cancel' },- })- }- />+ <div className="flex gap-1">+ {!row.cimd_url && (+ <LemonButton+ icon={<IconPencil />}+ size="small"+ tooltip="Set metadata URL"+ onClick={() => showBindDialog(row)}+ />+ )}+ <LemonButton+ icon={<IconTrash />}+ size="small"+ status="danger"+ tooltip="Revoke token"+ onClick={() =>+ LemonDialog.open({+ title: `Revoke token "${row.label}"?`,+ description:+ 'Partners using this token in their CIMD metadata will no longer be recognized and will fall back to the anonymous rate limit tier.',+ primaryButton: {+ children: 'Revoke',+ status: 'danger',+ onClick: () => deleteToken(row),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ />+ </div>),},]}@@ -123,7 +172,12 @@ export function CIMDVerificationTokens(): JSX.Element {<LemonButtontype="primary"onClick={() => createToken()}- disabledReason={!newTokenLabel.trim() ? 'Please enter a label' : undefined}+ loading={isCreatingToken}+ disabledReason={+ !newTokenLabel.trim()+ ? 'Please enter a label'+ : (validateCimdUrl(newTokenUrl.trim()) ?? undefined)+ }data-attr="confirm-create-cimd-verification-token">Create token@@ -145,6 +199,20 @@ export function CIMDVerificationTokens(): JSX.Element {<p className="text-secondary text-xs">Pick a label that helps you identify this token later. You'll only see the plaintext value once.</p>++ <label className="text-sm font-semibold pt-2 block" htmlFor="cimd-token-url">+ CIMD metadata URL+ </label>+ <LemonInput+ id="cimd-token-url"+ placeholder="https://example.com/.well-known/oauth-client-metadata.json"+ value={newTokenUrl}+ onChange={setNewTokenUrl}+ />+ <p className="text-secondary text-xs">+ The token only verifies at this URL, so a copy published anywhere else is ignored. Must be HTTPS+ and include a path, and the path is case-sensitive.+ </p></div></LemonModal>@@ -173,6 +241,51 @@ export function CIMDVerificationTokens(): JSX.Element {</div>)}</LemonModal>++ <LemonModal+ isOpen={!!bindingToken}+ onClose={hideBindDialog}+ title="Set metadata URL"+ footer={+ <>+ <LemonButton type="secondary" onClick={hideBindDialog}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={() => bindToken()}+ loading={isBindingToken}+ disabledReason={validateCimdUrl(bindUrl.trim()) ?? undefined}+ data-attr="confirm-bind-cimd-verification-token"+ >+ Set URL+ </LemonButton>+ </>+ }+ >+ {bindingToken && (+ <div className="space-y-2">+ <p className="text-secondary text-sm">+ "{bindingToken.label}" was issued before URL binding and has stopped verifying. Set the+ metadata URL it should verify at to restore verification.+ </p>+ <label className="text-sm font-semibold" htmlFor="cimd-token-bind-url">+ CIMD metadata URL+ </label>+ <LemonInput+ id="cimd-token-bind-url"+ placeholder="https://example.com/.well-known/oauth-client-metadata.json"+ value={bindUrl}+ onChange={setBindUrl}+ autoFocus+ />+ <p className="text-secondary text-xs">+ The token only verifies at this URL, so a copy published anywhere else is ignored. Must be+ HTTPS and include a path, and the path is case-sensitive.+ </p>+ </div>+ )}+ </LemonModal></div>)}diff --git a/frontend/src/scenes/settings/organization/cimdVerificationTokensLogic.ts b/frontend/src/scenes/settings/organization/cimdVerificationTokensLogic.tsindex ce3aa9d0d173..b99dba5d8bb8 100644--- a/frontend/src/scenes/settings/organization/cimdVerificationTokensLogic.ts+++ b/frontend/src/scenes/settings/organization/cimdVerificationTokensLogic.ts@@ -8,29 +8,69 @@ import {cimdVerificationTokensCreate,cimdVerificationTokensDestroy,cimdVerificationTokensList,+ cimdVerificationTokensPartialUpdate,} from '~/generated/core/api'import { CIMDVerificationTokenApi, CIMDVerificationTokenWithValueApi } from '~/generated/core/api.schemas'export type CIMDVerificationToken = CIMDVerificationTokenApiexport type CIMDVerificationTokenWithValue = CIMDVerificationTokenWithValueApi+/**+ * Cheap client-side check for the two most common mistakes (missing HTTPS, missing path)+ * so the user doesn't need a round trip to find out. The server is still the source of+ * truth for every other rejection reason (query string, port, etc).+ */+export function validateCimdUrl(url: string): string | null {+ if (!url) {+ return 'Please enter your CIMD metadata URL'+ }+ if (!url.startsWith('https://')) {+ return 'The metadata URL must start with https://'+ }+ let parsed: URL+ try {+ parsed = new URL(url)+ } catch {+ return 'Please enter a valid URL'+ }+ if (parsed.pathname === '/' || parsed.pathname === '') {+ return 'The metadata URL must include a path, e.g. /.well-known/oauth-client-metadata.json'+ }+ return null+}++function extractServerError(e: any, fallback: string): string {+ return e?.detail ?? e?.cimd_url?.[0] ?? e?.label?.[0] ?? fallback+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface cimdVerificationTokensLogicValues {+ bindUrl: string+ bindingToken: CIMDVerificationToken | null+ isBindingToken: booleanisCreateDialogOpen: boolean+ isCreatingToken: booleanjustCreatedToken: CIMDVerificationTokenWithValue | nullnewTokenLabel: string+ newTokenUrl: stringtokens: CIMDVerificationToken[]tokensLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface cimdVerificationTokensLogicActions {+ bindToken: () => {+ value: true+ }createToken: () => {value: true}deleteToken: (token: CIMDVerificationToken) => {token: CIMDVerificationTokenApi}+ hideBindDialog: () => {+ value: true+ }hideCreateDialog: () => {value: true}@@ -49,12 +89,27 @@ export interface cimdVerificationTokensLogicActions {tokens: CIMDVerificationTokenApi[]payload?: any}+ setBindUrl: (url: string) => {+ url: string+ }+ setIsBindingToken: (binding: boolean) => {+ binding: boolean+ }+ setIsCreatingToken: (creating: boolean) => {+ creating: boolean+ }setJustCreatedToken: (token: CIMDVerificationTokenWithValue | null) => {token: CIMDVerificationTokenWithValueApi | null}setNewTokenLabel: (label: string) => {label: string}+ setNewTokenUrl: (url: string) => {+ url: string+ }+ showBindDialog: (token: CIMDVerificationToken) => {+ token: CIMDVerificationTokenApi+ }showCreateDialog: () => {value: true}@@ -72,9 +127,16 @@ export const cimdVerificationTokensLogic = kea<cimdVerificationTokensLogicType>(showCreateDialog: true,hideCreateDialog: true,setNewTokenLabel: (label: string) => ({ label }),+ setNewTokenUrl: (url: string) => ({ url }),+ setIsCreatingToken: (creating: boolean) => ({ creating }),setJustCreatedToken: (token: CIMDVerificationTokenWithValue | null) => ({ token }),createToken: true,deleteToken: (token: CIMDVerificationToken) => ({ token }),+ showBindDialog: (token: CIMDVerificationToken) => ({ token }),+ hideBindDialog: true,+ setBindUrl: (url: string) => ({ url }),+ setIsBindingToken: (binding: boolean) => ({ binding }),+ bindToken: true,}),reducers({@@ -85,6 +147,12 @@ export const cimdVerificationTokensLogic = kea<cimdVerificationTokensLogicType>(hideCreateDialog: () => false,},],+ isCreatingToken: [+ false,+ {+ setIsCreatingToken: (_, { creating }) => creating,+ },+ ],newTokenLabel: ['',{@@ -92,12 +160,40 @@ export const cimdVerificationTokensLogic = kea<cimdVerificationTokensLogicType>(hideCreateDialog: () => '',},],+ newTokenUrl: [+ '',+ {+ setNewTokenUrl: (_, { url }) => url,+ hideCreateDialog: () => '',+ },+ ],justCreatedToken: [null as CIMDVerificationTokenWithValue | null,{setJustCreatedToken: (_, { token }) => token,},],+ bindingToken: [+ null as CIMDVerificationToken | null,+ {+ showBindDialog: (_, { token }) => token,+ hideBindDialog: () => null,+ },+ ],+ bindUrl: [+ '',+ {+ setBindUrl: (_, { url }) => url,+ showBindDialog: () => '',+ hideBindDialog: () => '',+ },+ ],+ isBindingToken: [+ false,+ {+ setIsBindingToken: (_, { binding }) => binding,+ },+ ],}),loaders({@@ -127,13 +223,22 @@ export const cimdVerificationTokensLogic = kea<cimdVerificationTokensLogicType>(lemonToast.error('Please enter a label for this token.')return}+ const cimdUrl = values.newTokenUrl.trim()+ const urlError = validateCimdUrl(cimdUrl)+ if (urlError) {+ lemonToast.error(urlError)+ return+ }+ actions.setIsCreatingToken(true)try {- const created = await cimdVerificationTokensCreate(orgId, { label })+ const created = await cimdVerificationTokensCreate(orgId, { label, cimd_url: cimdUrl })actions.setJustCreatedToken(created)actions.hideCreateDialog()actions.loadTokens()} catch (e: any) {- lemonToast.error(e?.detail || 'Failed to create token')+ lemonToast.error(extractServerError(e, 'Failed to create token'))+ } finally {+ actions.setIsCreatingToken(false)}},deleteToken: async ({ token }) => {@@ -146,7 +251,31 @@ export const cimdVerificationTokensLogic = kea<cimdVerificationTokensLogicType>(lemonToast.success('Token revoked')actions.loadTokens()} catch (e: any) {- lemonToast.error(e?.detail || 'Failed to revoke token')+ lemonToast.error(extractServerError(e, 'Failed to revoke token'))+ }+ },+ bindToken: async () => {+ const orgId = organizationLogic.values.currentOrganization?.id+ const token = values.bindingToken+ if (!orgId || !token) {+ return+ }+ const cimdUrl = values.bindUrl.trim()+ const urlError = validateCimdUrl(cimdUrl)+ if (urlError) {+ lemonToast.error(urlError)+ return+ }+ actions.setIsBindingToken(true)+ try {+ await cimdVerificationTokensPartialUpdate(orgId, token.id, { cimd_url: cimdUrl })+ lemonToast.success('Metadata URL set. The token will verify there now.')+ actions.hideBindDialog()+ actions.loadTokens()+ } catch (e: any) {+ lemonToast.error(extractServerError(e, 'Failed to set metadata URL'))+ } finally {+ actions.setIsBindingToken(false)}},})),diff --git a/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx b/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsxindex a43be5ba8812..41e25be23774 100644--- a/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx+++ b/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx@@ -48,6 +48,34 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {],max_proxy_records: 2,},+ // One bound token and one left over from before URL binding, so the story+ // covers the warning banner and the "Not verifying" cell as well as the+ // ordinary row.+ '/api/organizations/:organization_id/cimd_verification_tokens/': {+ count: 2,+ next: null,+ previous: null,+ results: [+ {+ id: 'b7d3a1c2-0000-4000-8000-000000000001',+ label: 'Production CIMD partner',+ cimd_url: 'https://partner.example.com/.well-known/oauth-client-metadata.json',+ mask_value: 'phvt...4f2a',+ created_by: null,+ created_at: '2023-05-20T10:00:00Z',+ last_used_at: '2023-05-24T18:30:00Z',+ },+ {+ id: 'b7d3a1c2-0000-4000-8000-000000000002',+ label: 'Legacy token',+ cimd_url: null,+ mask_value: 'phvt...9c11',+ created_by: null,+ created_at: '2023-04-02T09:15:00Z',+ last_used_at: null,+ },+ ],+ },},patch: {'/api/projects/:id': async ({ request }) => {@@ -86,3 +114,7 @@ export const SettingsOrganizationDangerZone: Story = { args: { sectionId: 'organexport const SettingsOrganizationBilling: Story = { args: { sectionId: 'organization-billing' } }export const SettingsOrganizationStartupProgram: Story = { args: { sectionId: 'organization-startup-program' } }++export const SettingsOrganizationCimdVerificationTokens: Story = {+ args: { sectionId: 'organization-cimd-verification-tokens' },+}diff --git a/posthog/api/cimd_verification_token.py b/posthog/api/cimd_verification_token.pyindex 8148989fc510..1228d712c797 100644--- a/posthog/api/cimd_verification_token.py+++ b/posthog/api/cimd_verification_token.py@@ -1,4 +1,5 @@from typing import Any+from urllib.parse import urlparsefrom django.core.cache import cachefrom django.views.decorators.debug import sensitive_variables@@ -7,22 +8,41 @@ from drf_spectacular.utils import extend_schemafrom rest_framework import mixins, serializers, viewsetsfrom rest_framework.response import Response+from posthog.api.oauth.cimd import _cache_key, validate_cimd_urlfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models.activity_logging.activity_log import Detail, log_activity-from posthog.models.oauth import CIMDVerificationToken, OAuthApplication, create_cimd_verification_token+from posthog.models.oauth import (+ CIMDVerificationToken,+ OAuthApplication,+ create_cimd_verification_token,+ normalize_cimd_url,+)from posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermissionclass CIMDVerificationTokenSerializer(serializers.ModelSerializer):+ """Read shape for list/retrieve/create-response. `cimd_url` is nullable here for+ tokens issued before URL binding; the write serializers below require a value."""+created_by = UserBasicSerializer(read_only=True)+ cimd_url = serializers.CharField(+ max_length=2048,+ read_only=True,+ allow_null=True,+ help_text=(+ "HTTPS URL of the CIMD metadata document this token verifies at. "+ "Null on tokens issued before URL binding; those no longer verify until bound via PATCH or reissued."+ ),+ )class Meta:model = CIMDVerificationTokenfields = ["id","label",+ "cimd_url","mask_value","created_by","created_at",@@ -30,11 +50,75 @@ class CIMDVerificationTokenSerializer(serializers.ModelSerializer):]read_only_fields = ["id",+ "label","mask_value","created_by","created_at","last_used_at",]+ # `label` is set here rather than declared as a field: a serializer attribute+ # named `label` shadows DRF's own `Field.label`, which mypy rejects.+ extra_kwargs = {+ "label": {"help_text": "Human-readable name to identify this token later, e.g. 'Production CIMD partner'."}+ }+++class _CIMDUrlWriteValidationMixin:+ """Shared write-path validation for `cimd_url` on the create and update serializers.++ Beyond format/safety, this also rejects a URL that normalizes to no path (e.g.+ `https://host//`, whose `//` survives `validate_cimd_url`'s raw shape check but+ collapses to an empty path in `normalize_cimd_url`). Without this, such a URL is+ accepted at issuance and can then never match any fetch URL, since a pathless URL is+ itself rejected as a client_id, so the token would silently never verify.++ Returns the normalized form, which is what gets persisted. `create` would normalize+ anyway inside `create_cimd_verification_token`, but PATCH writes `validated_data`+ straight through, and an unnormalized binding never matches the normalized fetch URL.+ """++ def validate_cimd_url(self, value: str) -> str:+ value = value.strip()+ # Skips the DNS check: the URL is often not serving yet at issuance time,+ # and the fetch path re-validates with SSRF checks before it ever loads it.+ valid, error = validate_cimd_url(value, what="CIMD metadata URL")+ if not valid:+ raise serializers.ValidationError(error)+ try:+ # Accessing .port is what validates it; urlparse itself accepts "host:abc".+ _ = urlparse(value).port+ except ValueError:+ raise serializers.ValidationError("CIMD metadata URL has an invalid port.")+ normalized = normalize_cimd_url(value)+ if not urlparse(normalized).path:+ raise serializers.ValidationError(+ "CIMD metadata URL must include a path component. A URL ending only in "+ "slashes normalizes to no path and could never verify."+ )+ return normalized+++class CIMDVerificationTokenCreateSerializer(_CIMDUrlWriteValidationMixin, serializers.ModelSerializer):+ """Write shape for `create`. `cimd_url` is required and non-null: only tokens+ issued before URL binding existed are nullable, not new ones."""++ cimd_url = serializers.CharField(+ max_length=2048,+ required=True,+ allow_null=False,+ help_text=(+ "HTTPS URL of the CIMD metadata document this token will be published in. "+ "The token only verifies at this URL, so a copy hosted anywhere else is rejected. "+ "Host case, an explicit :443 and a trailing slash are normalized away; the path is case-sensitive."+ ),+ )++ class Meta:+ model = CIMDVerificationToken+ fields = ["label", "cimd_url"]+ extra_kwargs = {+ "label": {"help_text": "Human-readable name to identify this token later, e.g. 'Production CIMD partner'."}+ }def validate_label(self, value: str) -> str:value = value.strip()@@ -57,12 +141,43 @@ class CIMDVerificationTokenWithValueSerializer(CIMDVerificationTokenSerializer):read_only_fields = [*CIMDVerificationTokenSerializer.Meta.read_only_fields, "value"]+class CIMDVerificationTokenUpdateSerializer(_CIMDUrlWriteValidationMixin, serializers.ModelSerializer):+ """Write shape for `partial_update` (PATCH). Exposes only `cimd_url`, and only ever+ performs a null -> value transition: `validate` rejects any instance whose `cimd_url`+ is already set, so an existing binding can never be re-pointed through this endpoint.+ """++ cimd_url = serializers.CharField(+ max_length=2048,+ required=True,+ allow_null=False,+ help_text=(+ "HTTPS URL of the CIMD metadata document to bind this token to. Only settable "+ "once, on a token with no existing binding; an already-bound token must be reissued instead."+ ),+ )++ class Meta:+ model = CIMDVerificationToken+ fields = ["cimd_url"]++ def validate(self, attrs: dict[str, str]) -> dict[str, str]:+ if self.instance is not None and self.instance.cimd_url:+ raise serializers.ValidationError(+ {+ "cimd_url": "This token is already bound to a CIMD URL and cannot be re-pointed here. Reissue the token instead."+ }+ )+ return attrs++@extend_schema(extensions={"x-product": "core"})class CIMDVerificationTokenViewSet(TeamAndOrgViewSetMixin,mixins.CreateModelMixin,mixins.ListModelMixin,mixins.RetrieveModelMixin,+ mixins.UpdateModelMixin,mixins.DestroyModelMixin,viewsets.GenericViewSet,):@@ -74,6 +189,11 @@ class CIMDVerificationTokenViewSet(the metadata, matching the token links the partner app to this organization andgrants a higher default rate limit for account provisioning.+ Each token is scoped at creation to the one `cimd_url` it will be published at,+ and verifies nowhere else. Two organizations may name the same URL; only the one+ whose token is actually served there verifies, so claiming a URL cannot be used+ to block a partner from verifying theirs.+The plaintext value is only available on creation; we store a hash."""@@ -81,11 +201,24 @@ class CIMDVerificationTokenViewSet(permission_classes = [OrganizationAdminWritePermissions, TimeSensitiveActionPermission]queryset = CIMDVerificationToken.objects.select_related("created_by").order_by("-created_at")serializer_class = CIMDVerificationTokenSerializer+ # No PUT: partial_update (PATCH) only ever binds a null cimd_url, which a full+ # replace would make awkward to express safely; the create/reissue flow covers+ # replacing every other field. No TRACE either, PostHog's viewsets don't use it.+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]def safely_get_queryset(self, queryset):return queryset.filter(organization_id=self.organization_id)- @extend_schema(responses={201: CIMDVerificationTokenWithValueSerializer})+ def get_serializer_class(self) -> type[serializers.ModelSerializer]:+ if self.action == "create":+ return CIMDVerificationTokenCreateSerializer+ if self.action == "partial_update":+ return CIMDVerificationTokenUpdateSerializer+ return CIMDVerificationTokenSerializer++ @extend_schema(+ request=CIMDVerificationTokenCreateSerializer, responses={201: CIMDVerificationTokenWithValueSerializer}+ )@sensitive_variables("plaintext", "output")def create(self, request, *args: Any, **kwargs: Any) -> Response:serializer = self.get_serializer(data=request.data)@@ -93,6 +226,7 @@ class CIMDVerificationTokenViewSet(token, plaintext = create_cimd_verification_token(organization=self.organization,label=serializer.validated_data["label"],+ cimd_url=serializer.validated_data["cimd_url"],created_by=request.user if request.user.is_authenticated else None,)token.value = plaintext # type: ignore[attr-defined]@@ -109,6 +243,26 @@ class CIMDVerificationTokenViewSet()return Response(output, status=201)+ @extend_schema(request=CIMDVerificationTokenUpdateSerializer, responses={200: CIMDVerificationTokenSerializer})+ def partial_update(self, request, *args: Any, **kwargs: Any) -> Response:+ instance = self.get_object()+ serializer = self.get_serializer(instance, data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ serializer.save()+ instance.refresh_from_db()+ log_activity(+ organization_id=self.organization.id,+ team_id=None,+ user=request.user if request.user.is_authenticated else None,+ was_impersonated=is_impersonated(request),+ item_id=str(instance.id),+ scope="CIMDVerificationToken",+ activity="updated",+ detail=Detail(name=instance.label),+ )+ output = CIMDVerificationTokenSerializer(instance).data+ return Response(output, status=200)+def perform_destroy(self, instance: CIMDVerificationToken) -> None:org_id = instance.organization_idlabel = instance.label@@ -122,8 +276,6 @@ class CIMDVerificationTokenViewSet(# revoke-confirm UX ("partners using this token will no longer be# recognized") without touching apps that have a different linking# token.- from posthog.api.oauth.cimd import _cache_key-for url in OAuthApplication.objects.filter(is_cimd_client=True,organization_id=org_id,diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex c048351aaade..343f053ca369 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -11,6 +11,7 @@ import reimport jsonimport timeimport hashlib+from collections.abc import Callablefrom typing import TYPE_CHECKING, TypedDict, castfrom urllib.parse import urlparse@@ -33,6 +34,7 @@ from posthog.models.oauth import (OAuthApplication,TokenEndpointAuthMethod,find_cimd_verification_token,+ normalize_cimd_url,)from posthog.ph_client import ph_scoped_capturefrom posthog.rate_limit import IPThrottle@@ -47,6 +49,11 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)+# The signature shared by posthoganalytics.capture and the ph_scoped_capture callable, so+# every function on the capture path can accept either interchangeably. The return is+# `object` because the two disagree on it and no caller uses it.+CapturePhEvent = Callable[..., object]+# Limits per the CIMD specificationCIMD_MAX_DOCUMENT_SIZE = 5 * 1024 # 5KBCIMD_FETCH_TIMEOUT_SECONDS = 5@@ -165,23 +172,29 @@ def validate_fetchable_https_url(return True, None-def validate_cimd_url(url: str | None, *, perform_dns_check: bool = False) -> tuple[bool, str | None]:+def validate_cimd_url(+ url: str | None, *, perform_dns_check: bool = False, what: str = "CIMD client_id"+) -> tuple[bool, str | None]:"""Validate a CIMD URL for format and optionally SSRF safety.Adds the identity requirements a CIMD ``client_id`` carries on top of the safety checks:the URL is the client's stable identifier, so it must name a document (a path) and mustnot vary by query string.++ ``what`` names the thing being validated in the returned message. It defaults to the+ OAuth term because these errors usually surface against a ``client_id`` on /authorize,+ but the settings form calls the same value a metadata URL and passes its own label."""- safe, error = validate_fetchable_https_url(url, perform_dns_check=perform_dns_check, what="CIMD client_id")+ safe, error = validate_fetchable_https_url(url, perform_dns_check=perform_dns_check, what=what)if not safe:return False, errorparsed = urlparse(url or "")if not parsed.path or parsed.path == "/":- return False, "CIMD client_id must include a path component"+ return False, f"{what} must include a path component"if parsed.query:- return False, "CIMD client_id must not contain query parameters"+ return False, f"{what} must not contain query parameters"return True, None@@ -431,24 +444,105 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:return metadata, cache_ttl-def _resolve_verification_token(metadata: CIMDMetadataDocument) -> CIMDVerificationToken | None:+def _resolve_verification_token(+ metadata: CIMDMetadataDocument, url: str, *, capture_ph_event: CapturePhEvent = posthoganalytics.capture+) -> CIMDVerificationToken | None:"""Look up a verification token from CIMD metadata, preferring the nested`com.posthog.verification_token` and falling back to the legacy top-level`posthog_verification_token`. Falls back to the top-level token when the nestedone is absent OR present-but-unrecognized, so a typo'd nested token doesn't drop- a partner whose legacy token still resolves. Returns the token record, or None."""+ a partner whose legacy token still resolves. Returns the token record, or None.++ A token only resolves at the URL it was issued for. The document is public,+ so a token found here may have been copied from someone else's document —+ `url` is the only thing distinguishing the real publisher from a copier.++ A recognized nested token bound to some other URL resolves to None rather than+ falling through to the legacy field: it means this document is quoting someone+ else's credential, and trying a second one would be working around that."""com_posthog = metadata.get("com.posthog")if isinstance(com_posthog, dict):nested_raw = com_posthog.get("verification_token")if nested_raw and isinstance(nested_raw, str):token = find_cimd_verification_token(nested_raw)if token is not None:- return token+ return token if _token_is_bound_to_url(token, url, capture_ph_event=capture_ph_event) else Noneraw = metadata.get("posthog_verification_token")if not raw or not isinstance(raw, str):return None- return find_cimd_verification_token(raw)+ token = find_cimd_verification_token(raw)+ if token is None:+ return None+ return token if _token_is_bound_to_url(token, url, capture_ph_event=capture_ph_event) else None+++def _token_is_bound_to_url(+ token: CIMDVerificationToken, url: str, *, capture_ph_event: CapturePhEvent = posthoganalytics.capture+) -> bool:+ """Whether this token was issued for the document we just fetched.++ Fails closed on tokens with no URL: those pre-date binding and could not be+ migrated automatically, so they must be reissued rather than keep verifying+ any document that quotes them. Also fails closed when the app has no metadata+ URL at all, under its own reason — otherwise it would fall into the mismatch+ branch below and pollute the metric used to spot copied tokens."""+ if not token.cimd_url:+ _capture_verification_rejected(token, url, reason="token_not_bound", capture_ph_event=capture_ph_event)+ return False+ if not url:+ _capture_verification_rejected(token, url, reason="app_url_missing", capture_ph_event=capture_ph_event)+ return False+ if token.cimd_url != normalize_cimd_url(url):+ _capture_verification_rejected(token, url, reason="url_mismatch", capture_ph_event=capture_ph_event)+ return False+ return True+++CAPTURE_VERIFICATION_REJECTED_MIN_INTERVAL = 300 # 5 minutes+++def _verification_rejected_capture_key(token: CIMDVerificationToken, url: str, reason: str) -> str:+ url_hash = hashlib.sha256(url.encode()).hexdigest()+ return f"cimd:verification_rejected:{token.pk}:{reason}:{url_hash}"+++def _capture_verification_rejected(+ token: CIMDVerificationToken,+ url: str,+ *,+ reason: str,+ capture_ph_event: CapturePhEvent = posthoganalytics.capture,+) -> None:+ """`url_mismatch` means a valid token was presented at a document it was not+ issued for, the copied-token case this binding exists to stop. Every rejection+ reason shares this one event rather than getting its own, so the alert on it+ filters on `reason="url_mismatch"`.++ The capture (not the log below) is deduped per (token, url, reason) behind a+ cache sentinel, mirroring `_touch_verification_token`: an unbound legacy token+ or an app with no metadata URL would otherwise recapture on every refresh and+ bury the low-volume url_mismatch signal the alert exists to catch."""+ logger.warning(+ "cimd_verification_token_rejected",+ reason=reason,+ fetched_url=url,+ bound_url=token.cimd_url,+ organization_id=str(token.organization_id),+ )+ sentinel_key = _verification_rejected_capture_key(token, url, reason)+ if not cache.add(sentinel_key, True, timeout=CAPTURE_VERIFICATION_REJECTED_MIN_INTERVAL):+ return+ capture_ph_event(+ distinct_id=str(token.organization_id),+ event="cimd_verification_token_rejected",+ properties={+ "reason": reason,+ "fetched_url": url,+ "bound_url": token.cimd_url,+ "organization_id": str(token.organization_id),+ },+ )def _resolve_scopes(metadata: CIMDMetadataDocument) -> list[str] | None:@@ -513,7 +607,9 @@ def _resolve_client_authentication(metadata: CIMDMetadataDocument) -> tuple[str,return AbstractApplication.CLIENT_PUBLIC, None-def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthApplication:+def _create_cimd_application(+ url: str, metadata: CIMDMetadataDocument, *, capture_ph_event: CapturePhEvent = posthoganalytics.capture+) -> OAuthApplication:"""Create a new OAuthApplication from CIMD metadata."""client_name = metadata.get("client_name", "CIMD Client")try:@@ -525,7 +621,7 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthAredirect_uris = " ".join(metadata.get("redirect_uris", []))logo_uri = metadata.get("logo_uri") or None- verification = _resolve_verification_token(metadata)+ verification = _resolve_verification_token(metadata, url, capture_ph_event=capture_ph_event)resolved_scopes = _resolve_scopes(metadata)resolved_optional_scopes = _resolve_optional_scopes(metadata)@@ -601,7 +697,12 @@ def _retier_account_requests_limit(app: OAuthApplication, *, verified: bool) ->)-def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocument) -> OAuthApplication:+def _update_cimd_application(+ app: OAuthApplication,+ metadata: CIMDMetadataDocument,+ *,+ capture_ph_event: CapturePhEvent = posthoganalytics.capture,+) -> OAuthApplication:"""Update an existing OAuthApplication from refreshed CIMD metadata.@@ -627,7 +728,7 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocume# Re-evaluate verification on every refresh so a rotated/removed token# unlinks the app on the next fetch.- verification = _resolve_verification_token(metadata)+ verification = _resolve_verification_token(metadata, app.cimd_metadata_url or "", capture_ph_event=capture_ph_event)new_org = verification.organization if verification else Noneupdate_fields = ["name",@@ -676,7 +777,7 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocume# flipping A→B (or A→None, None→A) is visible in analytics, not# just buried in the generic refresh event.if old_org_id != new_org_id:- posthoganalytics.capture(+ capture_ph_event(distinct_id=app.cimd_metadata_url or str(app.pk),event="cimd_application_org_changed",properties={@@ -690,7 +791,9 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocumereturn app-def fetch_and_upsert_cimd_application(url: str, capture_ph_event=posthoganalytics.capture) -> OAuthApplication | None:+def fetch_and_upsert_cimd_application(+ url: str, capture_ph_event: CapturePhEvent = posthoganalytics.capture+) -> OAuthApplication | None:"""Fetch CIMD metadata and create or update the application.@@ -714,7 +817,7 @@ def fetch_and_upsert_cimd_application(url: str, capture_ph_event=posthoganalyticapp = OAuthApplication.objects.filter(cimd_metadata_url=url).first()if app:- updated = _update_cimd_application(app, metadata)+ updated = _update_cimd_application(app, metadata, capture_ph_event=capture_ph_event)logger.debug("cimd_app_updated", url=url, app_id=str(updated.pk))capture_ph_event(distinct_id=url,@@ -731,7 +834,7 @@ def fetch_and_upsert_cimd_application(url: str, capture_ph_event=posthoganalyticreturn updatedtry:- new_app = _create_cimd_application(url, metadata)+ new_app = _create_cimd_application(url, metadata, capture_ph_event=capture_ph_event)logger.debug("cimd_app_created", url=url, app_id=str(new_app.pk), client_name=new_app.name)capture_ph_event(distinct_id=url,diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex 85898f91345f..409b20fc2c65 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -25,6 +25,7 @@ from posthog.api.oauth.cimd import (CIMDValidationError,_fetch_lock_key,_resolve_scopes,+ _update_cimd_application,apply_provisioning_defaults,fetch_and_upsert_cimd_application,fetch_cimd_metadata,@@ -36,6 +37,7 @@ from posthog.api.oauth.cimd import (validate_fetchable_https_url,)from posthog.api.oauth.client_name import sanitize_client_name+from posthog.models import Organizationfrom posthog.models.oauth import OAuthApplication, TokenEndpointAuthMethod, create_cimd_verification_tokenfrom posthog.scopes import OAUTH_SCOPES_HIDDEN, PRIVILEGED_SCOPES@@ -652,7 +654,7 @@ class TestCIMDVerificationToken(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_valid_verification_token_links_app_to_organization(self, mock_get, _url_mock):token, plaintext = create_cimd_verification_token(- organization=self.organization, label="Test partner", created_by=self.user+ organization=self.organization, label="Test partner", cimd_url=VALID_CIMD_URL, created_by=self.user)metadata = _make_metadata(posthog_verification_token=plaintext)mock_get.return_value = _mock_response(metadata, headers={})@@ -686,7 +688,7 @@ class TestCIMDVerificationToken(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_verified_partner_gets_higher_rate_limit(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(- organization=self.organization, label="Verified partner", created_by=self.user+ organization=self.organization, label="Verified partner", cimd_url=VALID_CIMD_URL, created_by=self.user)metadata = _make_metadata(posthog_verification_token=plaintext)mock_get.return_value = _mock_response(metadata, headers={})@@ -716,7 +718,7 @@ class TestCIMDVerificationToken(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_unlinks_app_when_token_removed(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(- organization=self.organization, label="Rotating partner", created_by=self.user+ organization=self.organization, label="Rotating partner", cimd_url=VALID_CIMD_URL, created_by=self.user)# First fetch: with token → linkedmock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})@@ -741,7 +743,7 @@ class TestCIMDVerificationToken(APIBaseTest):# Partner adds a token and we refetch_, plaintext = create_cimd_verification_token(- organization=self.organization, label="Added later", created_by=self.user+ organization=self.organization, label="Added later", cimd_url=VALID_CIMD_URL, created_by=self.user)real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})@@ -772,7 +774,10 @@ class TestCIMDVerificationToken(APIBaseTest):)_, plaintext = create_cimd_verification_token(- organization=self.organization, label="Added post-registration", created_by=self.user+ organization=self.organization,+ label="Added post-registration",+ cimd_url=VALID_CIMD_URL,+ created_by=self.user,)real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})@@ -788,7 +793,7 @@ class TestCIMDVerificationToken(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_drops_rate_limit_when_token_removed(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(- organization=self.organization, label="Rotating partner", created_by=self.user+ organization=self.organization, label="Rotating partner", cimd_url=VALID_CIMD_URL, created_by=self.user)mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})_register_provisioning_partner()@@ -818,7 +823,7 @@ class TestCIMDVerificationToken(APIBaseTest):app.update_provisioning(rate_limit_source="admin")app.update_provisioning_rate_limits(account_requests=250)_, plaintext = create_cimd_verification_token(- organization=self.organization, label="Post-admin-override", created_by=self.user+ organization=self.organization, label="Post-admin-override", cimd_url=VALID_CIMD_URL, created_by=self.user)real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})@@ -830,6 +835,192 @@ class TestCIMDVerificationToken(APIBaseTest):self.assertEqual(refreshed.provisioning.rate_limit_source, "admin")+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+class TestCIMDVerificationTokenURLBinding(APIBaseTest):+ """The metadata document is public, so the token in it can be read and republished+ by anyone. These lock in that the URL is what decides who the token belongs to."""++ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_token_copied_to_another_url_does_not_link_the_app(self, mock_get, _url_mock):+ _, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Victim", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ attacker_url = "https://attacker.example.com/.well-known/oauth-client-metadata.json"+ mock_get.return_value = _mock_response(+ _make_metadata(url=attacker_url, posthog_verification_token=plaintext), headers={}+ )++ app = fetch_and_upsert_cimd_application(attacker_url)++ assert app is not None+ self.assertIsNone(app.organization_id)++ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_unbound_legacy_token_no_longer_verifies(self, mock_get, _url_mock):+ token, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Legacy", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ token.cimd_url = None+ token.save(update_fields=["cimd_url"])+ mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ self.assertIsNone(app.organization_id)++ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_claiming_a_url_does_not_block_the_real_publisher(self, mock_get, _url_mock):+ # No uniqueness on cimd_url, so a squatter naming someone else's URL first+ # cannot lock them out — only the token actually served there verifies.+ squatter_org = Organization.objects.create(name="Squatter")+ create_cimd_verification_token(+ organization=squatter_org, label="Squat", cimd_url=VALID_CIMD_URL, created_by=None+ )+ _, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Real partner", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ self.assertEqual(app.organization_id, self.organization.id)++ @parameterized.expand(+ [+ ("trailing_slash", VALID_CIMD_URL + "/"),+ ("uppercase_host", "https://APP.EXAMPLE.COM/.well-known/oauth-client-metadata.json"),+ ("explicit_default_port", "https://app.example.com:443/.well-known/oauth-client-metadata.json"),+ ]+ )+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_equivalent_url_spellings_still_verify(self, _name, issued_url, mock_get, _url_mock):+ _, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Partner", cimd_url=issued_url, created_by=self.user+ )+ mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ self.assertEqual(app.organization_id, self.organization.id)+++@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+class TestCIMDVerificationRejectedCaptureEvent(APIBaseTest):+ """`_capture_verification_rejected` emits `cimd_verification_token_rejected`. These lock in:+ the event reaching an injected capture callable (so it isn't silently dropped in Celery),+ a stable non-attacker-controlled distinct_id, the per-(token, url, reason) dedup, and a+ distinct reason for an app with no metadata URL."""++ def setUp(self):+ super().setUp()+ real_cache.clear()++ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_rejection_fires_through_injected_capture_on_refresh(self, mock_get, _url_mock):+ other_url = "https://other.example.com/.well-known/oauth-client-metadata.json"+ _, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Victim", cimd_url=other_url, created_by=self.user+ )+ mock_get.return_value = _mock_response(_make_metadata(), headers={})+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)+ assert app is not None++ # The copied-token rejection only triggers on refresh, since a first fetch has no+ # existing app to compare against — this is the path a bare posthoganalytics.capture+ # silently drops in Celery.+ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))+ mock_capture = MagicMock()+ mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL, capture_ph_event=mock_capture)++ assert refreshed is not None+ rejected = [+ call+ for call in mock_capture.call_args_list+ if call.kwargs.get("event") == "cimd_verification_token_rejected"+ ]+ self.assertEqual(len(rejected), 1)+ self.assertEqual(rejected[0].kwargs["properties"]["reason"], "url_mismatch")++ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_rejection_distinct_id_is_organization_not_url(self, mock_get, _url_mock):+ token, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Legacy", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ token.cimd_url = None+ token.save(update_fields=["cimd_url"])+ mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})+ mock_capture = MagicMock()++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL, capture_ph_event=mock_capture)++ assert app is not None+ rejected = [+ call+ for call in mock_capture.call_args_list+ if call.kwargs.get("event") == "cimd_verification_token_rejected"+ ]+ self.assertEqual(len(rejected), 1)+ self.assertEqual(rejected[0].kwargs["distinct_id"], str(self.organization.id))++ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_rejection_deduped_for_same_token_url_reason(self, mock_get, _url_mock):+ token, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Legacy", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ token.cimd_url = None+ token.save(update_fields=["cimd_url"])+ metadata = _make_metadata(posthog_verification_token=plaintext)+ mock_capture = MagicMock()++ mock_get.return_value = _mock_response(metadata, headers={})+ fetch_and_upsert_cimd_application(VALID_CIMD_URL, capture_ph_event=mock_capture)++ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))+ mock_get.return_value = _mock_response(metadata, headers={})+ fetch_and_upsert_cimd_application(VALID_CIMD_URL, capture_ph_event=mock_capture)++ rejected = [+ call+ for call in mock_capture.call_args_list+ if call.kwargs.get("event") == "cimd_verification_token_rejected"+ ]+ self.assertEqual(len(rejected), 1)++ def test_empty_app_metadata_url_rejects_as_app_url_missing_not_mismatch(self, _url_mock):+ _, plaintext = create_cimd_verification_token(+ organization=self.organization, label="Bound", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ app = OAuthApplication.objects.create(+ name="CIMD App",+ client_secret="",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="http://127.0.0.1:3000/callback",+ algorithm="RS256",+ is_cimd_client=True,+ cimd_metadata_url=None,+ )+ mock_capture = MagicMock()++ _update_cimd_application(+ app,+ cast(CIMDMetadataDocument, _make_metadata(posthog_verification_token=plaintext)),+ capture_ph_event=mock_capture,+ )++ rejected = [+ call+ for call in mock_capture.call_args_list+ if call.kwargs.get("event") == "cimd_verification_token_rejected"+ ]+ self.assertEqual(len(rejected), 1)+ self.assertEqual(rejected[0].kwargs["properties"]["reason"], "app_url_missing")++class TestAuthorizationServerMetadata(APIBaseTest):def test_advertises_cimd_support(self):client = APIClient()@@ -960,7 +1151,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_verification_token_dual_read(self, token_placement, mock_get, _url_mock):token, plaintext = create_cimd_verification_token(- organization=self.organization, label="Dual-read partner", created_by=self.user+ organization=self.organization, label="Dual-read partner", cimd_url=VALID_CIMD_URL, created_by=self.user)if token_placement == "nested":metadata = _make_metadata(com_posthog={"verification_token": plaintext})@@ -977,7 +1168,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_verification_token_falls_back_when_nested_unrecognized(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(- organization=self.organization, label="Fallback partner", created_by=self.user+ organization=self.organization, label="Fallback partner", cimd_url=VALID_CIMD_URL, created_by=self.user)metadata = _make_metadata(posthog_verification_token=plaintext,@@ -993,7 +1184,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):@patch("posthog.api.oauth.cimd.requests.Session.get")def test_nested_token_takes_precedence_over_top_level(self, mock_get, _url_mock):_, plaintext_nested = create_cimd_verification_token(- organization=self.organization, label="Nested partner", created_by=self.user+ organization=self.organization, label="Nested partner", cimd_url=VALID_CIMD_URL, created_by=self.user)metadata = _make_metadata(posthog_verification_token="phvt_fake_top_level",@@ -1005,6 +1196,30 @@ class TestCIMDComPostHogNamespace(APIBaseTest):assert app is not Noneself.assertEqual(app.organization_id, self.organization.id)+ # (d) continued: a nested token that resolves but is bound to a different URL must not+ # fall through to a valid legacy token bound to this one — a recognized nested token+ # forecloses the legacy fallback regardless of whether the legacy token would itself verify.+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_nested_token_bound_elsewhere_does_not_fall_back_to_legacy(self, mock_get, _url_mock):+ other_url = "https://other.example.com/.well-known/oauth-client-metadata.json"+ other_org = Organization.objects.create(name="Other org")+ _, plaintext_nested = create_cimd_verification_token(+ organization=other_org, label="Nested partner elsewhere", cimd_url=other_url, created_by=self.user+ )+ _, plaintext_legacy = create_cimd_verification_token(+ organization=self.organization, label="Legacy partner here", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ metadata = _make_metadata(+ posthog_verification_token=plaintext_legacy,+ com_posthog={"verification_token": plaintext_nested},+ )+ mock_get.return_value = _mock_response(metadata, headers={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ self.assertIsNone(app.organization_id)+# (a) + (e) present scopes are written to application.scopes on creation.@parameterized.expand([diff --git a/posthog/api/test/test_cimd_verification_token.py b/posthog/api/test/test_cimd_verification_token.pyindex 19a376e5279b..295766df4a27 100644--- a/posthog/api/test/test_cimd_verification_token.py+++ b/posthog/api/test/test_cimd_verification_token.py@@ -1,9 +1,14 @@from posthog.test.base import APIBaseTest+from parameterized import parameterizedfrom rest_framework import status+from posthog.api.oauth.cimd import _token_is_bound_to_urlfrom posthog.models import Organization, OrganizationMembership-from posthog.models.oauth import CIMDVerificationToken, create_cimd_verification_token+from posthog.models.oauth import CIMDVerificationToken, create_cimd_verification_token, normalize_cimd_url++VALID_CIMD_URL = "https://app.example.com/.well-known/oauth-client-metadata.json"+OTHER_VALID_CIMD_URL = "https://app.example.com/.well-known/other-metadata.json"class TestCIMDVerificationTokenViewSet(APIBaseTest):@@ -15,11 +20,12 @@ class TestCIMDVerificationTokenViewSet(APIBaseTest):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()- response = self.client.post(self._url(), {"label": "Prod partner"}, format="json")+ response = self.client.post(self._url(), {"label": "Prod partner", "cimd_url": VALID_CIMD_URL}, format="json")self.assertEqual(response.status_code, status.HTTP_201_CREATED)body = response.json()self.assertTrue(body["value"].startswith("phvt_"))self.assertEqual(body["label"], "Prod partner")+ self.assertEqual(body["cimd_url"], VALID_CIMD_URL)self.assertTrue(body["mask_value"].startswith("phvt"))self.assertIn("...", body["mask_value"])@@ -31,16 +37,18 @@ class TestCIMDVerificationTokenViewSet(APIBaseTest):def test_non_admin_cannot_create(self):self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()- response = self.client.post(self._url(), {"label": "blocked"}, format="json")+ response = self.client.post(self._url(), {"label": "blocked", "cimd_url": VALID_CIMD_URL}, format="json")self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)def test_list_returns_org_tokens_only_without_plaintext(self):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()- create_cimd_verification_token(organization=self.organization, label="Ours", created_by=self.user)+ create_cimd_verification_token(+ organization=self.organization, label="Ours", cimd_url=VALID_CIMD_URL, created_by=self.user+ )other_org = Organization.objects.create(name="Other")- create_cimd_verification_token(organization=other_org, label="Theirs", created_by=None)+ create_cimd_verification_token(organization=other_org, label="Theirs", cimd_url=VALID_CIMD_URL, created_by=None)response = self.client.get(self._url())self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -53,15 +61,89 @@ class TestCIMDVerificationTokenViewSet(APIBaseTest):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()token, _ = create_cimd_verification_token(- organization=self.organization, label="Revocable", created_by=self.user+ organization=self.organization, label="Revocable", cimd_url=VALID_CIMD_URL, created_by=self.user)response = self.client.delete(self._url(str(token.id)))self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)self.assertFalse(CIMDVerificationToken.objects.filter(id=token.id).exists())- def test_blank_label_rejected(self):+ @parameterized.expand(+ [+ ("blank_label", {"label": " ", "cimd_url": VALID_CIMD_URL}),+ ("missing_url", {"label": "No URL"}),+ ("null_url", {"label": "Null URL", "cimd_url": None}),+ ("http_url", {"label": "Insecure", "cimd_url": "http://app.example.com/cimd.json"}),+ ("url_without_path", {"label": "No path", "cimd_url": "https://app.example.com"}),+ ("non_numeric_port", {"label": "Bad port", "cimd_url": "https://app.example.com:abc/cimd.json"}),+ ("out_of_range_port", {"label": "Big port", "cimd_url": "https://app.example.com:99999/cimd.json"}),+ # Passes the raw shape check (path is "//", neither "" nor "/") but normalizes to+ # no path at all, so it could never match a real fetch URL. Must be rejected at+ # issuance rather than silently accepted and never verifying.+ ("no_path_after_normalizing", {"label": "Double slash", "cimd_url": "https://app.example.com//"}),+ ]+ )+ def test_invalid_payload_rejected(self, _name, payload):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()- response = self.client.post(self._url(), {"label": " "}, format="json")+ response = self.client.post(self._url(), payload, format="json")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(CIMDVerificationToken.objects.filter(organization=self.organization).exists())++ @parameterized.expand(+ [+ ("already_normalized", VALID_CIMD_URL),+ ("uppercase_host", "https://APP.Example.COM/.well-known/oauth-client-metadata.json"),+ ("explicit_default_port", "https://app.example.com:443/.well-known/oauth-client-metadata.json"),+ ("trailing_slash", VALID_CIMD_URL + "/"),+ ]+ )+ def test_patch_binds_unbound_token_to_normalized_value_and_it_then_verifies(self, _name, raw_url):+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ token, _ = create_cimd_verification_token(+ organization=self.organization, label="Legacy", cimd_url=VALID_CIMD_URL, created_by=self.user+ )+ token.cimd_url = None+ token.save(update_fields=["cimd_url"])++ response = self.client.patch(self._url(str(token.id)), {"cimd_url": raw_url}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["cimd_url"], VALID_CIMD_URL)+ token.refresh_from_db()+ # Asserting the stored column, not just the response body or the status code: the+ # ModelSerializer update path writes validated_data straight to the column, so a+ # PATCH that validated a raw spelling but returned it unnormalized would still 200+ # while storing a value that could never match a real fetch's normalized URL.+ self.assertEqual(token.cimd_url, VALID_CIMD_URL)+ self.assertTrue(_token_is_bound_to_url(token, VALID_CIMD_URL))++ def test_patch_on_already_bound_token_is_rejected_and_leaves_value_unchanged(self):+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ token, _ = create_cimd_verification_token(+ organization=self.organization, label="Bound", cimd_url=VALID_CIMD_URL, created_by=self.user+ )++ response = self.client.patch(self._url(str(token.id)), {"cimd_url": OTHER_VALID_CIMD_URL}, format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ token.refresh_from_db()+ self.assertEqual(token.cimd_url, normalize_cimd_url(VALID_CIMD_URL))++ def test_patch_is_org_scoped(self):+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ other_org = Organization.objects.create(name="Other")+ other_token, _ = create_cimd_verification_token(+ organization=other_org, label="Theirs", cimd_url=VALID_CIMD_URL, created_by=None+ )+ other_token.cimd_url = None+ other_token.save(update_fields=["cimd_url"])++ response = self.client.patch(self._url(str(other_token.id)), {"cimd_url": VALID_CIMD_URL}, format="json")++ self.assertIn(response.status_code, (status.HTTP_404_NOT_FOUND, status.HTTP_403_FORBIDDEN))+ other_token.refresh_from_db()+ self.assertIsNone(other_token.cimd_url)diff --git a/posthog/migrations/1295_cimdverificationtoken_cimd_url.py b/posthog/migrations/1295_cimdverificationtoken_cimd_url.pynew file mode 100644index 000000000000..3dedbab6f0b6--- /dev/null+++ b/posthog/migrations/1295_cimdverificationtoken_cimd_url.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-29 17:12++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1294_add_google_calendar_integration_kind"),+ ]++ operations = [+ migrations.AddField(+ model_name="cimdverificationtoken",+ name="cimd_url",+ field=models.URLField(blank=True, max_length=2048, null=True),+ ),+ ]diff --git a/posthog/migrations/1296_backfill_cimd_verification_token_url.py b/posthog/migrations/1296_backfill_cimd_verification_token_url.pynew file mode 100644index 000000000000..1a49d713ed48--- /dev/null+++ b/posthog/migrations/1296_backfill_cimd_verification_token_url.py@@ -0,0 +1,152 @@+from urllib.parse import urlparse++from django.db import migrations++import structlog++logger = structlog.get_logger(__name__)++# Sentinel a real normalized URL can never equal, so an unparseable input fails the+# equality checks upstream instead of silently matching something.+_UNNORMALIZABLE_URL = "\x00unnormalizable"+++def _normalize_cimd_url(url: str) -> str:+ """Frozen copy of posthog.models.oauth.normalize_cimd_url.++ Duplicated rather than imported: a migration module is loaded while Django+ builds the migration graph, so importing app code here runs it far too early.+ Migrations also have to stay pinned to the behavior they shipped with.+ """+ try:+ parsed = urlparse(url.strip())+ port = parsed.port+ except ValueError:+ # Covers both an unparseable port ("h:abc", "h:99999") and a URL urlparse+ # itself rejects ("https://[::1/x.json"). Either way there is nothing to+ # normalize into, so the caller must not treat this as a real URL.+ return _UNNORMALIZABLE_URL+ host = (parsed.hostname or "").lower()+ if port and port != 443:+ host = f"{host}:{port}"+ return f"{parsed.scheme.lower()}://{host}{parsed.path.rstrip('/')}"+++def backfill_cimd_url(apps, schema_editor):+ """Bind existing tokens to the document they already verified.++ Without this, every already-verified partner silently drops to the unverified+ rate-limit tier on their next metadata refresh.++ A token binds an organization to whichever CIMD document embeds it, so nothing+ here can rely on organization_id__isnull=False alone: the vulnerability this PR+ fixes is exactly that link being spoofable by copying a token into a document at+ another URL. Every row backfilled here has to be corroborated instead of merely+ plausible, so a candidate is written only when ALL of the following hold:++ - the organization's verified CIMD apps all normalize to one URL (cimd_metadata_url+ is unique, so two apps can only name one document by spelling it differently;+ two genuinely different URLs are ambiguous);+ - that URL normalizes to a real value;+ - the organization has exactly one token that isn't already bound;+ - that token has actually verified something before (last_used_at is set).++ Deliberately not required: that the token predate the app. A CIMD app self-registers+ on its first /authorize, and the admin issues a token and republishes the document+ afterwards, so a token newer than its app is the ordinary sequence rather than a+ suspicious one. Rejecting it skipped live partners while corroborating nothing that+ last_used_at does not already cover.++ Anything else is left null, which fails closed - those partners reissue a token+ against an explicit URL, or bind the existing one from the settings page.+ """+ CIMDVerificationToken = apps.get_model("posthog", "CIMDVerificationToken")+ OAuthApplication = apps.get_model("posthog", "OAuthApplication")++ # Pinned to the alias `migrate` is running on rather than letting the router pick, for the+ # same reasons as 1274: bin/migrate uses `default_direct`, and the router would otherwise+ # send these reads and the bulk_update to `default`, where DISABLE_SERVER_SIDE_CURSORS makes+ # .iterator() buffer the whole result set client-side, the writes commit outside the+ # migration's transaction, and there's no lock_timeout to fail fast under contention.+ db_alias = schema_editor.connection.alias++ verified_apps = (+ OAuthApplication.objects.using(db_alias)+ .filter(+ is_cimd_client=True,+ organization_id__isnull=False,+ cimd_metadata_url__isnull=False,+ )+ .exclude(cimd_metadata_url="")+ .values_list("organization_id", "cimd_metadata_url")+ .iterator()+ )++ # Normalized before grouping, not compared as raw strings: cimd_metadata_url is unique,+ # so two apps can only ever "share" a document by spelling it differently (host case,+ # an explicit :443, a trailing slash). Those are one document, not ambiguity.+ normalized_urls_by_org: dict[str, set[str]] = {}+ for org_id, url in verified_apps:+ normalized_urls_by_org.setdefault(str(org_id), set()).add(_normalize_cimd_url(url))++ skipped_ambiguous_url = 0+ skipped_unnormalizable_url = 0+ candidate_urls_by_org: dict[str, str] = {}+ for org_id, normalized_urls in normalized_urls_by_org.items():+ if _UNNORMALIZABLE_URL in normalized_urls:+ skipped_unnormalizable_url += 1+ continue+ if len(normalized_urls) != 1:+ skipped_ambiguous_url += 1+ continue+ (candidate_urls_by_org[org_id],) = normalized_urls++ tokens_by_org: dict[str, list] = {}+ candidate_tokens = (+ CIMDVerificationToken.objects.using(db_alias)+ .filter(organization_id__in=candidate_urls_by_org.keys(), cimd_url__isnull=True)+ .only("id", "organization_id", "last_used_at")+ .iterator()+ )+ for token in candidate_tokens:+ tokens_by_org.setdefault(str(token.organization_id), []).append(token)++ skipped_no_single_eligible_token = 0+ skipped_token_never_used = 0+ to_update = []+ written = []+ for org_id, normalized_url in candidate_urls_by_org.items():+ tokens = tokens_by_org.get(org_id, [])+ if len(tokens) != 1:+ skipped_no_single_eligible_token += 1+ continue+ token = tokens[0]+ if token.last_used_at is None:+ skipped_token_never_used += 1+ continue+ token.cimd_url = normalized_url+ to_update.append(token)+ written.append({"token_id": str(token.id), "organization_id": org_id, "cimd_url": normalized_url})++ if to_update:+ CIMDVerificationToken.objects.using(db_alias).bulk_update(to_update, ["cimd_url"], batch_size=1000)++ if written:+ logger.warning("cimd_verification_tokens_backfilled", bindings=written)+ logger.warning(+ "cimd_verification_tokens_backfill_skipped",+ ambiguous_url=skipped_ambiguous_url,+ unnormalizable_url=skipped_unnormalizable_url,+ no_single_eligible_token=skipped_no_single_eligible_token,+ token_never_used=skipped_token_never_used,+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1295_cimdverificationtoken_cimd_url"),+ ]++ operations = [+ migrations.RunPython(backfill_cimd_url, migrations.RunPython.noop, elidable=True),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex a5f696d09096..6b2a402fe98a 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1294_add_google_calendar_integration_kind+1296_backfill_cimd_verification_token_urldiff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex 809b547a0510..079c960d9833 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -721,13 +721,75 @@ def generate_random_token_cimd_verification() -> str:return "phvt_" + generate_random_token()+# Never a real normalized URL, so it only ever equals another call that hit the same+# unparseable-input branch. Issuance validates and normalizes before storing (see+# `CIMDVerificationTokenCreateSerializer` in posthog/api/cimd_verification_token.py), so no+# stored `CIMDVerificationToken.cimd_url` can ever equal this — it exists only to give the+# refresh path (which normalizes `OAuthApplication.cimd_metadata_url` read straight from the+# database, unrevalidated) a value to compare against instead of raising.+UNNORMALIZABLE_CIMD_URL = "\x00unnormalizable"+++def normalize_cimd_url(url: str) -> str:+ """Canonicalize a CIMD URL so issuance and verification compare equal.++ Both sides store/compare the output of this function, so the only thing that+ matters is that it is deterministic and collapses the variations a partner+ can plausibly produce for the same document: scheme and host case, an+ explicit `:443` (and `:0` — `port and port != 443` treats a falsy port the same as+ "no port"), and any number of trailing slashes. Reconstructing from `parsed.path`+ also drops a `;params` segment `urlparse` splits off the last path element, so+ `.../x.json`, `.../x.json;evil`, and `.../x.json///` all collapse to the same value.+ This is canonicalization for a database comparison, not a security boundary:+ `fetch_cimd_metadata` still requires `client_id == url` byte for byte against the+ real fetch URL.++ Deliberately does not touch path case or percent-encoding — those are+ server-defined and two paths differing there are legitimately different+ documents.++ The output is a persisted format, not just a comparison helper: it is stored in+ `CIMDVerificationToken.cimd_url`, and migration+ `1296_backfill_cimd_verification_token_url` keeps a frozen copy of this function's+ logic. Changing this function's output for any input silently unverifies every+ stored binding of that shape with no test failure elsewhere — see the golden-value+ table in `TestNormalizeCimdUrl` (posthog/models/test/test_oauth.py) before editing.+ """+ try:+ parsed = urlparse(url.strip())+ port = parsed.port+ except ValueError:+ # Covers both an unparseable port ("h:abc", "h:99999") and a urlparse failure on+ # the whole URL ("https://[::1/x.json" raises "Invalid IPv6 URL"). Nothing can be+ # served at either, so a sentinel that matches no real fetch is enough.+ return UNNORMALIZABLE_CIMD_URL+ host = (parsed.hostname or "").lower()+ if port and port != 443:+ host = f"{host}:{port}"+ path = parsed.path.rstrip("/")+ return f"{parsed.scheme.lower()}://{host}{path}"++class CIMDVerificationToken(models.Model):"""Token that links a CIMD partner app to a PostHog organization.A partner embeds the plaintext token in their CIMD metadata document under`posthog_verification_token`. On fetch, we hash and look up the token; if it- matches, we link the resulting OAuthApplication to this organization and- apply the verified-partner rate-limit tier.+ matches AND the document URL equals `cimd_url`, we link the resulting+ OAuthApplication to this organization and apply the verified-partner+ rate-limit tier.++ The token is served unauthenticated at the metadata URL, so possession of it+ proves nothing — anyone who reads the document can host the same value+ elsewhere. `cimd_url` is what makes the token unforgeable: it scopes the+ token to the one document it was issued for, so a copy hosted anywhere else+ fails to verify.++ `cimd_url` is deliberately NOT unique. Uniqueness would let anyone with a+ free organization reserve a partner's URL before that partner does and lock+ them out of verification permanently. Several organizations may claim the+ same URL; only the one whose token actually appears in the document at that+ URL verifies."""id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)@@ -735,6 +797,7 @@ class CIMDVerificationToken(models.Model):"posthog.Organization", on_delete=models.CASCADE, related_name="cimd_verification_tokens")label: models.CharField = models.CharField(max_length=40)+ cimd_url: models.URLField = models.URLField(max_length=2048, null=True, blank=True)mask_value: models.CharField = models.CharField(max_length=11, editable=False, null=True)secure_value: models.CharField = models.CharField(unique=True, max_length=300, editable=False)created_by: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]@@ -759,14 +822,18 @@ def find_cimd_verification_token(token: str) -> "CIMDVerificationToken | None":def create_cimd_verification_token(- *, organization: "Organization", label: str, created_by: "User | None" = None+ *, organization: "Organization", label: str, cimd_url: str, created_by: "User | None" = None) -> tuple[CIMDVerificationToken, str]:"""Create a new token, returning (instance, plaintext). Plaintext is only- available at creation time — we only persist its hash."""+ available at creation time — we only persist its hash.++ `cimd_url` is stored normalized so verification can compare it to the fetch+ URL as an exact string."""plaintext = generate_random_token_cimd_verification()token = CIMDVerificationToken.objects.create(organization=organization,label=label,+ cimd_url=normalize_cimd_url(cimd_url),created_by=created_by,secure_value=hash_key_value(plaintext),mask_value=mask_key_value(plaintext),diff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.pyindex c8887f9a3cd2..ad19d08d80e8 100644--- a/posthog/models/test/test_oauth.py+++ b/posthog/models/test/test_oauth.py@@ -11,10 +11,12 @@ from parameterized import parameterizedfrom posthog.models import Organization, Userfrom posthog.models.oauth import (+ UNNORMALIZABLE_CIMD_URL,OAuthAccessToken,OAuthApplication,OAuthGrant,OAuthRefreshToken,+ normalize_cimd_url,revoke_application_sessions,revoke_oauth_session,)@@ -580,3 +582,46 @@ class TestCarriesProvisioningConfig(SimpleTestCase):_provisioning_config=fields["config"].model_dump(mode="json"),)assert app.carries_provisioning_config is expected+++class TestNormalizeCimdUrl(SimpleTestCase):+ # `CIMDVerificationToken.cimd_url` stores this function's output directly, and migration+ # 1296_backfill_cimd_verification_token_url keeps a frozen copy of the same logic. Changing+ # what any of these inputs normalize to silently unverifies every stored token bound to a+ # URL of that shape, with no test failure elsewhere — that's what this table pins.+ @parameterized.expand(+ [+ ("trailing_slash", "https://a.example.com/cimd.json/", "https://a.example.com/cimd.json"),+ ("multiple_trailing_slashes", "https://a.example.com/cimd.json///", "https://a.example.com/cimd.json"),+ ("uppercase_host", "https://A.Example.COM/cimd.json", "https://a.example.com/cimd.json"),+ ("uppercase_scheme", "HTTPS://a.example.com/cimd.json", "https://a.example.com/cimd.json"),+ ("default_port_443", "https://a.example.com:443/cimd.json", "https://a.example.com/cimd.json"),+ ("port_zero", "https://a.example.com:0/cimd.json", "https://a.example.com/cimd.json"),+ ("path_params_stripped", "https://a.example.com/cimd.json;evil", "https://a.example.com/cimd.json"),+ ("surrounding_space", " https://a.example.com/cimd.json ", "https://a.example.com/cimd.json"),+ ]+ )+ def test_equivalent_spellings_collapse(self, _name, raw, expected):+ self.assertEqual(normalize_cimd_url(raw), expected)++ @parameterized.expand(+ [+ ("non_default_port", "https://a.example.com:8443/cimd.json"),+ ("path_case_is_significant", "https://a.example.com/CIMD.json"),+ ("different_path", "https://a.example.com/other.json"),+ ]+ )+ def test_distinct_documents_stay_distinct(self, _name, other):+ self.assertNotEqual(normalize_cimd_url(other), normalize_cimd_url("https://a.example.com/cimd.json"))++ @parameterized.expand(+ [+ ("non_numeric_port", "https://a.example.com:abc/cimd.json"),+ ("out_of_range_port", "https://a.example.com:99999/cimd.json"),+ # urlparse() itself raises "Invalid IPv6 URL" here, not just the .port accessor —+ # the case that reached _token_is_bound_to_url as an uncaught 500 on /authorize.+ ("invalid_ipv6_literal", "https://[::1/x.json"),+ ]+ )+ def test_unparseable_url_returns_sentinel_instead_of_raising(self, _name, raw):+ self.assertEqual(normalize_cimd_url(raw), UNNORMALIZABLE_CIMD_URL)diff --git a/posthog/test/test_migration_1296.py b/posthog/test/test_migration_1296.pynew file mode 100644index 000000000000..5627c3b16efb--- /dev/null+++ b/posthog/test/test_migration_1296.py@@ -0,0 +1,150 @@+from datetime import timedelta+from typing import Any++from posthog.test.base import TestMigrations++from django.utils import timezone++from parameterized import parameterized+++class BackfillCimdVerificationTokenUrlMigrationTest(TestMigrations):+ migrate_from = "1295_cimdverificationtoken_cimd_url"+ migrate_to = "1296_backfill_cimd_verification_token_url"++ CLASS_DATA_LEVEL_SETUP = False++ def setUpBeforeMigration(self, apps: Any) -> None:+ Organization = apps.get_model("posthog", "Organization")+ OAuthApplication = apps.get_model("posthog", "OAuthApplication")+ CIMDVerificationToken = apps.get_model("posthog", "CIMDVerificationToken")+ self.CIMDVerificationToken = CIMDVerificationToken++ base_time = timezone.now() - timedelta(days=30)++ # The historical model skips Organization.save's slug generation, so every org would+ # otherwise collide on the unique empty slug.+ def make_org(slug: str) -> Any:+ return Organization.objects.create(name=f"Org {slug}", slug=slug)++ def make_app(slug: str, org: Any, url: str, created: Any = base_time) -> Any:+ app = OAuthApplication.objects.create(+ name=f"App {slug}",+ client_id=f"client-{slug}",+ client_secret="",+ client_type="confidential",+ authorization_grant_type="authorization-code",+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=org,+ is_cimd_client=True,+ cimd_metadata_url=url,+ )+ # `created` is auto_now_add, so the value passed to create() above is+ # discarded on INSERT; .update() bypasses pre_save and lands it for real.+ OAuthApplication.objects.filter(pk=app.pk).update(created=created)+ return app++ def make_token(+ slug: str,+ org: Any,+ created_at: Any = base_time - timedelta(days=1),+ last_used_at: Any = base_time,+ cimd_url: str | None = None,+ ) -> Any:+ return CIMDVerificationToken.objects.create(+ organization=org,+ label=slug,+ secure_value=f"secure-{slug}",+ mask_value="x" * 11,+ created_at=created_at,+ last_used_at=last_used_at,+ cimd_url=cimd_url,+ )++ self.tokens: dict[str, Any] = {}++ # Unambiguous: one verified app, one corroborated token.+ org_happy = make_org("happy")+ make_app("happy", org_happy, "https://happy.example.com/.well-known/oauth-client-metadata.json")+ self.tokens["happy"] = make_token("happy", org_happy)++ # Two tokens on the org: can't tell which one verified the app.+ org_two_tokens = make_org("two-tokens")+ make_app("two-tokens", org_two_tokens, "https://two-tokens.example.com/.well-known/oauth-client-metadata.json")+ self.tokens["two_tokens_1"] = make_token("two-tokens-1", org_two_tokens)+ self.tokens["two_tokens_2"] = make_token("two-tokens-2", org_two_tokens)++ # Two apps at different URLs: ambiguous which one the token belongs to.+ org_diff_urls = make_org("diff-urls")+ make_app("diff-urls-1", org_diff_urls, "https://diff-urls-1.example.com/.well-known/oauth-client-metadata.json")+ make_app("diff-urls-2", org_diff_urls, "https://diff-urls-2.example.com/.well-known/oauth-client-metadata.json")+ self.tokens["diff_urls"] = make_token("diff-urls", org_diff_urls)++ # Two apps whose URLs differ only in spelling: cimd_metadata_url is unique, so this+ # is the only way two rows can name one document. They agree, so it is not ambiguous.+ org_same_url = make_org("same-url")+ make_app("same-url-1", org_same_url, "https://same-url.example.com/.well-known/oauth-client-metadata.json")+ make_app("same-url-2", org_same_url, "https://SAME-URL.example.com:443/.well-known/oauth-client-metadata.json")+ self.tokens["same_url"] = make_token("same-url", org_same_url)++ # Token never verified anything: no claim to any URL.+ org_never_used = make_org("never-used")+ make_app("never-used", org_never_used, "https://never-used.example.com/.well-known/oauth-client-metadata.json")+ self.tokens["never_used"] = make_token("never-used", org_never_used, last_used_at=None)++ # Token issued after the app self-registered, which is the ordinary sequence and+ # must still backfill.+ org_created_after = make_org("created-after")+ make_app(+ "created-after",+ org_created_after,+ "https://created-after.example.com/.well-known/oauth-client-metadata.json",+ )+ self.tokens["created_after_app"] = make_token(+ "created-after",+ org_created_after,+ created_at=base_time + timedelta(days=1),+ last_used_at=base_time + timedelta(days=2),+ )++ # Token already carries a deliberately-set cimd_url: replay must not clobber it.+ org_already_bound = make_org("already-bound")+ make_app(+ "already-bound",+ org_already_bound,+ "https://already-bound-app.example.com/.well-known/oauth-client-metadata.json",+ )+ self.tokens["already_bound"] = make_token(+ "already-bound", org_already_bound, cimd_url="https://already-bound.example.com/manual"+ )++ # App URL carries an explicit :443 that normalization must strip.+ org_port = make_org("port-443")+ make_app("port-443", org_port, "https://port-443.example.com:443/.well-known/oauth-client-metadata.json")+ self.tokens["port_443"] = make_token("port-443", org_port)++ # App URL carries a trailing slash that normalization must strip.+ org_slash = make_org("trailing-slash")+ make_app(+ "trailing-slash", org_slash, "https://trailing-slash.example.com/.well-known/oauth-client-metadata.json/"+ )+ self.tokens["trailing_slash"] = make_token("trailing-slash", org_slash)++ @parameterized.expand(+ [+ ("happy", "https://happy.example.com/.well-known/oauth-client-metadata.json"),+ ("two_tokens_1", None),+ ("two_tokens_2", None),+ ("diff_urls", None),+ ("same_url", "https://same-url.example.com/.well-known/oauth-client-metadata.json"),+ ("never_used", None),+ ("created_after_app", "https://created-after.example.com/.well-known/oauth-client-metadata.json"),+ ("already_bound", "https://already-bound.example.com/manual"),+ ("port_443", "https://port-443.example.com/.well-known/oauth-client-metadata.json"),+ ("trailing_slash", "https://trailing-slash.example.com/.well-known/oauth-client-metadata.json"),+ ]+ )+ def test_backfill_outcome(self, token_key: str, expected_cimd_url: str | None) -> None:+ token = self.CIMDVerificationToken.objects.get(pk=self.tokens[token_key].pk)+ assert token.cimd_url == expected_cimd_urldiff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex df39e4d492ba..abc945d0f0d1 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -43,6 +43,9 @@ tools:cimd-verification-tokens-list:operation: cimd_verification_tokens_listenabled: false+ cimd-verification-tokens-partial-update:+ operation: cimd_verification_tokens_partial_update+ enabled: falsecimd-verification-tokens-retrieve:operation: cimd_verification_tokens_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2ce07cccaf43..0f1545fd02e0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13275,10 +13275,20 @@ export namespace Schemas {truncated: boolean;}+ /**+ * Read shape for list/retrieve/create-response. `cimd_url` is nullable here for+ * tokens issued before URL binding; the write serializers below require a value.+ */export interface CIMDVerificationToken {readonly id: string;- /** @maxLength 40 */- label: string;+ /** Human-readable name to identify this token later, e.g. 'Production CIMD partner'. */+ readonly label: string;+ /**+ * HTTPS URL of the CIMD metadata document this token verifies at. Null on tokens issued before URL binding; those no longer verify until bound via PATCH or reissued.+ * @maxLength 2048+ * @nullable+ */+ readonly cimd_url: string | null;/** @nullable */readonly mask_value: string | null;readonly created_by: UserBasic;@@ -13287,6 +13297,23 @@ export namespace Schemas {readonly last_used_at: string | null;}+ /**+ * Write shape for `create`. `cimd_url` is required and non-null: only tokens+ * issued before URL binding existed are nullable, not new ones.+ */+ export interface CIMDVerificationTokenCreate {+ /**+ * Human-readable name to identify this token later, e.g. 'Production CIMD partner'.+ * @maxLength 40+ */+ label: string;+ /**+ * HTTPS URL of the CIMD metadata document this token will be published in. The token only verifies at this URL, so a copy hosted anywhere else is rejected. Host case, an explicit :443 and a trailing slash are normalized away; the path is case-sensitive.+ * @maxLength 2048+ */+ cimd_url: string;+ }+/*** Create-response variant that includes the plaintext token.*@@ -13295,8 +13322,14 @@ export namespace Schemas {*/export interface CIMDVerificationTokenWithValue {readonly id: string;- /** @maxLength 40 */- label: string;+ /** Human-readable name to identify this token later, e.g. 'Production CIMD partner'. */+ readonly label: string;+ /**+ * HTTPS URL of the CIMD metadata document this token verifies at. Null on tokens issued before URL binding; those no longer verify until bound via PATCH or reissued.+ * @maxLength 2048+ * @nullable+ */+ readonly cimd_url: string | null;/** @nullable */readonly mask_value: string | null;readonly created_by: UserBasic;@@ -52087,6 +52120,19 @@ export namespace Schemas {readonly updated_at?: string | null;}+ /**+ * Write shape for `partial_update` (PATCH). Exposes only `cimd_url`, and only ever+ * performs a null -> value transition: `validate` rejects any instance whose `cimd_url`+ * is already set, so an existing binding can never be re-pointed through this endpoint.+ */+ export interface PatchedCIMDVerificationTokenUpdate {+ /**+ * HTTPS URL of the CIMD metadata document to bind this token to. Only settable once, on a token with no existing binding; an already-bound token must be reissued instead.+ * @maxLength 2048+ */+ cimd_url?: string;+ }+/*** Writable canvas fields: metadata only — source changes go through publish/edit.*/