mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-01 12:40:48 +00:00
Compare commits
6 Commits
split/2-au
...
split/4-e2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59a23fbc2d | ||
|
|
4f4a793558 | ||
|
|
8f5450df7c | ||
|
|
7413f3f427 | ||
|
|
89f1c7cc72 | ||
|
|
8b068c827f |
@@ -190,6 +190,7 @@ const preview: Preview = {
|
||||
['Overview', 'Kafka', 'Kafka Detail', 'Celery'],
|
||||
'Onboarding',
|
||||
['Questionnaire', 'Add Data Source'],
|
||||
'Audit Logs',
|
||||
'Settings',
|
||||
[
|
||||
'Workspace',
|
||||
|
||||
@@ -61,5 +61,6 @@
|
||||
"AI_OBSERVABILITY_OVERVIEW": "SigNoz | AI Observability Overview",
|
||||
"AI_OBSERVABILITY_EXPLORER": "SigNoz | AI Observability Explorer",
|
||||
"AI_OBSERVABILITY_CONFIGURATION": "SigNoz | AI Observability Configuration",
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping"
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping",
|
||||
"AUDIT_LOGS": "SigNoz | Audit Logs"
|
||||
}
|
||||
@@ -82,5 +82,6 @@
|
||||
"AI_OBSERVABILITY_OVERVIEW": "SigNoz | AI Observability Overview",
|
||||
"AI_OBSERVABILITY_EXPLORER": "SigNoz | AI Observability Explorer",
|
||||
"AI_OBSERVABILITY_CONFIGURATION": "SigNoz | AI Observability Configuration",
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping"
|
||||
"AI_OBSERVABILITY_ATTRIBUTE_MAPPING": "SigNoz | AI Observability Attribute Mapping",
|
||||
"AUDIT_LOGS": "SigNoz | Audit Logs"
|
||||
}
|
||||
@@ -292,3 +292,10 @@ export const LLMObservabilityPage = Loadable(
|
||||
/* webpackChunkName: "LLM Observability Page" */ 'pages/LLMObservability'
|
||||
),
|
||||
);
|
||||
|
||||
export const AuditLogsPage = Loadable(
|
||||
() =>
|
||||
import(
|
||||
/* webpackChunkName: "Audit Logs Page" */ 'pages/AuditLogsModule/AuditLogsModule'
|
||||
),
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
AlertOverview,
|
||||
AllErrors,
|
||||
ApiMonitoring,
|
||||
AuditLogsPage,
|
||||
ChannelsEdit,
|
||||
ChannelsNew,
|
||||
CreateNewAlerts,
|
||||
@@ -408,6 +409,12 @@ const routes: AppRoutes[] = [
|
||||
key: 'AI_OBSERVABILITY_CONFIGURATION',
|
||||
isPrivate: true,
|
||||
},
|
||||
{
|
||||
path: ROUTES.AUDIT_LOGS,
|
||||
component: AuditLogsPage,
|
||||
key: 'AUDIT_LOGS',
|
||||
isPrivate: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const SUPPORT_ROUTE: AppRoutes = {
|
||||
|
||||
@@ -157,29 +157,33 @@ function OptionsMenu({
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="horizontal-line" />
|
||||
<div className="menu-container" data-testid="format-options-menu">
|
||||
<div className="title">FORMAT</div>
|
||||
{items.length > 0 && (
|
||||
<>
|
||||
<div className="horizontal-line" />
|
||||
<div className="menu-container" data-testid="format-options-menu">
|
||||
<div className="title">FORMAT</div>
|
||||
|
||||
<div className="menu-items">
|
||||
{items.map((item: any): JSX.Element => (
|
||||
<div
|
||||
className="item"
|
||||
key={item.label}
|
||||
data-testid={`format-option-${item.key}`}
|
||||
onClick={(): void => handleMenuItemClick(item.key)}
|
||||
>
|
||||
<div className={cx('item-label')}>
|
||||
{item.label}
|
||||
<div className="menu-items">
|
||||
{items.map((item: any): JSX.Element => (
|
||||
<div
|
||||
className="item"
|
||||
key={item.label}
|
||||
data-testid={`format-option-${item.key}`}
|
||||
onClick={(): void => handleMenuItemClick(item.key)}
|
||||
>
|
||||
<div className={cx('item-label')}>
|
||||
{item.label}
|
||||
|
||||
{selectedItem === item.key && (
|
||||
<Check size={12} data-testid="format-check-icon" />
|
||||
)}
|
||||
</div>
|
||||
{selectedItem === item.key && (
|
||||
<Check size={12} data-testid="format-check-icon" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{selectedItem && (
|
||||
<>
|
||||
@@ -191,6 +195,7 @@ function OptionsMenu({
|
||||
type="button"
|
||||
className="periscope-btn"
|
||||
aria-label="Fewer lines per row"
|
||||
data-testid="max-lines-fewer"
|
||||
onClick={(): void => handleLinesPerRowChange(maxLinesPerRow - 1)}
|
||||
>
|
||||
<Minus size={12} />
|
||||
@@ -211,6 +216,7 @@ function OptionsMenu({
|
||||
type="button"
|
||||
className="periscope-btn"
|
||||
aria-label="More lines per row"
|
||||
data-testid="max-lines-more"
|
||||
onClick={(): void => handleLinesPerRowChange(maxLinesPerRow + 1)}
|
||||
>
|
||||
<Plus size={12} />
|
||||
|
||||
@@ -228,6 +228,24 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the format section when there are no format items', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<LogsFormatOptionsMenu
|
||||
items={[]}
|
||||
selectedOptionFormat={undefined}
|
||||
config={{ fontSize: { value: FontSize.SMALL, onChange: jest.fn() } }}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('periscope-btn-format-options'));
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('font-size-select'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('format-options-menu')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fires onOpenColumns and closes the popover when "Edit columns" is clicked', async () => {
|
||||
const onOpenColumns = jest.fn();
|
||||
const { getByTestId } = renderWithOnOpen(onOpenColumns, 'table');
|
||||
|
||||
@@ -48,4 +48,5 @@ export enum LOCALSTORAGE {
|
||||
ALERT_RULES_LIST_VIEWS = 'ALERT_RULES_LIST_VIEWS',
|
||||
DASHBOARD_V2_PANEL_COLUMN_WIDTHS = 'DASHBOARD_V2_PANEL_COLUMN_WIDTHS',
|
||||
LLM_ATTRIBUTE_MAPPING_TEST_SPAN = 'LLM_ATTRIBUTE_MAPPING_TEST_SPAN',
|
||||
AUDIT_LOGS_OPTIONS = 'AUDIT_LOGS_OPTIONS',
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ import {
|
||||
aiAssistantMenuItem,
|
||||
USER_SETTINGS_MENU_LABELS,
|
||||
type UserSettingsMenuKey,
|
||||
auditLogsMenuItem,
|
||||
} from './menuItems';
|
||||
import NavItem from './NavItem/NavItem';
|
||||
import {
|
||||
@@ -958,6 +959,9 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
|
||||
onSelect: handleSettingsMenuItemClick,
|
||||
});
|
||||
|
||||
const isAuditLogsEnabled =
|
||||
(isCloudUser || isEnterpriseSelfHostedUser) && isAdmin;
|
||||
|
||||
return (
|
||||
<div className={cx('sidenav-container', isPinned && 'pinned')}>
|
||||
<div
|
||||
@@ -1198,6 +1202,8 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
|
||||
<div className="secondary-nav-items">
|
||||
{isAIAssistantEnabled && renderNavItems([aiAssistantMenuItem], false)}
|
||||
|
||||
{isAuditLogsEnabled && renderNavItems([auditLogsMenuItem], false)}
|
||||
|
||||
<div className="nav-dropdown-item">
|
||||
<Dropdown
|
||||
items={helpSupportItems}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
|
||||
import SideNav from '../SideNav';
|
||||
|
||||
jest.mock('hooks/useGetTenantLicense');
|
||||
|
||||
jest.mock('providers/cmdKProvider', () => ({
|
||||
useCmdK: (): { openCmdK: jest.Mock } => ({ openCmdK: jest.fn() }),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/hotkeys/useKeyboardHotkeys', () => ({
|
||||
useKeyboardHotkeys: (): Record<string, jest.Mock> => ({
|
||||
registerShortcut: jest.fn(),
|
||||
deregisterShortcut: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
type TenantLicense = ReturnType<typeof useGetTenantLicense>;
|
||||
|
||||
const NO_LICENSE: TenantLicense = {
|
||||
isCloudUser: false,
|
||||
isEnterpriseSelfHostedUser: false,
|
||||
isCommunityUser: false,
|
||||
isCommunityEnterpriseUser: false,
|
||||
};
|
||||
|
||||
const AUDIT_LOGS_NAV_ITEM = 'nav-item-audit-logs';
|
||||
|
||||
describe('SideNav audit logs entry', () => {
|
||||
it.each([
|
||||
['cloud', { ...NO_LICENSE, isCloudUser: true }],
|
||||
[
|
||||
'enterprise self-hosted',
|
||||
{ ...NO_LICENSE, isEnterpriseSelfHostedUser: true },
|
||||
],
|
||||
])('shows the entry to an admin on %s', (_, license) => {
|
||||
jest.mocked(useGetTenantLicense).mockReturnValue(license);
|
||||
|
||||
render(<SideNav isPinned />, undefined, { role: USER_ROLES.ADMIN });
|
||||
|
||||
expect(screen.getByTestId(AUDIT_LOGS_NAV_ITEM)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([USER_ROLES.EDITOR, USER_ROLES.VIEWER])(
|
||||
'hides the entry from a %s',
|
||||
(role) => {
|
||||
jest
|
||||
.mocked(useGetTenantLicense)
|
||||
.mockReturnValue({ ...NO_LICENSE, isCloudUser: true });
|
||||
|
||||
render(<SideNav isPinned />, undefined, { role });
|
||||
|
||||
expect(screen.queryByTestId(AUDIT_LOGS_NAV_ITEM)).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it('hides the entry from an admin on a community install', () => {
|
||||
jest
|
||||
.mocked(useGetTenantLicense)
|
||||
.mockReturnValue({ ...NO_LICENSE, isCommunityUser: true });
|
||||
|
||||
render(<SideNav isPinned />, undefined, { role: USER_ROLES.ADMIN });
|
||||
|
||||
expect(screen.queryByTestId(AUDIT_LOGS_NAV_ITEM)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
ChartArea,
|
||||
Cloudy,
|
||||
DraftingCompass,
|
||||
FileClock,
|
||||
FileKey2,
|
||||
Github,
|
||||
HardDrive,
|
||||
@@ -81,6 +82,14 @@ export const helpSupportMenuItem = {
|
||||
icon: <MessageSquareText size={16} />,
|
||||
};
|
||||
|
||||
export const auditLogsMenuItem = {
|
||||
key: ROUTES.AUDIT_LOGS,
|
||||
label: 'Audit Logs',
|
||||
icon: <FileClock size={16} />,
|
||||
isEnabled: true,
|
||||
itemKey: 'audit-logs',
|
||||
};
|
||||
|
||||
// The AI Assistant route is parameterized as `/ai-assistant/:conversationId`.
|
||||
// Sending the user to `/ai-assistant/new` triggers the page's fallback that
|
||||
// spawns a fresh conversation and replaces the URL with the real id, so
|
||||
|
||||
@@ -201,6 +201,7 @@ export const routesToSkip = [
|
||||
ROUTES.AI_OBSERVABILITY_CONFIGURATION,
|
||||
ROUTES.AI_OBSERVABILITY_ATTRIBUTE_MAPPING,
|
||||
ROUTES.AI_OBSERVABILITY_EXPLORER,
|
||||
ROUTES.AUDIT_LOGS,
|
||||
];
|
||||
|
||||
export const routesToDisable = [ROUTES.LOGS_EXPLORER];
|
||||
|
||||
38
frontend/src/pages/AuditLogs/AuditLogs.module.scss
Normal file
38
frontend/src/pages/AuditLogs/AuditLogs.module.scss
Normal file
@@ -0,0 +1,38 @@
|
||||
.auditLogsRoot {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.auditLogsRightPane {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.queryToolbar {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.queryToolbarLeft {
|
||||
display: flex;
|
||||
padding-left: var(--spacing-4);
|
||||
}
|
||||
|
||||
.queryToolbarRight {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.actionsRow {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: var(--spacing-4);
|
||||
padding: var(--spacing-4) var(--spacing-8);
|
||||
}
|
||||
11
frontend/src/pages/AuditLogs/README.md
Normal file
11
frontend/src/pages/AuditLogs/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Audit Logs
|
||||
|
||||
Explorer for audit events at `/audit-logs`, admins only. It queries `signal: logs` with `source: audit` through `/api/v5/query_range`.
|
||||
|
||||
- `index.tsx`: the page (quick filters, query bar, list, details drawer).
|
||||
- `components/`: query bar, order by, options menu, results, details drawer and cells.
|
||||
- `hooks/`: the paged query, columns, and the active-log detail.
|
||||
- `store/`: persisted display options (format, font size, max lines, filters panel).
|
||||
- `types.ts`, `utils.ts`, `constants.ts`: audit log types, field getters, export columns.
|
||||
|
||||
The Raw and Default formats reuse `RawLogView` and `ListLogView`, and the drawer reuses the log detail navigation.
|
||||
99
frontend/src/pages/AuditLogs/__tests__/AuditLogs.test.tsx
Normal file
99
frontend/src/pages/AuditLogs/__tests__/AuditLogs.test.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { useAuditLogsQuery } from '../hooks/useAuditLogsQuery';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import AuditLogs from '..';
|
||||
|
||||
jest.mock('../hooks/useAuditLogsQuery');
|
||||
jest.mock('components/QuickFilters/hooks/useSignalFieldApis');
|
||||
|
||||
jest.mock(
|
||||
'components/QuickFilters/QuickFiltersLayout/QuickFiltersLayout',
|
||||
() => ({
|
||||
__esModule: true,
|
||||
default: ({ children }: { children: React.ReactNode }): JSX.Element => (
|
||||
<div>{children}</div>
|
||||
),
|
||||
}),
|
||||
);
|
||||
jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
|
||||
__esModule: true,
|
||||
default: (): null => null,
|
||||
}));
|
||||
jest.mock('components/DownloadOptionsMenu/DownloadOptionsMenu', () => ({
|
||||
__esModule: true,
|
||||
default: (): null => null,
|
||||
}));
|
||||
jest.mock('../components/QueryBar', () => ({ QueryBar: (): null => null }));
|
||||
jest.mock('../components/OrderBy', () => ({ OrderBy: (): null => null }));
|
||||
jest.mock('../components/OptionsMenu', () => ({
|
||||
OptionsMenu: (): null => null,
|
||||
}));
|
||||
jest.mock('../components/QueryResults', () => ({
|
||||
QueryResults: (): JSX.Element => <div data-testid="results" />,
|
||||
}));
|
||||
|
||||
const mockCancelQueries = jest.fn();
|
||||
|
||||
jest.mock('react-query', () => ({
|
||||
...jest.requireActual('react-query'),
|
||||
useQueryClient: (): { cancelQueries: jest.Mock } => ({
|
||||
cancelQueries: mockCancelQueries,
|
||||
}),
|
||||
}));
|
||||
|
||||
const KEY = ['audit-key'];
|
||||
|
||||
function mockQuery(isFetching: boolean): void {
|
||||
jest
|
||||
.mocked(useAuditLogsQuery)
|
||||
.mockImplementation(({ listAuditLogsKeyRef }) => {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
listAuditLogsKeyRef.current = KEY;
|
||||
return {
|
||||
logs: [],
|
||||
isLoading: false,
|
||||
isFetching,
|
||||
isError: false,
|
||||
error: null,
|
||||
onEndReached: jest.fn(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('AuditLogs cancelling a query', () => {
|
||||
it('cancels the running request and shows the cancelled placeholder', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
mockQuery(true);
|
||||
render(<AuditLogs />);
|
||||
|
||||
await user.click(screen.getByTestId('audit-logs-run-query-btn-cancel'));
|
||||
|
||||
expect(mockCancelQueries).toHaveBeenCalledWith(KEY);
|
||||
expect(screen.getByText(/query cancelled/i)).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('results')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the results again when a new fetch starts', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
mockQuery(true);
|
||||
const { rerender } = render(<AuditLogs />);
|
||||
await user.click(screen.getByTestId('audit-logs-run-query-btn-cancel'));
|
||||
|
||||
mockQuery(false);
|
||||
rerender(<AuditLogs />);
|
||||
expect(screen.getByText(/query cancelled/i)).toBeInTheDocument();
|
||||
mockQuery(true);
|
||||
rerender(<AuditLogs />);
|
||||
|
||||
expect(screen.getByTestId('results')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
34
frontend/src/pages/AuditLogs/__tests__/auditLogFixture.ts
Normal file
34
frontend/src/pages/AuditLogs/__tests__/auditLogFixture.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { AuditLog, AuditOutcome, AuditPrincipalType } from '../types';
|
||||
|
||||
export function buildAuditLog(overrides: Partial<AuditLog> = {}): AuditLog {
|
||||
return {
|
||||
id: 'log-1',
|
||||
timestamp: 1_700_000_000_000_000_000,
|
||||
date: '2023-11-14T22:13:20Z',
|
||||
body: 'alice@acme.com (user-001) created dashboard (dash-001)',
|
||||
event_name: 'signoz.audit.create',
|
||||
severity_number: 9,
|
||||
severity_text: 'INFO',
|
||||
trace_id: '',
|
||||
span_id: '',
|
||||
trace_flags: 0,
|
||||
attributes: {
|
||||
'signoz.audit.action_category': 'configuration_change',
|
||||
'signoz.audit.outcome': AuditOutcome.SUCCESS,
|
||||
'signoz.audit.verb': 'create',
|
||||
'signoz.organization.id': 'org-001',
|
||||
'signoz.principal.id': 'user-001',
|
||||
'signoz.principal.type': AuditPrincipalType.USER,
|
||||
'signoz.principal.email': 'alice@acme.com',
|
||||
},
|
||||
resource: {
|
||||
attributes: {
|
||||
'service.name': 'signoz',
|
||||
'signoz.resource.kind': 'dashboard',
|
||||
'signoz.resource.id': 'dash-001-abcdef-123456',
|
||||
},
|
||||
},
|
||||
scope: { name: 'signoz.audit', version: '1', attributes: {} },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
144
frontend/src/pages/AuditLogs/__tests__/utils.test.ts
Normal file
144
frontend/src/pages/AuditLogs/__tests__/utils.test.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
|
||||
import { AuditOutcome, AuditPrincipalType } from '../types';
|
||||
import {
|
||||
EMPTY_VALUE,
|
||||
getAuditFieldValue,
|
||||
getBody,
|
||||
getEventName,
|
||||
getOutcome,
|
||||
getPrincipalEmail,
|
||||
getResourceId,
|
||||
getResourceName,
|
||||
getRowHoverColor,
|
||||
getVerb,
|
||||
isServiceAccount,
|
||||
truncateId,
|
||||
} from '../utils';
|
||||
import { buildAuditLog } from './auditLogFixture';
|
||||
|
||||
describe('utils', () => {
|
||||
describe('field getters', () => {
|
||||
it('read the values off the log', () => {
|
||||
const log = buildAuditLog();
|
||||
|
||||
expect(getOutcome(log)).toBe(AuditOutcome.SUCCESS);
|
||||
expect(getPrincipalEmail(log)).toBe('alice@acme.com');
|
||||
expect(getEventName(log)).toBe('signoz.audit.create');
|
||||
expect(getResourceName(log)).toBe('dashboard');
|
||||
expect(getResourceId(log)).toBe('dash-001-abcdef-123456');
|
||||
expect(getVerb(log)).toBe('create');
|
||||
expect(getBody(log)).toBe(
|
||||
'alice@acme.com (user-001) created dashboard (dash-001)',
|
||||
);
|
||||
});
|
||||
|
||||
it('fall back to the empty marker when a value is missing', () => {
|
||||
const log = buildAuditLog({
|
||||
event_name: '',
|
||||
body: '',
|
||||
attributes: {
|
||||
...buildAuditLog().attributes,
|
||||
'signoz.principal.email': undefined,
|
||||
'signoz.audit.verb': '',
|
||||
},
|
||||
resource: { attributes: { 'service.name': 'signoz' } },
|
||||
});
|
||||
|
||||
expect(getPrincipalEmail(log)).toBe(EMPTY_VALUE);
|
||||
expect(getEventName(log)).toBe(EMPTY_VALUE);
|
||||
expect(getResourceName(log)).toBe(EMPTY_VALUE);
|
||||
expect(getResourceId(log)).toBe(EMPTY_VALUE);
|
||||
expect(getVerb(log)).toBe(EMPTY_VALUE);
|
||||
expect(getBody(log)).toBe(EMPTY_VALUE);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isServiceAccount', () => {
|
||||
it.each([
|
||||
[AuditPrincipalType.SERVICE_ACCOUNT, true],
|
||||
[AuditPrincipalType.USER, false],
|
||||
[undefined, false],
|
||||
])('principal type %s gives %s', (principalType, expected) => {
|
||||
const log = buildAuditLog({
|
||||
attributes: {
|
||||
...buildAuditLog().attributes,
|
||||
'signoz.principal.type': principalType,
|
||||
},
|
||||
});
|
||||
|
||||
expect(isServiceAccount(log)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('truncateId', () => {
|
||||
it('keeps the first and last four characters of a long id', () => {
|
||||
expect(truncateId('abcdefghijklmnop')).toBe('abcd…mnop');
|
||||
});
|
||||
|
||||
it('leaves an id of head + tail + 1 characters untouched', () => {
|
||||
expect(truncateId('123456789')).toBe('123456789');
|
||||
});
|
||||
|
||||
it('truncates an id one character past that boundary', () => {
|
||||
expect(truncateId('1234567890')).toBe('1234…7890');
|
||||
});
|
||||
|
||||
it('leaves the empty marker untouched', () => {
|
||||
expect(truncateId(EMPTY_VALUE)).toBe(EMPTY_VALUE);
|
||||
});
|
||||
|
||||
it('honours custom head and tail lengths', () => {
|
||||
expect(truncateId('abcdefghijklmnop', 2, 3)).toBe('ab…nop');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAuditFieldValue', () => {
|
||||
it.each([
|
||||
['signoz.principal.email', 'alice@acme.com'],
|
||||
['event_name', 'signoz.audit.create'],
|
||||
['signoz.resource.kind', 'dashboard'],
|
||||
['signoz.resource.id', 'dash-001-abcdef-123456'],
|
||||
['signoz.audit.outcome', AuditOutcome.SUCCESS],
|
||||
])('resolves %s', (fieldName, expected) => {
|
||||
expect(getAuditFieldValue(buildAuditLog(), fieldName)).toBe(expected);
|
||||
});
|
||||
|
||||
it('returns undefined for a field it does not map', () => {
|
||||
expect(getAuditFieldValue(buildAuditLog(), 'service.name')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns undefined when the log does not carry the value', () => {
|
||||
const log = buildAuditLog({
|
||||
resource: { attributes: { 'service.name': 'signoz' } },
|
||||
});
|
||||
|
||||
expect(getAuditFieldValue(log, 'signoz.resource.id')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRowHoverColor', () => {
|
||||
const failure = buildAuditLog({
|
||||
severity_text: 'ERROR',
|
||||
severity_number: 17,
|
||||
});
|
||||
|
||||
it('colors an info row blue in dark mode', () => {
|
||||
expect(getRowHoverColor(true, buildAuditLog())).toBe(
|
||||
`${Color.BG_ROBIN_500}40`,
|
||||
);
|
||||
});
|
||||
|
||||
it('colors an error row red in dark mode', () => {
|
||||
expect(getRowHoverColor(true, failure)).toBe(`${Color.BG_CHERRY_500}40`);
|
||||
});
|
||||
|
||||
it('colors an info row blue in light mode', () => {
|
||||
expect(getRowHoverColor(false, buildAuditLog())).toBe(Color.BG_ROBIN_100);
|
||||
});
|
||||
|
||||
it('colors an error row red in light mode', () => {
|
||||
expect(getRowHoverColor(false, failure)).toBe(Color.BG_CHERRY_100);
|
||||
});
|
||||
});
|
||||
});
|
||||
31
frontend/src/pages/AuditLogs/components/CopyLinkButton.tsx
Normal file
31
frontend/src/pages/AuditLogs/components/CopyLinkButton.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import { useCallback } from 'react';
|
||||
import { Link } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
|
||||
|
||||
interface CopyLinkButtonProps {
|
||||
logId: string;
|
||||
}
|
||||
|
||||
export function CopyLinkButton({ logId }: CopyLinkButtonProps): JSX.Element {
|
||||
const { onLogCopy } = useCopyLogLink(logId);
|
||||
|
||||
const handleClick = useCallback((): void => onLogCopy(), [onLogCopy]);
|
||||
|
||||
return (
|
||||
<Tooltip title="Copy link to log" side="top">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
icon
|
||||
aria-label="Copy link to log"
|
||||
onClick={handleClick}
|
||||
testId="audit-log-detail-copy-link"
|
||||
>
|
||||
<Link size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
[data-testid='audit-log-detail-drawer'] {
|
||||
--drawer-body-padding: 0 var(--spacing-8);
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.summary {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--spacing-8) var(--spacing-10);
|
||||
padding: var(--spacing-8) var(--spacing-0) var(--spacing-10);
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
}
|
||||
|
||||
.logLine {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: var(--spacing-4);
|
||||
min-width: 0;
|
||||
margin-bottom: var(--spacing-2);
|
||||
}
|
||||
|
||||
.logText {
|
||||
min-width: 0;
|
||||
font-family: var(--code-base-400-font-family);
|
||||
font-size: var(--code-base-400-font-size);
|
||||
line-height: 18px;
|
||||
color: var(--l2-foreground);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: var(--code-base-400-font-family);
|
||||
}
|
||||
|
||||
.emphasis {
|
||||
color: var(--l1-foreground);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.hint {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
padding: var(--spacing-4) 0;
|
||||
color: var(--l3-foreground);
|
||||
background: var(--drawer-background);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.dataViewer {
|
||||
:global(.pretty-view__search-wrapper),
|
||||
:global(.pretty-view__search-input) {
|
||||
background: var(--drawer-background);
|
||||
}
|
||||
}
|
||||
157
frontend/src/pages/AuditLogs/components/DetailsDrawer.tsx
Normal file
157
frontend/src/pages/AuditLogs/components/DetailsDrawer.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Drawer } from '@signozhq/ui/drawer';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import cx from 'classnames';
|
||||
import LogStateIndicator from 'components/Logs/LogStateIndicator/LogStateIndicator';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { DataViewer } from 'periscope/components/DataViewer';
|
||||
|
||||
import { DATE_TIME_FORMATS } from '@/constants/dateTimeFormats';
|
||||
import { useTimezone } from '@/providers/Timezone';
|
||||
|
||||
import { AuditLog } from '../types';
|
||||
import {
|
||||
getBody,
|
||||
getOutcome,
|
||||
getPrincipalEmail,
|
||||
getResourceId,
|
||||
getResourceName,
|
||||
getVerb,
|
||||
isServiceAccount,
|
||||
} from '../utils';
|
||||
|
||||
import { CopyLinkButton } from './CopyLinkButton';
|
||||
import { DetailsField } from './DetailsField';
|
||||
import { OutcomeCell } from './QueryResultCells/OutcomeCell';
|
||||
|
||||
import styles from './DetailsDrawer.module.scss';
|
||||
import { useLogNavigation } from '@/components/LogDetail/LogDetailsHeader/useLogNavigation';
|
||||
import LogNavigation from '@/components/LogDetail/LogDetailsHeader/LogNavigation';
|
||||
import { LogNavigationHint } from '@/components/LogDetail/LogNavigationHint/LogNavigationHint';
|
||||
import { useArrowKeyNavigation } from '@/container/TracesExplorer/SpanDrawer/useArrowKeyNavigation';
|
||||
import { useCloseOnOutsideClick } from '@/hooks/logs/useCloseOnOutsideClick';
|
||||
|
||||
export const DetailsDrawer = ({
|
||||
logs,
|
||||
activeLog,
|
||||
handleCloseLogDetail,
|
||||
handleSetActiveLog,
|
||||
onScrollToLog,
|
||||
}: {
|
||||
logs: AuditLog[];
|
||||
activeLog: AuditLog | null;
|
||||
handleSetActiveLog: (log: AuditLog) => void;
|
||||
handleCloseLogDetail: () => void;
|
||||
onScrollToLog: (logId: string) => void;
|
||||
}): JSX.Element => {
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
|
||||
const { goToPrev, goToNext, isPrevDisabled, isNextDisabled } =
|
||||
useLogNavigation<AuditLog>({
|
||||
logs,
|
||||
activeLogId: activeLog?.id ?? '',
|
||||
onNavigateLog: handleSetActiveLog,
|
||||
onScrollToLog,
|
||||
});
|
||||
|
||||
useCloseOnOutsideClick(activeLog !== null, handleCloseLogDetail);
|
||||
|
||||
useArrowKeyNavigation({
|
||||
enabled: activeLog !== null,
|
||||
onNext: goToNext,
|
||||
onPrev: goToPrev,
|
||||
});
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
type="inspector"
|
||||
stack="overlay"
|
||||
open={activeLog !== null}
|
||||
onClose={handleCloseLogDetail}
|
||||
title={
|
||||
activeLog
|
||||
? formatTimezoneAdjustedTimestamp(
|
||||
activeLog.date,
|
||||
DATE_TIME_FORMATS.ISO_DATETIME_MS,
|
||||
)
|
||||
: ''
|
||||
}
|
||||
headerSuffix={
|
||||
<div className={styles.headerActions}>
|
||||
{activeLog && <CopyLinkButton logId={activeLog.id} />}
|
||||
<LogNavigation
|
||||
onNavigatePrev={goToPrev}
|
||||
onNavigateNext={goToNext}
|
||||
isPrevDisabled={isPrevDisabled}
|
||||
isNextDisabled={isNextDisabled}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
width="extra-wide"
|
||||
testId="audit-log-detail-drawer"
|
||||
closePosition="start"
|
||||
>
|
||||
{activeLog ? (
|
||||
<div className={styles.summary} data-testid="audit-log-detail-summary">
|
||||
<div className={styles.logLine} data-testid="audit-log-detail-body">
|
||||
<LogStateIndicator
|
||||
fontSize={FontSize.MEDIUM}
|
||||
severityText={activeLog.severity_text}
|
||||
severityNumber={activeLog.severity_number}
|
||||
flush
|
||||
/>
|
||||
<span className={styles.logText}>{getBody(activeLog)}</span>
|
||||
</div>
|
||||
<DetailsField label="Principal" testId="audit-log-detail-principal">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="primary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{getPrincipalEmail(activeLog)}
|
||||
</Typography>
|
||||
{isServiceAccount(activeLog) && (
|
||||
<Badge variant="outlined" color="info" textTransform="none">
|
||||
BOT
|
||||
</Badge>
|
||||
)}
|
||||
</DetailsField>
|
||||
<DetailsField label="Outcome" testId="audit-log-detail-outcome">
|
||||
<OutcomeCell outcome={getOutcome(activeLog)} />
|
||||
</DetailsField>
|
||||
<DetailsField label="Event" testId="audit-log-detail-event">
|
||||
<span className={cx(styles.mono, styles.emphasis)}>
|
||||
{getVerb(activeLog)}
|
||||
</span>
|
||||
</DetailsField>
|
||||
<DetailsField label="Resource" testId="audit-log-detail-resource">
|
||||
<span className={cx(styles.mono, styles.emphasis)}>
|
||||
{getResourceName(activeLog)}
|
||||
</span>
|
||||
</DetailsField>
|
||||
<DetailsField label="Resource ID" testId="audit-log-detail-resource-id">
|
||||
<span className={cx(styles.mono, styles.muted)}>
|
||||
{getResourceId(activeLog)}
|
||||
</span>
|
||||
</DetailsField>
|
||||
</div>
|
||||
) : null}
|
||||
<div className={styles.dataViewer}>
|
||||
<DataViewer
|
||||
data={activeLog ? activeLog : {}}
|
||||
drawerKey="audit-log-detail"
|
||||
fontSize={13}
|
||||
jsonString={JSON.stringify(activeLog ?? {}, null, 2)}
|
||||
/>
|
||||
</div>
|
||||
{activeLog ? (
|
||||
<div className={styles.hint} data-testid="audit-log-detail-navigation-hint">
|
||||
<LogNavigationHint />
|
||||
</div>
|
||||
) : null}
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.value {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
32
frontend/src/pages/AuditLogs/components/DetailsField.tsx
Normal file
32
frontend/src/pages/AuditLogs/components/DetailsField.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './DetailsField.module.scss';
|
||||
|
||||
interface DetailsFieldProps {
|
||||
label: string;
|
||||
testId: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function DetailsField({
|
||||
label,
|
||||
testId,
|
||||
children,
|
||||
}: DetailsFieldProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.field} data-testid={testId}>
|
||||
<Typography
|
||||
variant="uppercase"
|
||||
size="small"
|
||||
weight="bold"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{label}
|
||||
</Typography>
|
||||
<div className={styles.value}>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
.expandIcon {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { ArrowUpToLine, Filter } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
|
||||
import styles from './FilterExpandButton.module.scss';
|
||||
|
||||
interface FilterExpandButtonProps {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export function FilterExpandButton({
|
||||
onClick,
|
||||
}: FilterExpandButtonProps): JSX.Element {
|
||||
return (
|
||||
<Tooltip title="Show Filters">
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="md"
|
||||
aria-label="Show filters"
|
||||
color="secondary"
|
||||
onClick={onClick}
|
||||
testId="audit-logs-expand-filters-btn"
|
||||
>
|
||||
<Filter size={12} />
|
||||
<ArrowUpToLine size={12} className={styles.expandIcon} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
43
frontend/src/pages/AuditLogs/components/OptionsMenu.tsx
Normal file
43
frontend/src/pages/AuditLogs/components/OptionsMenu.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { useMemo } from 'react';
|
||||
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
|
||||
import { OptionsMenuConfig } from 'container/OptionsMenu/types';
|
||||
|
||||
import { useAuditLogsOptionsStore } from '../store/useAuditLogsOptionsStore';
|
||||
|
||||
const FORMAT_ITEMS = [
|
||||
{ key: 'raw', label: 'Raw' },
|
||||
{ key: 'list', label: 'Default' },
|
||||
{ key: 'table', label: 'Column' },
|
||||
];
|
||||
|
||||
export function OptionsMenu(): JSX.Element {
|
||||
const fontSize = useAuditLogsOptionsStore((state) => state.fontSize);
|
||||
const setFontSize = useAuditLogsOptionsStore((state) => state.setFontSize);
|
||||
const format = useAuditLogsOptionsStore((state) => state.format);
|
||||
const setFormat = useAuditLogsOptionsStore((state) => state.setFormat);
|
||||
const maxLines = useAuditLogsOptionsStore((state) => state.maxLines);
|
||||
const setMaxLines = useAuditLogsOptionsStore((state) => state.setMaxLines);
|
||||
|
||||
const config: OptionsMenuConfig = useMemo(
|
||||
() => ({
|
||||
fontSize: { value: fontSize, onChange: setFontSize },
|
||||
format: {
|
||||
value: format,
|
||||
onChange: setFormat,
|
||||
},
|
||||
maxLines: {
|
||||
value: maxLines,
|
||||
onChange: (value): void => setMaxLines(Number(value)),
|
||||
},
|
||||
}),
|
||||
[fontSize, setFontSize, format, setFormat, maxLines, setMaxLines],
|
||||
);
|
||||
|
||||
return (
|
||||
<LogsFormatOptionsMenu
|
||||
items={FORMAT_ITEMS}
|
||||
selectedOptionFormat={format}
|
||||
config={config}
|
||||
/>
|
||||
);
|
||||
}
|
||||
24
frontend/src/pages/AuditLogs/components/OrderBy.module.scss
Normal file
24
frontend/src/pages/AuditLogs/components/OrderBy.module.scss
Normal file
@@ -0,0 +1,24 @@
|
||||
.orderBy {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.select {
|
||||
:global(.order-by-select) {
|
||||
width: 100px;
|
||||
|
||||
:global(.ant-select-selector) {
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
53
frontend/src/pages/AuditLogs/components/OrderBy.tsx
Normal file
53
frontend/src/pages/AuditLogs/components/OrderBy.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { ArrowUp10, Minus } from '@signozhq/icons';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ListViewOrderBy from 'components/OrderBy/ListViewOrderBy';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { getListOrderBy, setListOrderBy } from 'utils/explorerUtils';
|
||||
|
||||
import styles from './OrderBy.module.scss';
|
||||
|
||||
const FIELD_KEYS_CONFIG = { source: TelemetrytypesSourceDTO.audit };
|
||||
|
||||
export function OrderBy(): JSX.Element {
|
||||
const { stagedQuery, currentQuery, redirectWithQueryBuilderData } =
|
||||
useQueryBuilder();
|
||||
|
||||
const orderBy = useMemo(() => getListOrderBy(stagedQuery), [stagedQuery]);
|
||||
|
||||
const handleOrderChange = useCallback(
|
||||
(value: string): void => {
|
||||
redirectWithQueryBuilderData(setListOrderBy(currentQuery, value));
|
||||
},
|
||||
[currentQuery, redirectWithQueryBuilderData],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.orderBy} data-testid="audit-logs-order-by">
|
||||
<div className={styles.label}>
|
||||
<Typography
|
||||
variant="label"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Order by
|
||||
</Typography>
|
||||
<Minus size={14} />
|
||||
<ArrowUp10 size={14} />
|
||||
</div>
|
||||
<div className={styles.select}>
|
||||
<ListViewOrderBy
|
||||
value={orderBy}
|
||||
onChange={handleOrderChange}
|
||||
dataSource={DataSource.LOGS}
|
||||
fieldKeysConfig={FIELD_KEYS_CONFIG}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
.queryBar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
39
frontend/src/pages/AuditLogs/components/QueryBar.tsx
Normal file
39
frontend/src/pages/AuditLogs/components/QueryBar.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import { QueryBuilderV2 } from '@/components/QueryBuilderV2';
|
||||
import styles from './QueryBar.module.scss';
|
||||
import { DataSource } from '@/types/common/queryBuilder';
|
||||
import { initialQueriesMap, PANEL_TYPES } from '@/constants/queryBuilder';
|
||||
import { useQueryBuilder } from '@/hooks/queryBuilder/useQueryBuilder';
|
||||
import { useMemo } from 'react';
|
||||
import { useShareBuilderUrl } from '@/hooks/queryBuilder/useShareBuilderUrl';
|
||||
import { TelemetrytypesSourceDTO } from '@/api/generated/services/sigNoz.schemas';
|
||||
|
||||
export function QueryBar(): JSX.Element {
|
||||
const { updateAllQueriesOperators } = useQueryBuilder();
|
||||
|
||||
const defaultValue = useMemo(
|
||||
() =>
|
||||
updateAllQueriesOperators(
|
||||
initialQueriesMap.logs,
|
||||
PANEL_TYPES.LIST,
|
||||
DataSource.LOGS,
|
||||
TelemetrytypesSourceDTO.audit,
|
||||
),
|
||||
[updateAllQueriesOperators],
|
||||
);
|
||||
|
||||
useShareBuilderUrl({ defaultValue });
|
||||
|
||||
return (
|
||||
<div className={styles.queryBar}>
|
||||
<QueryBuilderV2
|
||||
isRawQuery
|
||||
config={{
|
||||
initialDataSource: DataSource.LOGS,
|
||||
queryVariant: 'static',
|
||||
}}
|
||||
panelType={PANEL_TYPES.LIST}
|
||||
showOnlyWhereClause
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
.emailCell {
|
||||
--tanstack-table-cell-color: var(--l1-foreground);
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
min-width: 0;
|
||||
padding-right: var(--spacing-8);
|
||||
}
|
||||
|
||||
.email {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
|
||||
import styles from './EmailCell.module.scss';
|
||||
|
||||
interface EmailCellProps {
|
||||
email: string;
|
||||
isBot: boolean;
|
||||
}
|
||||
|
||||
export function EmailCell({ email, isBot }: EmailCellProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.emailCell}>
|
||||
<Tooltip title={email}>
|
||||
<TanStackTable.Text className={styles.email} data-testid="audit-logs-email">
|
||||
{email}
|
||||
</TanStackTable.Text>
|
||||
</Tooltip>
|
||||
{isBot && (
|
||||
<span className={styles.badge} data-testid="audit-logs-bot-badge">
|
||||
<Badge variant="outlined" color="info" textTransform="none">
|
||||
BOT
|
||||
</Badge>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
.monospaceCell {
|
||||
--tanstack-table-cell-color: var(--l1-foreground);
|
||||
|
||||
font-family: var(--code-base-400-font-family);
|
||||
font-weight: 500;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
|
||||
import styles from './MonospaceCell.module.scss';
|
||||
|
||||
interface MonospaceCellProps {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export function MonospaceCell({ value }: MonospaceCellProps): JSX.Element {
|
||||
return (
|
||||
<Tooltip title={value}>
|
||||
<TanStackTable.Text className={styles.monospaceCell}>
|
||||
{value}
|
||||
</TanStackTable.Text>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
|
||||
import { AuditOutcome } from '../../types';
|
||||
|
||||
interface OutcomeCellProps {
|
||||
outcome: AuditOutcome;
|
||||
}
|
||||
|
||||
export function OutcomeCell({ outcome }: OutcomeCellProps): JSX.Element {
|
||||
return (
|
||||
<Badge
|
||||
variant="outlined"
|
||||
color={outcome === AuditOutcome.SUCCESS ? 'success' : 'danger'}
|
||||
testId="audit-logs-outcome"
|
||||
>
|
||||
{outcome}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
.textCell {
|
||||
--tanstack-table-cell-color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.monospace {
|
||||
font-family: var(--code-base-400-font-family);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import cx from 'classnames';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
|
||||
import styles from './TextCell.module.scss';
|
||||
|
||||
interface TextCellProps {
|
||||
value: string;
|
||||
displayValue?: string;
|
||||
monospace?: boolean;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
export function TextCell({
|
||||
value,
|
||||
displayValue = value,
|
||||
monospace = false,
|
||||
testId,
|
||||
}: TextCellProps): JSX.Element {
|
||||
return (
|
||||
<Tooltip title={value}>
|
||||
<TanStackTable.Text
|
||||
className={cx(styles.textCell, { [styles.monospace]: monospace })}
|
||||
data-testid={testId}
|
||||
>
|
||||
{displayValue}
|
||||
</TanStackTable.Text>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
|
||||
interface TimeCellProps {
|
||||
date: string;
|
||||
}
|
||||
|
||||
export function TimeCell({ date }: TimeCellProps): JSX.Element {
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
|
||||
return (
|
||||
<TanStackTable.Text data-testid="audit-logs-time-cell">
|
||||
{formatTimezoneAdjustedTimestamp(date, DATE_TIME_FORMATS.ISO_DATETIME_MS)}
|
||||
</TanStackTable.Text>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { EmailCell } from '../EmailCell';
|
||||
|
||||
describe('EmailCell', () => {
|
||||
it('shows the email', () => {
|
||||
render(<EmailCell email="alice@acme.com" isBot={false} />);
|
||||
|
||||
expect(screen.getByTestId('audit-logs-email')).toHaveTextContent(
|
||||
'alice@acme.com',
|
||||
);
|
||||
});
|
||||
|
||||
it('shows a bot badge for a service account', () => {
|
||||
render(<EmailCell email="sa@acme.com" isBot />);
|
||||
|
||||
expect(screen.getByTestId('audit-logs-bot-badge')).toHaveTextContent('BOT');
|
||||
});
|
||||
|
||||
it('shows no badge for a user', () => {
|
||||
render(<EmailCell email="alice@acme.com" isBot={false} />);
|
||||
|
||||
expect(screen.queryByTestId('audit-logs-bot-badge')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { AuditOutcome } from '../../../types';
|
||||
import { OutcomeCell } from '../OutcomeCell';
|
||||
|
||||
describe('OutcomeCell', () => {
|
||||
it.each([
|
||||
[AuditOutcome.SUCCESS, 'success'],
|
||||
[AuditOutcome.FAILURE, 'danger'],
|
||||
])('shows the %s outcome as a %s badge', (outcome, color) => {
|
||||
render(<OutcomeCell outcome={outcome} />);
|
||||
|
||||
const badge = screen.getByTestId('audit-logs-outcome');
|
||||
expect(badge).toHaveTextContent(outcome);
|
||||
expect(badge).toHaveAttribute('data-color', color);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { TimeCell } from '../TimeCell';
|
||||
|
||||
describe('TimeCell', () => {
|
||||
it('shows the time in the format of the Logs table', () => {
|
||||
render(<TimeCell date="2023-11-14T22:13:20.123Z" />);
|
||||
|
||||
expect(screen.getByTestId('audit-logs-time-cell')).toHaveTextContent(
|
||||
/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.123$/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
.container {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.results {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.linkedRow td {
|
||||
background-color: var(--row-active-bg) !important;
|
||||
}
|
||||
|
||||
.list {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
background-color: var(--l1-background);
|
||||
}
|
||||
|
||||
.list :global(.ant-card) {
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
.list :global(.ant-card-body) {
|
||||
background-color: var(--l1-background);
|
||||
}
|
||||
|
||||
.small {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.medium {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.large {
|
||||
margin-top: 15px;
|
||||
}
|
||||
242
frontend/src/pages/AuditLogs/components/QueryResults.tsx
Normal file
242
frontend/src/pages/AuditLogs/components/QueryResults.tsx
Normal file
@@ -0,0 +1,242 @@
|
||||
import React, { CSSProperties, useCallback, useMemo, useRef } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
|
||||
import { LogsLoading } from 'container/LogsLoading/LogsLoading';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import APIError from 'types/api/error';
|
||||
import TanStackTable, {
|
||||
RowClickContext,
|
||||
TanStackTableHandle,
|
||||
} from 'components/TanStackTableView';
|
||||
|
||||
import { AuditLog } from '../types';
|
||||
import { getAuditFieldValue, getRowHoverColor } from '../utils';
|
||||
|
||||
import styles from './QueryResults.module.scss';
|
||||
import { useAuditLogColumns } from '../hooks/useAuditLogColumns';
|
||||
import { useAuditLogDetail } from '../hooks/useAuditLogDetail';
|
||||
import { DetailsDrawer } from './DetailsDrawer';
|
||||
import { LogsLoadingFooter } from '@/components/Logs/LogsLoadingFooter/LogsLoadingFooter';
|
||||
import useScrollToLog from '@/hooks/logs/useScrollToLog';
|
||||
import { useCopyLogLink } from '@/hooks/logs/useCopyLogLink';
|
||||
import { useAuditLogsOptionsStore } from '../store/useAuditLogsOptionsStore';
|
||||
import OverlayScrollbar from '@/components/OverlayScrollbar/OverlayScrollbar';
|
||||
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import RawLogView from '@/components/Logs/RawLogView';
|
||||
import ListLogView from '@/components/Logs/ListLogView';
|
||||
|
||||
interface QueryResultsProps {
|
||||
logs: AuditLog[];
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
error: APIError | null;
|
||||
onEndReached: () => void;
|
||||
}
|
||||
|
||||
export function QueryResults({
|
||||
logs,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
error,
|
||||
onEndReached,
|
||||
}: QueryResultsProps): JSX.Element {
|
||||
const { columns, fontSize, rawFields } = useAuditLogColumns();
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const format = useAuditLogsOptionsStore((state) => state.format);
|
||||
const maxLines = useAuditLogsOptionsStore((state) => state.maxLines);
|
||||
|
||||
const ref = useRef<TanStackTableHandle | VirtuosoHandle>(null);
|
||||
|
||||
const { activeLog, handleSetActiveLog, handleCloseLogDetail, onAddToQuery } =
|
||||
useAuditLogDetail();
|
||||
|
||||
const { activeLogId: deeplinkActiveLogId } = useCopyLogLink();
|
||||
|
||||
const deeplinkActiveLogIndex = useMemo(
|
||||
() => logs.findIndex(({ id }) => id === deeplinkActiveLogId),
|
||||
[logs, deeplinkActiveLogId],
|
||||
);
|
||||
const showLoading = isLoading || (isFetching && logs.length === 0);
|
||||
const showError = !showLoading && isError && !!error;
|
||||
const showEmpty = !showLoading && !showError && logs.length === 0;
|
||||
const showTable = !showLoading && !showError && logs.length > 0;
|
||||
|
||||
const handleScrollToLog = useScrollToLog({ logs, virtuosoRef: ref });
|
||||
|
||||
const getItemContent = useCallback(
|
||||
(_: number, log: AuditLog) => {
|
||||
if (format === 'raw') {
|
||||
return (
|
||||
<div key={log.id}>
|
||||
<RawLogView<AuditLog>
|
||||
data={log}
|
||||
isActiveLog={activeLog?.id === log.id}
|
||||
linesPerRow={maxLines}
|
||||
selectedFields={rawFields}
|
||||
getFieldValue={getAuditFieldValue}
|
||||
showActions
|
||||
fontSize={fontSize}
|
||||
onSetActiveLog={handleSetActiveLog}
|
||||
onClearActiveLog={handleCloseLogDetail}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (format === 'list') {
|
||||
return (
|
||||
<div key={log.id}>
|
||||
<ListLogView<AuditLog>
|
||||
logData={log}
|
||||
isActiveLog={activeLog?.id === log.id}
|
||||
activeLog={activeLog}
|
||||
linesPerRow={maxLines}
|
||||
selectedFields={rawFields}
|
||||
getFieldValue={getAuditFieldValue}
|
||||
showActions
|
||||
fontSize={fontSize}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onSetActiveLog={handleSetActiveLog}
|
||||
onClearActiveLog={handleCloseLogDetail}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
[
|
||||
format,
|
||||
maxLines,
|
||||
fontSize,
|
||||
rawFields,
|
||||
activeLog,
|
||||
handleSetActiveLog,
|
||||
handleCloseLogDetail,
|
||||
onAddToQuery,
|
||||
],
|
||||
);
|
||||
|
||||
const getRowKey = useCallback((log: AuditLog): string => log.id, []);
|
||||
|
||||
const getRowTestId = useCallback(
|
||||
(log: AuditLog): string => `audit-logs-table-row-${log.id}`,
|
||||
[],
|
||||
);
|
||||
|
||||
const getRowStyle = useCallback(
|
||||
(log: AuditLog): CSSProperties =>
|
||||
({
|
||||
'--row-active-bg': getRowHoverColor(isDarkMode, log),
|
||||
'--row-hover-bg': getRowHoverColor(isDarkMode, log),
|
||||
}) as CSSProperties,
|
||||
[isDarkMode],
|
||||
);
|
||||
|
||||
const isRowActive = useCallback(
|
||||
(log: AuditLog): boolean => log.id === activeLog?.id,
|
||||
[activeLog],
|
||||
);
|
||||
|
||||
const getRowClassName = useCallback(
|
||||
(log: AuditLog): string =>
|
||||
log.id === deeplinkActiveLogId ? styles.linkedRow : '',
|
||||
[deeplinkActiveLogId],
|
||||
);
|
||||
|
||||
const onRowClick = useCallback(
|
||||
(log: AuditLog, _itemKey: string, { isActive }: RowClickContext): void => {
|
||||
if (isActive) {
|
||||
handleCloseLogDetail();
|
||||
return;
|
||||
}
|
||||
handleSetActiveLog(log);
|
||||
},
|
||||
[handleCloseLogDetail, handleSetActiveLog],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
{showLoading && <LogsLoading />}
|
||||
|
||||
{showError && <ErrorInPlace error={error} data-testid="audit-logs-error" />}
|
||||
|
||||
{showEmpty && (
|
||||
<div className={styles.empty} data-testid="audit-logs-empty">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="p"
|
||||
align="center"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
No audit logs found for this query.
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showTable && (
|
||||
<div
|
||||
className={styles.results}
|
||||
data-testid="audit-logs-results"
|
||||
data-log-detail-ignore="true"
|
||||
>
|
||||
{format === 'table' ? (
|
||||
<TanStackTable<AuditLog>
|
||||
ref={ref as React.Ref<TanStackTableHandle>}
|
||||
testId="audit-logs-table"
|
||||
columns={columns}
|
||||
data={logs}
|
||||
isLoading={isFetching}
|
||||
getRowKey={getRowKey}
|
||||
getRowTestId={getRowTestId}
|
||||
getRowStyle={getRowStyle}
|
||||
onEndReached={onEndReached}
|
||||
isRowActive={isRowActive}
|
||||
activeRowIndex={deeplinkActiveLogIndex}
|
||||
getRowClassName={getRowClassName}
|
||||
cellTypographySize={fontSize}
|
||||
plainTextCellLineClamp={maxLines}
|
||||
onRowClick={onRowClick}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className={cx(styles.list, {
|
||||
[styles.small]: fontSize === FontSize.SMALL,
|
||||
[styles.medium]: fontSize === FontSize.MEDIUM,
|
||||
[styles.large]: fontSize === FontSize.LARGE,
|
||||
})}
|
||||
>
|
||||
<OverlayScrollbar isVirtuoso>
|
||||
<Virtuoso
|
||||
data-testid="logs-list-virtuoso-scroller"
|
||||
key={deeplinkActiveLogIndex || 'logs-virtuoso'}
|
||||
ref={ref as React.Ref<VirtuosoHandle>}
|
||||
initialTopMostItemIndex={
|
||||
deeplinkActiveLogIndex !== -1 ? deeplinkActiveLogIndex : 0
|
||||
}
|
||||
data={logs}
|
||||
endReached={onEndReached}
|
||||
totalCount={logs.length}
|
||||
itemContent={getItemContent}
|
||||
components={isFetching ? { Footer: LogsLoadingFooter } : {}}
|
||||
/>
|
||||
</OverlayScrollbar>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<DetailsDrawer
|
||||
logs={logs}
|
||||
activeLog={activeLog}
|
||||
handleCloseLogDetail={handleCloseLogDetail}
|
||||
handleSetActiveLog={handleSetActiveLog}
|
||||
onScrollToLog={handleScrollToLog}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import { CopyLinkButton } from '../CopyLinkButton';
|
||||
|
||||
const mockCopy = jest.fn();
|
||||
|
||||
jest.mock('react-use', () => ({
|
||||
...jest.requireActual('react-use'),
|
||||
useCopyToClipboard: (): [unknown, jest.Mock] => [null, mockCopy],
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
mockCopy.mockClear();
|
||||
});
|
||||
|
||||
describe('CopyLinkButton', () => {
|
||||
it('copies a link to the log on click', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
render(<CopyLinkButton logId="log-1" />, undefined, {
|
||||
initialRoute: ROUTES.AUDIT_LOGS,
|
||||
});
|
||||
|
||||
await user.click(screen.getByTestId('audit-log-detail-copy-link'));
|
||||
|
||||
expect(mockCopy).toHaveBeenCalledTimes(1);
|
||||
const link = mockCopy.mock.calls[0][0] as string;
|
||||
const params = new URL(link).searchParams;
|
||||
expect(new URL(link).pathname).toBe(ROUTES.AUDIT_LOGS);
|
||||
expect(params.get('activeLogId')).toBe('"log-1"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
import {
|
||||
fireEvent,
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import { AuditOutcome, AuditPrincipalType } from '../../types';
|
||||
import { buildAuditLog } from '../../__tests__/auditLogFixture';
|
||||
import { DetailsDrawer } from '../DetailsDrawer';
|
||||
|
||||
jest.mock('react-use', () => ({
|
||||
...jest.requireActual('react-use'),
|
||||
useCopyToClipboard: (): [unknown, jest.Mock] => [null, jest.fn()],
|
||||
}));
|
||||
|
||||
const first = buildAuditLog({ id: 'log-1' });
|
||||
const second = buildAuditLog({
|
||||
id: 'log-2',
|
||||
body: 'second body',
|
||||
event_name: 'signoz.audit.update',
|
||||
});
|
||||
const third = buildAuditLog({ id: 'log-3' });
|
||||
const logs = [first, second, third];
|
||||
|
||||
const handleSetActiveLog = jest.fn();
|
||||
const handleCloseLogDetail = jest.fn();
|
||||
const onScrollToLog = jest.fn();
|
||||
|
||||
function renderDrawer(activeLog: typeof first | null): void {
|
||||
render(
|
||||
<>
|
||||
<button type="button" data-testid="outside">
|
||||
outside
|
||||
</button>
|
||||
<DetailsDrawer
|
||||
logs={logs}
|
||||
activeLog={activeLog}
|
||||
handleSetActiveLog={handleSetActiveLog}
|
||||
handleCloseLogDetail={handleCloseLogDetail}
|
||||
onScrollToLog={onScrollToLog}
|
||||
/>
|
||||
</>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('DetailsDrawer', () => {
|
||||
it('stays closed without an active log', () => {
|
||||
renderDrawer(null);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('audit-log-detail-drawer'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the summary of the active log', async () => {
|
||||
renderDrawer(first);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('audit-log-detail-drawer'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByTestId('audit-log-detail-body')).toHaveTextContent(
|
||||
'alice@acme.com (user-001) created dashboard (dash-001)',
|
||||
);
|
||||
expect(screen.getByTestId('audit-log-detail-principal')).toHaveTextContent(
|
||||
'alice@acme.com',
|
||||
);
|
||||
expect(screen.getByTestId('audit-log-detail-event')).toHaveTextContent(
|
||||
'create',
|
||||
);
|
||||
expect(screen.getByTestId('audit-log-detail-resource')).toHaveTextContent(
|
||||
'dashboard',
|
||||
);
|
||||
expect(screen.getByTestId('audit-log-detail-resource-id')).toHaveTextContent(
|
||||
'dash-001-abcdef-123456',
|
||||
);
|
||||
expect(screen.getByTestId('audit-log-detail-outcome')).toHaveTextContent(
|
||||
AuditOutcome.SUCCESS,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the failure outcome', async () => {
|
||||
renderDrawer(
|
||||
buildAuditLog({
|
||||
attributes: {
|
||||
...first.attributes,
|
||||
'signoz.audit.outcome': AuditOutcome.FAILURE,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('audit-log-detail-outcome'),
|
||||
).resolves.toHaveTextContent(AuditOutcome.FAILURE);
|
||||
});
|
||||
|
||||
it('marks a service account principal with a bot badge', async () => {
|
||||
renderDrawer(
|
||||
buildAuditLog({
|
||||
attributes: {
|
||||
...first.attributes,
|
||||
'signoz.principal.type': AuditPrincipalType.SERVICE_ACCOUNT,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('audit-log-detail-principal'),
|
||||
).resolves.toHaveTextContent('BOT');
|
||||
});
|
||||
|
||||
it('does not mark a user principal as a bot', async () => {
|
||||
renderDrawer(first);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('audit-log-detail-principal'),
|
||||
).resolves.not.toHaveTextContent('BOT');
|
||||
});
|
||||
|
||||
it('shows the navigation hint', async () => {
|
||||
renderDrawer(first);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('audit-log-detail-navigation-hint'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables previous on the first log', async () => {
|
||||
renderDrawer(first);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('log-details-header-prev'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
expect(screen.getByTestId('log-details-header-next')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('disables next on the last log', async () => {
|
||||
renderDrawer(third);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('log-details-header-next'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
expect(screen.getByTestId('log-details-header-prev')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('moves to the next log and scrolls to it', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
renderDrawer(first);
|
||||
|
||||
await user.click(await screen.findByTestId('log-details-header-next'));
|
||||
|
||||
expect(handleSetActiveLog).toHaveBeenCalledWith(second);
|
||||
expect(onScrollToLog).toHaveBeenCalledWith('log-2');
|
||||
});
|
||||
|
||||
it('moves to the previous log and scrolls to it', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
renderDrawer(second);
|
||||
|
||||
await user.click(await screen.findByTestId('log-details-header-prev'));
|
||||
|
||||
expect(handleSetActiveLog).toHaveBeenCalledWith(first);
|
||||
expect(onScrollToLog).toHaveBeenCalledWith('log-1');
|
||||
});
|
||||
|
||||
it('moves to the next log on the down arrow', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
renderDrawer(first);
|
||||
await screen.findByTestId('audit-log-detail-drawer');
|
||||
|
||||
await user.keyboard('{ArrowDown}');
|
||||
|
||||
expect(handleSetActiveLog).toHaveBeenCalledWith(second);
|
||||
});
|
||||
|
||||
it('moves to the previous log on the up arrow', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
renderDrawer(second);
|
||||
await screen.findByTestId('audit-log-detail-drawer');
|
||||
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
expect(handleSetActiveLog).toHaveBeenCalledWith(first);
|
||||
});
|
||||
|
||||
it('leaves the arrow keys alone while closed', () => {
|
||||
renderDrawer(null);
|
||||
|
||||
const notPrevented = fireEvent.keyDown(document, { key: 'ArrowDown' });
|
||||
|
||||
expect(notPrevented).toBe(true);
|
||||
expect(handleSetActiveLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('closes on a click outside the drawer', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
renderDrawer(first);
|
||||
await screen.findByTestId('audit-log-detail-drawer');
|
||||
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(handleCloseLogDetail).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('offers a copy link button for the active log', async () => {
|
||||
renderDrawer(first);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('audit-log-detail-copy-link'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import { FilterExpandButton } from '../FilterExpandButton';
|
||||
|
||||
describe('FilterExpandButton', () => {
|
||||
it('calls onClick when pressed', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onClick = jest.fn();
|
||||
render(<FilterExpandButton onClick={onClick} />);
|
||||
|
||||
await user.click(screen.getByTestId('audit-logs-expand-filters-btn'));
|
||||
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import { useAuditLogsOptionsStore } from '../../store/useAuditLogsOptionsStore';
|
||||
import { OptionsMenu } from '../OptionsMenu';
|
||||
|
||||
async function openMenu(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
): Promise<void> {
|
||||
render(<OptionsMenu />);
|
||||
await user.click(screen.getByTestId('periscope-btn-format-options'));
|
||||
await screen.findByTestId('format-options-menu');
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'table', maxLines: 1 });
|
||||
});
|
||||
|
||||
describe('OptionsMenu', () => {
|
||||
it('offers the Raw, Default and Column formats', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
await openMenu(user);
|
||||
|
||||
expect(screen.getByTestId('format-option-raw')).toHaveTextContent('Raw');
|
||||
expect(screen.getByTestId('format-option-list')).toHaveTextContent('Default');
|
||||
expect(screen.getByTestId('format-option-table')).toHaveTextContent('Column');
|
||||
});
|
||||
|
||||
it('marks the stored format as selected', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
useAuditLogsOptionsStore.setState({ format: 'raw' });
|
||||
|
||||
await openMenu(user);
|
||||
|
||||
expect(screen.getByTestId('format-option-raw')).toContainElement(
|
||||
screen.getByTestId('format-check-icon'),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['raw', 'raw'],
|
||||
['list', 'list'],
|
||||
['table', 'table'],
|
||||
] as const)(
|
||||
'stores the %s format when it is chosen',
|
||||
async (key, expected) => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
useAuditLogsOptionsStore.setState({
|
||||
format: key === 'table' ? 'raw' : 'table',
|
||||
});
|
||||
await openMenu(user);
|
||||
|
||||
await user.click(screen.getByTestId(`format-option-${key}`));
|
||||
|
||||
expect(useAuditLogsOptionsStore.getState().format).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it('raises the max lines per row', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
await openMenu(user);
|
||||
|
||||
await user.click(screen.getByTestId('max-lines-more'));
|
||||
await user.click(screen.getByTestId('max-lines-more'));
|
||||
|
||||
expect(useAuditLogsOptionsStore.getState().maxLines).toBe(3);
|
||||
});
|
||||
|
||||
it('lowers the max lines per row but not below one', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
useAuditLogsOptionsStore.setState({ maxLines: 2 });
|
||||
await openMenu(user);
|
||||
|
||||
await user.click(screen.getByTestId('max-lines-fewer'));
|
||||
await user.click(screen.getByTestId('max-lines-fewer'));
|
||||
|
||||
expect(useAuditLogsOptionsStore.getState().maxLines).toBe(1);
|
||||
});
|
||||
|
||||
it('does not offer to edit columns', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
await openMenu(user);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('periscope-btn-edit-columns'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { OrderBy } from '../OrderBy';
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder');
|
||||
|
||||
jest.mock('components/OrderBy/ListViewOrderBy', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
value,
|
||||
onChange,
|
||||
fieldKeysConfig,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
fieldKeysConfig?: { source?: string };
|
||||
}): JSX.Element => (
|
||||
<div>
|
||||
<span data-testid="order-by-value">{value}</span>
|
||||
<span data-testid="order-by-source">{fieldKeysConfig?.source}</span>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="order-by-pick"
|
||||
aria-label="Pick ascending"
|
||||
onClick={(): void => onChange('timestamp:asc')}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
type QueryBuilder = ReturnType<typeof useQueryBuilder>;
|
||||
|
||||
const redirectWithQueryBuilderData = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilder['redirectWithQueryBuilderData']
|
||||
>;
|
||||
|
||||
function mockQueryBuilder(query: Query): void {
|
||||
const builder: Partial<QueryBuilder> = {
|
||||
stagedQuery: query,
|
||||
currentQuery: query,
|
||||
redirectWithQueryBuilderData,
|
||||
};
|
||||
jest.mocked(useQueryBuilder).mockReturnValue(builder as QueryBuilder);
|
||||
}
|
||||
|
||||
function withOrder(columnName: string, order: string): Query {
|
||||
return {
|
||||
...initialQueriesMap.logs,
|
||||
builder: {
|
||||
...initialQueriesMap.logs.builder,
|
||||
queryData: initialQueriesMap.logs.builder.queryData.map((queryData) => ({
|
||||
...queryData,
|
||||
orderBy: [{ columnName, order }],
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('OrderBy', () => {
|
||||
it('shows the order of the staged query', () => {
|
||||
mockQueryBuilder(withOrder('timestamp', 'desc'));
|
||||
|
||||
render(<OrderBy />);
|
||||
|
||||
expect(screen.getByTestId('order-by-value')).toHaveTextContent(
|
||||
'timestamp:desc',
|
||||
);
|
||||
});
|
||||
|
||||
it('suggests the fields of the audit source', () => {
|
||||
mockQueryBuilder(withOrder('timestamp', 'desc'));
|
||||
|
||||
render(<OrderBy />);
|
||||
|
||||
expect(screen.getByTestId('order-by-source')).toHaveTextContent('audit');
|
||||
});
|
||||
|
||||
it('writes a chosen order to the query', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
mockQueryBuilder(withOrder('timestamp', 'desc'));
|
||||
render(<OrderBy />);
|
||||
|
||||
await user.click(screen.getByTestId('order-by-pick'));
|
||||
|
||||
expect(redirectWithQueryBuilderData).toHaveBeenCalledTimes(1);
|
||||
const [nextQuery] = redirectWithQueryBuilderData.mock.calls[0];
|
||||
expect(nextQuery.builder.queryData[0].orderBy).toStrictEqual([
|
||||
{ columnName: 'timestamp', order: 'asc' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { QueryBar } from '../QueryBar';
|
||||
|
||||
jest.mock('hooks/queryBuilder/useShareBuilderUrl');
|
||||
|
||||
jest.mock('components/QueryBuilderV2', () => ({
|
||||
QueryBuilderV2: ({
|
||||
showOnlyWhereClause,
|
||||
panelType,
|
||||
}: {
|
||||
showOnlyWhereClause?: boolean;
|
||||
panelType: string;
|
||||
}): JSX.Element => (
|
||||
<div data-testid="query-builder">
|
||||
{`${panelType}:${String(showOnlyWhereClause)}`}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('QueryBar', () => {
|
||||
it('shows only the where clause for a list query', () => {
|
||||
render(<QueryBar />);
|
||||
|
||||
expect(screen.getByTestId('query-builder')).toHaveTextContent('list:true');
|
||||
});
|
||||
|
||||
it('starts from a logs query on the audit source', () => {
|
||||
render(<QueryBar />);
|
||||
|
||||
const { defaultValue } = jest.mocked(useShareBuilderUrl).mock.calls[0][0];
|
||||
const [queryData] = defaultValue.builder.queryData;
|
||||
expect(queryData.dataSource).toBe('logs');
|
||||
expect(queryData.source).toBe('audit');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
import ROUTES from 'constants/routes';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import APIError from 'types/api/error';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import { buildAuditLog } from '../../__tests__/auditLogFixture';
|
||||
import { useAuditLogsOptionsStore } from '../../store/useAuditLogsOptionsStore';
|
||||
import { QueryResults } from '../QueryResults';
|
||||
|
||||
jest.mock('react-use', () => ({
|
||||
...jest.requireActual('react-use'),
|
||||
useCopyToClipboard: (): [unknown, jest.Mock] => [null, jest.fn()],
|
||||
}));
|
||||
|
||||
const logs = [
|
||||
buildAuditLog({ id: 'log-1', body: 'first body' }),
|
||||
buildAuditLog({ id: 'log-2', body: 'second body' }),
|
||||
buildAuditLog({ id: 'log-3', body: 'third body' }),
|
||||
];
|
||||
|
||||
type Props = Partial<Parameters<typeof QueryResults>[0]>;
|
||||
|
||||
function renderResults(
|
||||
props: Props = {},
|
||||
initialRoute = ROUTES.AUDIT_LOGS,
|
||||
): void {
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight: 800, itemHeight: 40 }}>
|
||||
<QueryResults
|
||||
logs={logs}
|
||||
isLoading={false}
|
||||
isFetching={false}
|
||||
isError={false}
|
||||
error={null}
|
||||
onEndReached={jest.fn()}
|
||||
{...props}
|
||||
/>
|
||||
</VirtuosoMockContext.Provider>,
|
||||
undefined,
|
||||
{ initialRoute },
|
||||
);
|
||||
}
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
async function clickRow(user: User, rowId: string): Promise<void> {
|
||||
const row = screen.getByTestId(rowId);
|
||||
const isTableRow = rowId.startsWith('audit-logs-table-row');
|
||||
await user.click(
|
||||
isTableRow ? within(row).getByTestId('audit-logs-body-cell') : row,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'table', maxLines: 1 });
|
||||
});
|
||||
|
||||
describe('QueryResults', () => {
|
||||
describe('states', () => {
|
||||
it('shows the loading placeholder while the first page loads', () => {
|
||||
renderResults({ logs: [], isLoading: true });
|
||||
|
||||
expect(screen.getByAltText('wait-icon')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('audit-logs-results')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the empty state when there are no logs', () => {
|
||||
renderResults({ logs: [] });
|
||||
|
||||
expect(screen.getByTestId('audit-logs-empty')).toHaveTextContent(
|
||||
'No audit logs found for this query.',
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the error', () => {
|
||||
const error = new APIError({
|
||||
httpStatusCode: 400,
|
||||
error: {
|
||||
code: '400',
|
||||
message: 'invalid filter expression',
|
||||
url: '',
|
||||
errors: [],
|
||||
},
|
||||
});
|
||||
|
||||
renderResults({ logs: [], isError: true, error });
|
||||
|
||||
expect(screen.getByTestId('audit-logs-error')).toHaveTextContent(
|
||||
'invalid filter expression',
|
||||
);
|
||||
expect(screen.queryByTestId('audit-logs-empty')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps showing the loaded logs while the next page loads', () => {
|
||||
renderResults({ isFetching: true });
|
||||
|
||||
expect(screen.getByTestId('audit-logs-results')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('formats', () => {
|
||||
it('renders a table row per log in the Column format', () => {
|
||||
renderResults();
|
||||
|
||||
expect(screen.getByTestId('audit-logs-table-row-log-1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('audit-logs-table-row-log-3')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('logs-raw-row-log-1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a raw row per log in the Raw format', () => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'raw' });
|
||||
|
||||
renderResults();
|
||||
|
||||
expect(screen.getByTestId('logs-raw-row-log-1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('logs-raw-row-log-3')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('audit-logs-table')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the loading footer while the next page loads', () => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'raw' });
|
||||
|
||||
renderResults({ isFetching: true });
|
||||
|
||||
expect(screen.getByTestId('logs-loading-footer')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the loading footer when nothing is loading', () => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'raw' });
|
||||
|
||||
renderResults();
|
||||
|
||||
expect(screen.queryByTestId('logs-loading-footer')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders a list row per log in the Default format', () => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'list' });
|
||||
|
||||
renderResults();
|
||||
|
||||
expect(screen.getByTestId('logs-list-row-log-1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('logs-list-row-log-3')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('audit-logs-table')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the resource fields in the Raw line', () => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'raw' });
|
||||
|
||||
renderResults();
|
||||
|
||||
expect(screen.getByTestId('logs-raw-row-log-1')).toHaveTextContent(
|
||||
'dashboard | dash-001-abcdef-123456',
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the principal email in the Default format', () => {
|
||||
useAuditLogsOptionsStore.setState({ format: 'list' });
|
||||
|
||||
renderResults();
|
||||
|
||||
expect(screen.getByTestId('logs-list-row-log-1')).toHaveTextContent(
|
||||
'alice@acme.com',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('selection', () => {
|
||||
it.each([
|
||||
['table', 'audit-logs-table-row-log-2'],
|
||||
['raw', 'logs-raw-row-log-2'],
|
||||
['list', 'logs-list-row-log-2'],
|
||||
] as const)(
|
||||
'opens the details drawer on a %s row click',
|
||||
async (format, rowId) => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
useAuditLogsOptionsStore.setState({ format });
|
||||
renderResults();
|
||||
|
||||
await clickRow(user, rowId);
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('audit-log-detail-drawer'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByTestId('audit-log-detail-body')).toHaveTextContent(
|
||||
'second body',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['table', 'audit-logs-table-row-log-2'],
|
||||
['raw', 'logs-raw-row-log-2'],
|
||||
['list', 'logs-list-row-log-2'],
|
||||
] as const)(
|
||||
'closes the drawer when the open %s row is clicked again',
|
||||
async (format, rowId) => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
useAuditLogsOptionsStore.setState({ format });
|
||||
renderResults();
|
||||
await clickRow(user, rowId);
|
||||
await screen.findByTestId('audit-log-detail-drawer');
|
||||
|
||||
await clickRow(user, rowId);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('audit-log-detail-drawer'),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps the drawer open when another row is clicked', async () => {
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
renderResults();
|
||||
await clickRow(user, 'audit-logs-table-row-log-1');
|
||||
await screen.findByTestId('audit-log-detail-drawer');
|
||||
|
||||
await clickRow(user, 'audit-logs-table-row-log-2');
|
||||
|
||||
expect(screen.getByTestId('audit-log-detail-body')).toHaveTextContent(
|
||||
'second body',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
35
frontend/src/pages/AuditLogs/constants.ts
Normal file
35
frontend/src/pages/AuditLogs/constants.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { TableColumnDef } from 'components/TanStackTableView';
|
||||
|
||||
import { AuditLog } from './types';
|
||||
|
||||
const column = (
|
||||
name: string,
|
||||
fieldContext: TelemetryFieldKey['fieldContext'],
|
||||
): TelemetryFieldKey => ({
|
||||
name,
|
||||
signal: 'logs',
|
||||
fieldContext,
|
||||
fieldDataType: fieldContext === 'log' ? '' : 'string',
|
||||
isIndexed: false,
|
||||
});
|
||||
|
||||
export const AUDIT_FIELD_KEYS: TelemetryFieldKey[] = [
|
||||
column('timestamp', 'log'),
|
||||
column('signoz.principal.email', 'attribute'),
|
||||
column('event_name', 'log'),
|
||||
column('signoz.resource.kind', 'resource'),
|
||||
column('signoz.resource.id', 'resource'),
|
||||
column('signoz.audit.outcome', 'attribute'),
|
||||
column('body', 'log'),
|
||||
];
|
||||
|
||||
export const COLUMN_STATIC_OPTIONS: Pick<
|
||||
TableColumnDef<AuditLog>,
|
||||
'enableMove' | 'enableResize' | 'enableRemove' | 'canBeHidden'
|
||||
> = {
|
||||
enableMove: false,
|
||||
enableResize: false,
|
||||
enableRemove: false,
|
||||
canBeHidden: false,
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { useIsTextSelected } from 'hooks/useIsTextSelected';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
|
||||
import { buildAuditLog } from '../../__tests__/auditLogFixture';
|
||||
import { useAuditLogDetail } from '../useAuditLogDetail';
|
||||
|
||||
jest.mock('hooks/useIsTextSelected');
|
||||
jest.mock('hooks/useUrlQuery');
|
||||
|
||||
const mockIsTextSelected = jest.fn<boolean, []>();
|
||||
let compositeQuery = 'query-a';
|
||||
|
||||
const first = buildAuditLog({ id: 'log-1' });
|
||||
const second = buildAuditLog({ id: 'log-2' });
|
||||
|
||||
beforeEach(() => {
|
||||
compositeQuery = 'query-a';
|
||||
mockIsTextSelected.mockReturnValue(false);
|
||||
jest.mocked(useIsTextSelected).mockReturnValue(mockIsTextSelected);
|
||||
jest
|
||||
.mocked(useUrlQuery)
|
||||
.mockImplementation(
|
||||
() => new URLSearchParams({ [QueryParams.compositeQuery]: compositeQuery }),
|
||||
);
|
||||
});
|
||||
|
||||
describe('useAuditLogDetail', () => {
|
||||
it('starts with no active log', () => {
|
||||
const { result } = renderHook(() => useAuditLogDetail());
|
||||
|
||||
expect(result.current.activeLog).toBeNull();
|
||||
});
|
||||
|
||||
it('opens the log it is given', () => {
|
||||
const { result } = renderHook(() => useAuditLogDetail());
|
||||
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
|
||||
expect(result.current.activeLog).toStrictEqual(first);
|
||||
});
|
||||
|
||||
it('switches to another log', () => {
|
||||
const { result } = renderHook(() => useAuditLogDetail());
|
||||
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
act(() => result.current.handleSetActiveLog(second));
|
||||
|
||||
expect(result.current.activeLog).toStrictEqual(second);
|
||||
});
|
||||
|
||||
it('closes when the active log is selected again', () => {
|
||||
const { result } = renderHook(() => useAuditLogDetail());
|
||||
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
|
||||
expect(result.current.activeLog).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores a selection made while text is selected', () => {
|
||||
mockIsTextSelected.mockReturnValue(true);
|
||||
const { result } = renderHook(() => useAuditLogDetail());
|
||||
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
|
||||
expect(result.current.activeLog).toBeNull();
|
||||
});
|
||||
|
||||
it('closes on handleCloseLogDetail', () => {
|
||||
const { result } = renderHook(() => useAuditLogDetail());
|
||||
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
act(() => result.current.handleCloseLogDetail());
|
||||
|
||||
expect(result.current.activeLog).toBeNull();
|
||||
});
|
||||
|
||||
it('closes when the query in the URL changes', () => {
|
||||
const { result, rerender } = renderHook(() => useAuditLogDetail());
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
|
||||
compositeQuery = 'query-b';
|
||||
rerender();
|
||||
|
||||
expect(result.current.activeLog).toBeNull();
|
||||
});
|
||||
|
||||
it('stays open when the query in the URL is unchanged', () => {
|
||||
const { result, rerender } = renderHook(() => useAuditLogDetail());
|
||||
act(() => result.current.handleSetActiveLog(first));
|
||||
|
||||
rerender();
|
||||
|
||||
expect(result.current.activeLog).toStrictEqual(first);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
import { MutableRefObject, ReactNode } from 'react';
|
||||
import { QueryClient, QueryClientProvider, QueryKey } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider } from 'react-redux';
|
||||
import configureStore from 'redux-mock-store';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { UseCopyLogLink } from 'hooks/logs/types';
|
||||
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
|
||||
import { act, AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
|
||||
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import { buildLog } from 'components/Logs/__tests__/buildLog';
|
||||
import { useAuditLogsQuery } from '../useAuditLogsQuery';
|
||||
|
||||
jest.mock('lib/dashboard/getQueryResults');
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder');
|
||||
jest.mock('hooks/logs/useCopyLogLink');
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
type QueryBuilder = ReturnType<typeof useQueryBuilder>;
|
||||
|
||||
const stagedQuery: Query = { ...initialQueriesMap.logs, id: 'query-a' };
|
||||
|
||||
let queryClient: QueryClient;
|
||||
let timeRange = { minTime: 1_000, maxTime: 2_000 };
|
||||
let pageRows: Record<number, number> = {};
|
||||
let gate: Promise<void> | null = null;
|
||||
const requests: Query[] = [];
|
||||
let keyRef: MutableRefObject<QueryKey | undefined>;
|
||||
|
||||
function Wrapper({ children }: { children: ReactNode }): JSX.Element {
|
||||
return (
|
||||
<AllTheProviders>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Provider store={configureStore()({ globalTime: timeRange })}>
|
||||
{children}
|
||||
</Provider>
|
||||
</QueryClientProvider>
|
||||
</AllTheProviders>
|
||||
);
|
||||
}
|
||||
|
||||
function buildResponse(
|
||||
count: number,
|
||||
offset: number,
|
||||
): MetricQueryRangeSuccessResponse {
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: '',
|
||||
payload: {
|
||||
data: {
|
||||
resultType: '',
|
||||
newResult: {
|
||||
data: {
|
||||
resultType: '',
|
||||
result: [
|
||||
{
|
||||
queryName: 'A',
|
||||
series: null,
|
||||
list: Array.from({ length: count }, (_, i) => ({
|
||||
timestamp: '2023-11-14T22:13:20Z',
|
||||
data: buildLog({ id: `log-${offset + i}` }),
|
||||
})),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
result: [],
|
||||
},
|
||||
},
|
||||
} as MetricQueryRangeSuccessResponse;
|
||||
}
|
||||
|
||||
function buildCopyLogLink(activeLogId: string | null): UseCopyLogLink {
|
||||
return {
|
||||
isHighlighted: false,
|
||||
isLogsExplorerPage: false,
|
||||
activeLogId,
|
||||
onLogCopy: jest.fn(),
|
||||
onClearActiveLog: jest.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function mockQueryBuilder(builder: Partial<QueryBuilder>): void {
|
||||
jest.mocked(useQueryBuilder).mockReturnValue(builder as QueryBuilder);
|
||||
}
|
||||
|
||||
function renderQuery(): ReturnType<
|
||||
typeof renderHook<ReturnType<typeof useAuditLogsQuery>, unknown>
|
||||
> {
|
||||
return renderHook(() => useAuditLogsQuery({ listAuditLogsKeyRef: keyRef }), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
}
|
||||
|
||||
function lastRequest(): Query {
|
||||
return requests[requests.length - 1];
|
||||
}
|
||||
|
||||
function offsetOf(query: Query): number {
|
||||
return query.builder.queryData[0].offset ?? 0;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
timeRange = { minTime: 1_000, maxTime: 2_000 };
|
||||
pageRows = { 0: PAGE_SIZE, 100: 40 };
|
||||
gate = null;
|
||||
requests.length = 0;
|
||||
keyRef = { current: undefined };
|
||||
jest.mocked(useCopyLogLink).mockReturnValue(buildCopyLogLink(null));
|
||||
mockQueryBuilder({ stagedQuery, isEnabledQuery: true });
|
||||
jest.mocked(GetMetricQueryRange).mockImplementation(async ({ query }) => {
|
||||
requests.push(query);
|
||||
await gate;
|
||||
const offset = offsetOf(query);
|
||||
return buildResponse(pageRows[offset] ?? 0, offset);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useAuditLogsQuery', () => {
|
||||
it('requests the first page of the staged query', async () => {
|
||||
renderQuery();
|
||||
|
||||
await waitFor(() => expect(requests).toHaveLength(1));
|
||||
const [queryData] = lastRequest().builder.queryData;
|
||||
expect(queryData.offset).toBe(0);
|
||||
expect(queryData.pageSize).toBe(PAGE_SIZE);
|
||||
});
|
||||
|
||||
it('orders by timestamp and then id', async () => {
|
||||
renderQuery();
|
||||
|
||||
await waitFor(() => expect(requests).toHaveLength(1));
|
||||
expect(lastRequest().builder.queryData[0].orderBy).toStrictEqual([
|
||||
{ columnName: 'timestamp', order: 'desc' },
|
||||
{ columnName: 'id', order: 'desc' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns the rows of the first page', async () => {
|
||||
const { result } = renderQuery();
|
||||
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(PAGE_SIZE));
|
||||
expect(result.current.logs[0].id).toBe('log-0');
|
||||
});
|
||||
|
||||
it('requests the next page and appends its rows at the end', async () => {
|
||||
const { result } = renderQuery();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(PAGE_SIZE));
|
||||
|
||||
act(() => result.current.onEndReached());
|
||||
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(140));
|
||||
expect(offsetOf(lastRequest())).toBe(PAGE_SIZE);
|
||||
expect(result.current.logs[PAGE_SIZE].id).toBe('log-100');
|
||||
});
|
||||
|
||||
it('does not request another page while the previous one is loading', async () => {
|
||||
const { result } = renderQuery();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(PAGE_SIZE));
|
||||
let release: () => void = () => undefined;
|
||||
gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
act(() => result.current.onEndReached());
|
||||
await waitFor(() => expect(requests).toHaveLength(2));
|
||||
act(() => result.current.onEndReached());
|
||||
|
||||
expect(requests).toHaveLength(2);
|
||||
release();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(140));
|
||||
});
|
||||
|
||||
it('stops requesting pages once a page comes back short', async () => {
|
||||
const { result } = renderQuery();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(PAGE_SIZE));
|
||||
act(() => result.current.onEndReached());
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(140));
|
||||
|
||||
act(() => result.current.onEndReached());
|
||||
|
||||
expect(requests).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not request a page after a first page that is already short', async () => {
|
||||
pageRows = { 0: 5 };
|
||||
const { result } = renderQuery();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(5));
|
||||
|
||||
act(() => result.current.onEndReached());
|
||||
|
||||
expect(requests).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('adds the linked log id to the filter and the request', async () => {
|
||||
jest.mocked(useCopyLogLink).mockReturnValue(buildCopyLogLink('log-42'));
|
||||
|
||||
renderQuery();
|
||||
|
||||
await waitFor(() => expect(requests).toHaveLength(1));
|
||||
const [queryData] = lastRequest().builder.queryData;
|
||||
expect(queryData.filter?.expression).toBe("id <= 'log-42'");
|
||||
expect(queryData.filters?.items).toStrictEqual([
|
||||
expect.objectContaining({
|
||||
key: expect.objectContaining({ key: 'id' }),
|
||||
op: '<=',
|
||||
value: 'log-42',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('starts over from the first page when the linked log changes', async () => {
|
||||
jest.mocked(useCopyLogLink).mockReturnValue(buildCopyLogLink('log-1'));
|
||||
const { result, rerender } = renderQuery();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(PAGE_SIZE));
|
||||
act(() => result.current.onEndReached());
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(140));
|
||||
pageRows = { 0: 5 };
|
||||
jest.mocked(useCopyLogLink).mockReturnValue(buildCopyLogLink('log-2'));
|
||||
|
||||
rerender();
|
||||
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(5));
|
||||
const [queryData] = lastRequest().builder.queryData;
|
||||
expect(queryData.offset).toBe(0);
|
||||
expect(queryData.filter?.expression).toBe("id <= 'log-2'");
|
||||
});
|
||||
|
||||
it('starts over from the first page when the staged query changes', async () => {
|
||||
const { result, rerender } = renderQuery();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(PAGE_SIZE));
|
||||
act(() => result.current.onEndReached());
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(140));
|
||||
pageRows = { 0: 5 };
|
||||
mockQueryBuilder({
|
||||
stagedQuery: { ...stagedQuery, id: 'query-b' },
|
||||
isEnabledQuery: true,
|
||||
});
|
||||
|
||||
rerender();
|
||||
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(5));
|
||||
expect(offsetOf(lastRequest())).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['start', { minTime: 1_500, maxTime: 2_000 }],
|
||||
['end', { minTime: 1_000, maxTime: 2_500 }],
|
||||
])(
|
||||
'starts over from the first page when the %s time changes',
|
||||
async (_, nextRange) => {
|
||||
const { result, rerender } = renderQuery();
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(PAGE_SIZE));
|
||||
act(() => result.current.onEndReached());
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(140));
|
||||
pageRows = { 0: 5 };
|
||||
timeRange = nextRange;
|
||||
|
||||
rerender();
|
||||
|
||||
await waitFor(() => expect(result.current.logs).toHaveLength(5));
|
||||
expect(offsetOf(lastRequest())).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('requests nothing while the query is not enabled', () => {
|
||||
mockQueryBuilder({ stagedQuery, isEnabledQuery: false });
|
||||
|
||||
renderQuery();
|
||||
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('gives the page a key to cancel the running request', async () => {
|
||||
renderQuery();
|
||||
|
||||
await waitFor(() => expect(requests).toHaveLength(1));
|
||||
expect(keyRef.current).toStrictEqual(
|
||||
expect.arrayContaining(['audit-logs', stagedQuery]),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns a failed request as an API error', async () => {
|
||||
jest.mocked(GetMetricQueryRange).mockRejectedValue(new Error('boom'));
|
||||
|
||||
const { result } = renderQuery();
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(result.current.error).toBeInstanceOf(APIError);
|
||||
expect(result.current.error?.getErrorMessage()).toBe('boom');
|
||||
});
|
||||
});
|
||||
135
frontend/src/pages/AuditLogs/hooks/useAuditLogColumns.tsx
Normal file
135
frontend/src/pages/AuditLogs/hooks/useAuditLogColumns.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
import { ReactElement, useMemo } from 'react';
|
||||
import LogStateIndicator from 'components/Logs/LogStateIndicator/LogStateIndicator';
|
||||
import { TableColumnDef } from 'components/TanStackTableView';
|
||||
import { useAuditLogsOptionsStore } from '../store/useAuditLogsOptionsStore';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { IField } from 'types/api/logs/fields';
|
||||
|
||||
import { AUDIT_FIELD_KEYS, COLUMN_STATIC_OPTIONS } from '../constants';
|
||||
import { AuditLog, AuditLogsColumnIds } from '../types';
|
||||
import {
|
||||
getBody,
|
||||
getEventName,
|
||||
getOutcome,
|
||||
getPrincipalEmail,
|
||||
getResourceId,
|
||||
getResourceName,
|
||||
isServiceAccount,
|
||||
truncateId,
|
||||
} from '../utils';
|
||||
import { EmailCell } from '../components/QueryResultCells/EmailCell';
|
||||
import { MonospaceCell } from '../components/QueryResultCells/MonospaceCell';
|
||||
import { OutcomeCell } from '../components/QueryResultCells/OutcomeCell';
|
||||
import { TextCell } from '../components/QueryResultCells/TextCell';
|
||||
import { TimeCell } from '../components/QueryResultCells/TimeCell';
|
||||
|
||||
const RAW_FIELDS: IField[] = AUDIT_FIELD_KEYS.map(({ name }) => ({
|
||||
name,
|
||||
type: '',
|
||||
dataType: '',
|
||||
}));
|
||||
|
||||
interface UseAuditLogColumnsReturn {
|
||||
columns: TableColumnDef<AuditLog>[];
|
||||
fontSize: FontSize;
|
||||
rawFields: IField[];
|
||||
}
|
||||
|
||||
export const useAuditLogColumns = (): UseAuditLogColumnsReturn => {
|
||||
const fontSize = useAuditLogsOptionsStore((state) => state.fontSize);
|
||||
|
||||
const columns = useMemo(() => {
|
||||
const outcomeIndicator: TableColumnDef<AuditLog> = {
|
||||
id: AuditLogsColumnIds.OUTCOME_INDICATOR,
|
||||
header: '',
|
||||
pin: 'left',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { fixed: 32 },
|
||||
cell: ({ row }): ReactElement => (
|
||||
<LogStateIndicator
|
||||
fontSize={fontSize}
|
||||
severityText={row.severity_text}
|
||||
severityNumber={row.severity_number}
|
||||
/>
|
||||
),
|
||||
};
|
||||
|
||||
const time: TableColumnDef<AuditLog> = {
|
||||
id: AuditLogsColumnIds.TIME,
|
||||
header: 'Time',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { default: 170, min: 170 },
|
||||
accessorFn: (log): string => log.date,
|
||||
cell: ({ row }): ReactElement => <TimeCell date={row.date} />,
|
||||
};
|
||||
|
||||
const fields: TableColumnDef<AuditLog>[] = [
|
||||
{
|
||||
id: AuditLogsColumnIds.PRINCIPAL_EMAIL,
|
||||
header: 'Principal email',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { default: 260, max: 320, min: 220 },
|
||||
accessorFn: getPrincipalEmail,
|
||||
cell: ({ row }): ReactElement => (
|
||||
<EmailCell email={getPrincipalEmail(row)} isBot={isServiceAccount(row)} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: AuditLogsColumnIds.EVENT_NAME,
|
||||
header: 'Event name',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { default: 200, max: 240, min: 180 },
|
||||
accessorFn: getEventName,
|
||||
cell: ({ row }): ReactElement => (
|
||||
<MonospaceCell value={getEventName(row)} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: AuditLogsColumnIds.RESOURCE_NAME,
|
||||
header: 'Resource name',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { default: 170, max: 220, min: 140 },
|
||||
accessorFn: getResourceName,
|
||||
cell: ({ row }): ReactElement => (
|
||||
<MonospaceCell value={getResourceName(row)} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: AuditLogsColumnIds.RESOURCE_ID,
|
||||
header: 'Resource ID',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { default: 140, max: 160, min: 120 },
|
||||
accessorFn: getResourceId,
|
||||
cell: ({ row }): ReactElement => (
|
||||
<TextCell
|
||||
value={getResourceId(row)}
|
||||
displayValue={truncateId(getResourceId(row))}
|
||||
monospace
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: AuditLogsColumnIds.OUTCOME,
|
||||
header: 'Outcome',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { fixed: 120 },
|
||||
accessorFn: getOutcome,
|
||||
cell: ({ row }): ReactElement => <OutcomeCell outcome={getOutcome(row)} />,
|
||||
},
|
||||
{
|
||||
id: AuditLogsColumnIds.BODY,
|
||||
header: 'Body',
|
||||
...COLUMN_STATIC_OPTIONS,
|
||||
width: { default: 1000, min: 300, max: 1000, ignoreLastColumnFill: true },
|
||||
accessorFn: getBody,
|
||||
cell: ({ row }): ReactElement => (
|
||||
<TextCell value={getBody(row)} testId="audit-logs-body-cell" />
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return [outcomeIndicator, time, ...fields];
|
||||
}, [fontSize]);
|
||||
|
||||
return { columns, fontSize, rawFields: RAW_FIELDS };
|
||||
};
|
||||
40
frontend/src/pages/AuditLogs/hooks/useAuditLogDetail.ts
Normal file
40
frontend/src/pages/AuditLogs/hooks/useAuditLogDetail.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useActiveLog } from 'hooks/logs/useActiveLog';
|
||||
import { UseActiveLog } from 'hooks/logs/types';
|
||||
import { useIsTextSelected } from 'hooks/useIsTextSelected';
|
||||
|
||||
import { AuditLog } from '../types';
|
||||
|
||||
interface UseAuditLogDetailReturn {
|
||||
activeLog: AuditLog | null;
|
||||
handleSetActiveLog: (log: AuditLog) => void;
|
||||
handleCloseLogDetail: () => void;
|
||||
onAddToQuery: UseActiveLog['onAddToQuery'];
|
||||
}
|
||||
|
||||
export function useAuditLogDetail(): UseAuditLogDetailReturn {
|
||||
const { activeLog, onSetActiveLog, onClearActiveLog, onAddToQuery } =
|
||||
useActiveLog<AuditLog>();
|
||||
const isTextSelected = useIsTextSelected();
|
||||
|
||||
const handleSetActiveLog = useCallback(
|
||||
(log: AuditLog): void => {
|
||||
if (isTextSelected()) {
|
||||
return;
|
||||
}
|
||||
if (activeLog?.id === log.id) {
|
||||
onClearActiveLog();
|
||||
return;
|
||||
}
|
||||
onSetActiveLog(log);
|
||||
},
|
||||
[activeLog, isTextSelected, onClearActiveLog, onSetActiveLog],
|
||||
);
|
||||
|
||||
return {
|
||||
activeLog,
|
||||
handleSetActiveLog,
|
||||
handleCloseLogDetail: onClearActiveLog,
|
||||
onAddToQuery,
|
||||
};
|
||||
}
|
||||
145
frontend/src/pages/AuditLogs/hooks/useAuditLogsQuery.ts
Normal file
145
frontend/src/pages/AuditLogs/hooks/useAuditLogsQuery.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { MutableRefObject, useCallback, useMemo } from 'react';
|
||||
import { QueryKey, useInfiniteQuery } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import {
|
||||
initialFilters,
|
||||
initialQueriesMap,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import { DEFAULT_PER_PAGE_VALUE } from 'container/Controls/config';
|
||||
import {
|
||||
getListQuery,
|
||||
getQueryByPanelType,
|
||||
} from 'container/LogsExplorerViews/explorerUtils';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
|
||||
import { Warning } from 'types/api';
|
||||
import APIError from 'types/api/error';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { getListOrderBy } from 'utils/explorerUtils';
|
||||
|
||||
import { useCopyLogLink } from '@/hooks/logs/useCopyLogLink';
|
||||
import { AuditLog } from '../types';
|
||||
|
||||
const PAGE_SIZE = DEFAULT_PER_PAGE_VALUE;
|
||||
|
||||
interface UseAuditLogsQueryArgs {
|
||||
listAuditLogsKeyRef: MutableRefObject<QueryKey | undefined>;
|
||||
}
|
||||
|
||||
interface UseAuditLogsQueryReturn {
|
||||
logs: AuditLog[];
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
error: APIError | null;
|
||||
warning?: Warning;
|
||||
onEndReached: () => void;
|
||||
}
|
||||
|
||||
export function useAuditLogsQuery({
|
||||
listAuditLogsKeyRef,
|
||||
}: UseAuditLogsQueryArgs): UseAuditLogsQueryReturn {
|
||||
const { stagedQuery, isEnabledQuery } = useQueryBuilder();
|
||||
const { activeLogId } = useCopyLogLink();
|
||||
|
||||
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
|
||||
const listQuery = useMemo(() => getListQuery(stagedQuery), [stagedQuery]);
|
||||
const orderBy = useMemo(() => getListOrderBy(stagedQuery), [stagedQuery]);
|
||||
|
||||
const queryKey = useMemo(
|
||||
() => ['audit-logs', stagedQuery, minTime, maxTime, activeLogId],
|
||||
[stagedQuery, minTime, maxTime, activeLogId],
|
||||
);
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
listAuditLogsKeyRef.current = queryKey;
|
||||
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
error,
|
||||
hasNextPage,
|
||||
fetchNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery<MetricQueryRangeSuccessResponse, APIError | Error>({
|
||||
queryKey,
|
||||
queryFn: ({ pageParam = 1, signal }) =>
|
||||
GetMetricQueryRange(
|
||||
{
|
||||
query:
|
||||
getQueryByPanelType(stagedQuery, PANEL_TYPES.LIST, {
|
||||
page: pageParam as number,
|
||||
pageSize: PAGE_SIZE,
|
||||
filters: listQuery?.filters || initialFilters,
|
||||
filter: listQuery?.filter || { expression: '' },
|
||||
orderBy,
|
||||
activeLogId,
|
||||
}) ?? initialQueriesMap.logs,
|
||||
graphType: PANEL_TYPES.LIST,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
globalSelectedInterval: 'custom',
|
||||
},
|
||||
ENTITY_VERSION_V5,
|
||||
undefined,
|
||||
signal,
|
||||
),
|
||||
getNextPageParam: (lastPage, allPages) =>
|
||||
(lastPage.payload.data.newResult.data.result[0]?.list?.length ?? 0) ===
|
||||
PAGE_SIZE
|
||||
? allPages.length + 1
|
||||
: undefined,
|
||||
enabled: !!stagedQuery && isEnabledQuery,
|
||||
});
|
||||
|
||||
const logs = useMemo(
|
||||
() =>
|
||||
(data?.pages ?? []).flatMap((page) =>
|
||||
(page.payload.data.newResult.data.result[0]?.list ?? []).map(
|
||||
(item) => item.data as unknown as AuditLog,
|
||||
),
|
||||
),
|
||||
[data?.pages],
|
||||
);
|
||||
|
||||
const apiError = useMemo(() => {
|
||||
if (!error) {
|
||||
return null;
|
||||
}
|
||||
return error instanceof APIError
|
||||
? error
|
||||
: new APIError({
|
||||
httpStatusCode: 500,
|
||||
error: {
|
||||
code: 'UNKNOWN_ERROR',
|
||||
message: error.message,
|
||||
url: '',
|
||||
errors: [],
|
||||
},
|
||||
});
|
||||
}, [error]);
|
||||
|
||||
const onEndReached = useCallback((): void => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
void fetchNextPage({ cancelRefetch: false });
|
||||
}
|
||||
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
|
||||
return {
|
||||
logs,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
error: apiError,
|
||||
warning: data?.pages[data.pages.length - 1]?.warning,
|
||||
onEndReached,
|
||||
};
|
||||
}
|
||||
125
frontend/src/pages/AuditLogs/index.tsx
Normal file
125
frontend/src/pages/AuditLogs/index.tsx
Normal file
@@ -0,0 +1,125 @@
|
||||
import styles from './AuditLogs.module.scss';
|
||||
import { FilterExpandButton } from './components/FilterExpandButton';
|
||||
import { OptionsMenu } from './components/OptionsMenu';
|
||||
import { OrderBy } from './components/OrderBy';
|
||||
import { QueryBar } from './components/QueryBar';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import QueryCancelledPlaceholder from 'components/QueryCancelledPlaceholder';
|
||||
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import RunQueryBtn from '@/container/QueryBuilder/components/RunQueryBtn/RunQueryBtn';
|
||||
import { QueryKey, useQueryClient } from 'react-query';
|
||||
import { useQueryBuilder } from '@/hooks/queryBuilder/useQueryBuilder';
|
||||
import DateTimeSelectionV2 from '@/container/TopNav/DateTimeSelectionV2';
|
||||
import DownloadOptionsMenu from '@/components/DownloadOptionsMenu/DownloadOptionsMenu';
|
||||
import { DataSource } from '@/types/common/queryBuilder';
|
||||
import { AUDIT_FIELD_KEYS } from './constants';
|
||||
import { QueryResults } from './components/QueryResults';
|
||||
import { useAuditLogsQuery } from './hooks/useAuditLogsQuery';
|
||||
import { useAuditLogsOptionsStore } from './store/useAuditLogsOptionsStore';
|
||||
import QuickFiltersLayout from '@/components/QuickFilters/QuickFiltersLayout/QuickFiltersLayout';
|
||||
import { QuickFiltersSource } from '@/components/QuickFilters/types';
|
||||
import { SavedviewtypesSourceDTO } from '@/api/generated/services/sigNoz.schemas';
|
||||
import { useSignalFieldApis } from '@/components/QuickFilters/hooks/useSignalFieldApis';
|
||||
|
||||
function AuditLogs(): JSX.Element {
|
||||
const [isCancelled, setIsCancelled] = useState(false);
|
||||
|
||||
const showQuickFilters = useAuditLogsOptionsStore(
|
||||
(state) => state.showQuickFilters,
|
||||
);
|
||||
const setShowQuickFilters = useAuditLogsOptionsStore(
|
||||
(state) => state.setShowQuickFilters,
|
||||
);
|
||||
|
||||
const listAuditLogsKeyRef = useRef<QueryKey>();
|
||||
|
||||
const { handleRunQuery } = useQueryBuilder();
|
||||
|
||||
const { logs, isLoading, isFetching, isError, error, onEndReached } =
|
||||
useAuditLogsQuery({ listAuditLogsKeyRef });
|
||||
|
||||
useEffect(() => {
|
||||
if (isFetching) {
|
||||
setIsCancelled(false);
|
||||
}
|
||||
}, [isFetching]);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const handleCancelQuery = useCallback(() => {
|
||||
if (listAuditLogsKeyRef.current) {
|
||||
void queryClient.cancelQueries(listAuditLogsKeyRef.current);
|
||||
}
|
||||
setIsCancelled(true);
|
||||
}, [queryClient]);
|
||||
|
||||
const onStageRunQuery = useCallback(() => {
|
||||
setIsCancelled(false);
|
||||
handleRunQuery();
|
||||
}, [handleRunQuery]);
|
||||
|
||||
const handleToggleQuickFilters = useCallback(
|
||||
() => setShowQuickFilters(!showQuickFilters),
|
||||
[setShowQuickFilters, showQuickFilters],
|
||||
);
|
||||
|
||||
const quickFilterFieldApis = useSignalFieldApis();
|
||||
|
||||
return (
|
||||
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
|
||||
<div className={styles.auditLogsRoot} data-testid="audit-logs">
|
||||
<QuickFiltersLayout
|
||||
showFilters={showQuickFilters}
|
||||
onToggleFilters={handleToggleQuickFilters}
|
||||
savedViewProps={{ source: SavedviewtypesSourceDTO.audit }}
|
||||
quickFilterProps={{
|
||||
quickFilterSource: QuickFiltersSource.AUDIT_LOGS,
|
||||
useFieldApis: quickFilterFieldApis,
|
||||
}}
|
||||
>
|
||||
<div className={styles.auditLogsRightPane}>
|
||||
<div className={styles.queryToolbar}>
|
||||
<div className={styles.queryToolbarLeft}>
|
||||
{!showQuickFilters && (
|
||||
<FilterExpandButton onClick={handleToggleQuickFilters} />
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.queryToolbarRight}>
|
||||
<DateTimeSelectionV2 showAutoRefresh={false} hideShareModal />
|
||||
<RunQueryBtn
|
||||
isLoadingQueries={isFetching}
|
||||
handleCancelQuery={handleCancelQuery}
|
||||
onStageRunQuery={onStageRunQuery}
|
||||
testId="audit-logs-run-query-btn"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<QueryBar />
|
||||
<div className={styles.actionsRow}>
|
||||
<OrderBy />
|
||||
<DownloadOptionsMenu
|
||||
dataSource={DataSource.LOGS}
|
||||
selectedColumns={AUDIT_FIELD_KEYS}
|
||||
/>
|
||||
<OptionsMenu />
|
||||
</div>
|
||||
{isCancelled ? (
|
||||
<QueryCancelledPlaceholder subText='Click "Run Query" to load audit logs.' />
|
||||
) : (
|
||||
<QueryResults
|
||||
logs={logs}
|
||||
isLoading={isLoading}
|
||||
isFetching={isFetching}
|
||||
isError={isError}
|
||||
error={error}
|
||||
onEndReached={onEndReached}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</QuickFiltersLayout>
|
||||
</div>
|
||||
</Sentry.ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
export default AuditLogs;
|
||||
@@ -0,0 +1,39 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { FontSize, LogViewMode } from 'container/OptionsMenu/types';
|
||||
|
||||
interface AuditLogsOptionsState {
|
||||
fontSize: FontSize;
|
||||
setFontSize: (fontSize: FontSize) => void;
|
||||
format: LogViewMode;
|
||||
setFormat: (format: LogViewMode) => void;
|
||||
showQuickFilters: boolean;
|
||||
setShowQuickFilters: (newState: boolean) => void;
|
||||
maxLines: number;
|
||||
setMaxLines: (maxLines: number) => void;
|
||||
}
|
||||
|
||||
export const useAuditLogsOptionsStore = create<AuditLogsOptionsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
fontSize: FontSize.SMALL,
|
||||
setFontSize: (fontSize): void => {
|
||||
set({ fontSize });
|
||||
},
|
||||
format: 'table',
|
||||
setFormat: (format): void => {
|
||||
set({ format });
|
||||
},
|
||||
showQuickFilters: true,
|
||||
setShowQuickFilters: (showQuickFilters: boolean): void => {
|
||||
set({ showQuickFilters });
|
||||
},
|
||||
maxLines: 1,
|
||||
setMaxLines: (maxLines): void => {
|
||||
set({ maxLines });
|
||||
},
|
||||
}),
|
||||
{ name: LOCALSTORAGE.AUDIT_LOGS_OPTIONS },
|
||||
),
|
||||
);
|
||||
211
frontend/src/pages/AuditLogs/stories/AuditLogs.stories.mocks.tsx
generated
Normal file
211
frontend/src/pages/AuditLogs/stories/AuditLogs.stories.mocks.tsx
generated
Normal file
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { FontSize, type LogViewMode } from 'container/OptionsMenu/types';
|
||||
import { rest } from 'msw';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type {
|
||||
BuilderQuery,
|
||||
QueryRangeRequestV5,
|
||||
} from 'types/api/v5/queryRange';
|
||||
|
||||
import {
|
||||
choiceControl,
|
||||
countControl,
|
||||
toggleControl,
|
||||
} from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import {
|
||||
RESPONSE_STATES,
|
||||
type ResponseState,
|
||||
respondWith,
|
||||
} from '@/storybook/runtime/responseState';
|
||||
|
||||
import { useAuditLogsOptionsStore } from '../store/useAuditLogsOptionsStore';
|
||||
import {
|
||||
AUDIT_PAGE_SIZE,
|
||||
auditFieldKeysResponse,
|
||||
auditFieldValuesResponse,
|
||||
auditLogId,
|
||||
auditLogsResponse,
|
||||
auditQuickFiltersResponse,
|
||||
auditSavedViewsResponse,
|
||||
OUTCOME_MIXES,
|
||||
type OutcomeMix,
|
||||
QUICK_FILTER_MAX,
|
||||
RELATIVE_TIME,
|
||||
SAVED_VIEW_MAX,
|
||||
timeRangeState,
|
||||
} from './__story_mockdata__/auditLogs';
|
||||
|
||||
const EVENTS = 'Audit Logs · events';
|
||||
const LIST = 'Audit Logs · list';
|
||||
const FILTERS = 'Audit Logs · filters';
|
||||
|
||||
/** More than one page, so scrolling to the end asks for the next. */
|
||||
const EVENT_MAX = 250;
|
||||
|
||||
/** Lines a raw or default row wraps to before it is clipped. */
|
||||
const MAX_LINES_CAP = 10;
|
||||
|
||||
const LIST_FORMATS: readonly LogViewMode[] = ['table', 'list', 'raw'];
|
||||
|
||||
const FONT_SIZES = [FontSize.SMALL, FontSize.MEDIUM, FontSize.LARGE] as const;
|
||||
|
||||
/** The log a link points at, which is on the first page. */
|
||||
const LINKED_LOG_INDEX = 2;
|
||||
|
||||
const auditQuery: Query = {
|
||||
...initialQueriesMap.logs,
|
||||
builder: {
|
||||
...initialQueriesMap.logs.builder,
|
||||
queryData: initialQueriesMap.logs.builder.queryData.map((queryData) => ({
|
||||
...queryData,
|
||||
source: 'audit',
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* A copied link carries the query with it. Without one the page writes its own
|
||||
* to the URL, and that write drops `activeLogId`.
|
||||
*/
|
||||
const auditRoute = (linkedLog: boolean): string => {
|
||||
const linked = linkedLog
|
||||
? `&${QueryParams.activeLogId}=${encodeURIComponent(
|
||||
JSON.stringify(auditLogId(LINKED_LOG_INDEX)),
|
||||
)}&${QueryParams.compositeQuery}=${encodeURIComponent(JSON.stringify(auditQuery))}`
|
||||
: '';
|
||||
|
||||
return `${ROUTES.AUDIT_LOGS}?${QueryParams.relativeTime}=${RELATIVE_TIME}${linked}`;
|
||||
};
|
||||
|
||||
export const auditLogsMocks = defineStoryMocks({
|
||||
controls: {
|
||||
events: countControl('Audit events', {
|
||||
group: EVENTS,
|
||||
description:
|
||||
'Events in the time range. More than a page of them makes the list ask for the next one when it scrolls to the end.',
|
||||
value: 30,
|
||||
max: EVENT_MAX,
|
||||
}),
|
||||
outcomes: choiceControl<OutcomeMix>('Outcomes', {
|
||||
group: EVENTS,
|
||||
description:
|
||||
'Every third event fails in the mixed set, which tints its row red; all successes or all failures otherwise.',
|
||||
options: OUTCOME_MIXES,
|
||||
value: 'mixed',
|
||||
}),
|
||||
linkedLog: toggleControl('Linked log', {
|
||||
group: EVENTS,
|
||||
description:
|
||||
'The page opened from a "copy link to log" link: the list loads up to that log and highlights it.',
|
||||
value: false,
|
||||
}),
|
||||
format: choiceControl<LogViewMode>('Line format', {
|
||||
group: LIST,
|
||||
description: 'Columns, one entry per log, or the raw line.',
|
||||
options: LIST_FORMATS,
|
||||
value: 'table',
|
||||
}),
|
||||
maxLines: countControl('Max lines', {
|
||||
group: LIST,
|
||||
description: 'Lines a body wraps to before it is clipped.',
|
||||
value: 1,
|
||||
max: MAX_LINES_CAP,
|
||||
}),
|
||||
fontSize: choiceControl<FontSize>('Font size', {
|
||||
group: LIST,
|
||||
options: FONT_SIZES,
|
||||
value: FontSize.SMALL,
|
||||
}),
|
||||
filtersPanel: toggleControl('Filters panel', {
|
||||
group: FILTERS,
|
||||
description: 'The quick filters panel down the left of the page.',
|
||||
value: true,
|
||||
}),
|
||||
quickFilters: countControl('Quick filters', {
|
||||
group: FILTERS,
|
||||
description: 'Filters the org configured for audit logs.',
|
||||
value: QUICK_FILTER_MAX,
|
||||
max: QUICK_FILTER_MAX,
|
||||
}),
|
||||
filterValues: choiceControl<ResponseState>('Filter values', {
|
||||
group: FILTERS,
|
||||
description:
|
||||
'How `/fields/values` answers once a key and an operator are typed in the filter, apart from the page-wide Data control.',
|
||||
options: RESPONSE_STATES,
|
||||
value: 'loaded',
|
||||
}),
|
||||
savedViews: countControl('Saved views', {
|
||||
group: FILTERS,
|
||||
description: 'The views the saved views panel above the filters lists.',
|
||||
value: 2,
|
||||
max: SAVED_VIEW_MAX,
|
||||
}),
|
||||
},
|
||||
handlers: (values, response) => [
|
||||
rest.post(
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) => {
|
||||
const body = (await req.json()) as QueryRangeRequestV5;
|
||||
const spec = body.compositeQuery?.queries?.[0]?.spec as
|
||||
| BuilderQuery
|
||||
| undefined;
|
||||
|
||||
return auditLogsResponse(values.events, values.outcomes, {
|
||||
endMilli: body.end,
|
||||
offset: spec?.offset ?? 0,
|
||||
limit: spec?.limit ?? AUDIT_PAGE_SIZE,
|
||||
});
|
||||
}),
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v2/quick_filters/:source',
|
||||
response.json(() => auditQuickFiltersResponse(values.quickFilters)),
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v1/fields/keys',
|
||||
response.json((req) =>
|
||||
auditFieldKeysResponse(req.url.searchParams.get('searchText') ?? ''),
|
||||
),
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v1/fields/values',
|
||||
respondWith(values.filterValues, (req) =>
|
||||
auditFieldValuesResponse(
|
||||
req.url.searchParams.get('name') ?? '',
|
||||
req.url.searchParams.get('searchText') ?? '',
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
rest.get(
|
||||
'http://localhost/api/v2/saved_views',
|
||||
response.json(() => auditSavedViewsResponse(values.savedViews)),
|
||||
),
|
||||
],
|
||||
config: ({ linkedLog }) => ({
|
||||
route: auditRoute(linkedLog),
|
||||
reduxState: timeRangeState(),
|
||||
}),
|
||||
effect: ({ format, maxLines, fontSize, filtersPanel }) => {
|
||||
useAuditLogsOptionsStore.setState({
|
||||
format: format === 'raw' || format === 'list' ? format : 'table',
|
||||
maxLines,
|
||||
fontSize,
|
||||
showQuickFilters: filtersPanel,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export type AuditLogsArgs = PageStoryArgs<typeof auditLogsMocks>;
|
||||
76
frontend/src/pages/AuditLogs/stories/AuditLogs.stories.tsx
Normal file
76
frontend/src/pages/AuditLogs/stories/AuditLogs.stories.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
|
||||
import AuditLogs from '..';
|
||||
import { type AuditLogsArgs, auditLogsMocks } from './AuditLogs.stories.mocks';
|
||||
import { openAuditLogDetails } from './__story_mockdata__/auditLogs.play';
|
||||
|
||||
const pageStory = storyMocks(auditLogsMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
* The audit log explorer: query bar, quick filters, the event list and a details drawer.
|
||||
*
|
||||
* Route: `/audit-logs`.
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Pages/Audit Logs',
|
||||
tags: ['play'],
|
||||
component: AuditLogs,
|
||||
...pageStory,
|
||||
parameters: { ...pageStory.parameters },
|
||||
} satisfies Meta<AuditLogsArgs>;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<AuditLogsArgs>;
|
||||
|
||||
/** Events in the Column format. */
|
||||
export const Default: Story = {};
|
||||
|
||||
/** No events in the range. */
|
||||
export const NoEvents: Story = {
|
||||
args: { events: 0 },
|
||||
};
|
||||
|
||||
/** The first page still loading. */
|
||||
export const Loading: Story = {
|
||||
args: { dataState: 'loading' },
|
||||
};
|
||||
|
||||
/** Every request failed. */
|
||||
export const Error: Story = {
|
||||
args: { dataState: 'error' },
|
||||
// The mocked requests deliberately fail; the console errors are the state under test.
|
||||
parameters: { allowConsoleErrors: true },
|
||||
};
|
||||
|
||||
/** Failed events only. */
|
||||
export const FailedChanges: Story = {
|
||||
args: { outcomes: 'failure' },
|
||||
};
|
||||
|
||||
/** Events in the Default format. */
|
||||
export const DefaultFormat: Story = {
|
||||
args: { format: 'list' },
|
||||
};
|
||||
|
||||
/** Events in the Raw format. */
|
||||
export const RawFormat: Story = {
|
||||
args: { format: 'raw', maxLines: 3 },
|
||||
};
|
||||
|
||||
/** Quick filters panel collapsed. */
|
||||
export const FiltersCollapsed: Story = {
|
||||
args: { filtersPanel: false },
|
||||
};
|
||||
|
||||
/** Opened from a copied link. */
|
||||
export const LinkedLog: Story = {
|
||||
args: { linkedLog: true },
|
||||
};
|
||||
|
||||
/** A row open in the drawer. */
|
||||
export const DetailsDrawer: Story = {
|
||||
play: openAuditLogDetails,
|
||||
};
|
||||
64
frontend/src/pages/AuditLogs/stories/__story_mockdata__/auditLogs.play.ts
generated
Normal file
64
frontend/src/pages/AuditLogs/stories/__story_mockdata__/auditLogs.play.ts
generated
Normal file
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { expect, screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
import type { AuditLogsArgs } from '../AuditLogs.stories.mocks';
|
||||
import { auditEvent, auditLogId } from './auditLogs';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: AuditLogsArgs;
|
||||
}
|
||||
|
||||
/** The page fetches before it renders a row, which outlasts the 1s default. */
|
||||
const untilLoaded = { timeout: 15_000 };
|
||||
|
||||
const ROW_TEST_ID = {
|
||||
table: 'audit-logs-table-row',
|
||||
list: 'logs-list-row',
|
||||
raw: 'logs-raw-row',
|
||||
} as const;
|
||||
|
||||
/** No event, a failed fetch or a loading page renders no row to open. */
|
||||
const hasRows = (args: AuditLogsArgs): boolean =>
|
||||
args.dataState === 'loaded' && args.events >= 1;
|
||||
|
||||
const clickRow = async (args: AuditLogsArgs, index: number): Promise<void> => {
|
||||
const format =
|
||||
args.format === 'list' || args.format === 'raw' ? args.format : 'table';
|
||||
const row = await screen.findByTestId(
|
||||
`${ROW_TEST_ID[format]}-${auditLogId(index)}`,
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
|
||||
if (format === 'table') {
|
||||
// The table handles a click on its cells, not on the row.
|
||||
const { message } = auditEvent(index, args.outcomes, Date.now()).data.body;
|
||||
const cell = await within(row).findByText(
|
||||
new RegExp(message.slice(0, 20).replace(/[()]/g, '\\$&')),
|
||||
);
|
||||
await userEvent.click(cell);
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(row);
|
||||
};
|
||||
|
||||
/** Opens the details drawer on the first event. */
|
||||
export const openAuditLogDetails = async ({
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!hasRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await clickRow(args, 0);
|
||||
|
||||
await expect(
|
||||
await screen.findByTestId('audit-log-detail-drawer', undefined, untilLoaded),
|
||||
).toBeVisible();
|
||||
};
|
||||
359
frontend/src/pages/AuditLogs/stories/__story_mockdata__/auditLogs.ts
generated
Normal file
359
frontend/src/pages/AuditLogs/stories/__story_mockdata__/auditLogs.ts
generated
Normal file
@@ -0,0 +1,359 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import {
|
||||
type GetFieldsKeys200,
|
||||
type GetFieldsValues200,
|
||||
type GetQuickFilters200,
|
||||
type ListSavedViews200,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal as LogsSignal,
|
||||
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
QuickfiltertypesSourceDTO,
|
||||
SavedviewtypesPanelTypeDTO,
|
||||
SavedviewtypesSchemaVersionDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
TelemetrytypesFieldContextDTO,
|
||||
TelemetrytypesFieldDataTypeDTO,
|
||||
type TelemetrytypesTelemetryFieldKeyDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';
|
||||
import type { AppState } from 'store/reducers';
|
||||
import type { MetricRangePayloadV5 } from 'types/api/v5/queryRange';
|
||||
|
||||
import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';
|
||||
import { queryRangeV5RawResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
|
||||
|
||||
import { AuditOutcome, AuditPrincipalType } from '../../types';
|
||||
|
||||
export const RELATIVE_TIME: Time = '30m';
|
||||
|
||||
const THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;
|
||||
|
||||
const NANOSECONDS_IN_MS = 1_000_000;
|
||||
|
||||
const ONE_MINUTE_IN_MS = 60 * 1000;
|
||||
|
||||
/**
|
||||
* `globalTime` defaults its window from `window.location.pathname`, which in a
|
||||
* story is the preview's rather than the page's, so the time picker (reading the
|
||||
* route) and the queries (reading the store) would ask for different ranges.
|
||||
*/
|
||||
export const timeRangeState = (): Partial<AppState> => {
|
||||
const now = Date.now();
|
||||
|
||||
return {
|
||||
globalTime: {
|
||||
minTime: (now - THIRTY_MINUTES_IN_MS) * NANOSECONDS_IN_MS,
|
||||
maxTime: now * NANOSECONDS_IN_MS,
|
||||
loading: false,
|
||||
selectedTime: RELATIVE_TIME,
|
||||
isAutoRefreshDisabled: false,
|
||||
selectedAutoRefreshInterval: '',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const OUTCOME_MIXES = ['mixed', 'success', 'failure'] as const;
|
||||
|
||||
export type OutcomeMix = (typeof OUTCOME_MIXES)[number];
|
||||
|
||||
interface Principal {
|
||||
id: string;
|
||||
email: string;
|
||||
type: AuditPrincipalType;
|
||||
}
|
||||
|
||||
const PRINCIPALS: Principal[] = [
|
||||
{ id: 'user-001', email: 'alice@acme.com', type: AuditPrincipalType.USER },
|
||||
{ id: 'user-002', email: 'bob@acme.com', type: AuditPrincipalType.USER },
|
||||
{
|
||||
id: 'sa-001',
|
||||
email: 'ci-deployer@acme.com',
|
||||
type: AuditPrincipalType.SERVICE_ACCOUNT,
|
||||
},
|
||||
{ id: 'user-003', email: 'carol@acme.com', type: AuditPrincipalType.USER },
|
||||
];
|
||||
|
||||
const VERBS = ['create', 'update', 'delete', 'attach', 'detach'] as const;
|
||||
|
||||
const RESOURCES = [
|
||||
'dashboard',
|
||||
'alert-rule',
|
||||
'quick-filter',
|
||||
'saved-view',
|
||||
'user',
|
||||
'role',
|
||||
] as const;
|
||||
|
||||
const PAST_TENSE: Record<(typeof VERBS)[number], string> = {
|
||||
create: 'created',
|
||||
update: 'updated',
|
||||
delete: 'deleted',
|
||||
attach: 'attached',
|
||||
detach: 'detached',
|
||||
};
|
||||
|
||||
const hex = (index: number, length: number): string =>
|
||||
index.toString(16).padStart(length, '0');
|
||||
|
||||
export const auditLogId = (index: number): string =>
|
||||
`01JBQ${hex(9999 - index, 8).toUpperCase()}`;
|
||||
|
||||
const FAILURE_EVERY = 4;
|
||||
|
||||
const outcomeAt = (index: number, mix: OutcomeMix): AuditOutcome => {
|
||||
if (mix === 'success') {
|
||||
return AuditOutcome.SUCCESS;
|
||||
}
|
||||
if (mix === 'failure') {
|
||||
return AuditOutcome.FAILURE;
|
||||
}
|
||||
|
||||
return index % FAILURE_EVERY === FAILURE_EVERY - 1
|
||||
? AuditOutcome.FAILURE
|
||||
: AuditOutcome.SUCCESS;
|
||||
};
|
||||
|
||||
export interface AuditEventRow {
|
||||
timestamp: string;
|
||||
data: {
|
||||
id: string;
|
||||
timestamp: number;
|
||||
body: { message: string };
|
||||
event_name: string;
|
||||
severity_number: number;
|
||||
severity_text: string;
|
||||
trace_id: string;
|
||||
span_id: string;
|
||||
trace_flags: number;
|
||||
attributes: Record<string, string>;
|
||||
resource: { attributes: Record<string, string> };
|
||||
scope: { name: string; version: string; attributes: Record<string, string> };
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Newest first and one minute apart, the order the list requests
|
||||
* (`timestamp:desc`) and the order pagination assumes.
|
||||
*/
|
||||
export const auditEvent = (
|
||||
index: number,
|
||||
mix: OutcomeMix,
|
||||
endMilli: number,
|
||||
): AuditEventRow => {
|
||||
const principal = PRINCIPALS[index % PRINCIPALS.length];
|
||||
const verb = VERBS[index % VERBS.length];
|
||||
const resourceKind = RESOURCES[index % RESOURCES.length];
|
||||
const resourceId = `${resourceKind}-${hex(index + 1, 3)}-${hex(index * 7919, 6)}`;
|
||||
const outcome = outcomeAt(index, mix);
|
||||
const failed = outcome === AuditOutcome.FAILURE;
|
||||
const timestampMilli = endMilli - index * ONE_MINUTE_IN_MS;
|
||||
const actor = `${principal.email} (${principal.id})`;
|
||||
|
||||
return {
|
||||
timestamp: new Date(timestampMilli).toISOString(),
|
||||
data: {
|
||||
id: auditLogId(index),
|
||||
timestamp: timestampMilli * NANOSECONDS_IN_MS,
|
||||
body: {
|
||||
message: failed
|
||||
? `${actor} failed to ${verb} ${resourceKind} (${resourceId}): forbidden`
|
||||
: `${actor} ${PAST_TENSE[verb]} ${resourceKind} (${resourceId})`,
|
||||
},
|
||||
event_name: `signoz.audit.${verb}`,
|
||||
severity_number: failed ? 17 : 9,
|
||||
severity_text: failed ? 'ERROR' : 'INFO',
|
||||
trace_id: '',
|
||||
span_id: '',
|
||||
trace_flags: 0,
|
||||
attributes: {
|
||||
'signoz.audit.action_category': 'configuration_change',
|
||||
'signoz.audit.outcome': outcome,
|
||||
'signoz.audit.verb': verb,
|
||||
'signoz.organization.id': 'org-signoz',
|
||||
'signoz.principal.id': principal.id,
|
||||
'signoz.principal.type': principal.type,
|
||||
'signoz.principal.email': principal.email,
|
||||
'http.request.method': failed ? 'DELETE' : 'POST',
|
||||
'http.route': `/api/v1/${resourceKind}s`,
|
||||
'http.response.status_code': failed ? '403' : '200',
|
||||
},
|
||||
resource: {
|
||||
attributes: {
|
||||
'service.name': 'signoz',
|
||||
'signoz.resource.kind': resourceKind,
|
||||
'signoz.resource.id': resourceId,
|
||||
},
|
||||
},
|
||||
scope: { name: 'signoz.audit', version: '1', attributes: {} },
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** The page asks for 100 rows at a time and pages with `offset`. */
|
||||
export const AUDIT_PAGE_SIZE = 100;
|
||||
|
||||
export const auditLogsResponse = (
|
||||
total: number,
|
||||
mix: OutcomeMix,
|
||||
{
|
||||
endMilli,
|
||||
offset,
|
||||
limit,
|
||||
}: { endMilli: number; offset: number; limit: number },
|
||||
): MetricRangePayloadV5 => {
|
||||
const count = Math.max(0, Math.min(limit, total - offset));
|
||||
const rows = Array.from({ length: count }, (_unused, position) =>
|
||||
auditEvent(offset + position, mix, endMilli),
|
||||
);
|
||||
|
||||
return queryRangeV5RawResponse(rows);
|
||||
};
|
||||
|
||||
const { attribute, resource } = TelemetrytypesFieldContextDTO;
|
||||
const { string: stringType } = TelemetrytypesFieldDataTypeDTO;
|
||||
|
||||
const AUDIT_FIELDS: TelemetrytypesTelemetryFieldKeyDTO[] = [
|
||||
{
|
||||
name: 'signoz.audit.outcome',
|
||||
fieldContext: attribute,
|
||||
fieldDataType: stringType,
|
||||
},
|
||||
{
|
||||
name: 'signoz.audit.action_category',
|
||||
fieldContext: attribute,
|
||||
fieldDataType: stringType,
|
||||
},
|
||||
{
|
||||
name: 'signoz.audit.verb',
|
||||
fieldContext: attribute,
|
||||
fieldDataType: stringType,
|
||||
},
|
||||
{
|
||||
name: 'signoz.principal.email',
|
||||
fieldContext: attribute,
|
||||
fieldDataType: stringType,
|
||||
},
|
||||
{
|
||||
name: 'signoz.principal.type',
|
||||
fieldContext: attribute,
|
||||
fieldDataType: stringType,
|
||||
},
|
||||
{
|
||||
name: 'signoz.resource.kind',
|
||||
fieldContext: resource,
|
||||
fieldDataType: stringType,
|
||||
},
|
||||
{
|
||||
name: 'signoz.resource.id',
|
||||
fieldContext: resource,
|
||||
fieldDataType: stringType,
|
||||
},
|
||||
];
|
||||
|
||||
export const auditFieldKeysResponse = (
|
||||
searchText: string,
|
||||
): GetFieldsKeys200 => {
|
||||
const matches = AUDIT_FIELDS.filter((field) =>
|
||||
field.name.includes(searchText.toLowerCase()),
|
||||
);
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
keys: Object.fromEntries(matches.map((field) => [field.name, [field]])),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const STRING_VALUES: Record<string, string[]> = {
|
||||
'signoz.audit.outcome': [AuditOutcome.SUCCESS, AuditOutcome.FAILURE],
|
||||
'signoz.audit.action_category': ['configuration_change', 'access_control'],
|
||||
'signoz.audit.verb': [...VERBS],
|
||||
'signoz.principal.email': PRINCIPALS.map(({ email }) => email),
|
||||
'signoz.principal.type': [
|
||||
AuditPrincipalType.USER,
|
||||
AuditPrincipalType.SERVICE_ACCOUNT,
|
||||
],
|
||||
'signoz.resource.kind': [...RESOURCES],
|
||||
};
|
||||
|
||||
export const auditFieldValuesResponse = (
|
||||
name: string,
|
||||
searchText: string,
|
||||
): GetFieldsValues200 => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
values: {
|
||||
stringValues: (STRING_VALUES[name] ?? []).filter((value) =>
|
||||
value.toLowerCase().includes(searchText.toLowerCase()),
|
||||
),
|
||||
numberValues: [],
|
||||
relatedValues: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const QUICK_FILTER_NAMES = [
|
||||
'signoz.audit.outcome',
|
||||
'signoz.audit.action_category',
|
||||
'signoz.resource.kind',
|
||||
'signoz.principal.email',
|
||||
'signoz.principal.type',
|
||||
] as const;
|
||||
|
||||
export const QUICK_FILTER_MAX = QUICK_FILTER_NAMES.length;
|
||||
|
||||
export const auditQuickFiltersResponse = (count: number): GetQuickFilters200 =>
|
||||
quickFiltersResponse(
|
||||
QuickfiltertypesSourceDTO.audit,
|
||||
QUICK_FILTER_NAMES.slice(0, count).map(
|
||||
(name) =>
|
||||
AUDIT_FIELDS.find(
|
||||
(field) => field.name === name,
|
||||
) as TelemetrytypesTelemetryFieldKeyDTO,
|
||||
),
|
||||
);
|
||||
|
||||
const VIEWS = [
|
||||
{ name: 'Failed changes', createdBy: 'alice@acme.com' },
|
||||
{ name: 'Service account activity', createdBy: 'alice@acme.com' },
|
||||
{ name: 'Dashboard changes', createdBy: 'bob@acme.com' },
|
||||
{ name: 'Role and user changes', createdBy: 'carol@acme.com' },
|
||||
];
|
||||
|
||||
export const SAVED_VIEW_MAX = VIEWS.length;
|
||||
|
||||
export const auditSavedViewsResponse = (count: number): ListSavedViews200 => ({
|
||||
status: 'success',
|
||||
data: VIEWS.slice(0, count).map(({ name, createdBy }, index) => {
|
||||
const timestamp = `2026-08-${String(4 + index).padStart(2, '0')}T09:24:11Z`;
|
||||
|
||||
return {
|
||||
id: `storybook-audit-view-${index + 1}`,
|
||||
name: `storybook-audit-view-${index + 1}`,
|
||||
source: SavedviewtypesSourceDTO.audit,
|
||||
schemaVersion: SavedviewtypesSchemaVersionDTO.v2,
|
||||
createdAt: timestamp,
|
||||
createdBy,
|
||||
updatedAt: timestamp,
|
||||
updatedBy: createdBy,
|
||||
spec: {
|
||||
displayName: name,
|
||||
panelType: SavedviewtypesPanelTypeDTO.list,
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.raw,
|
||||
queries: [
|
||||
{
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
|
||||
spec: { name: 'A', signal: LogsSignal.logs },
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
74
frontend/src/pages/AuditLogs/types.ts
Normal file
74
frontend/src/pages/AuditLogs/types.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
export enum AuditOutcome {
|
||||
SUCCESS = 'success',
|
||||
FAILURE = 'failure',
|
||||
}
|
||||
|
||||
export enum AuditPrincipalType {
|
||||
USER = 'user',
|
||||
SERVICE_ACCOUNT = 'service_account',
|
||||
SYSTEM = 'system',
|
||||
ANONYMOUS = 'anonymous',
|
||||
}
|
||||
|
||||
export interface AuditLogAttributes {
|
||||
'signoz.audit.action_category': string;
|
||||
'signoz.audit.outcome': AuditOutcome;
|
||||
'signoz.audit.verb': string;
|
||||
'signoz.organization.id': string;
|
||||
'signoz.principal.id'?: string;
|
||||
'signoz.principal.type'?: AuditPrincipalType;
|
||||
'signoz.principal.email'?: string;
|
||||
'signoz.principal.identn.provider'?: string;
|
||||
'client.address'?: string;
|
||||
'http.request.method'?: string;
|
||||
'http.response.status_code'?: number;
|
||||
'http.route'?: string;
|
||||
'network.protocol.name'?: string;
|
||||
'network.protocol.version'?: string;
|
||||
'url.path'?: string;
|
||||
'url.scheme'?: string;
|
||||
'user_agent.original'?: string;
|
||||
}
|
||||
|
||||
export interface AuditLogResourceAttributes {
|
||||
'service.name': string;
|
||||
'service.version'?: string;
|
||||
'signoz.resource.id'?: string;
|
||||
'signoz.resource.kind'?: string;
|
||||
'signoz.resource.object'?: string;
|
||||
}
|
||||
|
||||
export interface AuditLogData {
|
||||
id: string;
|
||||
timestamp: number;
|
||||
body: { message: string };
|
||||
event_name: string;
|
||||
severity_number: number;
|
||||
severity_text: string;
|
||||
trace_id: string;
|
||||
span_id: string;
|
||||
trace_flags: number;
|
||||
attributes: AuditLogAttributes;
|
||||
resource: { attributes: AuditLogResourceAttributes };
|
||||
scope: {
|
||||
name: string;
|
||||
version: string;
|
||||
attributes: Record<string, string>;
|
||||
};
|
||||
}
|
||||
|
||||
export type AuditLog = Omit<AuditLogData, 'body'> & {
|
||||
body: string;
|
||||
date: string;
|
||||
};
|
||||
|
||||
export enum AuditLogsColumnIds {
|
||||
OUTCOME_INDICATOR = 'outcome-indicator',
|
||||
TIME = 'time',
|
||||
PRINCIPAL_EMAIL = 'principal-email',
|
||||
EVENT_NAME = 'event-name',
|
||||
RESOURCE_NAME = 'resource-name',
|
||||
RESOURCE_ID = 'resource-id',
|
||||
OUTCOME = 'outcome',
|
||||
BODY = 'body',
|
||||
}
|
||||
72
frontend/src/pages/AuditLogs/utils.ts
Normal file
72
frontend/src/pages/AuditLogs/utils.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { getBodyDisplay } from 'lib/logs/logBody';
|
||||
import { getRowBackgroundColor } from 'components/Logs/LogStateIndicator/getRowBackgroundColor';
|
||||
import { getLogIndicatorType } from 'components/Logs/LogStateIndicator/utils';
|
||||
|
||||
import { AuditLog, AuditOutcome, AuditPrincipalType } from './types';
|
||||
|
||||
export const EMPTY_VALUE = '—';
|
||||
|
||||
export function getOutcome(log: AuditLog): AuditOutcome {
|
||||
return log.attributes['signoz.audit.outcome'];
|
||||
}
|
||||
|
||||
export function getRowHoverColor(isDarkMode: boolean, log: AuditLog): string {
|
||||
return getRowBackgroundColor(isDarkMode, getLogIndicatorType(log));
|
||||
}
|
||||
|
||||
export function getPrincipalEmail(log: AuditLog): string {
|
||||
return log.attributes['signoz.principal.email'] || EMPTY_VALUE;
|
||||
}
|
||||
|
||||
export function isServiceAccount(log: AuditLog): boolean {
|
||||
return (
|
||||
log.attributes['signoz.principal.type'] === AuditPrincipalType.SERVICE_ACCOUNT
|
||||
);
|
||||
}
|
||||
|
||||
export function getEventName(log: AuditLog): string {
|
||||
return log.event_name || EMPTY_VALUE;
|
||||
}
|
||||
|
||||
export function getResourceName(log: AuditLog): string {
|
||||
return log.resource.attributes['signoz.resource.kind'] || EMPTY_VALUE;
|
||||
}
|
||||
|
||||
export function getResourceId(log: AuditLog): string {
|
||||
return log.resource.attributes['signoz.resource.id'] || EMPTY_VALUE;
|
||||
}
|
||||
|
||||
export function truncateId(id: string, head = 4, tail = 4): string {
|
||||
if (id === EMPTY_VALUE || id.length <= head + tail + 1) {
|
||||
return id;
|
||||
}
|
||||
return `${id.slice(0, head)}…${id.slice(-tail)}`;
|
||||
}
|
||||
|
||||
export function getBody(log: AuditLog): string {
|
||||
return getBodyDisplay(log.body) || EMPTY_VALUE;
|
||||
}
|
||||
|
||||
export function getVerb(log: AuditLog): string {
|
||||
return log.attributes['signoz.audit.verb'] || EMPTY_VALUE;
|
||||
}
|
||||
|
||||
export function getAuditFieldValue(
|
||||
log: AuditLog,
|
||||
fieldName: string,
|
||||
): string | undefined {
|
||||
switch (fieldName) {
|
||||
case 'signoz.principal.email':
|
||||
return log.attributes['signoz.principal.email'];
|
||||
case 'event_name':
|
||||
return log.event_name;
|
||||
case 'signoz.resource.kind':
|
||||
return log.resource.attributes['signoz.resource.kind'];
|
||||
case 'signoz.resource.id':
|
||||
return log.resource.attributes['signoz.resource.id'];
|
||||
case 'signoz.audit.outcome':
|
||||
return log.attributes['signoz.audit.outcome'];
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
.auditLogsModule {
|
||||
:global(.ant-tabs-nav) {
|
||||
padding: 0 16px;
|
||||
margin-bottom: 0;
|
||||
|
||||
&::before {
|
||||
border-bottom: 1px solid var(--l1-border) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tabItem {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 16px;
|
||||
}
|
||||
21
frontend/src/pages/AuditLogsModule/AuditLogsModule.tsx
Normal file
21
frontend/src/pages/AuditLogsModule/AuditLogsModule.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import { useLocation } from 'react-use';
|
||||
import RouteTab from 'components/RouteTab';
|
||||
import { TabRoutes } from 'components/RouteTab/types';
|
||||
|
||||
import { auditLogsExplorer } from './constants';
|
||||
|
||||
import styles from './AuditLogsModule.module.scss';
|
||||
|
||||
const routes: TabRoutes[] = [auditLogsExplorer];
|
||||
|
||||
export default function AuditLogsModule(): JSX.Element {
|
||||
const { pathname } = useLocation();
|
||||
|
||||
return (
|
||||
<RouteTab
|
||||
className={styles.auditLogsModule}
|
||||
routes={routes}
|
||||
activeKey={pathname}
|
||||
/>
|
||||
);
|
||||
}
|
||||
14
frontend/src/pages/AuditLogsModule/constants.tsx
Normal file
14
frontend/src/pages/AuditLogsModule/constants.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import Loadable from 'components/Loadable';
|
||||
import { TabRoutes } from 'components/RouteTab/types';
|
||||
import ROUTES from 'constants/routes';
|
||||
|
||||
import styles from './AuditLogsModule.module.scss';
|
||||
|
||||
const AuditLogsExplorer = Loadable(() => import('pages/AuditLogs'));
|
||||
|
||||
export const auditLogsExplorer: TabRoutes = {
|
||||
Component: AuditLogsExplorer,
|
||||
name: <div className={styles.tabItem} />,
|
||||
route: ROUTES.AUDIT_LOGS,
|
||||
key: ROUTES.AUDIT_LOGS,
|
||||
};
|
||||
@@ -40,6 +40,21 @@ export const CollapsedSideNav: Story = {
|
||||
args: { sidenav: 'collapsed' },
|
||||
};
|
||||
|
||||
/** An enterprise self-hosted admin: the side nav shows the Audit Logs entry. */
|
||||
export const EnterpriseSelfHosted: Story = {
|
||||
args: { license: 'enterprise' },
|
||||
};
|
||||
|
||||
/** An open-source install: the side nav has no Audit Logs entry. */
|
||||
export const Community: Story = {
|
||||
args: { license: 'community' },
|
||||
};
|
||||
|
||||
/** A cloud editor: the side nav has no Audit Logs entry, which is admin only. */
|
||||
export const Editor: Story = {
|
||||
args: { access: 'editor' },
|
||||
};
|
||||
|
||||
/** The trial banner above the shell. */
|
||||
export const TrialBanner: Story = {
|
||||
args: { banner: 'trial-expiry' },
|
||||
|
||||
@@ -4,7 +4,7 @@ const seederUrl = process.env.SIGNOZ_E2E_SEEDER_URL ?? '';
|
||||
|
||||
teardown('clear seeded telemetry', async ({ request }) => {
|
||||
expect(seederUrl, 'SIGNOZ_E2E_SEEDER_URL not set').not.toBe('');
|
||||
for (const signal of ['metrics', 'traces', 'logs'] as const) {
|
||||
for (const signal of ['metrics', 'traces', 'logs', 'audit'] as const) {
|
||||
const response = await request.delete(`${seederUrl}/telemetry/${signal}`, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
|
||||
156
tests/e2e/drivers/audit-logs/explorer.ts
generated
Normal file
156
tests/e2e/drivers/audit-logs/explorer.ts
generated
Normal file
@@ -0,0 +1,156 @@
|
||||
import { expect, type Locator, type Page } from '@playwright/test';
|
||||
|
||||
import { allowFor, SEEDED_DATA_TIMEOUT, SEEDED_TEST_BUDGET } from '../kit';
|
||||
import { dismissQuickFiltersAnnouncement } from '../logs/explorer';
|
||||
import { querySearchDriver, type QuerySearch } from '../querysearch';
|
||||
import { wheelTo } from '../scroll';
|
||||
|
||||
import { eventBody } from './seed';
|
||||
|
||||
export const AUDIT_LOGS_PATH = '/audit-logs';
|
||||
|
||||
const RELATIVE_TIME = '15m';
|
||||
const RUN_QUERY = 'audit-logs-run-query-btn';
|
||||
const FORMAT_OPTIONS = 'periscope-btn-format-options';
|
||||
const DRAWER = 'audit-log-detail-drawer';
|
||||
const RELOAD_BUDGET_MS = 60_000;
|
||||
|
||||
type AuditFormat = 'Raw' | 'Default' | 'Column';
|
||||
|
||||
const FORMATS: Record<AuditFormat, { rowPrefix: string }> = {
|
||||
Raw: { rowPrefix: 'logs-raw-row-' },
|
||||
Default: { rowPrefix: 'logs-list-row-' },
|
||||
Column: { rowPrefix: 'audit-logs-table-row-' },
|
||||
};
|
||||
|
||||
const ANY_ROW = Object.values(FORMATS)
|
||||
.map(({ rowPrefix }) => `[data-testid^="${rowPrefix}"]`)
|
||||
.join(',');
|
||||
|
||||
export interface AuditDrawer {
|
||||
root(target?: Page): Locator;
|
||||
field(
|
||||
name: 'principal' | 'outcome' | 'event' | 'resource' | 'resource-id',
|
||||
): Locator;
|
||||
body(): Locator;
|
||||
next(): Locator;
|
||||
prev(): Locator;
|
||||
/** Press copy link and return the clipboard text. */
|
||||
copyLink(): Promise<string>;
|
||||
}
|
||||
|
||||
export interface AuditLogs {
|
||||
search: QuerySearch;
|
||||
/** The query search of another tab, such as one opened from a link. */
|
||||
searchOf(target: Page): QuerySearch;
|
||||
drawer: AuditDrawer;
|
||||
/** Open the page filtered to `email`, reloading until its newest event renders. */
|
||||
gotoUntil(email: string): Promise<void>;
|
||||
/** Narrow the list to one principal, through the query bar. */
|
||||
filterTo(expression: string): Promise<void>;
|
||||
rows(target?: Page): Locator;
|
||||
rowByBody(text: string, target?: Page): Locator;
|
||||
/** A row by log id, in any format. */
|
||||
rowById(logId: string, target?: Page): Locator;
|
||||
/** Rows of the Column format that a link marked. */
|
||||
linkedRows(target?: Page): Locator;
|
||||
/** Open the row's details drawer from any format. */
|
||||
open(row: Locator): Promise<void>;
|
||||
/** Wheel the Column table down until `body` renders. */
|
||||
scrollUntil(body: string): Promise<void>;
|
||||
activeLogId(target?: Page): string;
|
||||
openInNewTab(url: string): Promise<Page>;
|
||||
}
|
||||
|
||||
export function auditLogsDriver(page: Page): AuditLogs {
|
||||
const search = querySearchDriver(page, { runTestId: RUN_QUERY });
|
||||
const rows = (target: Page = page): Locator => target.locator(ANY_ROW);
|
||||
|
||||
const drawer: AuditDrawer = {
|
||||
root: (target = page) => target.getByTestId(DRAWER),
|
||||
field: (name) => drawer.root().getByTestId(`audit-log-detail-${name}`),
|
||||
body: () => drawer.root().getByTestId('audit-log-detail-body'),
|
||||
next: () => drawer.root().getByTestId('log-details-header-next'),
|
||||
prev: () => drawer.root().getByTestId('log-details-header-prev'),
|
||||
copyLink: async () => {
|
||||
await page.context().grantPermissions(['clipboard-read', 'clipboard-write']);
|
||||
await drawer.root().getByTestId('audit-log-detail-copy-link').click();
|
||||
await expect(page.getByText('Copied to clipboard')).toBeVisible();
|
||||
return page.evaluate(() => navigator.clipboard.readText());
|
||||
},
|
||||
};
|
||||
|
||||
const audit: AuditLogs = {
|
||||
search,
|
||||
searchOf: (target) => querySearchDriver(target, { runTestId: RUN_QUERY }),
|
||||
drawer,
|
||||
|
||||
gotoUntil: async (email) => {
|
||||
allowFor(SEEDED_TEST_BUDGET);
|
||||
await dismissQuickFiltersAnnouncement(page);
|
||||
await page.goto(`${AUDIT_LOGS_PATH}?relativeTime=${RELATIVE_TIME}`);
|
||||
await expect(page.getByTestId(FORMAT_OPTIONS)).toBeVisible();
|
||||
await audit.filterTo(email);
|
||||
let attempt = 0;
|
||||
await expect(async () => {
|
||||
if (attempt > 0) {
|
||||
await page.reload();
|
||||
}
|
||||
attempt += 1;
|
||||
await expect(audit.rowByBody(eventBody(email, 0)).first()).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
}).toPass({ timeout: RELOAD_BUDGET_MS, intervals: [1_000] });
|
||||
},
|
||||
|
||||
filterTo: async (email) => {
|
||||
await search.apply(`signoz.principal.email = '${email}'`);
|
||||
},
|
||||
|
||||
rows,
|
||||
rowByBody: (text, target = page) => rows(target).filter({ hasText: text }),
|
||||
rowById: (logId, target = page) =>
|
||||
target.locator(`[data-testid$="-row-${logId}"]`),
|
||||
linkedRows: (target = page) =>
|
||||
target.locator('[data-testid^="audit-logs-table-row-"][class*="linkedRow"]'),
|
||||
|
||||
open: async (row) => {
|
||||
const isColumn = (await row.getAttribute('data-testid'))?.startsWith(
|
||||
FORMATS.Column.rowPrefix,
|
||||
);
|
||||
// The table handles a click on a cell, not on the row.
|
||||
await (isColumn ? row.locator('td').nth(1) : row).click();
|
||||
await expect(drawer.root()).toBeVisible();
|
||||
},
|
||||
|
||||
scrollUntil: async (body) => {
|
||||
allowFor(SEEDED_TEST_BUDGET);
|
||||
await expect(async () => {
|
||||
const target = audit.rowByBody(body).first();
|
||||
if (await target.count()) {
|
||||
await expect(target).toBeVisible();
|
||||
return;
|
||||
}
|
||||
await wheelTo(rows().last());
|
||||
await page.mouse.wheel(0, 4_000);
|
||||
expect(await audit.rowByBody(body).count()).toBeGreaterThan(0);
|
||||
}).toPass({ timeout: SEEDED_DATA_TIMEOUT, intervals: [500] });
|
||||
},
|
||||
|
||||
activeLogId: (target = page) => {
|
||||
const value = new URL(target.url()).searchParams.get('activeLogId');
|
||||
if (!value) {
|
||||
throw new Error(`No activeLogId in URL: ${target.url()}`);
|
||||
}
|
||||
return value.replace(/"/g, '');
|
||||
},
|
||||
|
||||
openInNewTab: async (url) => {
|
||||
const tab = await page.context().newPage();
|
||||
await tab.goto(url);
|
||||
return tab;
|
||||
},
|
||||
};
|
||||
|
||||
return audit;
|
||||
}
|
||||
26
tests/e2e/drivers/audit-logs/index.ts
generated
Normal file
26
tests/e2e/drivers/audit-logs/index.ts
generated
Normal file
@@ -0,0 +1,26 @@
|
||||
import { driver, kit, type Layer } from '../kit';
|
||||
|
||||
import { auditLogsDriver, type AuditLogs } from './explorer';
|
||||
import { withAuditSeed } from './seed';
|
||||
|
||||
export const withAuditLogs: Layer<{ audit: AuditLogs }> = (base) =>
|
||||
driver('audit', ({ page }) => auditLogsDriver(page))(base);
|
||||
|
||||
/** The audit logs `test`: the explorer and its drawer over one worker-scoped seed (`auditSeed`). */
|
||||
export const test = withAuditLogs(withAuditSeed(kit));
|
||||
|
||||
export { expect, SEEDED_DATA_TIMEOUT } from '../kit';
|
||||
export {
|
||||
AUDIT_LOGS_PATH,
|
||||
auditLogsDriver,
|
||||
type AuditDrawer,
|
||||
type AuditLogs,
|
||||
} from './explorer';
|
||||
export {
|
||||
EVENT_COUNT,
|
||||
eventBody,
|
||||
isFailure,
|
||||
PAGE_SIZE,
|
||||
principalFilter,
|
||||
type AuditSeed,
|
||||
} from './seed';
|
||||
68
tests/e2e/drivers/audit-logs/seed.ts
generated
Normal file
68
tests/e2e/drivers/audit-logs/seed.ts
generated
Normal file
@@ -0,0 +1,68 @@
|
||||
import { seeded, type WorkerLayer } from '../kit';
|
||||
import { seedAuditLogs, type SeederAuditLog } from '../telemetry';
|
||||
|
||||
export const EVENT_COUNT = 120;
|
||||
export const PAGE_SIZE = 100;
|
||||
const STEP_MS = 5_000;
|
||||
const FAILURE_EVERY = 4;
|
||||
|
||||
export interface AuditSeed {
|
||||
/** Every event carries it as its principal email. */
|
||||
email: string;
|
||||
total: number;
|
||||
failures: number;
|
||||
}
|
||||
|
||||
export const eventBody = (email: string, index: number): string =>
|
||||
`${email} event-${String(index).padStart(3, '0')}`;
|
||||
|
||||
export const principalFilter = (email: string): string =>
|
||||
`signoz.principal.email = '${email}'`;
|
||||
|
||||
export const isFailure = (index: number): boolean =>
|
||||
index % FAILURE_EVERY === FAILURE_EVERY - 1;
|
||||
|
||||
export function buildWorkerAuditLogs(
|
||||
email: string,
|
||||
now = Date.now(),
|
||||
): SeederAuditLog[] {
|
||||
return Array.from({ length: EVENT_COUNT }, (_, index) => {
|
||||
const failed = isFailure(index);
|
||||
return {
|
||||
timestamp: new Date(now - index * STEP_MS).toISOString(),
|
||||
body: eventBody(email, index),
|
||||
event_name: 'signoz.audit.update',
|
||||
severity_text: failed ? 'ERROR' : 'INFO',
|
||||
resources: {
|
||||
'service.name': 'signoz',
|
||||
'signoz.resource.kind': 'dashboard',
|
||||
'signoz.resource.id': `${email}-dash-${index}`,
|
||||
},
|
||||
attributes: {
|
||||
'signoz.audit.verb': 'update',
|
||||
'signoz.audit.outcome': failed ? 'failure' : 'success',
|
||||
'signoz.audit.action_category': 'configuration_change',
|
||||
'signoz.principal.id': `${email}-id`,
|
||||
'signoz.principal.email': email,
|
||||
'signoz.principal.type': 'user',
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* No teardown: the seeder cannot delete by marker, and additive rows under a
|
||||
* unique principal are invisible to every spec that filters by its own.
|
||||
*/
|
||||
export const withAuditSeed: WorkerLayer<{ auditSeed: AuditSeed }> = seeded(
|
||||
'auditSeed',
|
||||
async ({ page, workerIndex }) => {
|
||||
const email = `e2e-audit-w${workerIndex}-${Date.now()}@e2e.test`;
|
||||
await seedAuditLogs(page.request, buildWorkerAuditLogs(email));
|
||||
return {
|
||||
email,
|
||||
total: EVENT_COUNT,
|
||||
failures: Math.floor(EVENT_COUNT / FAILURE_EVERY),
|
||||
};
|
||||
},
|
||||
);
|
||||
16
tests/e2e/drivers/telemetry.ts
generated
16
tests/e2e/drivers/telemetry.ts
generated
@@ -13,6 +13,7 @@ import { seederUrl } from './api';
|
||||
|
||||
export type TelemetryPath =
|
||||
| '/telemetry/logs'
|
||||
| '/telemetry/audit'
|
||||
| '/telemetry/traces'
|
||||
| '/telemetry/metrics';
|
||||
|
||||
@@ -25,6 +26,16 @@ export interface SeederLog {
|
||||
attributes?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Shape of `AuditLog.from_dict` in `tests/fixtures/audit.py`. */
|
||||
export interface SeederAuditLog {
|
||||
timestamp: string;
|
||||
body: string;
|
||||
event_name: string;
|
||||
severity_text?: string;
|
||||
resources?: Record<string, string>;
|
||||
attributes?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const ATTEMPTS = 8;
|
||||
const BACKOFF_MS = 500;
|
||||
const TIMEOUT_MS = 15_000;
|
||||
@@ -84,3 +95,8 @@ export const seedLogs = (
|
||||
request: APIRequestContext,
|
||||
logs: SeederLog[],
|
||||
): Promise<void> => postToSeeder(request, '/telemetry/logs', logs);
|
||||
|
||||
export const seedAuditLogs = (
|
||||
request: APIRequestContext,
|
||||
logs: SeederAuditLog[],
|
||||
): Promise<void> => postToSeeder(request, '/telemetry/audit', logs);
|
||||
|
||||
41
tests/e2e/tests/audit-logs/drawer.spec.ts
Normal file
41
tests/e2e/tests/audit-logs/drawer.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { eventBody, expect, test } from '../../drivers/audit-logs';
|
||||
|
||||
test.describe('Audit Logs — details drawer', () => {
|
||||
test('TC-04 a row opens the drawer with the event summary', async ({
|
||||
audit,
|
||||
auditSeed,
|
||||
}) => {
|
||||
await audit.gotoUntil(auditSeed.email);
|
||||
|
||||
await audit.open(audit.rowByBody(eventBody(auditSeed.email, 0)));
|
||||
|
||||
await expect(audit.drawer.body()).toContainText(
|
||||
eventBody(auditSeed.email, 0),
|
||||
);
|
||||
await expect(audit.drawer.field('principal')).toContainText(auditSeed.email);
|
||||
await expect(audit.drawer.field('outcome')).toContainText('success');
|
||||
await expect(audit.drawer.field('resource')).toContainText('dashboard');
|
||||
await expect(audit.drawer.field('resource-id')).toContainText(
|
||||
`${auditSeed.email}-dash-0`,
|
||||
);
|
||||
});
|
||||
|
||||
test('TC-06 next and previous step through the events', async ({
|
||||
audit,
|
||||
auditSeed,
|
||||
}) => {
|
||||
await audit.gotoUntil(auditSeed.email);
|
||||
await audit.open(audit.rowByBody(eventBody(auditSeed.email, 0)));
|
||||
await expect(audit.drawer.prev()).toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
await audit.drawer.next().click();
|
||||
|
||||
await expect(audit.drawer.body()).toContainText(
|
||||
eventBody(auditSeed.email, 1),
|
||||
);
|
||||
await audit.drawer.prev().click();
|
||||
await expect(audit.drawer.body()).toContainText(
|
||||
eventBody(auditSeed.email, 0),
|
||||
);
|
||||
});
|
||||
});
|
||||
41
tests/e2e/tests/audit-logs/explorer.spec.ts
Normal file
41
tests/e2e/tests/audit-logs/explorer.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
EVENT_COUNT,
|
||||
eventBody,
|
||||
expect,
|
||||
PAGE_SIZE,
|
||||
test,
|
||||
} from '../../drivers/audit-logs';
|
||||
|
||||
test.describe('Audit Logs — explorer', () => {
|
||||
test('TC-01 the explorer lists the seeded events', async ({
|
||||
audit,
|
||||
auditSeed,
|
||||
noise,
|
||||
}) => {
|
||||
await audit.gotoUntil(auditSeed.email);
|
||||
|
||||
await expect(audit.rowByBody(eventBody(auditSeed.email, 0))).toBeVisible();
|
||||
await expect(
|
||||
audit.rows().filter({ hasNotText: auditSeed.email }),
|
||||
).toHaveCount(0);
|
||||
expect(noise.errors).toEqual([]);
|
||||
expect(noise.failedResponses).toEqual([]);
|
||||
});
|
||||
|
||||
test('TC-03 scrolling to the end loads the next page', async ({
|
||||
audit,
|
||||
auditSeed,
|
||||
}) => {
|
||||
expect(EVENT_COUNT).toBeGreaterThan(PAGE_SIZE);
|
||||
await audit.gotoUntil(auditSeed.email);
|
||||
await expect(
|
||||
audit.rowByBody(eventBody(auditSeed.email, EVENT_COUNT - 1)),
|
||||
).toHaveCount(0);
|
||||
|
||||
await audit.scrollUntil(eventBody(auditSeed.email, EVENT_COUNT - 1));
|
||||
|
||||
await expect(
|
||||
audit.rowByBody(eventBody(auditSeed.email, EVENT_COUNT - 1)),
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
39
tests/e2e/tests/audit-logs/link.spec.ts
Normal file
39
tests/e2e/tests/audit-logs/link.spec.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
eventBody,
|
||||
expect,
|
||||
principalFilter,
|
||||
test,
|
||||
} from '../../drivers/audit-logs';
|
||||
|
||||
test.describe('Audit Logs — copy link', () => {
|
||||
test('TC-08 a copied link opens the page on the linked event', async ({
|
||||
audit,
|
||||
auditSeed,
|
||||
}) => {
|
||||
await audit.gotoUntil(auditSeed.email);
|
||||
await audit.open(audit.rowByBody(eventBody(auditSeed.email, 2)));
|
||||
const link = await audit.drawer.copyLink();
|
||||
|
||||
const tab = await audit.openInNewTab(link);
|
||||
|
||||
const logId = audit.activeLogId(tab);
|
||||
await expect(audit.rowById(logId, tab)).toBeVisible();
|
||||
await expect(audit.linkedRows(tab)).toHaveCount(1);
|
||||
await expect(audit.linkedRows(tab).first()).toContainText(
|
||||
eventBody(auditSeed.email, 2),
|
||||
);
|
||||
});
|
||||
|
||||
test('TC-09 the copied link keeps the query', async ({ audit, auditSeed }) => {
|
||||
await audit.gotoUntil(auditSeed.email);
|
||||
await audit.open(audit.rowByBody(eventBody(auditSeed.email, 0)));
|
||||
|
||||
const link = await audit.drawer.copyLink();
|
||||
|
||||
const tab = await audit.openInNewTab(link);
|
||||
await audit.searchOf(tab).expectExpression(principalFilter(auditSeed.email));
|
||||
await expect(
|
||||
audit.rowByBody(eventBody(auditSeed.email, 0), tab),
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
104
tests/fixtures/audit.py
vendored
104
tests/fixtures/audit.py
vendored
@@ -10,6 +10,7 @@ from ksuid import KsuidMs
|
||||
|
||||
from fixtures import types
|
||||
from fixtures.fingerprint import LogsOrTracesFingerprint
|
||||
from fixtures.time import parse_timestamp
|
||||
|
||||
ALICE_CREATED_DASHBOARD = "alice@acme.com (user-001) created dashboard (dash-001)"
|
||||
ALICE_UPDATED_DASHBOARD = "alice@acme.com (user-001) updated dashboard (dash-001)"
|
||||
@@ -114,6 +115,17 @@ class AuditLog(ABC):
|
||||
)
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "AuditLog":
|
||||
return cls(
|
||||
timestamp=parse_timestamp(data["timestamp"]),
|
||||
resources=data.get("resources", {}),
|
||||
attributes=data.get("attributes", {}),
|
||||
body=data["body"],
|
||||
event_name=data.get("event_name", ""),
|
||||
severity_text=data.get("severity_text", "INFO"),
|
||||
)
|
||||
|
||||
def np_arr(self) -> np.array:
|
||||
return np.array(
|
||||
[
|
||||
@@ -137,55 +149,65 @@ class AuditLog(ABC):
|
||||
)
|
||||
|
||||
|
||||
def insert_audit_logs_to_clickhouse(conn, logs: list[AuditLog]) -> None:
|
||||
resources: list[AuditResource] = []
|
||||
for log in logs:
|
||||
resources.extend(log.resource)
|
||||
|
||||
if len(resources) > 0:
|
||||
conn.insert(
|
||||
database="signoz_audit",
|
||||
table="distributed_logs_resource",
|
||||
data=[resource.np_arr() for resource in resources],
|
||||
column_names=[
|
||||
"labels",
|
||||
"fingerprint",
|
||||
"seen_at_ts_bucket_start",
|
||||
],
|
||||
)
|
||||
|
||||
conn.insert(
|
||||
database="signoz_audit",
|
||||
table="distributed_logs",
|
||||
data=[log.np_arr() for log in logs],
|
||||
column_names=[
|
||||
"ts_bucket_start",
|
||||
"resource_fingerprint",
|
||||
"timestamp",
|
||||
"observed_timestamp",
|
||||
"id",
|
||||
"trace_id",
|
||||
"span_id",
|
||||
"trace_flags",
|
||||
"severity_text",
|
||||
"severity_number",
|
||||
"body",
|
||||
"scope",
|
||||
"attributes",
|
||||
"resource",
|
||||
"event_name",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def truncate_audit_tables(conn, cluster: str) -> None:
|
||||
for table in ["logs", "logs_resource"]:
|
||||
conn.query(f"TRUNCATE TABLE signoz_audit.{table} ON CLUSTER '{cluster}' SYNC")
|
||||
|
||||
|
||||
@pytest.fixture(name="insert_audit_logs", scope="function")
|
||||
def insert_audit_logs(
|
||||
clickhouse: types.TestContainerClickhouse,
|
||||
) -> Generator[Callable[[list[AuditLog]], None], Any]:
|
||||
def _insert_audit_logs(logs: list[AuditLog]) -> None:
|
||||
resources: list[AuditResource] = []
|
||||
for log in logs:
|
||||
resources.extend(log.resource)
|
||||
|
||||
if len(resources) > 0:
|
||||
clickhouse.conn.insert(
|
||||
database="signoz_audit",
|
||||
table="distributed_logs_resource",
|
||||
data=[resource.np_arr() for resource in resources],
|
||||
column_names=[
|
||||
"labels",
|
||||
"fingerprint",
|
||||
"seen_at_ts_bucket_start",
|
||||
],
|
||||
)
|
||||
|
||||
clickhouse.conn.insert(
|
||||
database="signoz_audit",
|
||||
table="distributed_logs",
|
||||
data=[log.np_arr() for log in logs],
|
||||
column_names=[
|
||||
"ts_bucket_start",
|
||||
"resource_fingerprint",
|
||||
"timestamp",
|
||||
"observed_timestamp",
|
||||
"id",
|
||||
"trace_id",
|
||||
"span_id",
|
||||
"trace_flags",
|
||||
"severity_text",
|
||||
"severity_number",
|
||||
"body",
|
||||
"scope",
|
||||
"attributes",
|
||||
"resource",
|
||||
"event_name",
|
||||
],
|
||||
)
|
||||
insert_audit_logs_to_clickhouse(clickhouse.conn, logs)
|
||||
|
||||
yield _insert_audit_logs
|
||||
|
||||
cluster = clickhouse.env["SIGNOZ_TELEMETRYSTORE_CLICKHOUSE_CLUSTER"]
|
||||
for table in ["logs", "logs_resource"]:
|
||||
clickhouse.conn.query(f"TRUNCATE TABLE signoz_audit.{table} ON CLUSTER '{cluster}' SYNC")
|
||||
truncate_audit_tables(
|
||||
clickhouse.conn,
|
||||
clickhouse.env["SIGNOZ_TELEMETRYSTORE_CLICKHOUSE_CLUSTER"],
|
||||
)
|
||||
|
||||
|
||||
def sample_audit_logs(now: datetime.datetime) -> list[AuditLog]:
|
||||
|
||||
@@ -6,6 +6,11 @@ from typing import Any
|
||||
import clickhouse_connect
|
||||
from fastapi import FastAPI, HTTPException, Response, status
|
||||
|
||||
from fixtures.audit import (
|
||||
AuditLog,
|
||||
insert_audit_logs_to_clickhouse,
|
||||
truncate_audit_tables,
|
||||
)
|
||||
from fixtures.logger import setup_logger
|
||||
from fixtures.logs import Logs, insert_logs_to_clickhouse, truncate_logs_tables
|
||||
from fixtures.metrics import (
|
||||
@@ -126,6 +131,31 @@ def delete_logs() -> Response:
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
@app.post("/telemetry/audit", status_code=status.HTTP_201_CREATED)
|
||||
def post_audit(payload: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
try:
|
||||
logs = [AuditLog.from_dict(item) for item in payload]
|
||||
insert_audit_logs_to_clickhouse(get_conn(), logs)
|
||||
logger.info("inserted %d audit logs", len(logs))
|
||||
return {"inserted": len(logs)}
|
||||
except KeyError as e:
|
||||
raise HTTPException(status_code=400, detail=f"missing required field: {e}") from e
|
||||
except Exception as e:
|
||||
logger.exception("insert failed")
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
@app.delete("/telemetry/audit", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_audit() -> Response:
|
||||
try:
|
||||
truncate_audit_tables(get_conn(), CH_CLUSTER)
|
||||
logger.info("truncated audit tables")
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
except Exception as e:
|
||||
logger.exception("truncate failed")
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
@app.post("/telemetry/metrics", status_code=status.HTTP_201_CREATED)
|
||||
def post_metrics(payload: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user