Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(platform): alert + gate admin impersonation start via Discord (#13299)

Nicholas Tindlea242bc9392a8
diff --git a/autogpt_platform/backend/backend/api/features/admin/impersonation_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/impersonation_admin_routes.py
new file mode 100644
index 0000000000..3f6102c928
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/admin/impersonation_admin_routes.py
@@ -0,0 +1,137 @@
+"""Admin endpoint that emits a Discord audit alert when an admin begins
+impersonating a user from the admin dashboard.
+
+Design (see plan): the alert GATES impersonation. The frontend awaits this
+endpoint before swapping identity, so:
+
+- No Discord bot token configured -> skip the alert and allow the swap (200,
+ alerted=False). Keeps non-Discord / self-hosted deployments working.
+- Token configured + alert delivered -> allow the swap (200, alerted=True).
+- Token configured + alert NOT delivered -> 502, which blocks the swap. We would
+ rather kill an admin's ability to impersonate than allow it with no audit
+ alert.
+
+`discord_send_alert` does NOT raise on every failure -- a bad token raises, but a
+missing/misconfigured channel merely returns a status string. So delivery is
+treated as successful ONLY when the returned status is the block's success
+sentinel ("Message sent"); any other status raises here. A bounded timeout keeps
+a slow Discord gateway login from holding the request (and the admin's click)
+open, and never crashes the service.
+"""
+
+import asyncio
+import logging
+from typing import Optional
+
+from autogpt_libs.auth import User, requires_admin_user
+from fastapi import APIRouter, Body, HTTPException, Security
+from pydantic import BaseModel
+
+from backend.data.user import get_user_email_by_id
+from backend.util.metrics import DiscordChannel, discord_send_alert
+from backend.util.settings import Settings
+
+logger = logging.getLogger(__name__)
+settings = Settings()
+
+# Success sentinel returned by SendDiscordMessageBlock on a delivered message
+# (backend/blocks/discord/bot_blocks.py). Anything else means "not delivered".
+_DISCORD_SENT_STATUS = "Message sent"
+
+# discord_send_alert opens a full discord.Client (client.start) per call, so a
+# send can take a few seconds; bound it generously to avoid false blocks.
+_DISCORD_ALERT_TIMEOUT_SECONDS = 10.0
+
+router = APIRouter(
+ prefix="/admin",
+ tags=["admin", "impersonation"],
+ dependencies=[Security(requires_admin_user)],
+)
+
+
+class ImpersonationNotifyRequest(BaseModel):
+ target_user_id: str
+
+
+class ImpersonationNotifyResponse(BaseModel):
+ # True when the Discord alert was delivered. False only when no bot token is
+ # configured (alert intentionally skipped). A failed-but-configured alert
+ # never returns False -- it raises 502 so the caller blocks the swap.
+ alerted: bool
+
+
+ "/impersonation/notify",
+ response_model=ImpersonationNotifyResponse,
+ summary="Notify Impersonation Start",
+)
+async def notify_impersonation_start(
+ body: ImpersonationNotifyRequest = Body(...),
+ admin: User = Security(requires_admin_user),
+) -> ImpersonationNotifyResponse:
+ """Emit a Discord audit alert when an admin starts impersonating a user.
+
+ Admin-only. The alert gates impersonation: callers must treat a non-2xx
+ response as "do not impersonate".
+ """
+ target_user_id = body.target_user_id
+ # Derive the actor from the JWT (requires_admin_user), NOT get_user_id, which
+ # honors the X-Act-As-User-Id header. A lingering impersonation cookie (a
+ # prior session or another tab) would otherwise make the audit name the
+ # impersonated user instead of the real acting admin.
+ admin_user_id = admin.user_id
+
+ # Always record a server-side trail, independent of Discord and of outcome.
+ logger.info(
+ f"Admin impersonation requested: {admin_user_id} acting as user "
+ f"{target_user_id} (via admin dashboard)"
+ )
+
+ if not settings.secrets.discord_bot_token:
+ logger.debug("Discord bot token not configured; skipping impersonation alert")
+ return ImpersonationNotifyResponse(alerted=False)
+
+ try:
+ await _send_impersonation_alert(admin, target_user_id)
+ except Exception:
+ logger.warning(
+ f"Failed to deliver impersonation Discord alert "
+ f"(admin={admin_user_id} target={target_user_id})",
+ exc_info=True,
+ )
+ raise HTTPException(
+ status_code=502,
+ detail="Could not deliver impersonation audit alert; impersonation blocked",
+ )
+
+ return ImpersonationNotifyResponse(alerted=True)
+
+
+async def _send_impersonation_alert(admin: User, target_user_id: str) -> None:
+ """Send the Discord alert. Raises if it was not actually delivered."""
+ # Prefer the email carried in the JWT; fall back to a DB lookup if absent.
+ admin_email = admin.email or await _resolve_email(admin.user_id)
+ target_email = await _resolve_email(target_user_id)
+
+ content = (
+ "🕵️ **Admin impersonation started**\n"
+ f"Admin: {admin_email or 'unknown'} (`{admin.user_id}`)\n"
+ f"Now viewing as: {target_email or 'unknown'} (`{target_user_id}`)\n"
+ "Source: admin dashboard"
+ )
+
+ status = await asyncio.wait_for(
+ discord_send_alert(content, DiscordChannel.PLATFORM),
+ timeout=_DISCORD_ALERT_TIMEOUT_SECONDS,
+ )
+ if status != _DISCORD_SENT_STATUS:
+ raise RuntimeError(f"Discord alert not delivered (status: {status!r})")
+
+
+async def _resolve_email(user_id: str) -> Optional[str]:
+ """Best-effort email lookup for a friendlier alert. Never raises."""
+ try:
+ return await get_user_email_by_id(user_id)
+ except Exception:
+ logger.warning("Failed to resolve email for user %s", user_id, exc_info=True)
+ return None
diff --git a/autogpt_platform/backend/backend/api/features/admin/impersonation_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/impersonation_admin_routes_test.py
new file mode 100644
index 0000000000..61201f335a
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/admin/impersonation_admin_routes_test.py
@@ -0,0 +1,222 @@
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import fastapi
+import fastapi.testclient
+import pytest
+import pytest_mock
+from autogpt_libs.auth.jwt_utils import get_jwt_payload
+
+from backend.util.metrics import DiscordChannel
+
+from .impersonation_admin_routes import router as impersonation_router
+
+app = fastapi.FastAPI()
+app.include_router(impersonation_router)
+
+client = fastapi.testclient.TestClient(app)
+
+_MOCK_MODULE = "backend.api.features.admin.impersonation_admin_routes"
+
+_TARGET_USER_ID = "target-user-id"
+_ADMIN_EMAIL = "[email protected]"
+_TARGET_EMAIL = "[email protected]"
+
+
[email protected](autouse=True)
+def setup_app_admin_auth(mock_jwt_admin):
+ """Make every request in this module authenticate as an admin by default."""
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_admin["get_jwt_payload"]
+ yield
+ app.dependency_overrides.clear()
+
+
+def _set_token(mocker: pytest_mock.MockerFixture, token: str) -> None:
+ """Swap the module's settings for a tiny stub exposing only what's read."""
+ mocker.patch(
+ f"{_MOCK_MODULE}.settings",
+ SimpleNamespace(secrets=SimpleNamespace(discord_bot_token=token)),
+ )
+
+
+def _patch_emails(mocker: pytest_mock.MockerFixture) -> None:
+ mocker.patch(
+ f"{_MOCK_MODULE}.get_user_email_by_id",
+ new_callable=AsyncMock,
+ side_effect=lambda uid: (
+ _ADMIN_EMAIL if uid != _TARGET_USER_ID else _TARGET_EMAIL
+ ),
+ )
+
+
+def _patch_alert(mocker: pytest_mock.MockerFixture, **kwargs) -> AsyncMock:
+ return mocker.patch(
+ f"{_MOCK_MODULE}.discord_send_alert", new_callable=AsyncMock, **kwargs
+ )
+
+
+def test_notify_alert_delivered_allows(mocker: pytest_mock.MockerFixture) -> None:
+ """Token set + Discord confirms delivery -> 200 alerted=True, sent to PLATFORM."""
+ _set_token(mocker, "fake-token")
+ _patch_emails(mocker)
+ mock_alert = _patch_alert(mocker, return_value="Message sent")
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"alerted": True}
+ mock_alert.assert_awaited_once()
+ # second positional arg is the channel
+ assert mock_alert.await_args.args[1] == DiscordChannel.PLATFORM
+
+
+def test_notify_no_token_skips_alert_allows(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """No bot token -> skip the alert and allow the swap (200 alerted=False)."""
+ _set_token(mocker, "")
+ mock_alert = _patch_alert(mocker, return_value="Message sent")
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"alerted": False}
+ mock_alert.assert_not_awaited()
+
+
+def test_notify_channel_not_found_blocks(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """Misconfigured channel returns a non-success status (no raise) -> 502 block."""
+ _set_token(mocker, "fake-token")
+ _patch_emails(mocker)
+ _patch_alert(mocker, return_value="Channel not found: local-alerts")
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 502
+
+
+def test_notify_send_raises_blocks(mocker: pytest_mock.MockerFixture) -> None:
+ """Discord send raising (e.g. bad token / login failure) -> 502 block."""
+ _set_token(mocker, "fake-token")
+ _patch_emails(mocker)
+ _patch_alert(mocker, side_effect=ValueError("Login error occurred"))
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 502
+
+
+def test_notify_requires_admin_role(mock_jwt_user) -> None:
+ """Non-admin callers are rejected with 403."""
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 403
+
+
+def test_notify_actor_is_jwt_admin_not_impersonation_header(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """The audit actor comes from the JWT, never the X-Act-As-User-Id header.
+
+ Regression: using get_user_id (impersonation-aware) here would let a lingering
+ impersonation header name the impersonated user as the actor.
+ """
+ _set_token(mocker, "fake-token")
+ _patch_emails(mocker)
+ mock_alert = _patch_alert(mocker, return_value="Message sent")
+
+ response = client.post(
+ "/admin/impersonation/notify",
+ json={"target_user_id": _TARGET_USER_ID},
+ headers={"X-Act-As-User-Id": "spoofed-impersonated-id"},
+ )
+
+ assert response.status_code == 200
+ content = mock_alert.await_args.args[0]
+ assert "spoofed-impersonated-id" not in content
+
+
+def test_notify_alert_timeout_blocks(mocker: pytest_mock.MockerFixture) -> None:
+ """A Discord send that exceeds the timeout is bounded and blocks the swap."""
+ _set_token(mocker, "fake-token")
+ _patch_emails(mocker)
+
+ async def slow_alert(*_args, **_kwargs):
+ await asyncio.sleep(1)
+ return "Message sent"
+
+ mocker.patch(f"{_MOCK_MODULE}.discord_send_alert", new=slow_alert)
+ mocker.patch(f"{_MOCK_MODULE}._DISCORD_ALERT_TIMEOUT_SECONDS", 0.05)
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 502
+
+
+def test_notify_missing_target_user_id_returns_422() -> None:
+ """A request body without target_user_id fails validation."""
+ response = client.post("/admin/impersonation/notify", json={})
+ assert response.status_code == 422
+
+
+def test_notify_email_lookup_failure_is_non_fatal(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """A failed email lookup degrades to 'unknown' but still delivers (200)."""
+ _set_token(mocker, "fake-token")
+ mocker.patch(
+ f"{_MOCK_MODULE}.get_user_email_by_id",
+ new_callable=AsyncMock,
+ side_effect=Exception("DB connection lost"),
+ )
+ mock_alert = _patch_alert(mocker, return_value="Message sent")
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"alerted": True}
+ content = mock_alert.await_args.args[0]
+ assert "[email protected]" in content # admin email from the JWT
+ assert "unknown" in content # target lookup failed, degraded gracefully
+
+
+def test_notify_admin_email_comes_from_jwt_without_db_lookup(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """The admin email is read from the JWT; only the target is looked up in DB."""
+ _set_token(mocker, "fake-token")
+ mock_email = mocker.patch(
+ f"{_MOCK_MODULE}.get_user_email_by_id",
+ new_callable=AsyncMock,
+ return_value=_TARGET_EMAIL,
+ )
+ mock_alert = _patch_alert(mocker, return_value="Message sent")
+
+ response = client.post(
+ "/admin/impersonation/notify", json={"target_user_id": _TARGET_USER_ID}
+ )
+
+ assert response.status_code == 200
+ content = mock_alert.await_args.args[0]
+ assert "[email protected]" in content
+ # Admin email came from the JWT, so the DB is only hit for the target.
+ mock_email.assert_awaited_once_with(_TARGET_USER_ID)
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 64357abee8..b4cb607202 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -22,6 +22,7 @@ import backend.api.features.admin.bot_analytics_routes
import backend.api.features.admin.credit_admin_routes
import backend.api.features.admin.diagnostics_admin_routes
import backend.api.features.admin.execution_analytics_routes
+import backend.api.features.admin.impersonation_admin_routes
import backend.api.features.admin.memory_admin_routes
import backend.api.features.admin.platform_cost_routes
import backend.api.features.admin.rate_limit_admin_routes
@@ -417,6 +418,11 @@ app.include_router(
tags=["v2", "admin"],
prefix="/api/executions",
)
+app.include_router(
+ backend.api.features.admin.impersonation_admin_routes.router,
+ tags=["v2", "admin"],
+ prefix="/api",
+)
app.include_router(
backend.api.features.admin.rate_limit_admin_routes.router,
tags=["v2", "admin"],
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminImpersonationPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminImpersonationPanel.tsx
index 0c30bb55c4..75fcee6c78 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminImpersonationPanel.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminImpersonationPanel.tsx
@@ -20,6 +20,7 @@ export function AdminImpersonationPanel() {
const {
isImpersonating,
impersonatedUserId,
+ isStarting,
startImpersonating,
stopImpersonating,
} = useAdminImpersonation();
@@ -31,10 +32,11 @@ export function AdminImpersonationPanel() {
error: creditsError,
} = useGetV1GetUserCredits();
- function handleStartImpersonation() {
+ async function handleStartImpersonation() {
setError("");
- if (!userIdInput.trim()) {
+ const trimmed = userIdInput.trim();
+ if (!trimmed) {
setError("Please enter a valid user ID");
return;
}
@@ -42,19 +44,15 @@ export function AdminImpersonationPanel() {
// Basic UUID validation
const uuidRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
- if (!uuidRegex.test(userIdInput.trim())) {
+ if (!uuidRegex.test(trimmed)) {
setError("Please enter a valid UUID format user ID");
return;
}
- try {
- startImpersonating(userIdInput.trim());
- setUserIdInput("");
- } catch (err) {
- setError(
- err instanceof Error ? err.message : "Failed to start impersonation",
- );
- }
+ // startImpersonating handles its own errors (toast) and gates on the audit
+ // alert. Don't clear the input here: on success the page reloads, and on a
+ // blocked/failed alert we keep the entered ID so the admin can retry.
+ await startImpersonating(trimmed);
}
function handleStopImpersonation() {
@@ -110,11 +108,11 @@ export function AdminImpersonationPanel() {
<div className="flex space-x-2">
<Button
- onClick={handleStartImpersonation}
- disabled={isImpersonating || !userIdInput.trim()}
+ onClick={() => void handleStartImpersonation()}
+ disabled={isImpersonating || isStarting || !userIdInput.trim()}
className="min-w-[100px]"
>
- {isImpersonating ? "Active" : "Start"}
+ {isImpersonating ? "Active" : isStarting ? "Starting…" : "Start"}
</Button>
{isImpersonating && (
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/AdminImpersonationPanel.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/AdminImpersonationPanel.test.tsx
new file mode 100644
index 0000000000..a104c7d420
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/AdminImpersonationPanel.test.tsx
@@ -0,0 +1,114 @@
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { getPostV2NotifyImpersonationStartMockHandler200 } from "@/app/api/__generated__/endpoints/admin/admin.msw";
+import { getGetV1GetUserCreditsMockHandler } from "@/app/api/__generated__/endpoints/credits/credits.msw";
+import { ImpersonationState } from "@/lib/impersonation";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+
+import { AdminImpersonationPanel } from "../AdminImpersonationPanel";
+
+const NOTIFY_URL =
+ "http://localhost:3000/api/proxy/api/admin/impersonation/notify";
+const VALID_UUID = "2e7ea138-2097-425d-9cad-c660f29cc251";
+
+const toastMock = vi.fn();
+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/components/molecules/Toast/use-toast")
+ >();
+ return { ...actual, useToast: () => ({ toast: toastMock }) };
+});
+
+const reloadMock = vi.fn();
+
+beforeEach(() => {
+ toastMock.mockClear();
+ reloadMock.mockClear();
+ sessionStorage.clear();
+ Object.defineProperty(window.location, "reload", {
+ configurable: true,
+ value: reloadMock,
+ });
+ // Avoid persisting impersonation state across tests; assert reload instead.
+ vi.spyOn(ImpersonationState, "set").mockImplementation(() => {});
+ // The panel renders a live-credits demo; keep that query happy.
+ server.use(getGetV1GetUserCreditsMockHandler());
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function typeUserId(value: string) {
+ fireEvent.change(screen.getByLabelText(/user id to impersonate/i), {
+ target: { value },
+ });
+}
+
+function clickStart() {
+ fireEvent.click(screen.getByRole("button", { name: /^start$/i }));
+}
+
+describe("AdminImpersonationPanel", () => {
+ test("disables Start until a user id is entered", () => {
+ render(<AdminImpersonationPanel />);
+ const start = screen.getByRole("button", {
+ name: /^start$/i,
+ }) as HTMLButtonElement;
+ expect(start.disabled).toBe(true);
+
+ typeUserId(VALID_UUID);
+ expect(start.disabled).toBe(false);
+ });
+
+ test("rejects a non-UUID value with an inline error and no swap", async () => {
+ render(<AdminImpersonationPanel />);
+ typeUserId("not-a-uuid");
+ clickStart();
+
+ expect(await screen.findByText(/valid uuid format/i)).toBeDefined();
+ expect(reloadMock).not.toHaveBeenCalled();
+ });
+
+ test("keeps the entered id and shows a destructive toast when the alert is blocked (502)", async () => {
+ server.use(
+ http.post(NOTIFY_URL, () => new HttpResponse(null, { status: 502 })),
+ );
+
+ render(<AdminImpersonationPanel />);
+ const input = screen.getByLabelText(
+ /user id to impersonate/i,
+ ) as HTMLInputElement;
+ typeUserId(VALID_UUID);
+ clickStart();
+
+ await waitFor(() => {
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ );
+ });
+ // The fix: a blocked alert must not wipe the entered UUID.
+ expect(input.value).toBe(VALID_UUID);
+ expect(reloadMock).not.toHaveBeenCalled();
+ });
+
+ test("starts impersonation (reload) when the audit alert is delivered", async () => {
+ server.use(
+ getPostV2NotifyImpersonationStartMockHandler200({ alerted: true }),
+ );
+
+ render(<AdminImpersonationPanel />);
+ typeUserId(VALID_UUID);
+ clickStart();
+
+ await waitFor(() => expect(reloadMock).toHaveBeenCalledTimes(1));
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/useAdminImpersonation.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/useAdminImpersonation.test.tsx
new file mode 100644
index 0000000000..1371fa9037
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/__tests__/useAdminImpersonation.test.tsx
@@ -0,0 +1,145 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { delay, http, HttpResponse } from "msw";
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { getPostV2NotifyImpersonationStartMockHandler200 } from "@/app/api/__generated__/endpoints/admin/admin.msw";
+import { ImpersonationState } from "@/lib/impersonation";
+import { server } from "@/mocks/mock-server";
+import { act, renderHook, waitFor } from "@/tests/integrations/test-utils";
+
+import { useAdminImpersonation } from "../useAdminImpersonation";
+
+const NOTIFY_URL =
+ "http://localhost:3000/api/proxy/api/admin/impersonation/notify";
+const TARGET_USER_ID = "target-user-id";
+
+function wrapper({ children }: { children: ReactNode }) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
+
+const toastMock = vi.fn();
+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/components/molecules/Toast/use-toast")
+ >();
+ return { ...actual, useToast: () => ({ toast: toastMock }) };
+});
+
+const reloadMock = vi.fn();
+let setSpy: ReturnType<typeof vi.spyOn>;
+
+beforeEach(() => {
+ toastMock.mockClear();
+ reloadMock.mockClear();
+ // jsdom can't navigate; intercept the reload the hook fires on a successful swap.
+ Object.defineProperty(window.location, "reload", {
+ configurable: true,
+ value: reloadMock,
+ });
+ // Avoid real sessionStorage/cookie writes; assert call instead.
+ setSpy = vi.spyOn(ImpersonationState, "set").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("useAdminImpersonation", () => {
+ test("blocks the swap and shows a destructive toast when the audit alert fails (502)", async () => {
+ server.use(
+ http.post(NOTIFY_URL, () => new HttpResponse(null, { status: 502 })),
+ );
+
+ const { result } = renderHook(() => useAdminImpersonation(), { wrapper });
+
+ await act(async () => {
+ void result.current.startImpersonating(TARGET_USER_ID);
+ });
+
+ await waitFor(() => {
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ );
+ });
+ // The swap must NOT happen when the audit alert is not delivered.
+ expect(setSpy).not.toHaveBeenCalled();
+ expect(reloadMock).not.toHaveBeenCalled();
+ });
+
+ test("proceeds with the swap when the audit alert is delivered", async () => {
+ server.use(
+ getPostV2NotifyImpersonationStartMockHandler200({ alerted: true }),
+ );
+
+ const { result } = renderHook(() => useAdminImpersonation(), { wrapper });
+
+ await act(async () => {
+ void result.current.startImpersonating(TARGET_USER_ID);
+ });
+
+ await waitFor(() => expect(reloadMock).toHaveBeenCalledTimes(1));
+ expect(setSpy).toHaveBeenCalledWith(TARGET_USER_ID);
+ expect(toastMock).not.toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ );
+ });
+
+ test("rejects an empty user id without calling the API or swapping", async () => {
+ const apiHit = vi.fn();
+ server.use(
+ http.post(NOTIFY_URL, () => {
+ apiHit();
+ return new HttpResponse(JSON.stringify({ alerted: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }),
+ );
+
+ const { result } = renderHook(() => useAdminImpersonation(), { wrapper });
+
+ await act(async () => {
+ void result.current.startImpersonating(" ");
+ });
+
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: expect.stringMatching(/user id is required/i),
+ variant: "destructive",
+ }),
+ );
+ expect(apiHit).not.toHaveBeenCalled();
+ expect(setSpy).not.toHaveBeenCalled();
+ expect(reloadMock).not.toHaveBeenCalled();
+ });
+
+ test("drops a re-entrant second start so only one audit alert is sent", async () => {
+ let calls = 0;
+ server.use(
+ http.post(NOTIFY_URL, async () => {
+ calls++;
+ await delay(10);
+ return new HttpResponse(JSON.stringify({ alerted: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }),
+ );
+
+ const { result } = renderHook(() => useAdminImpersonation(), { wrapper });
+
+ await act(async () => {
+ // Fire twice before the first resolves; the re-entry guard drops the 2nd.
+ void result.current.startImpersonating(TARGET_USER_ID);
+ void result.current.startImpersonating(TARGET_USER_ID);
+ });
+
+ await waitFor(() => expect(reloadMock).toHaveBeenCalled());
+ expect(calls).toBe(1);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.ts b/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.ts
index 330510be49..f1990fe1ad 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/useAdminImpersonation.ts
@@ -1,16 +1,18 @@
"use client";
-import { useState, useCallback } from "react";
+import { useState, useCallback, useRef } from "react";
import { ImpersonationState } from "@/lib/impersonation";
import { useToast } from "@/components/molecules/Toast/use-toast";
+import { usePostV2NotifyImpersonationStart } from "@/app/api/__generated__/endpoints/admin/admin";
interface AdminImpersonationState {
isImpersonating: boolean;
impersonatedUserId: string | null;
+ isStarting: boolean;
}
interface AdminImpersonationActions {
- startImpersonating: (userId: string) => void;
+ startImpersonating: (userId: string) => Promise<void>;
stopImpersonating: () => void;
}
@@ -22,11 +24,18 @@ export function useAdminImpersonation(): AdminImpersonationHook {
ImpersonationState.get,
);
const { toast } = useToast();
+ const { mutateAsync: notifyImpersonationStart, isPending: isStarting } =
+ usePostV2NotifyImpersonationStart();
+ // Synchronous re-entry guard: `isStarting` only flips on re-render, so rapid
+ // double-clicks could otherwise fire two audit alerts for one impersonation.
+ const startingRef = useRef(false);
const isImpersonating = Boolean(impersonatedUserId);
const startImpersonating = useCallback(
- (userId: string) => {
+ async (userId: string) => {
+ if (startingRef.current) return;
+
if (!userId.trim()) {
toast({
title: "User ID is required for impersonation",
@@ -35,7 +44,24 @@ export function useAdminImpersonation(): AdminImpersonationHook {
return;
}
+ startingRef.current = true;
try {
+ // The audit alert GATES impersonation. Await it BEFORE setting state so
+ // the request authenticates as the admin (the X-Act-As-User-Id header is
+ // derived from sessionStorage, which isn't populated yet). The Orval
+ // mutator throws on non-2xx, so a failed/blocked alert aborts the swap
+ // rather than impersonate without an audit trail.
+ try {
+ await notifyImpersonationStart({ data: { target_user_id: userId } });
+ } catch {
+ toast({
+ title: "Couldn't start impersonation",
+ description: "Audit alert failed — impersonation blocked.",
+ variant: "destructive",
+ });
+ return;
+ }
+
ImpersonationState.set(userId);
setImpersonatedUserId(userId);
window.location.reload();
@@ -46,9 +72,11 @@ export function useAdminImpersonation(): AdminImpersonationHook {
description: error instanceof Error ? error.message : "Unknown error",
variant: "destructive",
});
+ } finally {
+ startingRef.current = false;
}
},
- [toast],
+ [toast, notifyImpersonationStart],
);
const stopImpersonating = useCallback(() => {
@@ -69,6 +97,7 @@ export function useAdminImpersonation(): AdminImpersonationHook {
return {
isImpersonating,
impersonatedUserId,
+ isStarting,
startImpersonating,
stopImpersonating,
};
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 8e33b45f46..222c3df55f 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1220,6 +1220,48 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/admin/impersonation/notify": {
+ "post": {
+ "tags": ["v2", "admin", "admin", "impersonation"],
+ "summary": "Notify Impersonation Start",
+ "description": "Emit a Discord audit alert when an admin starts impersonating a user.\n\nAdmin-only. The alert gates impersonation: callers must treat a non-2xx\nresponse as \"do not impersonate\".",
+ "operationId": "postV2Notify impersonation start",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ImpersonationNotifyRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ImpersonationNotifyResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/admin/memory/{user_id}/communities": {
"get": {
"tags": ["v2", "admin", "admin", "memory"],
@@ -21443,6 +21485,20 @@
"required": ["image_url"],
"title": "ImageURLResponse"
},
+ "ImpersonationNotifyRequest": {
+ "properties": {
+ "target_user_id": { "type": "string", "title": "Target User Id" }
+ },
+ "type": "object",
+ "required": ["target_user_id"],
+ "title": "ImpersonationNotifyRequest"
+ },
+ "ImpersonationNotifyResponse": {
+ "properties": { "alerted": { "type": "boolean", "title": "Alerted" } },
+ "type": "object",
+ "required": ["alerted"],
+ "title": "ImpersonationNotifyResponse"
+ },
"IngestionDrainStatus": {
"type": "string",
"enum": ["drained", "skipped", "timed_out"],