:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
Revert "feat(conversations): log in as customer directly from support ticket" (#72954)
Luke Beltonda228c990dfe
diff --git a/ee/admin/loginas_views.py b/ee/admin/loginas_views.pyindex bc46e855ba54..008d574608b0 100644--- a/ee/admin/loginas_views.py+++ b/ee/admin/loginas_views.py@@ -1,11 +1,5 @@import json-import uuid-from typing import TYPE_CHECKING, cast-from urllib.parse import urlencode-from django.apps import apps-from django.conf import settings-from django.db.models import Qfrom django.http import Http404, HttpResponseRedirect, JsonResponsefrom django.views.decorators.http import require_http_methods@@ -18,81 +12,10 @@ from posthog.helpers.impersonation import get_original_user_from_sessionfrom posthog.middleware import (IMPERSONATION_READ_ONLY_SESSION_KEY,IMPERSONATION_REASON_SESSION_KEY,- IMPERSONATION_TICKET_ID_SESSION_KEY,is_read_only_impersonation,)from posthog.models import User-if TYPE_CHECKING:- from products.conversations.backend.models import Ticket--REGION_DOMAINS: dict[str, str] = {- "US": "us.posthog.com",- "EU": "eu.posthog.com",-}---def _get_ticket(ticket_id: str, user: User) -> "Ticket | None":- """Fetch a support ticket by ID, restricted to PostHog's internal support team.-- In local dev (DEBUG — asserted off in production) the lookup falls back to the- staff user's current project, so the flow is testable without recreating the- internal project id or setting POSTHOG_INTERNAL_TEAM_ID.- """- ticket_model = apps.get_model("conversations", "Ticket")- team_id = settings.POSTHOG_INTERNAL_TEAM_ID- if settings.DEBUG and user.current_team_id:- team_id = user.current_team_id- try:- return cast("Ticket", ticket_model.objects.get(id=ticket_id, team_id=team_id))- except ticket_model.DoesNotExist:- return None---def _configure_impersonation_session(- request,- staff_user,- target_user,- *,- is_read_only: bool = True,- reason: str = "",- ticket_id: str | None = None,-) -> None:- """Set session flags and capture analytics after a successful impersonation login."""- if not is_impersonated_session(request):- return-- if is_read_only:- request.session[IMPERSONATION_READ_ONLY_SESSION_KEY] = True- elif IMPERSONATION_READ_ONLY_SESSION_KEY in request.session:- # Re-impersonating the same user keeps the existing session (Django only flushes on a- # user change), so clear a prior read-only flag to honor the mode requested here.- del request.session[IMPERSONATION_READ_ONLY_SESSION_KEY]-- # Persist the reason server-side so it survives both Django-admin and in-app starts,- # and can be surfaced to the frontend (autofill).- request.session[IMPERSONATION_REASON_SESSION_KEY] = reason-- if ticket_id:- request.session[IMPERSONATION_TICKET_ID_SESSION_KEY] = ticket_id-- properties = {- "mode": "read_only" if is_read_only else "read_write",- "reason": reason,- "staff_user_id": staff_user.id,- "staff_user_email": staff_user.email,- "target_user_id": target_user.id if target_user else None,- "target_user_email": target_user.email if target_user else None,- }- if ticket_id:- properties["ticket_id"] = ticket_id-- posthoganalytics.capture(- distinct_id=str(staff_user.distinct_id),- event="impersonation_started",- properties=properties,- )-def loginas_user(request, user_id):staff_user = request.user@@ -109,13 +32,30 @@ def loginas_user(request, user_id):)if login_succeeded:+ is_read_only = request.POST.get("read_only") != "false"+ if is_read_only:+ request.session[IMPERSONATION_READ_ONLY_SESSION_KEY] = True+ elif IMPERSONATION_READ_ONLY_SESSION_KEY in request.session:+ # Re-impersonating the same user keeps the existing session (Django only flushes on a+ # user change), so clear a prior read-only flag to honor the mode requested here.+ del request.session[IMPERSONATION_READ_ONLY_SESSION_KEY]++ # Persist the reason server-side so it survives both Django-admin and in-app starts,+ # and can be surfaced to the frontend (autofill).+ request.session[IMPERSONATION_REASON_SESSION_KEY] = request.POST.get("reason", "")+target_user = User.objects.filter(id=user_id).first()- _configure_impersonation_session(- request,- staff_user,- target_user,- is_read_only=request.POST.get("read_only") != "false",- reason=request.POST.get("reason", ""),+ posthoganalytics.capture(+ distinct_id=str(staff_user.distinct_id),+ event="impersonation_started",+ properties={+ "mode": "read_only" if is_read_only else "read_write",+ "reason": request.POST.get("reason", ""),+ "staff_user_id": staff_user.id,+ "staff_user_email": staff_user.email,+ "target_user_id": user_id,+ "target_user_email": target_user.email if target_user else None,+ },)return response@@ -157,120 +97,3 @@ def upgrade_impersonation(request):)return JsonResponse({"success": True})---@require_http_methods(["POST"])-def loginas_user_from_ticket(request):- """Initiate read-only impersonation from a support ticket, resolving the ticket's customer email to a User.-- Staff/permission checks are also enforced by CAN_LOGIN_AS in django-loginas- (see posthog/settings/web.py) when loginas_user_login is called.- """- if not request.user.is_staff:- return JsonResponse({"error": "Not found"}, status=404)-- try:- data = json.loads(request.body)- ticket_id = data.get("ticket_id", "").strip()- except (json.JSONDecodeError, AttributeError):- return JsonResponse({"error": "Invalid request body"}, status=400)-- if not ticket_id:- return JsonResponse({"error": "ticket_id is required"}, status=400)-- try:- uuid.UUID(ticket_id)- except ValueError:- return JsonResponse({"error": "ticket_id must be a valid UUID"}, status=400)-- ticket = _get_ticket(ticket_id, request.user)- if not ticket:- if settings.DEBUG:- error = "Ticket not found in your current project (in local dev, tickets are looked up in the project you're currently in)."- else:- error = (- f"Ticket not found. Ticket impersonation is only possible for tickets in "- f"project {settings.POSTHOG_INTERNAL_TEAM_ID} (PostHog's internal support project, US region)."- )- return JsonResponse({"error": error}, status=404)-- # Block when the claimed identity was assessed but not attested (False). A null- # value means the signal was never assessed (e.g. pre-dates it), which the UI- # surfaces as a caution rather than a hard block, so only reject an explicit False.- if ticket.identity_verified is False:- return JsonResponse(- {- "error": "This ticket's identity could not be verified, so logging in as the customer is disabled. Verify the customer's identity and login from admin manually."- },- status=400,- )-- # When the ticket originated in another region, point staff at that region's- # admin rather than trying (and failing) to resolve the user locally. The region- # trait is customer-suppliable, so unknown values fall through to a local lookup.- ticket_region = ((ticket.anonymous_traits or {}).get("region") or "").upper()- current_region = (settings.CLOUD_DEPLOYMENT or "").upper()- if ticket_region in REGION_DOMAINS and current_region in REGION_DOMAINS and ticket_region != current_region:- email = (ticket.anonymous_traits or {}).get("email", "")- redirect_url = f"https://{REGION_DOMAINS[ticket_region]}/admin/posthog/user/"- if email:- redirect_url += f"?{urlencode({'q': email})}"- return JsonResponse({"redirect_region": ticket_region, "redirect_url": redirect_url})-- if ticket.identity_verified:- # On verified tickets the attested identity is the read-only distinct_id — a- # PostHog distinct_id for HMAC-verified widget tickets, an attested email for- # Slack/Teams/SPF-verified email ones. The email trait stays mutable (customers- # on widget messages, staff via the tickets API) even after verification, so- # resolving by it would let a verified ticket point login-as at an unrelated- # account. Match users identified by distinct_id or by email — both compared- # against the attested value, with no fallback to the mutable trait.- if not ticket.distinct_id:- return JsonResponse({"error": "No user found for this ticket's verified identity"}, status=404)- target_user = User.objects.filter(- Q(distinct_id=ticket.distinct_id) | Q(email__iexact=ticket.distinct_id)- ).first()- if not target_user:- return JsonResponse({"error": "No user found for this ticket's verified identity"}, status=404)- else:- email = ticket.anonymous_traits.get("email") if ticket.anonymous_traits else None- if not email:- return JsonResponse({"error": "Ticket has no associated email"}, status=400)-- target_user = User.objects.filter(email__iexact=email).first()- if not target_user:- return JsonResponse({"error": "No user found for this email"}, status=404)-- reason = f"Support ticket #{ticket.ticket_number}"-- # django-loginas reads the reason from request.POST, so inject it for the reason check.- request.POST = request.POST.copy()- request.POST["reason"] = reason-- staff_user = request.user- loginas_user_login(request, str(target_user.id))-- # A loginas rejection (CAN_LOGIN_AS, missing reason) redirects without touching the- # session, and its rejection redirect can equal the success one (referer defaults- # to "/"), so neither the response nor is_impersonated_session alone can distinguish- # this attempt from an impersonation that was already active. A successful login- # rebinds request.user to the target — gate the session mutations on that, so a- # rejected attempt can't stamp this ticket (or an impersonation_started event for- # its user) onto an unrelated session.- login_succeeded = is_impersonated_session(request) and request.user.pk == target_user.pk- if not login_succeeded:- return JsonResponse({"error": "Failed to initiate impersonation"}, status=403)-- _configure_impersonation_session(- request,- staff_user,- target_user,- is_read_only=True,- reason=reason,- ticket_id=str(ticket.id),- )-- # The resolved account's email can differ from the ticket's mutable email trait;- # return it so the frontend keys its return-to-ticket context on the identity- # actually impersonated.- return JsonResponse({"success": True, "ticket_id": str(ticket.id), "email": target_user.email})diff --git a/ee/urls.py b/ee/urls.pyindex 3d20a799a130..844f4e2a425f 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -15,7 +15,7 @@ from posthog.views import api_key_search_view, redis_edit_ttl_view, redis_valuesfrom products.cdp.backend.api import hooks-from ee.admin.loginas_views import loginas_user, loginas_user_from_ticket, upgrade_impersonation+from ee.admin.loginas_views import loginas_user, upgrade_impersonationfrom ee.admin.oauth_views import admin_auth_check, admin_oauth_successfrom ee.api import integrationfrom ee.api.agentic_provisioning import views as agentic_provisioning_views@@ -227,7 +227,6 @@ if settings.ADMIN_PORTAL_ENABLED:),path("admin/login/user/<str:user_id>/", loginas_user, name="loginas-user-login"),path("admin/impersonation/upgrade/", upgrade_impersonation, name="impersonation-upgrade"),- path("admin/impersonation/from-ticket/", loginas_user_from_ticket, name="impersonation-from-ticket"),path("admin/", include("loginas.urls")),path("admin/", admin.site.urls),]diff --git a/frontend/src/layout/navigation/ImpersonationNotice/AdminLoginButtons.tsx b/frontend/src/layout/navigation/ImpersonationNotice/AdminLoginButtons.tsxindex 5126766fea24..4a910cd909ab 100644--- a/frontend/src/layout/navigation/ImpersonationNotice/AdminLoginButtons.tsx+++ b/frontend/src/layout/navigation/ImpersonationNotice/AdminLoginButtons.tsx@@ -1,32 +1,40 @@-import { useActions, useValues } from 'kea'-import { LemonButton } from '@posthog/lemon-ui'-import { impersonationNoticeLogic } from './impersonationNoticeLogic'+import { AdminLoginUrl, ImpersonationTicketContext } from './impersonationNoticeLogic'-export function AdminLoginButtons(): JSX.Element {- const { ticketContext, isInitiatingImpersonation } = useValues(impersonationNoticeLogic)- const { initiateImpersonation } = useActions(impersonationNoticeLogic)+export function AdminLoginButtons({+ ticketContext,+ adminLoginUrls,+}: {+ ticketContext: ImpersonationTicketContext | null+ adminLoginUrls: AdminLoginUrl[]+}): JSX.Element {+ const disabledReason = !ticketContext?.email ? 'This ticket has no associated email' : undefined- const disabledReason = !ticketContext?.email- ? 'This ticket has no associated email'- : ticketContext.identityVerified === false- ? "This customer's identity could not be verified, so login as is disabled"- : undefined+ // Region is ambiguous when we couldn't infer it, so we offer one button per+ // region and label each so staff know which admin page they're opening.+ const showRegionLabel = adminLoginUrls.length > 1- // Resolving the customer's region and user happens server-side, so a single- // button suffices — staff are routed to the right region automatically.return (<div className="flex flex-wrap justify-end gap-2">- <LemonButton- type="secondary"- size="small"- disabledReason={disabledReason}- loading={isInitiatingImpersonation}- onClick={() => initiateImpersonation()}- >- Login as {ticketContext?.email || 'customer'}- </LemonButton>+ {disabledReason ? (+ <LemonButton type="secondary" size="small" disabledReason={disabledReason}>+ Login as {ticketContext?.email || 'customer'}+ </LemonButton>+ ) : (+ adminLoginUrls.map(({ region, url }) => (+ <LemonButton+ key={region}+ type="secondary"+ size="small"+ tooltip="This currently redirects to the admin login page, but in future will log you in directly."+ onClick={() => window.open(url, '_blank')}+ >+ Login as {ticketContext?.email}+ {showRegionLabel ? ` (${region})` : ''}+ </LemonButton>+ ))+ )}</div>)}diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsxindex 9043ebcb500a..fd55c88f2756 100644--- a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx@@ -18,8 +18,13 @@ import { userLogic } from 'scenes/userLogic'import { OrganizationMemberType } from '~/types'import { AdminLoginButtons } from './AdminLoginButtons'-import { ExpiredSessionInfo, ImpersonationTicketContext, impersonationNoticeLogic } from './impersonationNoticeLogic'-import { ImpersonationReasonModal, ImpersonationReasonModalCancelButton } from './ImpersonationReasonModal'+import {+ AdminLoginUrl,+ ExpiredSessionInfo,+ ImpersonationTicketContext,+ impersonationNoticeLogic,+} from './impersonationNoticeLogic'+import { ImpersonationReasonModal } from './ImpersonationReasonModal'// One row in the "Change user" dropdown: name on top, email beneath in muted text, level pill on the right.function ChangeUserMenuItemLabel({@@ -77,7 +82,13 @@ function CountDown({ datetime, callback }: { datetime: dayjs.Dayjs; callback?: (return <span className="tabular-nums">{countdown}</span>}-function LoginAsContent({ ticketContext }: { ticketContext: ImpersonationTicketContext }): JSX.Element {+function LoginAsContent({+ ticketContext,+ adminLoginUrls,+}: {+ ticketContext: ImpersonationTicketContext+ adminLoginUrls: AdminLoginUrl[]+}): JSX.Element {return (<><p className="ImpersonationNotice__message">@@ -89,43 +100,17 @@ function LoginAsContent({ ticketContext }: { ticketContext: ImpersonationTicketC'No customer email on this ticket')}</p>- <AdminLoginButtons />+ <AdminLoginButtons ticketContext={ticketContext} adminLoginUrls={adminLoginUrls} /></>)}function ImpersonationExpiredOverlay({ expiredSessionInfo }: { expiredSessionInfo: ExpiredSessionInfo }): JSX.Element {- const { isReImpersonating, expiredSessionFromTicket, returnTicketLabel, returnTicketReason, isReturningToTicket } =- useValues(impersonationNoticeLogic)- const { reImpersonate, returnToPostHog, returnToTicket } = useActions(impersonationNoticeLogic)+ const { isReImpersonating } = useValues(impersonationNoticeLogic)+ const { reImpersonate, returnToPostHog } = useActions(impersonationNoticeLogic)const [readOnly, setReadOnly] = useState(true)- const cancelButton: ImpersonationReasonModalCancelButton =- expiredSessionFromTicket && returnTicketLabel- ? {- label: returnTicketLabel,- onClick: () => returnToTicket(),- loading: isReturningToTicket,- }- : {- label: 'Return to admin',- status: 'danger',- onClick: () => {- window.location.href = '/admin/'- },- sideAction: {- dropdown: {- placement: 'top-end',- overlay: (- <LemonButton fullWidth onClick={() => returnToPostHog()}>- Return to PostHog- </LemonButton>- ),- },- },- }-return (<ImpersonationReasonModalisOpen@@ -134,9 +119,25 @@ function ImpersonationExpiredOverlay({ expiredSessionInfo }: { expiredSessionInfdescription={`Your session impersonating ${expiredSessionInfo.email} has expired.`}confirmText="Re-impersonate"loading={isReImpersonating}- initialReason={expiredSessionFromTicket ? returnTicketReason : (expiredSessionInfo.reason ?? '')}+ initialReason={expiredSessionInfo.reason ?? ''}onConfirm={(reason) => reImpersonate(reason, readOnly)}- cancelButton={cancelButton}+ cancelButton={{+ label: 'Return to admin',+ status: 'danger',+ onClick: () => {+ window.location.href = '/admin/'+ },+ sideAction: {+ dropdown: {+ placement: 'top-end',+ overlay: (+ <LemonButton fullWidth onClick={() => returnToPostHog()}>+ Return to PostHog+ </LemonButton>+ ),+ },+ },+ }}><LemonCheckbox checked={readOnly} onChange={setReadOnly} label="Read-only mode (recommended)" /></ImpersonationReasonModal>@@ -154,10 +155,6 @@ function ImpersonationNoticeContent(): JSX.Element {hasOtherMembers,isChangingUser,membersLoading,- canReturnToTicket,- returnTicketLabel,- returnTicketReason,- isReturningToTicket,} = useValues(impersonationNoticeLogic)const {closeUpgradeModal,@@ -167,7 +164,6 @@ function ImpersonationNoticeContent(): JSX.Element {returnToPostHog,changeUser,ensureAllMembersLoaded,- returnToTicket,} = useActions(impersonationNoticeLogic)// The user the operator picked to switch to; drives the confirm-reason modal.@@ -261,34 +257,23 @@ function ImpersonationNoticeContent(): JSX.Element {Upgrade to read-write</LemonButton>)}- {canReturnToTicket ? (- <LemonButton- type="primary"- size="small"- loading={isReturningToTicket}- onClick={() => returnToTicket()}- >- {returnTicketLabel}- </LemonButton>- ) : (- <LemonButton- type="primary"- size="small"- onClick={() => logout()}- sideAction={{- dropdown: {- placement: 'top-end',- overlay: (- <LemonButton fullWidth size="small" onClick={() => returnToPostHog()}>- Log out to PostHog- </LemonButton>- ),- },- }}- >- Log out to admin- </LemonButton>- )}+ <LemonButton+ type="primary"+ size="small"+ onClick={() => logout()}+ sideAction={{+ dropdown: {+ placement: 'top-end',+ overlay: (+ <LemonButton fullWidth size="small" onClick={() => returnToPostHog()}>+ Log out to PostHog+ </LemonButton>+ ),+ },+ }}+ >+ Log out to admin+ </LemonButton></div>{isReadOnly && (<ImpersonationReasonModal@@ -299,7 +284,7 @@ function ImpersonationNoticeContent(): JSX.Element {description="Read-write mode allows you to make changes on behalf of the user. Please provide a reason for this upgrade."confirmText="Upgrade"loading={isImpersonationUpgradeInProgress}- initialReason={canReturnToTicket ? returnTicketReason : (storedReason ?? '')}+ initialReason={storedReason ?? ''}/>)}<ImpersonationReasonModal@@ -324,8 +309,15 @@ function ImpersonationNoticeContent(): JSX.Element {export function ImpersonationNotice(): JSX.Element | null {const { user } = useValues(userLogic)- const { isMinimized, isReadOnly, isImpersonated, isSessionExpired, expiredSessionInfo, ticketContext } =- useValues(impersonationNoticeLogic)+ const {+ isMinimized,+ isReadOnly,+ isImpersonated,+ isSessionExpired,+ expiredSessionInfo,+ ticketContext,+ adminLoginUrls,+ } = useValues(impersonationNoticeLogic)const { minimize, maximize, setPageVisible } = useActions(impersonationNoticeLogic)const { isVisible: isPageVisible } = usePageVisibility()@@ -401,7 +393,7 @@ export function ImpersonationNotice(): JSX.Element | null {</div><div className="ImpersonationNotice__content">{showLoginAs ? (- <LoginAsContent ticketContext={ticketContext!} />+ <LoginAsContent ticketContext={ticketContext!} adminLoginUrls={adminLoginUrls} />) : (<ImpersonationNoticeContent />)}diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsxindex 73e167dd506d..48e5937024b9 100644--- a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx@@ -7,7 +7,6 @@ export interface ImpersonationReasonModalCancelButton {status?: 'default' | 'danger'onClick: () => voidsideAction?: SideAction- loading?: boolean}export interface ImpersonationReasonModalProps {@@ -84,7 +83,6 @@ export function ImpersonationReasonModal({status={cancel.status}onClick={cancel.onClick}sideAction={cancel.sideAction}- loading={cancel.loading}>{cancel.label}</LemonButton>diff --git a/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.ts b/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.tsindex dcd1d147f163..00f15f4392f8 100644--- a/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.ts+++ b/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.ts@@ -97,35 +97,3 @@ export async function adminLoginAs({ userId, reason, readOnly }: AdminLoginAsParthrow new Error(`django-loginas request resulted in status ${loginResponse.status}`)}}--export interface LoginAsFromTicketResult {- success?: boolean- ticket_id?: string- // Email of the account actually impersonated — can differ from the ticket's- // mutable email trait when the target was resolved from the attested identity.- email?: string- // Set when the ticket belongs to a different region; staff should be sent there instead.- redirect_url?: string- redirect_region?: string-}--export async function loginAsFromTicket(ticketId: string): Promise<LoginAsFromTicketResult> {- await ensureAdminOAuth2()-- const response = await fetch('/admin/impersonation/from-ticket/', {- method: 'POST',- credentials: 'same-origin',- mode: 'cors',- headers: {- 'X-CSRFToken': getCookie('posthog_csrftoken') as string,- 'Content-Type': 'application/json',- },- body: JSON.stringify({ ticket_id: ticketId }),- })-- const data: LoginAsFromTicketResult & { error?: string } = await response.json().catch(() => ({}))- if (!response.ok) {- throw new Error(data.error || `Impersonation request resulted in status ${response.status}`)- }- return data-}diff --git a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.tsindex 9ec8d8a5a14f..5c5807c974b9 100644--- a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts+++ b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts@@ -28,7 +28,6 @@ jest.mock('@posthog/lemon-ui', () => {...actual.lemonToast,success: jest.fn(),error: jest.fn(),- info: jest.fn(),},}})@@ -69,9 +68,6 @@ describe('impersonationNoticeLogic', () => {let logic: ReturnType<typeof impersonationNoticeLogic.build>beforeEach(() => {- // returnToTicketContext is a persisted reducer; clear storage so a value set- // in one test doesn't leak into the next.- localStorage.clear()useMocks({get: {'/api/users/@me/': () => [200, MOCK_DEFAULT_USER],@@ -166,260 +162,47 @@ describe('impersonationNoticeLogic', () => {isReadOnly: true,})})- })-- describe('initiateImpersonation listener', () => {- const TICKET_ID = 'b6d0f1e2-0000-4000-8000-000000000000'-- it('opens the other region admin and clears loading when the ticket is cross-region', async () => {- logic.actions.setTicketContext({ ticketId: TICKET_ID, email: '[email protected]', region: Region.EU })- useMocks({- get: { '/admin/auth_check': () => [200, {}] },- post: {- '/admin/impersonation/from-ticket/': () => [- 200,- { redirect_region: 'EU', redirect_url: 'https://eu.posthog.com/admin/posthog/user/?q=a' },- ],- },- })- const openSpy = jest.spyOn(window, 'open').mockReturnValue({} as Window)-- await expectLogic(logic, () => {- logic.actions.initiateImpersonation()- })- .toFinishAllListeners()- .toMatchValues({ isInitiatingImpersonation: false })-- expect(openSpy).toHaveBeenCalledWith('https://eu.posthog.com/admin/posthog/user/?q=a', '_blank')- expect(lemonToast.info).toHaveBeenCalled()- openSpy.mockRestore()- })-- it('surfaces a manual open action instead of a success toast when the cross-region popup is blocked', async () => {- logic.actions.setTicketContext({ ticketId: TICKET_ID, email: '[email protected]', region: Region.EU })- useMocks({- get: { '/admin/auth_check': () => [200, {}] },- post: {- '/admin/impersonation/from-ticket/': () => [- 200,- { redirect_region: 'EU', redirect_url: 'https://eu.posthog.com/admin/posthog/user/?q=a' },- ],- },- })- const openSpy = jest.spyOn(window, 'open').mockReturnValue(null)-- await expectLogic(logic, () => {- logic.actions.initiateImpersonation()- })- .toFinishAllListeners()- .toMatchValues({ isInitiatingImpersonation: false })-- expect(lemonToast.info).not.toHaveBeenCalled()- expect(lemonToast.error).toHaveBeenCalledWith(- expect.stringContaining('Popup blocked'),- expect.objectContaining({ button: expect.objectContaining({ label: 'Open' }) })- )- openSpy.mockRestore()- })-- it('shows an error toast and clears loading when the endpoint fails', async () => {- logic.actions.setTicketContext({ ticketId: TICKET_ID, email: '[email protected]', region: Region.US })- useMocks({- get: { '/admin/auth_check': () => [200, {}] },- post: {- '/admin/impersonation/from-ticket/': () => [404, { error: 'No user found for this email' }],- },- })- await expectLogic(logic, () => {- logic.actions.initiateImpersonation()+ describe('adminLoginUrls', () => {+ it('returns no urls when there is no ticket context', async () => {+ await expectLogic(logic).toMatchValues({ adminLoginUrls: [] })})- .toFinishAllListeners()- .toMatchValues({ isInitiatingImpersonation: false })- expect(lemonToast.error).toHaveBeenCalledWith('No user found for this email')- })+ it('returns no urls when the ticket has no email', async () => {+ logic.actions.setTicketContext({ ticketId: '1', email: '', region: Region.US })- it('does nothing without a ticket context', async () => {- await expectLogic(logic, () => {- logic.actions.initiateImpersonation()+ await expectLogic(logic).toMatchValues({ adminLoginUrls: [] })})- .toFinishAllListeners()- .toMatchValues({ isInitiatingImpersonation: false })- expect(lemonToast.error).not.toHaveBeenCalled()- })+ it('returns a single region url when the region is known', async () => {+ logic.actions.setTicketContext({ ticketId: '1', email: '[email protected]', region: Region.EU })- it('persists the return-to-ticket context on the same-region success path', async () => {- logic.actions.setTicketContext({- ticketId: TICKET_ID,- ticketNumber: 42,- email: '[email protected]',- region: Region.US,- })- useMocks({- get: { '/admin/auth_check': () => [200, {}] },- post: {- '/admin/impersonation/from-ticket/': () => [- 200,- // The backend returns the resolved account's email, which can differ- // from the ticket trait — the stored context must use the resolved one.- { success: true, ticket_id: TICKET_ID, email: '[email protected]' },+ await expectLogic(logic).toMatchValues({+ adminLoginUrls: [+ {+ region: Region.EU,+ url: 'https://eu.posthog.com/admin/posthog/user/?q=a%2Bb%40example.com',+ },],- },- })- const originalLocation = window.location- Object.defineProperty(window, 'location', {- configurable: true,- writable: true,- value: { ...originalLocation, replace: jest.fn() },- })-- try {- await expectLogic(logic, () => {- logic.actions.initiateImpersonation()})- .toFinishAllListeners()- .toMatchValues({- returnToTicketContext: { ticketNumber: 42, email: '[email protected]' },- })-- expect(window.location.replace).toHaveBeenCalledWith('/')- } finally {- Object.defineProperty(window, 'location', {- configurable: true,- writable: true,- value: originalLocation,- })- }- })- })-- describe('returnToTicket listener', () => {- it('logs out of impersonation back to the ticket and shows a loading state', async () => {- logic.actions.setReturnToTicketContext({ ticketNumber: 42, email: '[email protected]' })-- const originalLocation = window.location- Object.defineProperty(window, 'location', {- configurable: true,- writable: true,- value: { ...originalLocation, href: originalLocation.href },})- try {- await expectLogic(logic, () => {- logic.actions.returnToTicket()- })- .toFinishAllListeners()- // Context is intentionally kept so the button doesn't flip variants- // before navigating; isReturningToTicket drives the loading state.- .toMatchValues({- returnToTicketContext: { ticketNumber: 42, email: '[email protected]' },- isReturningToTicket: true,- })-- expect(window.location.href).toBe('/admin/logout/?next=%2Fsupport%2Ftickets%2F42')- } finally {- Object.defineProperty(window, 'location', {- configurable: true,- writable: true,- value: originalLocation,- })- }- })+ it('falls back to both production regions when the region is unknown', async () => {+ logic.actions.setTicketContext({ ticketId: '1', email: '[email protected]' })- it('does nothing when there is no stored ticket context', async () => {- const originalLocation = window.location- Object.defineProperty(window, 'location', {- configurable: true,- writable: true,- value: { ...originalLocation, href: 'sentinel' },- })-- try {- await expectLogic(logic, () => {- logic.actions.returnToTicket()- }).toFinishAllListeners()-- expect(window.location.href).toBe('sentinel')- } finally {- Object.defineProperty(window, 'location', {- configurable: true,- writable: true,- value: originalLocation,+ await expectLogic(logic).toMatchValues({+ adminLoginUrls: [+ {+ region: Region.US,+ url: 'https://us.posthog.com/admin/posthog/user/?q=slack%40example.com',+ },+ {+ region: Region.EU,+ url: 'https://eu.posthog.com/admin/posthog/user/?q=slack%40example.com',+ },+ ],})- }- })- })-- describe('canReturnToTicket selector', () => {- const matchingEmail = MOCK_IMPERSONATED_USER.email-- it.each([- { name: 'no stored context', context: null as any, user: MOCK_IMPERSONATED_USER, expected: false },- {- name: 'not impersonated',- context: { ticketNumber: 42, email: matchingEmail },- user: MOCK_DEFAULT_USER,- expected: false,- },- {- name: 'impersonating a different email',- context: { ticketNumber: 42, email: '[email protected]' },- user: MOCK_IMPERSONATED_USER,- expected: false,- },- {- name: 'impersonating the stored email',- context: { ticketNumber: 42, email: matchingEmail },- user: MOCK_IMPERSONATED_USER,- expected: true,- },- ])('is $expected when $name', async ({ context, user, expected }) => {- userLogic.actions.loadUserSuccess(user)- if (context) {- logic.actions.setReturnToTicketContext(context)- }-- await expectLogic(logic).toMatchValues({ canReturnToTicket: expected })- })- })-- describe('expiredSessionFromTicket selector', () => {- it.each([- {- name: 'no expired session',- expired: null as any,- context: { ticketNumber: 42, email: '[email protected]' },- expected: false,- },- {- name: 'no stored context',- expired: { email: '[email protected]', userId: 1, isImpersonatedUntil: null },- context: null as any,- expected: false,- },- {- name: 'emails differ',- expired: { email: '[email protected]', userId: 1, isImpersonatedUntil: null },- context: { ticketNumber: 42, email: '[email protected]' },- expected: false,- },- {- name: 'emails match',- expired: { email: '[email protected]', userId: 1, isImpersonatedUntil: null },- context: { ticketNumber: 42, email: '[email protected]' },- expected: true,- },- ])('is $expected when $name', async ({ expired, context, expected }) => {- if (expired) {- logic.actions.setSessionExpired(expired)- }- if (context) {- logic.actions.setReturnToTicketContext(context)- }-- await expectLogic(logic).toMatchValues({ expiredSessionFromTicket: expected })+ })})})@@ -641,31 +424,6 @@ describe('impersonationNoticeLogic', () => {expect(lemonToast.success).not.toHaveBeenCalled()})-- it('drops a stored ticket when loading as a non-impersonated user', async () => {- logic.actions.setReturnToTicketContext({ ticketNumber: 42, email: '[email protected]' })-- await expectLogic(logic, () => {- logic.actions.loadUserSuccess(MOCK_DEFAULT_USER)- }).toMatchValues({ returnToTicketContext: null })- })-- it('drops a stored ticket when impersonating a different customer', async () => {- logic.actions.setReturnToTicketContext({ ticketNumber: 42, email: '[email protected]' })-- await expectLogic(logic, () => {- logic.actions.loadUserSuccess(MOCK_IMPERSONATED_USER)- }).toMatchValues({ returnToTicketContext: null })- })-- it('keeps a stored ticket while still impersonating its customer', async () => {- const context = { ticketNumber: 42, email: MOCK_IMPERSONATED_USER.email }- logic.actions.setReturnToTicketContext(context)-- await expectLogic(logic, () => {- logic.actions.loadUserSuccess(MOCK_IMPERSONATED_USER)- }).toMatchValues({ returnToTicketContext: context })- })})describe('setPageVisible listener', () => {diff --git a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.tsindex baf0e9b62e6e..0e850cc43d9a 100644--- a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts+++ b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts@@ -4,15 +4,15 @@ import { urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { CLOUD_HOSTNAMES } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { fullName } from 'lib/utils/strings'import { membersLogic } from 'scenes/organization/membersLogic'-import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { OrganizationMemberType, Region, UserType } from '~/types'-import { adminLoginAs, loginAsFromTicket } from './adminLoginAs'+import { adminLoginAs } from './adminLoginAs'export interface ExpiredSessionInfo {email: string@@ -28,20 +28,23 @@ export interface ExpiredSessionInfo {export interface ImpersonationTicketContext {ticketId: string- ticketNumber?: numberemail: stringregion?: Region- // Trust signal from the ticket: true = verified, false = assessed but unverified- // (login-as disabled), null/undefined = never assessed (login-as allowed with a caution).- identityVerified?: boolean | null}-// Persisted across the post-impersonation page reload so the notice can offer a-// one-click return to the originating support ticket. We key on email so a stale-// value never attaches itself to an unrelated impersonation session.-export interface ReturnToTicketContext {- ticketNumber: number- email: string+export interface AdminLoginUrl {+ region: Region+ url: string+}++// When a ticket's region is unknown (e.g. tickets opened from a Slack channel+// carry no app URL to infer it from), fall back to offering a lookup in each+// production cloud region rather than no link at all.+const ADMIN_LOOKUP_REGIONS: Region[] = [Region.US, Region.EU]++function adminLoginUrlForRegion(region: Region, email: string): string {+ const domain = CLOUD_HOSTNAMES[region]+ return `https://${domain}/admin/posthog/user/?q=${encodeURIComponent(email)}`}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -51,24 +54,18 @@ export interface impersonationNoticeLogicValues {membersLoading: boolean // membersLogicisImpersonationUpgradeInProgress: boolean // userLogicuser: UserType | null // userLogic- canReturnToTicket: boolean- expiredSessionFromTicket: boolean+ adminLoginUrls: AdminLoginUrl[]expiredSessionInfo: ExpiredSessionInfo | nullhasOtherMembers: booleanisChangingUser: booleanisImpersonated: boolean- isInitiatingImpersonation: booleanisMinimized: booleanisReImpersonating: booleanisReadOnly: boolean- isReturningToTicket: booleanisSessionExpired: booleanisUpgradeModalOpen: booleanorderedMembers: OrganizationMemberType[]pageHiddenAt: number | null- returnTicketLabel: string | null- returnTicketReason: string- returnToTicketContext: ReturnToTicketContext | nullticketContext: ImpersonationTicketContext | null}@@ -93,9 +90,6 @@ export interface impersonationNoticeLogicActions {}user: UserType | null} // userLogic- logout: (preserveLocation?: any) => {- preserveLocation: any- } // userLogicupgradeImpersonation: (reason: string) => {reason: string} // userLogic@@ -128,12 +122,6 @@ export interface impersonationNoticeLogicActions {closeUpgradeModal: () => {value: true}- initiateImpersonation: () => {- value: true- }- initiateImpersonationComplete: () => {- value: true- }maximize: () => {value: true}@@ -156,15 +144,9 @@ export interface impersonationNoticeLogicActions {returnToPostHog: () => {value: true}- returnToTicket: () => {- value: true- }setPageVisible: (visible: boolean) => {visible: boolean}- setReturnToTicketContext: (context: ReturnToTicketContext | null) => {- context: ReturnToTicketContext | null- }setSessionExpired: (info: ExpiredSessionInfo | null) => {info: ExpiredSessionInfo | null}@@ -178,6 +160,7 @@ export interface impersonationNoticeLogicMeta {__keaTypeGenInternalSelectorTypes: {isReadOnly: (user: UserType | null) => booleanisImpersonated: (user: UserType | null) => boolean+ adminLoginUrls: (ticketContext: ImpersonationTicketContext | null) => AdminLoginUrl[]isSessionExpired: (expiredSessionInfo: ExpiredSessionInfo | null) => booleanorderedMembers: (members: OrganizationMemberType[] | null,@@ -185,13 +168,6 @@ export interface impersonationNoticeLogicMeta {user: UserType | null) => OrganizationMemberType[]hasOtherMembers: (orderedMembers: OrganizationMemberType[], user: UserType | null) => boolean- canReturnToTicket: (user: UserType | null, returnToTicketContext: ReturnToTicketContext | null) => boolean- expiredSessionFromTicket: (- expiredSessionInfo: ExpiredSessionInfo | null,- returnToTicketContext: ReturnToTicketContext | null- ) => boolean- returnTicketLabel: (returnToTicketContext: ReturnToTicketContext | null) => string | null- returnTicketReason: (returnToTicketContext: ReturnToTicketContext | null) => string}}@@ -214,7 +190,7 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([],actions: [userLogic,- ['upgradeImpersonation', 'upgradeImpersonationSuccess', 'loadUser', 'loadUserSuccess', 'logout'],+ ['upgradeImpersonation', 'upgradeImpersonationSuccess', 'loadUser', 'loadUserSuccess'],membersLogic,['ensureAllMembersLoaded'],],@@ -228,16 +204,12 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([setPageVisible: (visible: boolean) => ({ visible }),clearPageHiddenAt: true,setTicketContext: (context: ImpersonationTicketContext | null) => ({ context }),- initiateImpersonation: true,- initiateImpersonationComplete: true,setSessionExpired: (info: ExpiredSessionInfo | null) => ({ info }),reImpersonate: (reason: string, readOnly: boolean) => ({ reason, readOnly }),reImpersonateFailure: (error: string) => ({ error }),changeUser: (userId: number, reason?: string) => ({ userId, reason }),changeUserFailure: (error: string) => ({ error }),returnToPostHog: true,- setReturnToTicketContext: (context: ReturnToTicketContext | null) => ({ context }),- returnToTicket: true,}),reducers({@@ -270,13 +242,6 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([setTicketContext: (_, { context }) => context,},],- isInitiatingImpersonation: [- false,- {- initiateImpersonation: () => true,- initiateImpersonationComplete: () => false,- },- ],expiredSessionInfo: [null as ExpiredSessionInfo | null,{@@ -298,24 +263,24 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([changeUserFailure: () => false,},],- returnToTicketContext: [- null as ReturnToTicketContext | null,- { persist: true },- {- setReturnToTicketContext: (_, { context }) => context,- },- ],- isReturningToTicket: [- false,- {- returnToTicket: () => true,- },- ],}),selectors({isReadOnly: [(s) => [s.user], (user: UserType | null): boolean => user?.is_impersonated_read_only ?? true],isImpersonated: [(s) => [s.user], (user: UserType | null): boolean => user?.is_impersonated ?? false],+ adminLoginUrls: [+ (s) => [s.ticketContext],+ (ticketContext: ImpersonationTicketContext | null): AdminLoginUrl[] => {+ if (!ticketContext?.email) {+ return []+ }+ const regions = ticketContext.region ? [ticketContext.region] : ADMIN_LOOKUP_REGIONS+ return regions.map((region) => ({+ region,+ url: adminLoginUrlForRegion(region, ticketContext.email),+ }))+ },+ ],isSessionExpired: [(s) => [s.expiredSessionInfo], (info: ExpiredSessionInfo | null): boolean => info !== null],// Current user (via me) is shown in place among members, so their row appears before members load.orderedMembers: [@@ -340,95 +305,14 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([(orderedMembers: OrganizationMemberType[], user: UserType | null): boolean =>orderedMembers.some((member) => member.user.uuid !== user?.uuid),],- canReturnToTicket: [- (s) => [s.user, s.returnToTicketContext],- (user: UserType | null, context: ReturnToTicketContext | null): boolean =>- context !== null && (user?.is_impersonated ?? false) && user?.email === context.email,- ],- // The expired session belongs to a ticket impersonation if its email matches- // the stored ticket context — the live user may already be gone by then.- expiredSessionFromTicket: [- (s) => [s.expiredSessionInfo, s.returnToTicketContext],- (expired: ExpiredSessionInfo | null, context: ReturnToTicketContext | null): boolean =>- expired !== null && context !== null && expired.email === context.email,- ],- returnTicketLabel: [- (s) => [s.returnToTicketContext],- (context: ReturnToTicketContext | null): string | null =>- context ? `Return to ticket #${context.ticketNumber}` : null,- ],- returnTicketReason: [- (s) => [s.returnToTicketContext],- (context: ReturnToTicketContext | null): string =>- context ? `Investigating ticket #${context.ticketNumber}` : '',- ],}),listeners(({ actions, values }) => ({returnToPostHog: () => {// Restore the original staff login (via the loginas logout endpoint) and// land back in the PostHog app rather than the Django admin.- actions.setReturnToTicketContext(null)window.location.href = `/admin/logout/?next=${encodeURIComponent('/')}`},- returnToTicket: () => {- const { returnToTicketContext } = values- if (!returnToTicketContext) {- return- }- // Returning to the ticket means dropping the customer impersonation and- // landing back on the support ticket as the original staff user.- const next = urls.supportTicketDetail(returnToTicketContext.ticketNumber)- window.location.href = `/admin/logout/?next=${encodeURIComponent(next)}`- },- logout: () => {- // A plain logout abandons impersonation entirely; drop the stored ticket- // so it can't reattach to a later session for the same customer email.- actions.setReturnToTicketContext(null)- },- initiateImpersonation: async () => {- const { ticketContext } = values- if (!ticketContext) {- actions.initiateImpersonationComplete()- return- }-- try {- const result = await loginAsFromTicket(ticketContext.ticketId)- if (result.redirect_url) {- // Ticket belongs to another region — open that region's admin instead.- // This runs several awaits after the click, so the browser may block- // the popup; surface the URL behind a button (a click restores the- // user gesture) instead of reporting success with no tab.- const redirectUrl = result.redirect_url- const opened = window.open(redirectUrl, '_blank')- if (opened) {- lemonToast.info(`This ticket is from ${result.redirect_region}. Opening in a new tab…`)- } else {- lemonToast.error(`Popup blocked — open the ${result.redirect_region} admin to continue.`, {- button: { label: 'Open', action: () => window.open(redirectUrl, '_blank') },- })- }- actions.initiateImpersonationComplete()- return- }- // Staying in this tab as the impersonated customer — remember the- // ticket so the notice can offer a one-click return after the reload.- // Prefer the resolved account's email: the ticket trait can diverge from- // it on verified tickets, and the return button gates on an email match.- if (ticketContext.ticketNumber != null) {- actions.setReturnToTicketContext({- ticketNumber: ticketContext.ticketNumber,- email: result.email || ticketContext.email,- })- }- // Reload into the app as the impersonated customer.- window.location.replace('/')- } catch (e) {- lemonToast.error(e instanceof Error ? e.message : 'Failed to impersonate user')- actions.initiateImpersonationComplete()- }- },upgradeImpersonationSuccess: () => {if (values.isUpgradeModalOpen && !values.isReadOnly) {actions.closeUpgradeModal()@@ -470,16 +354,6 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([}},loadUserSuccess: ({ user }) => {- // Keep the stored ticket only while we're still impersonating the customer it- // belongs to. Any other load — back to staff, or impersonating someone else —- // means it has outlived its session, so drop it before it can reattach to an- // unrelated impersonation. A same-customer re-impersonation by a non-ticket- // path is indistinguishable here (we have no server-side signal tying an- // impersonation to a ticket) and will still match.- const ticket = values.returnToTicketContext- if (ticket && !(user?.is_impersonated && user.email === ticket.email)) {- actions.setReturnToTicketContext(null)- }const { expiredSessionInfo } = valuesif (!expiredSessionInfo) {returndiff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 5fb96e69c762..1d7d69399ef7 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -61,7 +61,6 @@ from posthog.helpers.two_factor_session import (set_two_factor_verified_in_session,)from posthog.helpers.user_devices import has_valid_known_device_cookie-from posthog.middleware import IMPERSONATION_TICKET_ID_SESSION_KEYfrom posthog.models import OrganizationDomain, Userfrom posthog.models.activity_logging import signal_handlers # noqa: F401from posthog.models.webauthn_credential import WebauthnCredential@@ -99,13 +98,7 @@ def logout(request):if is_impersonated_session(request):impersonated_user_pk = request.user.pk- ticket_id = request.session.get(IMPERSONATION_TICKET_ID_SESSION_KEY)restore_original_login(request)- # When the session was started from a support ticket, land staff back on- # that ticket rather than the Django admin user page. ticket_id is a- # server-stored UUID, so this is always a safe relative path.- if ticket_id:- return redirect(f"/support/tickets/{ticket_id}")return redirect(f"/admin/posthog/user/{impersonated_user_pk}/change/")auth_logout(request)diff --git a/posthog/middleware.py b/posthog/middleware.pyindex e6df327675e1..a3266f69cb9d 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -1313,9 +1313,6 @@ IMPERSONATION_READ_ONLY_SESSION_KEY = "impersonation_read_only"# in-app starts and can be surfaced to the frontend and the activity log.IMPERSONATION_REASON_SESSION_KEY = "impersonation_reason"-# Session key holding the support ticket an impersonation session was started from-IMPERSONATION_TICKET_ID_SESSION_KEY = "impersonation_ticket_id"-def is_read_only_impersonation(request: HttpRequest) -> bool:"""Check if the current session is a read-only impersonation session."""diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 0642858dde54..463ba782e84c 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -72,11 +72,6 @@ LLM_ANALYTICS_INTERNAL_TEAM_ID: int = 2# Must hold the same value in both regions; unset disables the proxy.PERSONAL_SPEND_CROSS_REGION_SECRET: str = get_from_env("PERSONAL_SPEND_CROSS_REGION_SECRET", "")-# PostHog's own internal support project (US cloud). Support tickets and ticket-based-# "login as customer" impersonation are scoped to this team. Set the env var in local-# dev to point at your dev project; override in tests via @override_settings.-POSTHOG_INTERNAL_TEAM_ID: int = get_from_env("POSTHOG_INTERNAL_TEAM_ID", 2, type_cast=int)-# Duckgres - URL, internal secret, and PG endpoint for the managed warehouse serviceDUCKGRES_API_URL: str | None = get_from_env("DUCKGRES_API_URL", optional=True)DUCKGRES_INTERNAL_SECRET: str | None = get_from_env("DUCKGRES_INTERNAL_SECRET", optional=True)diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex b4b1680e25d7..785cee01aa8f 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -1,5 +1,4 @@import json-import uuidfrom datetime import datetime, timedeltafrom typing import Any, cast@@ -26,7 +25,7 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParametefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_team-from posthog.middleware import IMPERSONATION_TICKET_ID_SESSION_KEY, per_request_logging_context_middleware+from posthog.middleware import per_request_logging_context_middlewarefrom posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -34,7 +33,6 @@ from posthog.settings import SITE_URLfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort-from products.conversations.backend.models import Ticketfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insight@@ -2317,189 +2315,3 @@ class TestPerRequestLoggingContextMiddlewareMcpHeaders(APIBaseTest):assert "mcp_session_id" not in ctxassert "mcp_conversation_id" not in ctxspan.set_attribute.assert_not_called()---@override_settings(ADMIN_PORTAL_ENABLED=True, CLOUD_DEPLOYMENT="US")-class TestLoginAsFromTicket(APIBaseTest):- other_user: User-- def setUp(self):- super().setUp()- self.other_user = User.objects.create_and_join(- self.organization, email="[email protected]", password="123456"- )- self.user.is_staff = True- self.user.save()-- # The loginas admin view expects form-encoded POST data, which is Django- # Client's default (APIClient defaults to JSON).- self.client = cast(Any, DjangoClient())- self.client.force_login(self.user)-- def _create_ticket(self, traits: dict, channel_source: str = "widget") -> Ticket:- return Ticket.objects.create_with_number(- team=self.team,- widget_session_id="widget-session",- distinct_id="distinct-1",- channel_source=channel_source,- status="new",- anonymous_traits=traits,- )-- def _post(self, body: dict):- return self.client.post(- reverse("impersonation-from-ticket"),- data=json.dumps(body),- content_type="application/json",- )-- def _as_internal_team(self):- return override_settings(POSTHOG_INTERNAL_TEAM_ID=self.team.pk)-- def test_logs_in_as_customer_from_ticket(self):- ticket = self._create_ticket({"email": "[email protected]"})- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 200- assert res.json()["success"] is True- assert self.client.get("/api/users/@me").json()["email"] == "[email protected]"-- def test_logout_after_ticket_login_redirects_to_ticket(self):- ticket = self._create_ticket({"email": "[email protected]"})- with self._as_internal_team():- self._post({"ticket_id": str(ticket.id)})-- res = self.client.post("/logout/")- assert res.status_code == 302- assert res.headers["Location"] == f"/support/tickets/{ticket.id}"- assert self.client.get("/api/users/@me").json()["email"] == self.user.email-- def test_non_staff_cannot_login_from_ticket(self):- self.user.is_staff = False- self.user.save()- ticket = self._create_ticket({"email": "[email protected]"})- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 404- assert self.client.get("/api/users/@me").json()["email"] == self.user.email-- def test_unknown_ticket_returns_404(self):- with self._as_internal_team():- res = self._post({"ticket_id": str(uuid.uuid4())})- assert res.status_code == 404-- def test_ticket_without_email_returns_400(self):- ticket = self._create_ticket({})- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 400-- def test_no_user_for_email_returns_404(self):- ticket = self._create_ticket({"email": "[email protected]"})- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 404-- def test_unknown_region_falls_back_to_local_login(self):- # The region trait is customer-suppliable — an unknown value must not 500.- ticket = self._create_ticket({"email": "[email protected]", "region": "APAC"})- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 200- assert res.json()["success"] is True- assert self.client.get("/api/users/@me").json()["email"] == "[email protected]"-- def test_cross_region_ticket_returns_redirect_without_impersonating(self):- ticket = self._create_ticket({"email": "[email protected]", "region": "EU"})- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 200- data = res.json()- assert data["redirect_region"] == "EU"- assert data["redirect_url"].startswith("https://eu.posthog.com/admin/posthog/user/")- # Staff stay themselves — impersonation must not start for another region.- assert self.client.get("/api/users/@me").json()["email"] == self.user.email-- @parameterized.expand(- [- # Only an explicit False blocks; None (never assessed) and True allow login.- ("verified", True, 200, "[email protected]"),- ("unassessed", None, 200, "[email protected]"),- ("unverified", False, 400, None),- ]- )- def test_identity_verified_gates_login(self, _name, identity_verified, expected_status, expected_email):- ticket = self._create_ticket({"email": "[email protected]"})- ticket.identity_verified = identity_verified- # Verified widget tickets resolve from the attested distinct_id, not the email trait.- ticket.distinct_id = "[email protected]"- ticket.save(update_fields=["identity_verified", "distinct_id"])- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == expected_status- impersonated_email = self.client.get("/api/users/@me").json()["email"]- if expected_email is None:- # Blocked — staff must not have been logged in as the customer.- assert impersonated_email == self.user.email- else:- assert impersonated_email == expected_email-- @parameterized.expand(- [- # Widget verification attests a PostHog distinct_id; Slack/Teams/email- # channels attest an email — both land in the read-only distinct_id field.- ("widget", "distinct_id"),- ("slack", "email"),- ]- )- def test_verified_ticket_resolves_from_attested_identity_not_email_trait(self, channel_source, attested_field):- # The email trait stays mutable after verification, so a verified ticket- # claiming someone else's email must impersonate the attested identity.- attested = User.objects.create_and_join(self.organization, email="[email protected]", password="123456")- ticket = self._create_ticket({"email": "[email protected]"}, channel_source=channel_source)- ticket.identity_verified = True- ticket.distinct_id = str(attested.distinct_id) if attested_field == "distinct_id" else attested.email- ticket.save(update_fields=["identity_verified", "distinct_id"])- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 200- assert self.client.get("/api/users/@me").json()["email"] == "[email protected]"-- def test_rejected_login_during_active_impersonation_is_not_reported_as_success(self):- staff_target = User.objects.create_and_join(self.organization, email="[email protected]", password="123456")- staff_target.is_staff = True- staff_target.save()-- first = self._create_ticket({"email": "[email protected]"})- second = self._create_ticket({"email": "[email protected]"})- with self._as_internal_team():- assert self._post({"ticket_id": str(first.id)}).status_code == 200- res = self._post({"ticket_id": str(second.id)})-- # CAN_LOGIN_AS rejects staff targets without touching the session, so the- # session still impersonates the first customer — the failure must not- # masquerade as success or re-stamp the ticket context.- assert res.status_code == 403- assert self.client.get("/api/users/@me").json()["email"] == "[email protected]"- assert self.client.session.get(IMPERSONATION_TICKET_ID_SESSION_KEY) == str(first.id)-- def test_verified_ticket_with_unresolvable_identity_does_not_fall_back_to_email(self):- ticket = self._create_ticket({"email": "[email protected]"})- ticket.identity_verified = True- ticket.distinct_id = "no-such-distinct-id"- ticket.save(update_fields=["identity_verified", "distinct_id"])- with self._as_internal_team():- res = self._post({"ticket_id": str(ticket.id)})- assert res.status_code == 404- assert self.client.get("/api/users/@me").json()["email"] == self.user.email-- @parameterized.expand(- [- ("missing", {}),- ("blank", {"ticket_id": " "}),- ("invalid_uuid", {"ticket_id": "not-a-uuid"}),- ]- )- def test_invalid_ticket_id_returns_400(self, _name, body):- res = self._post(body)- assert res.status_code == 400diff --git a/products/conversations/backend/api/tests/test_widget.py b/products/conversations/backend/api/tests/test_widget.pyindex ef74e7d6897c..7d2194452a58 100644--- a/products/conversations/backend/api/tests/test_widget.py+++ b/products/conversations/backend/api/tests/test_widget.py@@ -1,9 +1,8 @@import uuid-from posthog.test.base import BaseTest, override_settings+from posthog.test.base import BaseTestfrom unittest.mock import patch-from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient@@ -543,48 +542,6 @@ class TestWidgetAPI(BaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- @parameterized.expand(- [- ("us", "https://us.posthog.com/project/2/home", "US"),- ("eu", "https://eu.posthog.com/project/2/home", "EU"),- ("unknown_subdomain", "https://app.posthog.com/home", None),- ("non_posthog", "https://example.com/home", None),- ]- )- def test_infers_region_for_internal_team(self, _name, current_url, expected_region):- with override_settings(POSTHOG_INTERNAL_TEAM_ID=self.team.pk):- response = self.client.post(- "/api/conversations/v1/widget/message",- {- "message": "Hi",- "widget_session_id": self.widget_session_id,- "distinct_id": self.distinct_id,- "session_context": {"current_url": current_url},- },- format="json",- **self._get_headers(),- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- ticket = Ticket.objects.get(id=response.json()["ticket_id"])- self.assertEqual(ticket.anonymous_traits.get("region"), expected_region)-- def test_does_not_infer_region_for_other_teams(self):- # team.pk is not the internal support team here, so no region is inferred.- response = self.client.post(- "/api/conversations/v1/widget/message",- {- "message": "Hi",- "widget_session_id": self.widget_session_id,- "distinct_id": self.distinct_id,- "session_context": {"current_url": "https://eu.posthog.com/project/2/home"},- },- format="json",- **self._get_headers(),- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- ticket = Ticket.objects.get(id=response.json()["ticket_id"])- self.assertNotIn("region", ticket.anonymous_traits)-class TestWidgetCacheInvalidation(BaseTest):"""Test that widget message creation invalidates unread count cache."""diff --git a/products/conversations/backend/api/widget.py b/products/conversations/backend/api/widget.pyindex e89877deab23..f15816b64f91 100644--- a/products/conversations/backend/api/widget.py+++ b/products/conversations/backend/api/widget.py@@ -13,9 +13,7 @@ Anonymous users are controlled by widget_session_id. Verified users are controllimport uuidimport logging-from urllib.parse import urlparse-from django.conf import settingsfrom django.db.models import F, Qfrom rest_framework import serializers, status@@ -55,19 +53,6 @@ from products.conversations.backend.services.identity import verify_identity_haslogger = logging.getLogger(__name__)-_REGION_BY_SUBDOMAIN = {"us": "US", "eu": "EU"}---def _infer_posthog_region(current_url: str) -> str | None:- """Map a *.posthog.com app URL to its cloud region (US/EU), or None if not inferable."""- try:- hostname = urlparse(current_url).hostname or ""- except ValueError:- return None- if not hostname.endswith(".posthog.com"):- return None- return _REGION_BY_SUBDOMAIN.get(hostname.split(".")[0])-class IdentityVerificationFailed(Exception):"""Raised when identity fields are present but HMAC verification fails."""@@ -149,12 +134,6 @@ class WidgetMessageView(APIView):session_id = serializer.validated_data.get("session_id")session_context = serializer.validated_data.get("session_context", {})- # For PostHog's internal support project, infer the region from the app URL- # so ticket-based "login as customer" can route staff to the right region.- if team.pk == settings.POSTHOG_INTERNAL_TEAM_ID and (current_url := session_context.get("current_url")):- if region := _infer_posthog_region(current_url):- traits["region"] = region-# Handle optional ticket_id (UUID field)raw_ticket_id = request.data.get("ticket_id")ticket_id = Nonediff --git a/products/conversations/frontend/scenes/ticket/StaffActionsPanel.tsx b/products/conversations/frontend/scenes/ticket/StaffActionsPanel.tsxindex ea349d2568f6..3851aa84e5a5 100644--- a/products/conversations/frontend/scenes/ticket/StaffActionsPanel.tsx+++ b/products/conversations/frontend/scenes/ticket/StaffActionsPanel.tsx@@ -1,16 +1,12 @@import { useValues } from 'kea'-import { LemonBanner, LemonCollapse } from '@posthog/lemon-ui'+import { LemonCollapse } from '@posthog/lemon-ui'import { AdminLoginButtons } from '~/layout/navigation/ImpersonationNotice/AdminLoginButtons'import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'export function StaffActionsPanel(): JSX.Element {- const { ticketContext } = useValues(impersonationNoticeLogic)-- // null/undefined means the identity signal was never assessed for this ticket —- // login as is still allowed, but warn staff to confirm they have the right customer.- const identityUnknown = !!ticketContext?.email && ticketContext.identityVerified == null+ const { ticketContext, adminLoginUrls } = useValues(impersonationNoticeLogic)return (<LemonCollapse@@ -22,14 +18,8 @@ export function StaffActionsPanel(): JSX.Element {header: 'Staff actions',content: (<div className="space-y-2">- {identityUnknown && (- <LemonBanner type="warning">- This ticket's identity hasn't been verified. Confirm you're logging in as the right- customer before proceeding.- </LemonBanner>- )}- <div className="flex items-center justify-between gap-2">- <span className="text-xs text-muted-alt">+ <div className="flex flex-col gap-2">+ <span className="text-xs text-muted-alt break-all">{ticketContext?.email ? (<>Customer: <span className="text-success">{ticketContext.email}</span>@@ -38,7 +28,7 @@ export function StaffActionsPanel(): JSX.Element {'No customer email on this ticket')}</span>- <AdminLoginButtons />+ <AdminLoginButtons ticketContext={ticketContext} adminLoginUrls={adminLoginUrls} /></div></div>),diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 681d720a770c..4bb0c22b53ac 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -923,10 +923,8 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([impersonationNoticeLogic.findMounted()?.actions.setTicketContext({ticketId: ticket.id,- ticketNumber: ticket.ticket_number,email: ticket.anonymous_traits?.email || '',region: regionFromUrl(ticket.session_context?.current_url),- identityVerified: ticket.identity_verified,})// Load session context data