Compare commits

...

2 Commits

Author SHA1 Message Date
Hardik
59a23fbc2d test(audit-logs): assert the copied link keeps the principal filter 2026-12-01 16:54:52 +05:30
Hardik
4f4a793558 test(audit-logs): add the audit logs e2e specs and seeding 2026-12-01 16:35:44 +05:30
10 changed files with 481 additions and 42 deletions

View File

@@ -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
View 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
View 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
View 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),
};
},
);

View File

@@ -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);

View 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),
);
});
});

View 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();
});
});

View 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();
});
});

View File

@@ -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]:

View File

@@ -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: