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.

chore(ci): add critical-path playwright specs for auth, keys, flags, ingestion (#71488)

Georges-Antoine Assieaf2bd609250
diff --git a/playwright/e2e/api-keys.spec.ts b/playwright/e2e/api-keys.spec.ts
new file mode 100644
index 000000000000..33ea6e5e89ac
--- /dev/null
+++ b/playwright/e2e/api-keys.spec.ts
@@ -0,0 +1,62 @@
+import { randomString } from '../utils'
+import { PlaywrightWorkspaceSetupResult, expect, test } from '../utils/workspace-test-base'
+
+test.describe('Personal API keys', () => {
+ let workspace: PlaywrightWorkspaceSetupResult | null = null
+
+ test.beforeAll(async ({ playwrightSetup }) => {
+ workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+ })
+
+ test.beforeEach(async ({ page, playwrightSetup }) => {
+ await playwrightSetup.login(page, workspace!)
+ })
+
+ test('key created in the UI authorizes the API and stops working after deletion', async ({ page, request }) => {
+ const label = randomString('e2e-key')
+ let apiKey = ''
+
+ await test.step('create a key with the all-access preset', async () => {
+ await page.goto('/settings/user-api-keys')
+ await page.getByRole('button', { name: 'Create personal API key' }).click()
+ await page.getByPlaceholder('For example "Reports bot" or "Zapier"').fill(label)
+ await page.getByRole('button', { name: 'All access', exact: true }).click()
+ await page.getByText('Select preset').click()
+ await page.locator('.Popover__content').getByText('All access').click()
+ await page.getByRole('button', { name: 'Create key' }).click()
+ })
+
+ await test.step('capture the one-time key value', async () => {
+ const dialog = page.locator('.LemonModal').filter({ hasText: 'Personal API key ready' })
+ await expect(dialog).toBeVisible()
+ const snippet = (await dialog.locator('code').textContent()) ?? ''
+ apiKey = snippet.match(/phx_\w+/)?.[0] ?? ''
+ expect(apiKey).toMatch(/^phx_/)
+ await page.keyboard.press('Escape')
+ await expect(dialog).not.toBeVisible()
+ })
+
+ await test.step('the key authorizes an API request', async () => {
+ const resp = await request.get('/api/users/@me/', {
+ headers: { Authorization: `Bearer ${apiKey}` },
+ })
+ expect(resp.status()).toBe(200)
+ expect((await resp.json()).email).toBe(workspace!.user_email)
+ })
+
+ await test.step('delete the key via the row menu', async () => {
+ const row = page.locator('tr', { hasText: label })
+ await row.locator('td').last().getByRole('button').click()
+ await page.getByRole('menuitem', { name: 'Delete' }).click()
+ await page.getByRole('button', { name: 'Permanently delete' }).click()
+ await expect(row).not.toBeVisible()
+ })
+
+ await test.step('the deleted key no longer authorizes', async () => {
+ const resp = await request.get('/api/users/@me/', {
+ headers: { Authorization: `Bearer ${apiKey}` },
+ })
+ expect(resp.status()).toBe(401)
+ })
+ })
+})
diff --git a/playwright/e2e/feature-flags.spec.ts b/playwright/e2e/feature-flags.spec.ts
new file mode 100644
index 000000000000..359b6a026723
--- /dev/null
+++ b/playwright/e2e/feature-flags.spec.ts
@@ -0,0 +1,34 @@
+import { randomString } from '../utils'
+import { expect, test } from '../utils/workspace-test-base'
+
+// Flag evaluation (`/flags`) is served by the separate Rust flags service, which the
+// e2e environment does not wire up: the dev proxy resolves `feature-flags` to
+// host-gateway:3001 where nothing listens in CI, and the container reads the default
+// `posthog` database rather than the e2e one. Until that service is plumbed into the
+// e2e stack, this spec covers the browser-only creation path and stops at persistence.
+test.describe('Feature flags', () => {
+ test('a flag created in the UI is persisted and listed', async ({ page, playwrightSetup }) => {
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+ await playwrightSetup.login(page, workspace)
+ const flagKey = randomString('e2e-flag')
+
+ await test.step('create a 100% rollout flag via the UI', async () => {
+ await page.goto('/feature_flags')
+ await page.locator('[data-attr="new-feature-flag"]').click()
+ await page.locator('[data-attr="blank-feature-flag-template"]').click()
+ await page.locator('[data-attr="feature-flag-key"]').fill(flagKey)
+ await page.locator('[data-attr="rollout-percentage"]').fill('100')
+ const saveButton = page.locator('[data-attr="save-feature-flag"]').first()
+ await expect(saveButton).toBeEnabled()
+ await saveButton.click()
+ await page.waitForURL(/\/feature_flags\/\d+/)
+ })
+
+ await test.step('the flag appears enabled in the flags list', async () => {
+ await page.goto('/feature_flags')
+ const row = page.locator('table tbody tr').filter({ hasText: flagKey })
+ await expect(row).toBeVisible()
+ await expect(row).toContainText('100%')
+ })
+ })
+})
diff --git a/playwright/e2e/ingestion-capture.spec.ts b/playwright/e2e/ingestion-capture.spec.ts
new file mode 100644
index 000000000000..e1e72a26be82
--- /dev/null
+++ b/playwright/e2e/ingestion-capture.spec.ts
@@ -0,0 +1,62 @@
+import { randomString } from '../utils'
+import { expect, test } from '../utils/workspace-test-base'
+
+// Capture and flags are served by separate Rust services fronted by the Caddy dev proxy,
+// not by the Django server Playwright's baseURL points at.
+const PROXY_BASE_URL = process.env.E2E_PROXY_URL || 'http://localhost:8010'
+
+test.describe('Event ingestion', () => {
+ test('an event sent to the real capture endpoint becomes queryable', async ({ request, playwrightSetup }) => {
+ test.setTimeout(120_000)
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+ const eventName = randomString('e2e_ingestion_')
+ const authHeaders = { Authorization: `Bearer ${workspace.personal_api_key}` }
+ let apiToken = ''
+
+ await test.step('fetch the team api token', async () => {
+ const team = await request.get(`/api/environments/${workspace.team_id}/`, { headers: authHeaders })
+ expect(team.ok()).toBe(true)
+ apiToken = (await team.json()).api_token
+ })
+
+ await test.step('send an event through the capture endpoint', async () => {
+ const captured = await request.post(`${PROXY_BASE_URL}/e/`, {
+ data: {
+ api_key: apiToken,
+ event: eventName,
+ distinct_id: randomString('e2e-user-'),
+ timestamp: new Date().toISOString(),
+ },
+ })
+ expect(captured.ok()).toBe(true)
+ })
+
+ await test.step('poll until the event has been ingested and is queryable', async () => {
+ await expect
+ .poll(
+ async () => {
+ const resp = await request.post(`/api/environments/${workspace.team_id}/query/`, {
+ headers: authHeaders,
+ data: {
+ // Without this the endpoint serves a cached result for up to 5 minutes,
+ // so the first poll's zero would be replayed for the rest of the window.
+ refresh: 'force_blocking',
+ query: {
+ kind: 'HogQLQuery',
+ query: `SELECT count() FROM events WHERE event = '${eventName}'`,
+ },
+ },
+ })
+ // A 4xx other than rate limiting means the query itself is bad — waiting won't fix it.
+ if (resp.status() >= 400 && resp.status() < 500 && resp.status() !== 429) {
+ throw new Error(`query endpoint returned ${resp.status()}: ${await resp.text()}`)
+ }
+ const body = await resp.json()
+ return Number(body.results?.[0]?.[0] ?? 0)
+ },
+ { timeout: 90_000, intervals: [2_000, 5_000] }
+ )
+ .toBeGreaterThan(0)
+ })
+ })
+})
diff --git a/playwright/e2e/invite-signup.spec.ts b/playwright/e2e/invite-signup.spec.ts
new file mode 100644
index 000000000000..8cb96b642d67
--- /dev/null
+++ b/playwright/e2e/invite-signup.spec.ts
@@ -0,0 +1,78 @@
+import { randomString } from '../utils'
+import { expect, test } from '../utils/workspace-test-base'
+
+test.describe('Invites', () => {
+ test('an invited teammate can sign up through the invite link and lands in the organization', async ({
+ page,
+ browser,
+ playwrightSetup,
+ }) => {
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+
+ // Force link-generation mode so the modal flow is deterministic regardless of
+ // whether the environment has an email service configured. Preflight is both
+ // server-rendered into POSTHOG_APP_CONTEXT and refreshed via the API, so patch both.
+ await page.addInitScript(() => {
+ let appContext: any = undefined
+ Object.defineProperty(window, 'POSTHOG_APP_CONTEXT', {
+ get() {
+ if (appContext?.preflight) {
+ appContext.preflight.email_service_available = false
+ }
+ return appContext
+ },
+ set(value) {
+ appContext = value
+ },
+ configurable: true,
+ })
+ })
+ await page.route('**/_preflight*', async (route) => {
+ const response = await route.fetch()
+ const body = await response.json()
+ await route.fulfill({ response, json: { ...body, email_service_available: false } })
+ })
+
+ await playwrightSetup.login(page, workspace)
+ const inviteeEmail = `${randomString('invitee-')}@posthog.com`
+ let inviteUrl = ''
+
+ await test.step('generate an invite link from org settings', async () => {
+ await page.goto('/settings/organization-members')
+ await page.getByTestId('invite-teammate-button').click()
+ await page.getByTestId('invite-email-input').fill(inviteeEmail)
+ await page.getByTestId('invite-generate-invite-link').click()
+ await page.getByRole('button', { name: 'Done' }).click()
+ })
+
+ await test.step('read the invite link from the invites table', async () => {
+ const link = page.getByTestId('invite-link')
+ await expect(link).toBeVisible()
+ inviteUrl = (await link.textContent()) ?? ''
+ expect(inviteUrl).toMatch(/\/signup\/[0-9a-f-]{36}/)
+ })
+
+ await test.step('accept the invite in a fresh browser session', async () => {
+ const context = await browser.newContext()
+ const invitePage = await context.newPage()
+ await invitePage.goto(inviteUrl)
+ await invitePage.locator('[data-attr=password]').fill(`E2e!${randomString('pw-')}`)
+ await invitePage.locator('[data-attr=first_name]').fill('Invited Hedgehog')
+ await invitePage.locator('[data-attr=signup-role-at-organization]').click()
+ await invitePage.locator('.Popover__content').getByText('Engineering').click()
+ await invitePage.locator('[data-attr=password-signup]').click()
+ // Where signup lands depends on whether the server has an email backend configured:
+ // with one, it routes to email verification instead of logging the invitee straight in.
+ await invitePage.waitForURL(/\/(project|verify_email)\//, { timeout: 30000 })
+ await context.close()
+
+ // Membership is created when the invite is used, before that branch, so it holds either way.
+ const members = await page.request.get(`/api/organizations/${workspace.organization_id}/members/`)
+ expect(members.status()).toBe(200)
+ const emails = (await members.json()).results.map(
+ (member: { user: { email: string } }) => member.user.email
+ )
+ expect(emails).toContain(inviteeEmail)
+ })
+ })
+})
diff --git a/playwright/e2e/settings-danger-zone.spec.ts b/playwright/e2e/settings-danger-zone.spec.ts
new file mode 100644
index 000000000000..8d3bfa89e9ca
--- /dev/null
+++ b/playwright/e2e/settings-danger-zone.spec.ts
@@ -0,0 +1,41 @@
+import { expect, test } from '../utils/workspace-test-base'
+
+test.describe('Project danger zone', () => {
+ test('deleting a project requires typed confirmation and actually deletes it', async ({
+ page,
+ playwrightSetup,
+ }) => {
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+ await playwrightSetup.loginAndNavigateToTeam(page, workspace)
+
+ let projectName = ''
+
+ await test.step('open the danger zone and the delete modal', async () => {
+ await page.goto('/settings/project-danger-zone')
+ const deleteButton = page.locator('[data-attr=delete-project-button]')
+ await expect(deleteButton).toBeVisible()
+ projectName = ((await deleteButton.innerText()) ?? '').replace(/^Delete\s+/, '').trim()
+ await deleteButton.click()
+ await expect(page.getByText('Delete the project and its data?')).toBeVisible()
+ })
+
+ await test.step('confirm stays disabled until the exact project name is typed', async () => {
+ const modal = page.locator('.LemonModal').filter({ hasText: 'Delete the project and its data?' })
+ const confirmButton = page.locator('[data-attr=delete-project-ok]')
+ await expect(confirmButton).toBeDisabled()
+ await modal.getByRole('textbox').fill('wrong-name')
+ await expect(confirmButton).toBeDisabled()
+ await modal.getByRole('textbox').fill(projectName)
+ await expect(confirmButton).toBeEnabled()
+ })
+
+ await test.step('confirming marks the project for deletion and locks it out', async () => {
+ await page.locator('[data-attr=delete-project-ok]').click()
+ // Deletion is async: the API marks is_pending_deletion and the app
+ // hard-navigates to the lockout screen.
+ await page.waitForURL(/\/project-pending-deletion/, { timeout: 20_000 })
+ const resp = await page.request.get(`/api/projects/${workspace.team_id}/`)
+ expect((await resp.json()).is_pending_deletion).toBe(true)
+ })
+ })
+})
diff --git a/playwright/e2e/two-factor.spec.ts b/playwright/e2e/two-factor.spec.ts
new file mode 100644
index 000000000000..6b19d1906271
--- /dev/null
+++ b/playwright/e2e/two-factor.spec.ts
@@ -0,0 +1,71 @@
+import { createHmac } from 'crypto'
+
+import { LoginPage } from '../page-models/loginPage'
+import { LOGIN_PASSWORD } from '../utils/playwright-test-core'
+import { expect, test } from '../utils/workspace-test-base'
+
+function base32Decode(secret: string): Buffer {
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
+ let bits = 0
+ let value = 0
+ const bytes: number[] = []
+ for (const char of secret.replace(/=+$/, '').toUpperCase()) {
+ value = (value << 5) | alphabet.indexOf(char)
+ bits += 5
+ if (bits >= 8) {
+ bytes.push((value >>> (bits - 8)) & 0xff)
+ bits -= 8
+ }
+ }
+ return Buffer.from(bytes)
+}
+
+function totp(secret: string, atMs: number): string {
+ const counter = Buffer.alloc(8)
+ counter.writeBigUInt64BE(BigInt(Math.floor(atMs / 1000 / 30)))
+ const hmac = createHmac('sha1', base32Decode(secret)).update(counter).digest()
+ const offset = hmac[hmac.length - 1] & 0xf
+ return String((hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000).padStart(6, '0')
+}
+
+test.describe('Two-factor authentication', () => {
+ test('login requires a TOTP code once 2FA is enabled', async ({ page, playwrightSetup }) => {
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+ await playwrightSetup.login(page, workspace)
+ let secret = ''
+
+ await test.step('enable TOTP from user settings', async () => {
+ await page.goto('/settings/user-profile')
+ await page.getByRole('button', { name: 'Setup', exact: true }).click()
+ const modal = page.locator('.LemonModal').filter({ hasText: 'authenticator' })
+ const secretText = modal.getByText(/^[A-Z2-7]{16,}$/)
+ await expect(secretText).toBeVisible()
+ secret = (await secretText.textContent()) ?? ''
+ await page.locator('[data-attr=token]').fill(totp(secret, Date.now()))
+ await page.locator('[data-attr="2fa-setup"]').click()
+ await expect(page.locator('[data-attr="2fa-setup"]')).not.toBeVisible({ timeout: 15000 })
+ })
+
+ await test.step('log out via the account menu', async () => {
+ await page.locator('[data-attr=new-account-menu-button]').click()
+ await page.locator('[data-attr=new-account-menu-logout-button]').click()
+ await page.waitForURL(/\/login/, { timeout: 15000 })
+ })
+
+ await test.step('password login lands on the 2FA challenge instead of the app', async () => {
+ const loginPage = new LoginPage(page)
+ await loginPage.enterUsername(workspace.user_email)
+ await loginPage.enterPassword(LOGIN_PASSWORD)
+ await loginPage.clickLogin()
+ await expect(page.locator('[data-attr=token]')).toBeVisible({ timeout: 15000 })
+ })
+
+ await test.step('a valid TOTP code completes the login', async () => {
+ // Use the next 30s window: the current window's code was consumed during
+ // setup, and django_otp rejects token reuse within the same window.
+ await page.locator('[data-attr=token]').fill(totp(secret, Date.now() + 30_000))
+ await page.locator('[data-attr="2fa-login"]').click()
+ await page.waitForURL(/\/project\//, { timeout: 30000 })
+ })
+ })
+})
diff --git a/tools/playwright_area_map.json b/tools/playwright_area_map.json
index 7a7908234f83..3fe9b08256df 100644
--- a/tools/playwright_area_map.json
+++ b/tools/playwright_area_map.json
@@ -108,15 +108,27 @@
"retention": ["playwright/e2e/product-analytics/retention.spec.ts"],
"persons": ["playwright/e2e/persons/persons.spec.ts"],
"persons-management": ["playwright/e2e/persons/persons.spec.ts"],
- "authentication": ["playwright/e2e/auth.spec.ts", "playwright/e2e/auth-password-reset.spec.ts"],
+ "authentication": [
+ "playwright/e2e/auth.spec.ts",
+ "playwright/e2e/auth-password-reset.spec.ts",
+ "playwright/e2e/two-factor.spec.ts",
+ "playwright/e2e/invite-signup.spec.ts"
+ ],
"onboarding": ["playwright/e2e/before-onboarding.spec.ts", "playwright/e2e/signup.spec.ts"],
"data-management": ["playwright/e2e/event-definitions.spec.ts", "playwright/e2e/annotations.spec.ts"],
"annotations": ["playwright/e2e/annotations.spec.ts"],
"toolbar-launch": ["playwright/e2e/toolbar.spec.ts"],
- "settings": ["playwright/e2e/before-onboarding.spec.ts"],
- "feature-flags": ["products/surveys/frontend/e2e/quickcreate.spec.ts"]
+ "settings": [
+ "playwright/e2e/before-onboarding.spec.ts",
+ "playwright/e2e/api-keys.spec.ts",
+ "playwright/e2e/two-factor.spec.ts",
+ "playwright/e2e/invite-signup.spec.ts",
+ "playwright/e2e/settings-danger-zone.spec.ts"
+ ],
+ "feature-flags": ["playwright/e2e/feature-flags.spec.ts", "products/surveys/frontend/e2e/quickcreate.spec.ts"]
},
"explicit": {
+ "products/feature_flags/frontend/**": ["playwright/e2e/feature-flags.spec.ts"],
"products/product_analytics/frontend/**": ["playwright/e2e/product-analytics/"],
"products/dashboards/frontend/**": [
"playwright/e2e/product-analytics/dashboards.spec.ts",
@@ -144,6 +156,7 @@
"full_suite_only": [
"playwright/e2e/oauth-mcp-consent.spec.ts",
"playwright/e2e/preflight.spec.ts",
- "playwright/e2e/system-status.spec.ts"
+ "playwright/e2e/system-status.spec.ts",
+ "playwright/e2e/ingestion-capture.spec.ts"
]
}