Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
fix(webui): keep the session on a transient /info failure; update user cache optimistically
Sergey Kozyrenko789caf0dfe5e
diff --git a/frontend/src/features/authentication/email-change-form.test.tsx b/frontend/src/features/authentication/email-change-form.test.tsxindex e694e03b..958cd370 100644--- a/frontend/src/features/authentication/email-change-form.test.tsx+++ b/frontend/src/features/authentication/email-change-form.test.tsx@@ -2,7 +2,8 @@ import { render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { beforeEach, describe, expect, it, vi } from 'vitest';-const { put, refreshAuthInfo } = vi.hoisted(() => ({+const { patchUser, put, refreshAuthInfo } = vi.hoisted(() => ({+ patchUser: vi.fn(),put: vi.fn(),refreshAuthInfo: vi.fn().mockResolvedValue(undefined),}));@@ -15,7 +16,7 @@ vi.mock('@/lib/axios', async (importOriginal) => {});vi.mock('@/providers/user-provider', () => ({- useUser: () => ({ refreshAuthInfo }),+ useUser: () => ({ patchUser, refreshAuthInfo }),}));vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));@@ -27,6 +28,7 @@ const apiError = (code: string, msg: string) => ({ response: { data: { code, msgbeforeEach(() => {put.mockReset().mockResolvedValue({ status: 'success' });refreshAuthInfo.mockClear();+ patchUser.mockClear();});describe('EmailChangeForm', () => {@@ -41,6 +43,7 @@ describe('EmailChangeForm', () => {await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce());expect(put).toHaveBeenCalledWith('/user/email', { current_password: 'Oldpass0!', mail: '[email protected]' });+ expect(patchUser).toHaveBeenCalledWith({ mail: '[email protected]' });expect(refreshAuthInfo).toHaveBeenCalledOnce();});diff --git a/frontend/src/features/authentication/email-change-form.tsx b/frontend/src/features/authentication/email-change-form.tsxindex 4f1ba357..aeae139d 100644--- a/frontend/src/features/authentication/email-change-form.tsx+++ b/frontend/src/features/authentication/email-change-form.tsx@@ -41,7 +41,7 @@ type EmailChangeFormValues = z.infer<typeof emailChangeSchema>;export function EmailChangeForm({ isModal = true, onCancel, onSuccess }: EmailChangeFormProps) {const [error, setError] = useState<null | string>(null);- const { refreshAuthInfo } = useUser();+ const { patchUser, refreshAuthInfo } = useUser();const form = useForm<EmailChangeFormValues>({defaultValues: {@@ -63,6 +63,7 @@ export function EmailChangeForm({ isModal = true, onCancel, onSuccess }: EmailChform.reset();toast.success('Email successfully updated');+ patchUser({ mail: values.newEmail });await refreshAuthInfo();onSuccess?.();diff --git a/frontend/src/features/authentication/name-change-form.test.tsx b/frontend/src/features/authentication/name-change-form.test.tsxindex 63000a6a..1ab783cd 100644--- a/frontend/src/features/authentication/name-change-form.test.tsx+++ b/frontend/src/features/authentication/name-change-form.test.tsx@@ -2,7 +2,8 @@ import { render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { beforeEach, describe, expect, it, vi } from 'vitest';-const { put, refreshAuthInfo } = vi.hoisted(() => ({+const { patchUser, put, refreshAuthInfo } = vi.hoisted(() => ({+ patchUser: vi.fn(),put: vi.fn(),refreshAuthInfo: vi.fn().mockResolvedValue(undefined),}));@@ -15,7 +16,7 @@ vi.mock('@/lib/axios', async (importOriginal) => {});vi.mock('@/providers/user-provider', () => ({- useUser: () => ({ authInfo: { user: { name: 'Old Name' } }, refreshAuthInfo }),+ useUser: () => ({ authInfo: { user: { name: 'Old Name' } }, patchUser, refreshAuthInfo }),}));vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));@@ -27,6 +28,7 @@ const apiError = (code: string, msg: string) => ({ response: { data: { code, msgbeforeEach(() => {put.mockReset().mockResolvedValue({ status: 'success' });refreshAuthInfo.mockClear();+ patchUser.mockClear();});describe('NameChangeForm', () => {@@ -48,6 +50,7 @@ describe('NameChangeForm', () => {await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce());expect(put).toHaveBeenCalledWith('/user/name', { name: 'New Name' });+ expect(patchUser).toHaveBeenCalledWith({ name: 'New Name' });expect(refreshAuthInfo).toHaveBeenCalledOnce();});diff --git a/frontend/src/features/authentication/name-change-form.tsx b/frontend/src/features/authentication/name-change-form.tsxindex 1a87e03d..a7f03e6b 100644--- a/frontend/src/features/authentication/name-change-form.tsx+++ b/frontend/src/features/authentication/name-change-form.tsx@@ -35,7 +35,7 @@ type NameChangeFormValues = z.infer<typeof nameChangeSchema>;export function NameChangeForm({ isModal = true, onCancel, onSuccess }: NameChangeFormProps) {const [error, setError] = useState<null | string>(null);- const { authInfo, refreshAuthInfo } = useUser();+ const { authInfo, patchUser, refreshAuthInfo } = useUser();const form = useForm<NameChangeFormValues>({defaultValues: {@@ -52,6 +52,7 @@ export function NameChangeForm({ isModal = true, onCancel, onSuccess }: NameChantoast.success('Name successfully updated');+ patchUser({ name: values.name });await refreshAuthInfo();onSuccess?.();diff --git a/frontend/src/pages/settings/settings-account.test.tsx b/frontend/src/pages/settings/settings-account.test.tsxindex bae2ec4e..deceba31 100644--- a/frontend/src/pages/settings/settings-account.test.tsx+++ b/frontend/src/pages/settings/settings-account.test.tsx@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const { authState } = vi.hoisted(() => ({ authState: { value: null as unknown } }));vi.mock('@/providers/user-provider', () => ({- useUser: () => ({ authInfo: authState.value, refreshAuthInfo: vi.fn() }),+ useUser: () => ({ authInfo: authState.value, patchUser: vi.fn(), refreshAuthInfo: vi.fn() }),}));import SettingsAccount from './settings-account';diff --git a/frontend/src/providers/user-provider.test.tsx b/frontend/src/providers/user-provider.test.tsxnew file mode 100644index 00000000..56df46fd--- /dev/null+++ b/frontend/src/providers/user-provider.test.tsx@@ -0,0 +1,82 @@+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { get } = vi.hoisted(() => ({ get: vi.fn() }));++vi.mock('@/lib/axios', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/axios')>();++ return { ...actual, api: { ...actual.api, get } };+});++vi.mock('sonner', () => ({ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));++import { AUTH_STORAGE_KEY, UserProvider, useUser } from './user-provider';++const session = {+ expires_at: '2099-01-01T00:00:00Z',+ type: 'user',+ user: { mail: '[email protected]', name: 'Me', type: 'local' },+};++function Probe() {+ const { authInfo, refreshAuthInfo } = useUser();+ const location = useLocation();+ const navigate = useNavigate();++ return (+ <div>+ <span data-testid="mail">{authInfo?.user?.mail ?? 'none'}</span>+ <span data-testid="path">{location.pathname}</span>+ <button onClick={() => void refreshAuthInfo()}>refresh</button>+ <button onClick={() => navigate('/dashboard')}>go</button>+ </div>+ );+}++function renderProvider(initialPath: string) {+ return render(+ <MemoryRouter initialEntries={[initialPath]}>+ <UserProvider>+ <Probe />+ </UserProvider>+ </MemoryRouter>,+ );+}++beforeEach(() => {+ localStorage.clear();+ get.mockReset().mockRejectedValue(new Error('network'));+ localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(session));+});++describe('UserProvider transient /info handling', () => {+ it('keeps the session when refreshAuthInfo hits a transient /info failure', async () => {+ const user = userEvent.setup();+ // /oauth/result is public, so neither the navigation refresh nor the /login effect fires —+ // refreshAuthInfo runs only on our explicit click.+ renderProvider('/oauth/result');++ expect(await screen.findByText('[email protected]')).toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'refresh' }));+ await waitFor(() => expect(get).toHaveBeenCalled());++ expect(screen.getByTestId('mail')).toHaveTextContent('[email protected]');+ });++ it('keeps the session and stays on the page when the navigation refresh fails transiently', async () => {+ const user = userEvent.setup();+ renderProvider('/oauth/result');++ expect(await screen.findByText('[email protected]')).toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'go' }));+ await waitFor(() => expect(get).toHaveBeenCalled());++ expect(screen.getByTestId('path')).toHaveTextContent('/dashboard');+ expect(screen.getByTestId('mail')).toHaveTextContent('[email protected]');+ });+});diff --git a/frontend/src/providers/user-provider.tsx b/frontend/src/providers/user-provider.tsxindex 73ae640e..9d4ec473 100644--- a/frontend/src/providers/user-provider.tsx+++ b/frontend/src/providers/user-provider.tsx@@ -5,6 +5,7 @@ import { useLocation, useNavigate } from 'react-router-dom';import { toast } from 'sonner';import type { AuthInfo } from '@/models/info';+import type { User } from '@/models/user';import { api } from '@/lib/axios';import { getReturnUrlParam } from '@/lib/utils/auth';@@ -31,6 +32,7 @@ interface UserContextType {login: (credentials: LoginCredentials) => Promise<LoginResult>;loginWithOAuth: (provider: OAuthProvider) => Promise<LoginResult>;logout: (returnUrl?: string) => Promise<void>;+ patchUser: (patch: Partial<User>) => void;refreshAuthInfo: () => Promise<void>;setAuth: (authInfo: AuthInfo) => void;}@@ -118,6 +120,17 @@ export function UserProvider({ children }: { children: ReactNode }) {return expirationDate > now;}, [authInfo]);+ const patchUser = useCallback(+ (patch: Partial<User>) => {+ if (!authInfo?.user) {+ return;+ }++ setAuth({ ...authInfo, user: { ...authInfo.user, ...patch } });+ },+ [authInfo, setAuth],+ );+const refreshAuthInfo = useCallback(async () => {try {const info = await api.get<AuthInfo>('/info');@@ -128,7 +141,8 @@ export function UserProvider({ children }: { children: ReactNode }) {clearAuth();}} catch {- clearAuth();+ // A transient /info failure (network, 5xx, timeout) is not auth loss — the axios+ // interceptor hard-redirects on a real 401/403. Keep the current session.}}, [setAuth, clearAuth]);@@ -340,10 +354,8 @@ export function UserProvider({ children }: { children: ReactNode }) {navigate(`/login${returnParam}`);}} catch {- clearAuth();- toast.error('Session expired. Please login again.');- const returnParam = getReturnUrlParam(location.pathname);- navigate(`/login${returnParam}`);+ // A transient /info failure on navigation must not log the user out — a network+ // blip is not session expiry; the interceptor redirects on a real 401/403.}};@@ -373,6 +385,7 @@ export function UserProvider({ children }: { children: ReactNode }) {login,loginWithOAuth,logout,+ patchUser,refreshAuthInfo,setAuth,}}