Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions static/gsAdmin/views/layout.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import fetchMock from 'jest-fetch-mock';
import {ConfigFixture} from 'sentry-fixture/config';
import {UserFixture} from 'sentry-fixture/user';

import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';

import {ConfigStore} from 'sentry/stores/configStore';

import {Layout} from 'admin/views/layout';

function renderLayout() {
return render(<Layout />, {
initialRouterConfig: {
location: {pathname: '/_admin/'},
route: '/_admin/*',
children: [{path: '*', element: <div>Admin content</div>}],
},
});
}

describe('Layout superuser preflight check', () => {
beforeEach(() => {
fetchMock.resetMocks();
ConfigStore.loadInitialData(ConfigFixture({user: UserFixture()}));
// SuperuserStaffAccessForm calls /authenticators/ on mount
MockApiClient.addMockResponse({
url: '/authenticators/',
body: [],
});
});

afterEach(() => {
MockApiClient.clearMockResponses();
});

it('renders outlet content when superuser check returns 200', async () => {
fetchMock.mockResponse(req =>
req.url.includes('superuser-check')
? Promise.resolve({body: '', status: 200})
: Promise.resolve({body: '{}', status: 200})
);

renderLayout();

expect(await screen.findByText('Admin content')).toBeInTheDocument();
});

it('renders re-auth form instead of outlet when superuser check returns 403', async () => {
fetchMock.mockResponse(req =>
req.url.includes('superuser-check')
? Promise.resolve({body: '', status: 403})
: Promise.resolve({body: '{}', status: 200})
);

renderLayout();

expect(await screen.findByRole('button', {name: 'Continue'})).toBeInTheDocument();
expect(screen.queryByText('Admin content')).not.toBeInTheDocument();
});

it('renders error state (not re-auth form) when superuser check returns a non-403 server error', async () => {
fetchMock.mockResponse(req =>
req.url.includes('superuser-check')
? Promise.resolve({body: '', status: 500})
: Promise.resolve({body: '{}', status: 200})
);

renderLayout();

expect(
await screen.findByText('There was an error loading data.')
).toBeInTheDocument();
expect(screen.queryByRole('button', {name: 'Continue'})).not.toBeInTheDocument();
expect(screen.queryByText('Admin content')).not.toBeInTheDocument();
});

it('retries the superuser check when Retry is clicked after a server error', async () => {
let superuserCheckCallCount = 0;
fetchMock.mockResponse(req => {
if (!req.url.includes('superuser-check')) {
return Promise.resolve({body: '{}', status: 200});
}
superuserCheckCallCount++;
return Promise.resolve({
body: '',
status: superuserCheckCallCount === 1 ? 500 : 200,
});
});

renderLayout();

await userEvent.click(await screen.findByRole('button', {name: 'Retry'}));

expect(await screen.findByText('Admin content')).toBeInTheDocument();
expect(
screen.queryByText('There was an error loading data.')
).not.toBeInTheDocument();
});
});
44 changes: 40 additions & 4 deletions static/gsAdmin/views/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useState} from 'react';
import {type ReactNode, useEffect, useState} from 'react';
import {Outlet} from 'react-router-dom';
import {ThemeProvider} from '@emotion/react';
import styled from '@emotion/styled';
Expand All @@ -9,8 +9,12 @@ import {GlobalModal} from '@sentry/scraps/modal';

import Indicators from 'sentry/components/indicators';
import {ListLink} from 'sentry/components/links/listLink';
import {LoadingError} from 'sentry/components/loadingError';
import {LoadingIndicator} from 'sentry/components/loadingIndicator';
import SuperuserStaffAccessForm from 'sentry/components/superuserStaffAccessForm';
import {IconSentry, IconSliders} from 'sentry/icons';
import {ScrapsProviders} from 'sentry/scrapsProviders';
import {ConfigStore} from 'sentry/stores/configStore';
import {localStorageWrapper} from 'sentry/utils/localStorage';
// eslint-disable-next-line no-restricted-imports
import {darkTheme, lightTheme} from 'sentry/utils/theme/theme';
Expand Down Expand Up @@ -40,6 +44,40 @@ const useToggleTheme = () => {

export function Layout() {
const [isDark, theme, toggleTheme] = useToggleTheme();
// null = preflight check in progress, true = verified, false = needs re-auth, 'error' = unexpected server error
const [superuserReady, setSuperuserReady] = useState<boolean | null | 'error'>(null);

const checkSuperuser = () => {
setSuperuserReady(null);
// Verify the superuser/staff session is still active before rendering any
// admin content. We use the native fetch API here intentionally to bypass
// the Sentry API client's SUPERUSER_REQUIRED error handler, which would
// open a modal overlay over the (not yet rendered) page content.
fetch('/api/0/_admin/superuser-check/', {credentials: 'include'})
.then(res => {
if (res.ok) setSuperuserReady(true);
else if (res.status === 403) setSuperuserReady(false);
else setSuperuserReady('error');
})
.catch(() => setSuperuserReady('error'));
Comment thread
swartzrock marked this conversation as resolved.
};

useEffect(() => {
checkSuperuser();
}, []);

const hasStaff = ConfigStore.get('user')?.isStaff ?? false;

let content: ReactNode;
if (superuserReady === null) {
content = <LoadingIndicator />;
} else if (superuserReady === true) {
content = <Outlet />;
} else if (superuserReady === 'error') {
content = <LoadingError onRetry={checkSuperuser} />;
} else {
content = <SuperuserStaffAccessForm hasStaff={hasStaff} />;
}

return (
<ThemeProvider theme={theme}>
Expand Down Expand Up @@ -98,9 +136,7 @@ export function Layout() {
</ThemeToggle>
</div>
</Sidebar>
<Content>
<Outlet />
</Content>
<Content>{content}</Content>
</AppContainer>
</ScrapsProviders>
</ThemeProvider>
Expand Down
Loading