Skip to content

: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.

feat(provisioning): cimd verification tokens for partner-org linking (#55620)

Matt Brooker5e7c6f905b10
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index f032319ed9f2..bc6c82eb6421 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -169,6 +169,9 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"ExplicitTeamMembership",
# --- Other internal (no user-facing lookup by ID) ---
"AlertCheck",
+ # Global CIMD URL blocklist - queried by `cimd_url` (unique), never by user-supplied ID.
+ # `created_by` is for audit only.
+ "CIMDBlocklistEntry",
"CohortCalculationHistory",
"ColumnConfiguration",
"DataDeletionRequest",
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 9ef2470bc506..f03adde582ce 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -511,7 +511,8 @@ rules:
metavariable: $MODEL
regex: |
(?x)(
- LegalDocument
+ CIMDVerificationToken
+ |LegalDocument
|OrganizationMembership
|OrganizationDomain
|OrganizationIntegration
@@ -574,7 +575,8 @@ rules:
metavariable: $MODEL
regex: |
(?x)(
- LegalDocument
+ CIMDVerificationToken
+ |LegalDocument
|OrganizationMembership
|OrganizationDomain
|OrganizationIntegration
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index 6fd86e4215a2..3dd9fd3cc00c 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -3,7 +3,9 @@ from __future__ import annotations
import hmac
import time
import uuid
+import hashlib
+from django.core.cache import cache
from django.utils import timezone
import structlog
@@ -13,7 +15,7 @@ from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import Request
from posthog.api.oauth.cimd import (
- CIMD_PROVISIONING_DEFAULTS,
+ apply_provisioning_defaults,
get_application_by_client_id,
is_cimd_client_id,
is_cimd_registration_in_progress,
@@ -147,9 +149,7 @@ class ProvisioningAuthentication(BaseAuthentication):
if app is not None:
try:
if not app.is_provisioning_partner:
- for field, value in CIMD_PROVISIONING_DEFAULTS.items():
- setattr(app, field, value)
- app.save(update_fields=list(CIMD_PROVISIONING_DEFAULTS.keys()))
+ apply_provisioning_defaults(app)
except Exception as e:
logger.warning(
"provisioning_cimd_backfill_error",
@@ -164,9 +164,13 @@ class ProvisioningAuthentication(BaseAuthentication):
return None
return app if app.provisioning_active else None
- # New CIMD URL: kick off background registration, don't block the worker
+ # New CIMD URL: kick off background registration, don't block the worker.
+ # cache.add is atomic - coalesces concurrent first-time requests so only
+ # one gets to enqueue until the worker's own fetch lock takes over.
if not is_cimd_registration_in_progress(client_id):
- register_cimd_provisioning_application_task.delay(client_id)
+ enqueue_key = f"cimd:enqueued:{hashlib.sha256(client_id.encode()).hexdigest()}"
+ if cache.add(enqueue_key, True, timeout=30):
+ register_cimd_provisioning_application_task.delay(client_id)
self.cimd_registration_pending = True
return None
diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
index 81cde5858e3a..d9cf9113dc53 100644
--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py
+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
@@ -755,11 +755,8 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
cimd_metadata_url=CIMD_PROV_URL,
)
with patch(
- "ee.api.agentic_provisioning.authentication.CIMD_PROVISIONING_DEFAULTS",
- new_callable=lambda: MagicMock(
- items=MagicMock(side_effect=RuntimeError("simulated DB error")),
- keys=MagicMock(return_value=[]),
- ),
+ "ee.api.agentic_provisioning.authentication.apply_provisioning_defaults",
+ side_effect=RuntimeError("simulated DB error"),
):
_, challenge = _pkce_pair()
res = self.client.post(
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 1a8d3fc8a9d5..2d7b460fc2d2 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -82,6 +82,106 @@ export interface PaginatedSubscriptionDeliveryListApi {
results: SubscriptionDeliveryApi[]
}
+/**
+ * * `engineering` - Engineering
+ * `data` - Data
+ * `product` - Product Management
+ * `founder` - Founder
+ * `leadership` - Leadership
+ * `marketing` - Marketing
+ * `sales` - Sales / Success
+ * `other` - Other
+ */
+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
+
+export const RoleAtOrganizationEnumApi = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Other: 'other',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+export type NullEnumApi = (typeof NullEnumApi)[keyof typeof NullEnumApi]
+
+export const NullEnumApi = {} as const
+
+/**
+ * @nullable
+ */
+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null | null
+
+export interface UserBasicApi {
+ readonly id: number
+ readonly uuid: string
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null
+ /** @maxLength 150 */
+ first_name?: string
+ /** @maxLength 150 */
+ last_name?: string
+ /** @maxLength 254 */
+ email: string
+ /** @nullable */
+ is_email_verified?: boolean | null
+ /** @nullable */
+ readonly hedgehog_config: UserBasicApiHedgehogConfig
+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | NullEnumApi | null
+}
+
+export interface CIMDVerificationTokenApi {
+ readonly id: string
+ /** @maxLength 40 */
+ label: string
+ /** @nullable */
+ readonly mask_value: string | null
+ readonly created_by: UserBasicApi
+ readonly created_at: string
+ /** @nullable */
+ readonly last_used_at: string | null
+}
+
+export interface PaginatedCIMDVerificationTokenListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: CIMDVerificationTokenApi[]
+}
+
+/**
+ * Create-response variant that includes the plaintext token.
+
+Only emitted from the create endpoint - storage-side we only persist the
+hash, so subsequent reads use the base serializer.
+ */
+export interface CIMDVerificationTokenWithValueApi {
+ readonly id: string
+ /** @maxLength 40 */
+ label: string
+ /** @nullable */
+ readonly mask_value: string | null
+ readonly created_by: UserBasicApi
+ readonly created_at: string
+ /** @nullable */
+ readonly last_used_at: string | null
+ /** Plaintext token, only returned on creation */
+ readonly value: string
+}
+
export interface OrganizationDomainApi {
readonly id: string
/** @maxLength 128 */
@@ -175,65 +275,6 @@ export const OrganizationMembershipLevelEnumApi = {
Number15: 15,
} as const
-/**
- * * `engineering` - Engineering
- * `data` - Data
- * `product` - Product Management
- * `founder` - Founder
- * `leadership` - Leadership
- * `marketing` - Marketing
- * `sales` - Sales / Success
- * `other` - Other
- */
-export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
-
-export const RoleAtOrganizationEnumApi = {
- Engineering: 'engineering',
- Data: 'data',
- Product: 'product',
- Founder: 'founder',
- Leadership: 'leadership',
- Marketing: 'marketing',
- Sales: 'sales',
- Other: 'other',
-} as const
-
-export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
-
-export const BlankEnumApi = {
- '': '',
-} as const
-
-export type NullEnumApi = (typeof NullEnumApi)[keyof typeof NullEnumApi]
-
-export const NullEnumApi = {} as const
-
-/**
- * @nullable
- */
-export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null | null
-
-export interface UserBasicApi {
- readonly id: number
- readonly uuid: string
- /**
- * @maxLength 200
- * @nullable
- */
- distinct_id?: string | null
- /** @maxLength 150 */
- first_name?: string
- /** @maxLength 150 */
- last_name?: string
- /** @maxLength 254 */
- email: string
- /** @nullable */
- is_email_verified?: boolean | null
- /** @nullable */
- readonly hedgehog_config: UserBasicApiHedgehogConfig
- role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | NullEnumApi | null
-}
-
export interface OrganizationInviteApi {
readonly id: string
/** @maxLength 254 */
@@ -3211,6 +3252,17 @@ export const SubscriptionsDeliveriesListStatus = {
Starting: 'starting',
} as const
+export type CimdVerificationTokensListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type DomainsListParams = {
/**
* Number of results to return per page.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 5d8810119d0d..1535457dc064 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -11,6 +11,9 @@ import { apiMutator } from '../../lib/api-orval-mutator'
import type {
BulkUpdateTagsRequestApi,
BulkUpdateTagsResponseApi,
+ CIMDVerificationTokenApi,
+ CIMDVerificationTokenWithValueApi,
+ CimdVerificationTokensListParams,
DashboardTemplateApi,
DomainsListParams,
EnterprisePropertyDefinitionApi,
@@ -27,6 +30,7 @@ import type {
OrganizationInviteApi,
OrganizationInviteDelegateApi,
OrganizationsProjectsListParams,
+ PaginatedCIMDVerificationTokenListApi,
PaginatedEnterprisePropertyDefinitionListApi,
PaginatedExportedAssetListApi,
PaginatedFileSystemListApi,
@@ -136,6 +140,120 @@ export const subscriptionsDeliveriesRetrieve = async (
})
}
+/**
+ * Manage CIMD verification tokens for an organization.
+
+A partner embeds the plaintext token in their CIMD metadata document under
+`posthog_verification_token`. 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.
+
+The plaintext value is only available on creation; we store a hash.
+ */
+export const getCimdVerificationTokensListUrl = (organizationId: string, params?: CimdVerificationTokensListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/organizations/${organizationId}/cimd_verification_tokens/?${stringifiedParams}`
+ : `/api/organizations/${organizationId}/cimd_verification_tokens/`
+}
+
+export const cimdVerificationTokensList = async (
+ organizationId: string,
+ params?: CimdVerificationTokensListParams,
+ options?: RequestInit
+): Promise<PaginatedCIMDVerificationTokenListApi> => {
+ return apiMutator<PaginatedCIMDVerificationTokenListApi>(getCimdVerificationTokensListUrl(organizationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+/**
+ * Manage CIMD verification tokens for an organization.
+
+A partner embeds the plaintext token in their CIMD metadata document under
+`posthog_verification_token`. 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.
+
+The plaintext value is only available on creation; we store a hash.
+ */
+export const getCimdVerificationTokensCreateUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/cimd_verification_tokens/`
+}
+
+export const cimdVerificationTokensCreate = async (
+ organizationId: string,
+ cIMDVerificationTokenApi: NonReadonly<CIMDVerificationTokenApi>,
+ options?: RequestInit
+): Promise<CIMDVerificationTokenWithValueApi> => {
+ return apiMutator<CIMDVerificationTokenWithValueApi>(getCimdVerificationTokensCreateUrl(organizationId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(cIMDVerificationTokenApi),
+ })
+}
+
+/**
+ * Manage CIMD verification tokens for an organization.
+
+A partner embeds the plaintext token in their CIMD metadata document under
+`posthog_verification_token`. 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.
+
+The plaintext value is only available on creation; we store a hash.
+ */
+export const getCimdVerificationTokensRetrieveUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/cimd_verification_tokens/${id}/`
+}
+
+export const cimdVerificationTokensRetrieve = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CIMDVerificationTokenApi> => {
+ return apiMutator<CIMDVerificationTokenApi>(getCimdVerificationTokensRetrieveUrl(organizationId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+/**
+ * Manage CIMD verification tokens for an organization.
+
+A partner embeds the plaintext token in their CIMD metadata document under
+`posthog_verification_token`. 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.
+
+The plaintext value is only available on creation; we store a hash.
+ */
+export const getCimdVerificationTokensDestroyUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/cimd_verification_tokens/${id}/`
+}
+
+export const cimdVerificationTokensDestroy = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getCimdVerificationTokensDestroyUrl(organizationId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getDomainsListUrl = (organizationId: string, params?: DomainsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 42715821dece..620bdbc93031 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -9,6 +9,22 @@
*/
import * as zod from 'zod'
+/**
+ * Manage CIMD verification tokens for an organization.
+
+A partner embeds the plaintext token in their CIMD metadata document under
+`posthog_verification_token`. 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.
+
+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 domainsCreateBodyDomainMax = 128
export const domainsCreateBodySsoEnforcementMax = 28
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index e3aaeb13bc69..d29e3f98f296 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -124,6 +124,7 @@ import { WebAnalyticsEnablePreAggregatedTables } from './environment/WebAnalytic
import { AIHipaaDisclaimer, getExternalAIProvidersTooltipTitle } from './organization/aiConsentCopy'
import { ApprovalPolicies } from './organization/Approvals/ApprovalPolicies'
import { ChangeRequestsList } from './organization/Approvals/ChangeRequestsList'
+import { CIMDVerificationTokens } from './organization/CIMDVerificationTokens'
import { Invites } from './organization/Invites'
import { Members } from './organization/Members'
import { OAuthApps } from './organization/OAuthApps'
@@ -1586,6 +1587,20 @@ export const SETTINGS_MAP: SettingSection[] = [
},
],
},
+ {
+ level: 'organization',
+ id: 'organization-cimd-verification-tokens',
+ title: 'CIMD verification tokens',
+ settings: [
+ {
+ id: 'organization-cimd-verification-tokens-list',
+ title: 'CIMD verification tokens',
+ description: 'Link CIMD partner applications to this organization for higher rate limits and identity.',
+ component: <CIMDVerificationTokens />,
+ keywords: ['cimd', 'oauth', 'partner', 'provisioning', 'verification', 'token', 'api', 'rate limit'],
+ },
+ ],
+ },
{
level: 'organization',
id: 'organization-proxy',
diff --git a/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx b/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx
new file mode 100644
index 000000000000..8b70689280a5
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/CIMDVerificationTokens.tsx
@@ -0,0 +1,176 @@
+import { useActions, useValues } from 'kea'
+
+import { IconTrash } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonInput, LemonModal, LemonTable, 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'
+
+import { cimdVerificationTokensLogic, 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)
+
+ return (
+ <div className="space-y-4">
+ <p className="text-secondary">
+ Verification tokens link a CIMD partner application to this organization. Add the token to your CIMD
+ metadata document under <code>posthog_verification_token</code>. Verified partners get a higher default
+ rate limit for account provisioning and a clear identity trail. See the{' '}
+ <Link
+ to="https://posthog.com/docs/integrate/provisioning#host-a-cimd-metadata-document"
+ target="_blank"
+ >
+ docs
+ </Link>{' '}
+ for the metadata format.
+ </p>
+
+ <div className="flex justify-end">
+ <LemonButton type="primary" onClick={showCreateDialog} data-attr="create-cimd-verification-token">
+ Create verification token
+ </LemonButton>
+ </div>
+
+ {!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" />
+ <h3 className="text-base font-semibold mb-1">No verification tokens</h3>
+ <p className="text-secondary">Create one to link a CIMD partner app to this organization.</p>
+ </div>
+ ) : (
+ <LemonTable
+ loading={tokensLoading}
+ dataSource={tokens}
+ columns={[
+ {
+ title: 'Label',
+ key: 'label',
+ render: (_, row: CIMDVerificationToken) => (
+ <span className="font-semibold">{row.label}</span>
+ ),
+ },
+ {
+ title: 'Token',
+ key: 'mask_value',
+ render: (_, row: CIMDVerificationToken) => (
+ <code className="text-xs bg-fill-primary rounded px-1.5 py-0.5 font-mono">
+ {row.mask_value ?? '—'}
+ </code>
+ ),
+ },
+ {
+ title: 'Created',
+ key: 'created_at',
+ render: (_, row: CIMDVerificationToken) => (
+ <span className="text-muted text-sm">{humanFriendlyDetailedTime(row.created_at)}</span>
+ ),
+ },
+ {
+ title: 'Last used',
+ key: 'last_used_at',
+ render: (_, row: CIMDVerificationToken) => (
+ <span className="text-muted text-sm">
+ {row.last_used_at ? humanFriendlyDetailedTime(row.last_used_at) : 'Never'}
+ </span>
+ ),
+ },
+ {
+ title: '',
+ 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' },
+ })
+ }
+ />
+ ),
+ },
+ ]}
+ />
+ )}
+
+ <LemonModal
+ isOpen={isCreateDialogOpen}
+ onClose={hideCreateDialog}
+ title="Create CIMD verification token"
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={hideCreateDialog}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={() => createToken()}
+ disabledReason={!newTokenLabel.trim() ? 'Please enter a label' : undefined}
+ data-attr="confirm-create-cimd-verification-token"
+ >
+ Create token
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="space-y-2">
+ <label className="text-sm font-semibold" htmlFor="cimd-token-label">
+ Label
+ </label>
+ <LemonInput
+ id="cimd-token-label"
+ placeholder="e.g. Production CIMD partner"
+ value={newTokenLabel}
+ onChange={setNewTokenLabel}
+ autoFocus
+ />
+ <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>
+ </div>
+ </LemonModal>
+
+ <LemonModal
+ isOpen={!!justCreatedToken}
+ onClose={() => setJustCreatedToken(null)}
+ closable={false}
+ title="Token created"
+ footer={
+ <LemonButton type="primary" onClick={() => setJustCreatedToken(null)}>
+ Done
+ </LemonButton>
+ }
+ >
+ {justCreatedToken && (
+ <div className="space-y-3">
+ <LemonBanner type="warning">
+ Copy this token now - you won't be able to see it again. If you lose it, you'll need to
+ revoke and create a new one.
+ </LemonBanner>
+ <p className="text-secondary">
+ Add it to your CIMD metadata document as the <code>posthog_verification_token</code> field.
+ </p>
+ <CodeSnippet language={Language.Text}>{justCreatedToken.value}</CodeSnippet>
+ </div>
+ )}
+ </LemonModal>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/cimdVerificationTokensLogic.ts b/frontend/src/scenes/settings/organization/cimdVerificationTokensLogic.ts
new file mode 100644
index 000000000000..a322be68c14d
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/cimdVerificationTokensLogic.ts
@@ -0,0 +1,108 @@
+import { actions, afterMount, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import {
+ cimdVerificationTokensCreate,
+ cimdVerificationTokensDestroy,
+ cimdVerificationTokensList,
+} from '~/generated/core/api'
+import { CIMDVerificationTokenApi, CIMDVerificationTokenWithValueApi } from '~/generated/core/api.schemas'
+
+import type { cimdVerificationTokensLogicType } from './cimdVerificationTokensLogicType'
+
+export type CIMDVerificationToken = CIMDVerificationTokenApi
+export type CIMDVerificationTokenWithValue = CIMDVerificationTokenWithValueApi
+
+export const cimdVerificationTokensLogic = kea<cimdVerificationTokensLogicType>([
+ path(['scenes', 'settings', 'organization', 'cimdVerificationTokensLogic']),
+
+ actions({
+ showCreateDialog: true,
+ hideCreateDialog: true,
+ setNewTokenLabel: (label: string) => ({ label }),
+ setJustCreatedToken: (token: CIMDVerificationTokenWithValue | null) => ({ token }),
+ createToken: true,
+ deleteToken: (token: CIMDVerificationToken) => ({ token }),
+ }),
+
+ reducers({
+ isCreateDialogOpen: [
+ false,
+ {
+ showCreateDialog: () => true,
+ hideCreateDialog: () => false,
+ },
+ ],
+ newTokenLabel: [
+ '',
+ {
+ setNewTokenLabel: (_, { label }) => label,
+ hideCreateDialog: () => '',
+ },
+ ],
+ justCreatedToken: [
+ null as CIMDVerificationTokenWithValue | null,
+ {
+ setJustCreatedToken: (_, { token }) => token,
+ },
+ ],
+ }),
+
+ loaders({
+ tokens: [
+ [] as CIMDVerificationToken[],
+ {
+ loadTokens: async () => {
+ const orgId = organizationLogic.values.currentOrganization?.id
+ if (!orgId) {
+ return []
+ }
+ const response = await cimdVerificationTokensList(orgId)
+ return response.results
+ },
+ },
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ createToken: async () => {
+ const orgId = organizationLogic.values.currentOrganization?.id
+ if (!orgId) {
+ return
+ }
+ const label = values.newTokenLabel.trim()
+ if (!label) {
+ lemonToast.error('Please enter a label for this token.')
+ return
+ }
+ try {
+ const created = await cimdVerificationTokensCreate(orgId, { label })
+ actions.setJustCreatedToken(created)
+ actions.hideCreateDialog()
+ actions.loadTokens()
+ } catch (e: any) {
+ lemonToast.error(e?.detail || 'Failed to create token')
+ }
+ },
+ deleteToken: async ({ token }) => {
+ const orgId = organizationLogic.values.currentOrganization?.id
+ if (!orgId) {
+ return
+ }
+ try {
+ await cimdVerificationTokensDestroy(orgId, token.id)
+ lemonToast.success('Token revoked')
+ actions.loadTokens()
+ } catch (e: any) {
+ lemonToast.error(e?.detail || 'Failed to revoke token')
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadTokens()
+ }),
+])
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 6d71445cbdf2..a578712f73fd 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -55,6 +55,7 @@ export type SettingSectionId =
| 'organization-details'
| 'organization-integrations'
| 'organization-oauth-apps'
+ | 'organization-cimd-verification-tokens'
| 'organization-members'
| 'organization-roles'
| 'organization-authentication'
@@ -152,6 +153,7 @@ export type SettingId =
| 'organization-display-name'
| 'organization-integrations-list'
| 'organization-oauth-apps-list'
+ | 'organization-cimd-verification-tokens-list'
| 'invites'
| 'members'
| 'authentication-domains'
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index d9e09452874c..926348da215c 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -132,6 +132,7 @@ from . import (
annotation,
async_migration,
authentication,
+ cimd_verification_token,
cli_auth,
comments,
dead_letter_queue,
@@ -678,6 +679,12 @@ organizations_router.register(
"organization_domains",
["organization_id"],
)
+organizations_router.register(
+ r"cimd_verification_tokens",
+ cimd_verification_token.CIMDVerificationTokenViewSet,
+ "organization_cimd_verification_tokens",
+ ["organization_id"],
+)
organizations_router.register(
r"legal_documents",
legal_documents.LegalDocumentViewSet,
diff --git a/posthog/api/cimd_verification_token.py b/posthog/api/cimd_verification_token.py
new file mode 100644
index 000000000000..a0cf129ebae0
--- /dev/null
+++ b/posthog/api/cimd_verification_token.py
@@ -0,0 +1,143 @@
+from typing import Any
+
+from django.core.cache import cache
+from django.views.decorators.debug import sensitive_variables
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import mixins, serializers, viewsets
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+from posthog.models.activity_logging.activity_log import Detail, log_activity
+from posthog.models.oauth import CIMDVerificationToken, OAuthApplication, create_cimd_verification_token
+from posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermission
+
+
+class CIMDVerificationTokenSerializer(serializers.ModelSerializer):
+ created_by = UserBasicSerializer(read_only=True)
+
+ class Meta:
+ model = CIMDVerificationToken
+ fields = [
+ "id",
+ "label",
+ "mask_value",
+ "created_by",
+ "created_at",
+ "last_used_at",
+ ]
+ read_only_fields = [
+ "id",
+ "mask_value",
+ "created_by",
+ "created_at",
+ "last_used_at",
+ ]
+
+ def validate_label(self, value: str) -> str:
+ value = value.strip()
+ if not value:
+ raise serializers.ValidationError("Label cannot be empty.")
+ return value
+
+
+class CIMDVerificationTokenWithValueSerializer(CIMDVerificationTokenSerializer):
+ """Create-response variant that includes the plaintext token.
+
+ Only emitted from the create endpoint - storage-side we only persist the
+ hash, so subsequent reads use the base serializer.
+ """
+
+ value = serializers.CharField(read_only=True, help_text="Plaintext token, only returned on creation")
+
+ class Meta(CIMDVerificationTokenSerializer.Meta):
+ fields = [*CIMDVerificationTokenSerializer.Meta.fields, "value"]
+ read_only_fields = [*CIMDVerificationTokenSerializer.Meta.read_only_fields, "value"]
+
+
+@extend_schema(tags=["core"])
+class CIMDVerificationTokenViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.CreateModelMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.DestroyModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Manage CIMD verification tokens for an organization.
+
+ A partner embeds the plaintext token in their CIMD metadata document under
+ `posthog_verification_token`. 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.
+
+ The plaintext value is only available on creation; we store a hash.
+ """
+
+ scope_object = "organization"
+ permission_classes = [OrganizationAdminWritePermissions, TimeSensitiveActionPermission]
+ queryset = CIMDVerificationToken.objects.select_related("created_by").order_by("-created_at")
+ serializer_class = CIMDVerificationTokenSerializer
+
+ def safely_get_queryset(self, queryset):
+ return queryset.filter(organization_id=self.organization_id)
+
+ @extend_schema(responses={201: CIMDVerificationTokenWithValueSerializer})
+ @sensitive_variables("plaintext", "output")
+ def create(self, request, *args: Any, **kwargs: Any) -> Response:
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ token, plaintext = create_cimd_verification_token(
+ organization=self.organization,
+ label=serializer.validated_data["label"],
+ created_by=request.user if request.user.is_authenticated else None,
+ )
+ token.value = plaintext # type: ignore[attr-defined]
+ output = CIMDVerificationTokenWithValueSerializer(token).data
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=None,
+ user=request.user if request.user.is_authenticated else None,
+ was_impersonated=getattr(request, "impersonated_session", False),
+ item_id=str(token.id),
+ scope="CIMDVerificationToken",
+ activity="created",
+ detail=Detail(name=token.label),
+ )
+ return Response(output, status=201)
+
+ def perform_destroy(self, instance: CIMDVerificationToken) -> None:
+ org_id = instance.organization_id
+ label = instance.label
+ token_id = str(instance.id)
+ instance.delete()
+
+ # Force metadata re-fetch for CIMD partner apps linked to this org so
+ # verification is re-evaluated on the next request. If another token on
+ # this org still matches the metadata, the app stays linked; otherwise
+ # it drops back to the unverified tier on next fetch. This matches the
+ # 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,
+ cimd_metadata_url__isnull=False,
+ ).values_list("cimd_metadata_url", flat=True):
+ if url:
+ cache.delete(_cache_key(url))
+
+ request = self.request
+ log_activity(
+ organization_id=org_id,
+ team_id=None,
+ user=request.user if request.user.is_authenticated else None,
+ was_impersonated=getattr(request, "impersonated_session", False),
+ item_id=token_id,
+ scope="CIMDVerificationToken",
+ activity="deleted",
+ detail=Detail(name=label),
+ )
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index bd481aa01d3f..b30a2849b1e7 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -27,7 +27,12 @@ from oauth2_provider.models import AbstractApplication
from rest_framework.throttling import SimpleRateThrottle
from posthog.exceptions_capture import capture_exception
-from posthog.models.oauth import OAuthApplication
+from posthog.models.oauth import (
+ CIMDBlocklistEntry,
+ CIMDVerificationToken,
+ OAuthApplication,
+ find_cimd_verification_token,
+)
from posthog.ph_client import ph_scoped_capture
from posthog.rate_limit import IPThrottle
from posthog.security.url_validation import is_url_allowed
@@ -96,6 +101,10 @@ class CIMDMetadataDocument(TypedDict, total=False):
grant_types: list[str]
response_types: list[str]
token_endpoint_auth_method: str
+ # Optional PostHog extension: if present, PostHog will look up the token
+ # and link this CIMD app to the owning organization. Verified partners get
+ # a higher default rate limit and an identity trail for abuse response.
+ posthog_verification_token: str
def validate_cimd_url(url: str | None, *, perform_dns_check: bool = False) -> tuple[bool, str | None]:
@@ -152,19 +161,34 @@ def _blocked_key(url: str) -> str:
return f"cimd:blocked:{url_hash}"
-def block_cimd_url(url: str, ttl: int = 86400 * 365) -> None:
- """Add a CIMD URL to the blocklist. Used by admin to prevent re-registration after deletion."""
+def block_cimd_url(url: str, *, reason: str = "", created_by=None, ttl: int = 86400 * 365) -> None:
+ """Add a CIMD URL to the blocklist. Persists in Postgres; Redis is cache."""
+ CIMDBlocklistEntry.objects.update_or_create(
+ cimd_url=url,
+ defaults={"reason": reason, "created_by": created_by},
+ )
cache.set(_blocked_key(url), True, timeout=ttl)
def unblock_cimd_url(url: str) -> None:
"""Remove a CIMD URL from the blocklist."""
+ CIMDBlocklistEntry.objects.filter(cimd_url=url).delete()
cache.delete(_blocked_key(url))
def is_cimd_url_blocked(url: str) -> bool:
- """Check if a CIMD URL has been blocklisted."""
- return bool(cache.get(_blocked_key(url)))
+ """Check if a CIMD URL has been blocklisted.
+
+ Postgres is source of truth; Redis is a read-through cache so the hot
+ path stays a single in-memory lookup. A cache miss falls back to a DB
+ read and re-warms the cache, so a Redis flush doesn't expose blocked
+ URLs."""
+ cached = cache.get(_blocked_key(url))
+ if cached is not None:
+ return bool(cached)
+ blocked = CIMDBlocklistEntry.objects.filter(cimd_url=url).exists()
+ cache.set(_blocked_key(url), blocked, timeout=86400 * 365)
+ return blocked
def _parse_cache_ttl(response: requests.Response) -> int:
@@ -286,6 +310,15 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:
return metadata, cache_ttl
+def _resolve_verification_token(metadata: CIMDMetadataDocument) -> CIMDVerificationToken | None:
+ """Look up a CIMD metadata `posthog_verification_token`. Returns the token
+ record (with its organization) on match, or None if missing or invalid."""
+ raw = metadata.get("posthog_verification_token")
+ if not raw or not isinstance(raw, str):
+ return None
+ return find_cimd_verification_token(raw)
+
+
def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthApplication:
"""Create a new OAuthApplication from CIMD metadata."""
client_name = metadata.get("client_name", "CIMD Client")
@@ -296,6 +329,7 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthA
redirect_uris = " ".join(metadata.get("redirect_uris", []))
logo_uri = metadata.get("logo_uri") or None
+ verification = _resolve_verification_token(metadata)
app = OAuthApplication(
name=client_name,
@@ -309,14 +343,28 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthA
cimd_metadata_url=url,
cimd_metadata_last_fetched=timezone.now(),
logo_uri=logo_uri,
- organization=None,
+ organization=verification.organization if verification else None,
user=None,
)
app.full_clean()
app.save()
+ if verification is not None:
+ _touch_verification_token(verification)
return app
+TOUCH_VERIFICATION_TOKEN_MIN_INTERVAL = 300 # 5 minutes
+
+
+def _touch_verification_token(token: CIMDVerificationToken) -> None:
+ # Bump last_used_at at most once per TOUCH_VERIFICATION_TOKEN_MIN_INTERVAL
+ # per token to avoid vacuum / lock-contention pressure on busy partners.
+ sentinel_key = f"cimd:token_touched:{token.pk}"
+ if not cache.add(sentinel_key, True, timeout=TOUCH_VERIFICATION_TOKEN_MIN_INTERVAL):
+ return
+ CIMDVerificationToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now())
+
+
def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocument) -> OAuthApplication:
"""
Update an existing OAuthApplication from refreshed CIMD metadata.
@@ -336,14 +384,66 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocume
app.logo_uri = new_uri if (new_uri := metadata.get("logo_uri")) is not None else app.logo_uri
app.cimd_metadata_last_fetched = timezone.now()
+ # Re-evaluate verification on every refresh so a rotated/removed token
+ # unlinks the app on the next fetch.
+ verification = _resolve_verification_token(metadata)
+ new_org = verification.organization if verification else None
+ update_fields = ["name", "redirect_uris", "logo_uri", "cimd_metadata_last_fetched"]
+ old_org_id = app.organization_id
+ new_org_id = new_org.id if new_org else None
+ if old_org_id != new_org_id:
+ app.organization = new_org
+ update_fields.append("organization")
+ # When verification status flips on an already-provisioning app, keep
+ # the rate-limit tier in sync. Only bump when the source is one of our
+ # default tiers — explicit admin overrides (source="admin") and
+ # legacy rows with no source recorded (source="") stay put. Legacy
+ # rows are treated conservatively as admin to avoid clobbering values
+ # that pre-date this field.
+ if app.is_provisioning_partner and app.provisioning_rate_limit_account_requests_source in (
+ "default_unverified",
+ "default_verified",
+ ):
+ became_verified = old_org_id is None and new_org_id is not None
+ became_unverified = old_org_id is not None and new_org_id is None
+ if became_verified:
+ app.provisioning_rate_limit_account_requests = CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT
+ app.provisioning_rate_limit_account_requests_source = "default_verified"
+ update_fields.extend(
+ ["provisioning_rate_limit_account_requests", "provisioning_rate_limit_account_requests_source"]
+ )
+ elif became_unverified:
+ app.provisioning_rate_limit_account_requests = CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT
+ app.provisioning_rate_limit_account_requests_source = "default_unverified"
+ update_fields.extend(
+ ["provisioning_rate_limit_account_requests", "provisioning_rate_limit_account_requests_source"]
+ )
+
try:
app.full_clean()
- app.save(update_fields=["name", "redirect_uris", "logo_uri", "cimd_metadata_last_fetched"])
+ app.save(update_fields=update_fields)
except ValidationError as e:
logger.warning("cimd_update_validation_failed", url=app.cimd_metadata_url, error=str(e))
capture_exception(e)
# Refresh from DB so we don't return a mutated-but-unsaved object
app.refresh_from_db()
+ else:
+ if verification is not None:
+ _touch_verification_token(verification)
+ # Emit a distinct event on org re-linking so a metadata compromise
+ # 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(
+ distinct_id=app.cimd_metadata_url or str(app.pk),
+ event="cimd_application_org_changed",
+ properties={
+ "cimd_url": app.cimd_metadata_url,
+ "app_id": str(app.pk),
+ "old_organization_id": str(old_org_id) if old_org_id else None,
+ "new_organization_id": str(new_org_id) if new_org_id else None,
+ },
+ )
return app
@@ -382,6 +482,8 @@ def fetch_and_upsert_cimd_application(url: str, capture_ph_event=posthoganalytic
"client_name": metadata.get("client_name"),
"app_id": str(updated.pk),
"cache_ttl": cache_ttl,
+ "is_verified": updated.organization_id is not None,
+ "organization_id": str(updated.organization_id) if updated.organization_id else None,
},
)
return updated
@@ -399,6 +501,9 @@ def fetch_and_upsert_cimd_application(url: str, capture_ph_event=posthoganalytic
"redirect_uris_count": len(metadata.get("redirect_uris", [])),
"has_logo": bool(metadata.get("logo_uri")),
"cache_ttl": cache_ttl,
+ "is_verified": new_app.organization_id is not None,
+ "organization_id": str(new_app.organization_id) if new_app.organization_id else None,
+ "had_verification_token_attempt": bool(metadata.get("posthog_verification_token")),
},
)
return new_app
@@ -432,9 +537,7 @@ def register_cimd_provisioning_application_task(url: str) -> None:
if app is None:
return
if not app.is_provisioning_partner:
- for field, value in CIMD_PROVISIONING_DEFAULTS.items():
- setattr(app, field, value)
- app.save(update_fields=list(CIMD_PROVISIONING_DEFAULTS.keys()))
+ apply_provisioning_defaults(app)
capture_ph_event(
distinct_id=url,
event="cimd_provisioning_partner_registered",
@@ -442,7 +545,9 @@ def register_cimd_provisioning_application_task(url: str) -> None:
"cimd_url": url,
"client_name": app.name,
"app_id": str(app.pk),
- "account_requests_rate_limit": CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,
+ "account_requests_rate_limit": app.provisioning_rate_limit_account_requests,
+ "is_verified": app.organization_id is not None,
+ "organization_id": str(app.organization_id) if app.organization_id else None,
},
)
except (CIMDFetchError, CIMDValidationError) as e:
@@ -500,8 +605,11 @@ def get_application_by_client_id(client_id: str) -> OAuthApplication:
# app is opted into provisioning at the same trust level as other PKCE partners.
# The account-request rate limit is set to a conservative floor so a single
# self-serve partner cannot burn through bulk user-onboarding calls — admin can
-# raise it per-partner once a partner demonstrates legitimate volume.
-CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT = 10 # per hour
+# raise it per-partner once a partner demonstrates legitimate volume. Verified
+# partners (those who presented a valid `posthog_verification_token`) get a
+# higher default since abuse is traceable to a real PostHog organization.
+CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT = 10 # per hour, anonymous CIMD
+CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT = 100 # per hour, verified CIMD
CIMD_PROVISIONING_DEFAULTS = {
"provisioning_auth_method": "pkce",
"provisioning_active": True,
@@ -511,6 +619,35 @@ CIMD_PROVISIONING_DEFAULTS = {
}
+def _cimd_provisioning_defaults_for(app: OAuthApplication) -> dict:
+ """Return the provisioning default profile to apply to this CIMD app on
+ first-time registration. Verified apps (linked to a PostHog org) get the
+ higher account-request rate limit."""
+ defaults = dict(CIMD_PROVISIONING_DEFAULTS)
+ if app.organization_id is not None:
+ defaults["provisioning_rate_limit_account_requests"] = CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT
+ defaults["provisioning_rate_limit_account_requests_source"] = "default_verified"
+ else:
+ defaults["provisioning_rate_limit_account_requests_source"] = "default_unverified"
+ return defaults
+
+
+def apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:
+ """Apply provisioning defaults to a CIMD app and persist them.
+
+ Computes the correct defaults (verified vs anonymous rate limit) based on
+ the app's organization linkage, sets the fields, and saves. Respects
+ `provisioning_disabled` as a kill switch - returns the app untouched
+ rather than re-enabling a partner an admin has explicitly disabled."""
+ if app.provisioning_disabled:
+ return app
+ defaults = _cimd_provisioning_defaults_for(app)
+ for field, value in defaults.items():
+ setattr(app, field, value)
+ app.save(update_fields=list(defaults.keys()))
+ return app
+
+
def get_or_create_cimd_provisioning_application(url: str) -> OAuthApplication | None:
"""
Resolve a CIMD URL to an OAuthApplication configured as a provisioning partner.
@@ -528,9 +665,7 @@ def get_or_create_cimd_provisioning_application(url: str) -> OAuthApplication |
app = get_or_create_cimd_application(url)
if not app.is_provisioning_partner:
- for field, value in CIMD_PROVISIONING_DEFAULTS.items():
- setattr(app, field, value)
- app.save(update_fields=list(CIMD_PROVISIONING_DEFAULTS.keys()))
+ apply_provisioning_defaults(app)
posthoganalytics.capture(
distinct_id=url,
event="cimd_provisioning_partner_registered",
@@ -538,7 +673,9 @@ def get_or_create_cimd_provisioning_application(url: str) -> OAuthApplication |
"cimd_url": url,
"client_name": app.name,
"app_id": str(app.pk),
- "account_requests_rate_limit": CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,
+ "account_requests_rate_limit": app.provisioning_rate_limit_account_requests,
+ "is_verified": app.organization_id is not None,
+ "organization_id": str(app.organization_id) if app.organization_id else None,
},
)
return app
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index 541b4f3a7495..a9f9e57ac1be 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -18,6 +18,7 @@ from rest_framework.test import APIClient
from posthog.api.oauth.cimd import (
CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,
+ CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT,
CIMDFetchError,
CIMDValidationError,
_fetch_lock_key,
@@ -30,7 +31,7 @@ from posthog.api.oauth.cimd import (
refresh_cimd_metadata_task,
validate_cimd_url,
)
-from posthog.models.oauth import OAuthApplication
+from posthog.models.oauth import OAuthApplication, create_cimd_verification_token
def generate_rsa_key() -> str:
@@ -548,6 +549,202 @@ class TestGetOrCreateCimdProvisioningApplication(APIBaseTest):
unblock_cimd_url(VALID_CIMD_URL)
+@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
+@override_settings(
+ OAUTH2_PROVIDER={
+ **settings.OAUTH2_PROVIDER,
+ "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
+ }
+)
+class TestCIMDVerificationToken(APIBaseTest):
+ @patch("posthog.api.oauth.cimd.requests.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
+ )
+ metadata = _make_metadata(posthog_verification_token=plaintext)
+ mock_get.return_value = _mock_response(metadata, headers={})
+
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert app is not None
+ self.assertEqual(app.organization_id, self.organization.id)
+ token.refresh_from_db()
+ self.assertIsNotNone(token.last_used_at)
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_invalid_verification_token_leaves_app_unlinked(self, mock_get, _url_mock):
+ metadata = _make_metadata(posthog_verification_token="phvt_totally_made_up")
+ 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)
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_missing_verification_token_leaves_app_unlinked(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(), 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.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
+ )
+ metadata = _make_metadata(posthog_verification_token=plaintext)
+ mock_get.return_value = _mock_response(metadata, headers={})
+
+ app = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)
+
+ assert app is not None
+ self.assertEqual(app.organization_id, self.organization.id)
+ self.assertEqual(
+ app.provisioning_rate_limit_account_requests,
+ CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT,
+ )
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_unverified_partner_gets_default_rate_limit(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+
+ app = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)
+
+ assert app is not None
+ self.assertIsNone(app.organization_id)
+ self.assertEqual(
+ app.provisioning_rate_limit_account_requests,
+ CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,
+ )
+
+ @patch("posthog.api.oauth.cimd.requests.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
+ )
+ # First fetch: with token → linked
+ 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)
+
+ # Second fetch: metadata no longer contains the token → must unlink
+ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+ assert refreshed is not None
+ self.assertIsNone(refreshed.organization_id)
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_refresh_links_app_when_token_added(self, mock_get, _url_mock):
+ # First fetch: no token → unlinked
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+ assert app is not None
+ self.assertIsNone(app.organization_id)
+
+ # Partner adds a token and we refetch
+ _, plaintext = create_cimd_verification_token(
+ organization=self.organization, label="Added later", 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={})
+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+ assert refreshed is not None
+ self.assertEqual(refreshed.organization_id, self.organization.id)
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_non_string_verification_token_is_ignored(self, mock_get, _url_mock):
+ metadata = _make_metadata()
+ metadata["posthog_verification_token"] = {"not": "a string"}
+ 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)
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_refresh_bumps_rate_limit_when_token_added_post_registration(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ get_or_create_cimd_provisioning_application(VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ self.assertIsNone(app.organization_id)
+ self.assertEqual(
+ app.provisioning_rate_limit_account_requests,
+ CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,
+ )
+
+ _, plaintext = create_cimd_verification_token(
+ organization=self.organization, label="Added post-registration", 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={})
+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert refreshed is not None
+ self.assertEqual(refreshed.organization_id, self.organization.id)
+ self.assertEqual(
+ refreshed.provisioning_rate_limit_account_requests,
+ CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT,
+ )
+
+ @patch("posthog.api.oauth.cimd.requests.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
+ )
+ mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})
+ get_or_create_cimd_provisioning_application(VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ self.assertEqual(app.organization_id, self.organization.id)
+ self.assertEqual(
+ app.provisioning_rate_limit_account_requests,
+ CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT,
+ )
+
+ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert refreshed is not None
+ self.assertIsNone(refreshed.organization_id)
+ self.assertEqual(
+ refreshed.provisioning_rate_limit_account_requests,
+ CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,
+ )
+
+ @patch("posthog.api.oauth.cimd.requests.get")
+ def test_refresh_preserves_admin_custom_rate_limit(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ get_or_create_cimd_provisioning_application(VALID_CIMD_URL)
+ app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)
+ app.provisioning_rate_limit_account_requests = 250
+ app.provisioning_rate_limit_account_requests_source = "admin"
+ app.save(
+ update_fields=[
+ "provisioning_rate_limit_account_requests",
+ "provisioning_rate_limit_account_requests_source",
+ ]
+ )
+
+ _, plaintext = create_cimd_verification_token(
+ organization=self.organization, label="Post-admin-override", 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={})
+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert refreshed is not None
+ self.assertEqual(refreshed.organization_id, self.organization.id)
+ self.assertEqual(refreshed.provisioning_rate_limit_account_requests, 250)
+ self.assertEqual(refreshed.provisioning_rate_limit_account_requests_source, "admin")
+
+
@override_settings(
OAUTH2_PROVIDER={
**settings.OAUTH2_PROVIDER,
diff --git a/posthog/api/test/test_cimd_verification_token.py b/posthog/api/test/test_cimd_verification_token.py
new file mode 100644
index 000000000000..19a376e5279b
--- /dev/null
+++ b/posthog/api/test/test_cimd_verification_token.py
@@ -0,0 +1,67 @@
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+from posthog.models import Organization, OrganizationMembership
+from posthog.models.oauth import CIMDVerificationToken, create_cimd_verification_token
+
+
+class TestCIMDVerificationTokenViewSet(APIBaseTest):
+ def _url(self, detail_id: str | None = None) -> str:
+ base = f"/api/organizations/{self.organization.id}/cimd_verification_tokens/"
+ return f"{base}{detail_id}/" if detail_id else base
+
+ def test_admin_can_create_and_sees_plaintext_once(self):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ response = self.client.post(self._url(), {"label": "Prod partner"}, 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.assertTrue(body["mask_value"].startswith("phvt"))
+ self.assertIn("...", body["mask_value"])
+
+ token = CIMDVerificationToken.objects.get(id=body["id"])
+ self.assertEqual(token.organization_id, self.organization.id)
+ self.assertEqual(token.created_by_id, self.user.id)
+ self.assertNotEqual(token.secure_value, body["value"])
+
+ def test_non_admin_cannot_create(self):
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ response = self.client.post(self._url(), {"label": "blocked"}, 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.ADMIN
+ self.organization_membership.save()
+
+ create_cimd_verification_token(organization=self.organization, label="Ours", created_by=self.user)
+ other_org = Organization.objects.create(name="Other")
+ create_cimd_verification_token(organization=other_org, label="Theirs", created_by=None)
+
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["label"], "Ours")
+ self.assertNotIn("value", results[0])
+
+ def test_admin_can_revoke(self):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ token, _ = create_cimd_verification_token(
+ organization=self.organization, label="Revocable", 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):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ response = self.client.post(self._url(), {"label": " "}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambr
index f6aed6851619..27550356de42 100644
--- a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambr
+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambr
@@ -3702,6 +3702,88 @@
use_hive_partitioning=0
'''
# ---
+# name: TestTrends.test_trends_any_event_total_count.10
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.11
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.12
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.13
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestTrends.test_trends_any_event_total_count.2
'''
SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
@@ -3731,6 +3813,90 @@
use_hive_partitioning=0
'''
# ---
+# name: TestTrends.test_trends_any_event_total_count.3
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.4
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.5
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.6
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.7
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.8
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_any_event_total_count.9
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
# name: TestTrends.test_trends_breakdown_cumulative
'''
/* celery:posthog.tasks.tasks.sync_insight_caching_state */
@@ -3800,7 +3966,31 @@
use_hive_partitioning=0
'''
# ---
-# name: TestTrends.test_trends_breakdown_cumulative_poe_v2
+# name: TestTrends.test_trends_breakdown_cumulative.10
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.11
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.12
'''
SELECT groupArray(1)(date)[1] AS date,
arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
@@ -3857,80 +4047,233 @@
use_hive_partitioning=0
'''
# ---
-# name: TestTrends.test_trends_breakdown_normalize_url
+# name: TestTrends.test_trends_breakdown_cumulative.2
'''
- SELECT groupArray(1)(date)[1] AS date,
- arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
- FROM
- (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
- arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
- and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total,
- breakdown_value AS breakdown_value,
- rowNumberInAllBlocks() AS row_number
- FROM
- (SELECT day_start AS day_start,
- sum(count) OVER (PARTITION BY breakdown_value
- ORDER BY day_start ASC) AS count,
- breakdown_value AS breakdown_value
- FROM
- (SELECT sum(total) AS count,
- day_start AS day_start,
- breakdown_value AS breakdown_value
- FROM
- (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
- min(toStartOfDay(toTimeZone(e.timestamp, 'UTC'))) AS day_start,
- ifNull(nullIf(leftUTF8(toString(if(empty(trim(TRAILING '/?#'
- FROM replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$current_url'), ''), 'null'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- FROM replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$current_url'), ''), 'null'), '^"|"$', '')))), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
- GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id),
- breakdown_value)
- GROUP BY day_start,
- breakdown_value
- ORDER BY day_start ASC,
- breakdown_value ASC)
- ORDER BY day_start ASC)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
- WHERE isNotNull(breakdown_value)
- GROUP BY breakdown_value
- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
- LIMIT 50000 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
'''
# ---
-# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown
+# name: TestTrends.test_trends_breakdown_cumulative.3
'''
- SELECT sum(total) AS total,
- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
- FROM
- (SELECT count AS total,
- breakdown_value AS breakdown_value,
- row_number() OVER (
- ORDER BY total DESC) AS row_number
- FROM
- (SELECT sum(total) AS count,
- breakdown_value AS breakdown_value
- FROM
- (SELECT ifNull(quantile(0.5)(accurateCastOrNull(session_duration, 'Float64')), 0) AS total,
- breakdown_value AS breakdown_value
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.4
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.5
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.6
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.7
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.8
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative.9
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_cumulative_poe_v2
+ '''
+ SELECT groupArray(1)(date)[1] AS date,
+ arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
+ if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
+ FROM
+ (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total,
+ breakdown_value AS breakdown_value,
+ rowNumberInAllBlocks() AS row_number
+ FROM
+ (SELECT day_start AS day_start,
+ sum(count) OVER (PARTITION BY breakdown_value
+ ORDER BY day_start ASC) AS count,
+ breakdown_value AS breakdown_value
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start,
+ breakdown_value AS breakdown_value
+ FROM
+ (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
+ min(toStartOfDay(toTimeZone(e.timestamp, 'UTC'))) AS day_start,
+ ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$some_property'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id),
+ breakdown_value)
+ GROUP BY day_start,
+ breakdown_value
+ ORDER BY day_start ASC,
+ breakdown_value ASC)
+ ORDER BY day_start ASC)
+ GROUP BY breakdown_value
+ ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
+ WHERE isNotNull(breakdown_value)
+ GROUP BY breakdown_value
+ ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_normalize_url
+ '''
+ SELECT groupArray(1)(date)[1] AS date,
+ arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
+ if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
+ FROM
+ (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total,
+ breakdown_value AS breakdown_value,
+ rowNumberInAllBlocks() AS row_number
+ FROM
+ (SELECT day_start AS day_start,
+ sum(count) OVER (PARTITION BY breakdown_value
+ ORDER BY day_start ASC) AS count,
+ breakdown_value AS breakdown_value
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start,
+ breakdown_value AS breakdown_value
+ FROM
+ (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
+ min(toStartOfDay(toTimeZone(e.timestamp, 'UTC'))) AS day_start,
+ ifNull(nullIf(leftUTF8(toString(if(empty(trim(TRAILING '/?#'
+ FROM replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$current_url'), ''), 'null'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
+ FROM replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$current_url'), ''), 'null'), '^"|"$', '')))), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id),
+ breakdown_value)
+ GROUP BY day_start,
+ breakdown_value
+ ORDER BY day_start ASC,
+ breakdown_value ASC)
+ ORDER BY day_start ASC)
+ GROUP BY breakdown_value
+ ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
+ WHERE isNotNull(breakdown_value)
+ GROUP BY breakdown_value
+ ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown
+ '''
+ SELECT sum(total) AS total,
+ if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
+ FROM
+ (SELECT count AS total,
+ breakdown_value AS breakdown_value,
+ row_number() OVER (
+ ORDER BY total DESC) AS row_number
+ FROM
+ (SELECT sum(total) AS count,
+ breakdown_value AS breakdown_value
+ FROM
+ (SELECT ifNull(quantile(0.5)(accurateCastOrNull(session_duration, 'Float64')), 0) AS total,
+ breakdown_value AS breakdown_value
FROM
(SELECT any(e__session.`$session_duration`) AS session_duration,
ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$some_property'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
@@ -4153,9 +4496,33 @@
use_hive_partitioning=0
'''
# ---
-# name: TestTrends.test_trends_compare_day_interval_relative_range.2
+# name: TestTrends.test_trends_compare_day_interval_relative_range.10
'''
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.11
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.12
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
FROM
@@ -4165,7 +4532,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2019-12-28 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -4182,9 +4549,9 @@
use_hive_partitioning=0
'''
# ---
-# name: TestTrends.test_trends_compare_day_interval_relative_range.3
+# name: TestTrends.test_trends_compare_day_interval_relative_range.13
'''
- SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
FROM
@@ -4194,7 +4561,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2019-12-28 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -4211,20 +4578,179 @@
use_hive_partitioning=0
'''
# ---
-# name: TestTrends.test_trends_count_per_user_average_aggregated
+# name: TestTrends.test_trends_compare_day_interval_relative_range.14
'''
- SELECT total AS total
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
FROM
- (SELECT avg(total) AS total
+ (SELECT sum(total) AS count,
+ day_start AS day_start
FROM
- (SELECT count() AS total
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.2
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-21 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2019-12-28 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.3
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.4
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.5
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.6
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.7
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.8
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_compare_day_interval_relative_range.9
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_count_per_user_average_aggregated
+ '''
+ SELECT total AS total
+ FROM
+ (SELECT avg(total) AS total
+ FROM
+ (SELECT count() AS total
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
WHERE and(equals(e.team_id, 99999), equals(e.event, 'viewed video'), greaterOrEquals(e.timestamp, minus(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(0))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-07 23:59:59', 'UTC'))))
GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)))
@@ -4519,6 +5045,160 @@
use_hive_partitioning=0
'''
# ---
+# name: TestTrends.test_trends_per_day_cumulative.10
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.11
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.12
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total
+ FROM
+ (SELECT day_start AS day_start,
+ sum(count) OVER (
+ ORDER BY day_start ASC) AS count
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.2
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.3
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.4
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.5
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.6
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.7
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.8
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_cumulative.9
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
# name: TestTrends.test_trends_per_day_dau_cumulative
'''
/* celery:posthog.tasks.tasks.sync_insight_caching_state */
@@ -4572,6 +5252,167 @@
use_hive_partitioning=0
'''
# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.10
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.11
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.12
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date)) AS total
+ FROM
+ (SELECT day_start AS day_start,
+ sum(count) OVER (
+ ORDER BY day_start ASC) AS count
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
+ min(toStartOfDay(toTimeZone(e.timestamp, 'UTC'))) AS day_start
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'sign up'))
+ GROUP BY if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id))
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.2
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.3
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.4
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.5
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.6
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.7
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.8
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
+# name: TestTrends.test_trends_per_day_dau_cumulative.9
+ '''
+ /* celery:posthog.tasks.tasks.sync_insight_caching_state */
+ SELECT team_id,
+ date_diff('second', max(timestamp), now()) AS age
+ FROM events
+ WHERE timestamp > date_sub(DAY, 3, now())
+ AND timestamp < now()
+ GROUP BY team_id
+ ORDER BY age;
+ '''
+# ---
# name: TestTrends.test_trends_person_breakdown_with_session_property_single_aggregate_math_and_breakdown
'''
SELECT sum(total) AS total,
diff --git a/posthog/migrations/1150_cimd_verification_token.py b/posthog/migrations/1150_cimd_verification_token.py
new file mode 100644
index 000000000000..52107e5fa765
--- /dev/null
+++ b/posthog/migrations/1150_cimd_verification_token.py
@@ -0,0 +1,55 @@
+# Generated by Django 4.2.29 on 2026-04-21 19:24
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1149_integrationrepositorycacheentry_user_integration"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CIMDVerificationToken",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ ("label", models.CharField(max_length=40)),
+ ("mask_value", models.CharField(editable=False, max_length=11, null=True)),
+ ("secure_value", models.CharField(editable=False, max_length=300, unique=True)),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ ("last_used_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "organization",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="cimd_verification_tokens",
+ to="posthog.organization",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "CIMD Verification Token",
+ "verbose_name_plural": "CIMD Verification Tokens",
+ },
+ ),
+ ]
diff --git a/posthog/migrations/1151_cimd_followup_hardening.py b/posthog/migrations/1151_cimd_followup_hardening.py
new file mode 100644
index 000000000000..d79fb4d9ef5a
--- /dev/null
+++ b/posthog/migrations/1151_cimd_followup_hardening.py
@@ -0,0 +1,68 @@
+# Generated by Django 4.2.29 on 2026-04-23 20:04
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1150_cimd_verification_token"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="oauthapplication",
+ name="provisioning_disabled",
+ field=models.BooleanField(
+ default=False,
+ help_text="Kill switch for misbehaving partners. When true, apply_provisioning_defaults will not re-enable the app on subsequent CIMD requests.",
+ ),
+ ),
+ migrations.AddField(
+ model_name="oauthapplication",
+ name="provisioning_rate_limit_account_requests_source",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("default_unverified", "default_unverified"),
+ ("default_verified", "default_verified"),
+ ("admin", "admin"),
+ ],
+ default="",
+ help_text="Records who set provisioning_rate_limit_account_requests so verification flips don't overwrite an explicit admin override.",
+ max_length=24,
+ ),
+ ),
+ migrations.CreateModel(
+ name="CIMDBlocklistEntry",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ ("cimd_url", models.URLField(max_length=2048, unique=True)),
+ ("reason", models.CharField(blank=True, default="", max_length=200)),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "CIMD Blocklist Entry",
+ "verbose_name_plural": "CIMD Blocklist Entries",
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 93c1c620790b..88eca70d6152 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1149_integrationrepositorycacheentry_user_integration
+1151_cimd_followup_hardening
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 45692944e0e1..02223389291a 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -96,7 +96,14 @@ from .user_repo_preference import UserRepoPreference
from .user_scene_personalisation import UserScenePersonalisation
from .user_home_settings import UserHomeSettings
from .web_analytics_filter_preset import WebAnalyticsFilterPreset
-from .oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthIDToken, OAuthRefreshToken
+from .oauth import (
+ CIMDVerificationToken,
+ OAuthAccessToken,
+ OAuthApplication,
+ OAuthGrant,
+ OAuthIDToken,
+ OAuthRefreshToken,
+)
from ..approvals.models import Approval, ApprovalPolicy, ChangeRequest
@@ -117,6 +124,7 @@ __all__ = [
"BatchExportDestination",
"BatchExportRun",
"BatchImport",
+ "CIMDVerificationToken",
"Cohort",
"CohortPeople",
"CohortCalculationHistory",
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 3feccc722ea9..ee9145d45682 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -6,6 +6,8 @@ from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.db import models
+from django.dispatch import receiver
+from django.utils import timezone
from oauth2_provider.models import (
AbstractAccessToken,
@@ -16,7 +18,7 @@ from oauth2_provider.models import (
)
from posthog.helpers.encrypted_fields import EncryptedCharField
-from posthog.models.utils import UUIDT
+from posthog.models.utils import UUIDT, generate_random_token, hash_key_value, mask_key_value
if TYPE_CHECKING:
from posthog.models import Organization, User
@@ -142,12 +144,33 @@ class OAuthApplication(AbstractApplication):
provisioning_rate_limit_account_requests: models.IntegerField = models.IntegerField(
null=True, blank=True, help_text="Override default rate limit for account_requests (per hour)"
)
+ provisioning_rate_limit_account_requests_source: models.CharField = models.CharField(
+ max_length=24,
+ blank=True,
+ default="",
+ choices=[
+ ("default_unverified", "default_unverified"),
+ ("default_verified", "default_verified"),
+ ("admin", "admin"),
+ ],
+ help_text=(
+ "Records who set provisioning_rate_limit_account_requests so verification flips don't "
+ "overwrite an explicit admin override."
+ ),
+ )
provisioning_rate_limit_token_exchanges: models.IntegerField = models.IntegerField(
null=True, blank=True, help_text="Override default rate limit for token exchanges (per hour)"
)
provisioning_rate_limit_resource_creates: models.IntegerField = models.IntegerField(
null=True, blank=True, help_text="Override default rate limit for resource creates (per hour)"
)
+ provisioning_disabled: models.BooleanField = models.BooleanField(
+ default=False,
+ help_text=(
+ "Kill switch for misbehaving partners. When true, apply_provisioning_defaults will not "
+ "re-enable the app on subsequent CIMD requests."
+ ),
+ )
provisioning_skip_existing_user_consent: models.BooleanField = models.BooleanField(
default=False,
help_text="Skip user consent when linking existing accounts. Only enable for fully trusted partners.",
@@ -391,3 +414,96 @@ def revoke_oauth_session(
# Delete all grants for this user+application
OAuthGrant.objects.filter(user=user, application=application).delete()
+
+
+def generate_random_token_cimd_verification() -> str:
+ return "phvt_" + generate_random_token()
+
+
+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.
+ """
+
+ id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)
+ organization: "Organization" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]
+ "posthog.Organization", on_delete=models.CASCADE, related_name="cimd_verification_tokens"
+ )
+ label: models.CharField = models.CharField(max_length=40)
+ 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]
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
+ )
+ created_at: models.DateTimeField = models.DateTimeField(default=timezone.now)
+ last_used_at: models.DateTimeField = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ verbose_name = "CIMD Verification Token"
+ verbose_name_plural = "CIMD Verification Tokens"
+
+
+def find_cimd_verification_token(token: str) -> "CIMDVerificationToken | None":
+ if not token or not token.startswith("phvt_"):
+ return None
+ secure_value = hash_key_value(token)
+ try:
+ return CIMDVerificationToken.objects.select_related("organization").get(secure_value=secure_value)
+ except CIMDVerificationToken.DoesNotExist:
+ return None
+
+
+def create_cimd_verification_token(
+ *, organization: "Organization", label: 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."""
+ plaintext = generate_random_token_cimd_verification()
+ token = CIMDVerificationToken.objects.create(
+ organization=organization,
+ label=label,
+ created_by=created_by,
+ secure_value=hash_key_value(plaintext),
+ mask_value=mask_key_value(plaintext),
+ )
+ return token, plaintext
+
+
+class CIMDBlocklistEntry(models.Model):
+ """Persistent blocklist for CIMD partner URLs.
+
+ Source of truth for is_cimd_url_blocked - the Redis check is a read-through
+ cache. Persisting in Postgres means the blocklist survives Redis flushes /
+ LRU eviction and a deleted CIMD app can stay blocked across restarts.
+ """
+
+ id: models.UUIDField = models.UUIDField(primary_key=True, default=UUIDT, editable=False)
+ cimd_url: models.URLField = models.URLField(max_length=2048, unique=True)
+ reason: models.CharField = models.CharField(max_length=200, blank=True, default="")
+ created_at: models.DateTimeField = models.DateTimeField(default=timezone.now)
+ created_by: "User | None" = models.ForeignKey( # type: ignore[assignment] # ty: ignore[invalid-assignment]
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
+ )
+
+ class Meta:
+ verbose_name = "CIMD Blocklist Entry"
+ verbose_name_plural = "CIMD Blocklist Entries"
+
+
+@receiver(models.signals.post_delete, sender=OAuthApplication)
+def _block_cimd_url_on_application_delete(sender, instance: OAuthApplication, **kwargs):
+ # Auto-blocklist a CIMD URL when its app is deleted, so a metadata refresh
+ # can't immediately recreate the same partner. Admin can explicitly
+ # unblock via unblock_cimd_url if they want to allow re-registration.
+ if not (instance.is_cimd_client and instance.cimd_metadata_url):
+ return
+ from posthog.api.oauth.cimd import block_cimd_url
+
+ block_cimd_url(
+ instance.cimd_metadata_url,
+ reason=f"Auto-blocked on deletion of OAuthApplication {instance.pk}",
+ )
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 38dada70d7eb..a082e4848acd 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -44,6 +44,18 @@ tools:
change-organization-create:
operation: organizations_projects_change_organization_create
enabled: false
+ cimd-verification-tokens-create:
+ operation: cimd_verification_tokens_create
+ enabled: false
+ cimd-verification-tokens-destroy:
+ operation: cimd_verification_tokens_destroy
+ enabled: false
+ cimd-verification-tokens-list:
+ operation: cimd_verification_tokens_list
+ enabled: false
+ cimd-verification-tokens-retrieve:
+ operation: cimd_verification_tokens_retrieve
+ enabled: false
cohorts-activity-retrieve:
operation: cohorts_activity_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3e6fea1bd0d4..63faf7cfe762 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7974,6 +7974,38 @@ export namespace Schemas {
Sunday: 'sunday',
} as const;
+ export interface CIMDVerificationToken {
+ readonly id: string;
+ /** @maxLength 40 */
+ label: string;
+ /** @nullable */
+ readonly mask_value: string | null;
+ readonly created_by: UserBasic;
+ readonly created_at: string;
+ /** @nullable */
+ readonly last_used_at: string | null;
+ }
+
+ /**
+ * Create-response variant that includes the plaintext token.
+
+ Only emitted from the create endpoint - storage-side we only persist the
+ hash, so subsequent reads use the base serializer.
+ */
+ export interface CIMDVerificationTokenWithValue {
+ readonly id: string;
+ /** @maxLength 40 */
+ label: string;
+ /** @nullable */
+ readonly mask_value: string | null;
+ readonly created_by: UserBasic;
+ readonly created_at: string;
+ /** @nullable */
+ readonly last_used_at: string | null;
+ /** Plaintext token, only returned on creation */
+ readonly value: string;
+ }
+
export interface CalendarHeatmapFilter {
/** @nullable */
dummy?: string | null;
@@ -24501,6 +24533,15 @@ export namespace Schemas {
results: BatchImport[];
}
+ export interface PaginatedCIMDVerificationTokenList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: CIMDVerificationToken[];
+ }
+
export interface PaginatedChangeRequestList {
count: number;
/** @nullable */
@@ -43516,6 +43557,17 @@ export namespace Schemas {
search?: string;
};
+ export type CimdVerificationTokensListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type DomainsListParams = {
/**
* Number of results to return per page.