import { describe, expect, it } from 'vitest' import { logAttributeFilterId, logsFiltersToUrlParams } from './UnifiedLogs.filters' import { getFacetCountQuery, getLogsChartQuery, getLogsCountQuery, getRequestCorrelationIds, getRequestTimelineQuery, getUnifiedLogsQuery, isUserFilterUnreachable, } from './UnifiedLogs.queries' import { getLogsChartQuery as getLogsChartQueryBQ, getLogsCountQuery as getLogsCountQueryBQ, getUnifiedLogsQuery as getUnifiedLogsQueryBQ, } from './UnifiedLogs.queries.bq' import type { UnifiedLogsScope } from './UnifiedLogs.types' import { createUnifiedLogsSearch } from './UnifiedLogs.utils' const baseSearch = createUnifiedLogsSearch({ date: [new Date('2026-05-08T09:00:00Z'), new Date('2026-05-08T10:00:00Z')], }) const withFilters = (...entries: string[]) => createUnifiedLogsSearch({ ...baseSearch, filter: entries }) const FUNCTION_SCOPE: UnifiedLogsScope = { filters: [ { column: 'log_type', operator: '=', value: 'edge function' }, { column: 'log_type', operator: '=', value: 'edge function runtime' }, { column: 'function_id', operator: '=', value: 'fn-123' }, ], } const withScope = (scope: UnifiedLogsScope, ...entries: string[]) => createUnifiedLogsSearch({ ...baseSearch, filter: entries }, scope) const withFunctionScope = (...entries: string[]) => withScope(FUNCTION_SCOPE, ...entries) const withUser = (user: string, ...entries: string[]) => createUnifiedLogsSearch({ ...baseSearch, user, filter: entries }) describe('UnifiedLogs.queries (OTEL flat)', () => { describe('getUnifiedLogsQuery', () => { it('defaults to postgres + edge log types when none specified', () => { const sql = getUnifiedLogsQuery(baseSearch) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(`source = 'postgres_logs'`) expect(where).toContain(`source = 'edge_logs'`) expect(where).not.toContain(`source = 'postgrest_logs'`) }) it.each([ ['postgrest', 'postgrest_logs', '%/rest/%'], ['storage', 'storage_logs', '%/storage/%'], ])( 'routes the `%s` log type solely to %s (mutually exclusive from edge_logs)', (logType, source, edgePath) => { const sql = getUnifiedLogsQuery(withFilters(`log_type:eq:${logType}`)) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(`source = '${source}'`) expect(where).not.toContain(`source = 'edge_logs'`) expect(where).not.toContain(`log_attributes['request.path'] LIKE '${edgePath}'`) } ) it('routes the `compute` log type to every worker OTEL stream', () => { const sql = getUnifiedLogsQuery(withFilters('log_type:eq:compute')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain( `log_attributes['subservice'] IN ('worker_ingress_logs','worker_guest_logs','worker_api_logs')` ) expect(where).not.toContain(`source = 'compute'`) }) it('classifies every worker OTEL stream as compute in the projected log type', () => { const sql = getUnifiedLogsQuery(baseSearch) expect(sql).toContain( `WHEN log_attributes['subservice'] IN ('worker_ingress_logs','worker_guest_logs','worker_api_logs') THEN 'compute'` ) }) it('excludes every worker OTEL stream when the compute log type is negated', () => { const sql = getUnifiedLogsQuery(withFilters('log_type:neq:compute')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain( `NOT (log_attributes['subservice'] IN ('worker_ingress_logs','worker_guest_logs','worker_api_logs'))` ) }) it('keeps edge function runtime output out of the list when a log type is excluded', () => { const sql = getUnifiedLogsQuery(withFilters('log_type:neq:postgres')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(`NOT (source = 'postgres_logs')`) expect(where).toContain(`NOT (source = 'function_logs')`) }) it('reads the path edge function rows store under request.pathname, falling back to request.path when it is missing', () => { const sql = getUnifiedLogsQuery(withFilters('log_type:eq:edge function')) expect(sql).toContain( "source = 'function_edge_logs' AND log_attributes['request.pathname'] != '', log_attributes['request.pathname']" ) }) it('projects only Compute fields that exist on worker logs', () => { const sql = getUnifiedLogsQuery(withFilters('log_type:eq:compute')) const workerCondition = "log_attributes['subservice'] IN ('worker_ingress_logs','worker_guest_logs','worker_api_logs')" expect(sql).toContain(`WHEN ${workerCondition} THEN null`) expect(sql).toContain( `if(${workerCondition} OR source = 'etl_replication_logs', null, if(source = 'storage_logs', log_attributes['req.method'], log_attributes['request.method']))` ) expect(sql).toContain( `if(${workerCondition} OR source = 'etl_replication_logs', null, multiIf(source = 'storage_logs', log_attributes['req.url'], source = 'function_edge_logs' AND log_attributes['request.pathname'] != '', log_attributes['request.pathname'], log_attributes['request.path']))` ) expect(sql).toContain( `if(${workerCondition} OR source IN ('function_logs', 'etl_replication_logs'), log_attributes, map()) AS metadata` ) }) it('escapes single quotes in filter values to prevent SQL injection', () => { const sql = getUnifiedLogsQuery( withFilters(`method:eq:G'ET`, `pathname:eq:/customers'; DROP TABLE logs --`) ) // Single quotes are doubled (SQL-standard escaping) by pg-meta's // literal(); a raw single quote from user input never closes its // string literal early. expect(sql).toContain(`'G''ET'`) expect(sql).toContain(`'/customers''; DROP TABLE logs --'`) }) it('translates method/status/pathname filters to log_attributes predicates', () => { const sql = getUnifiedLogsQuery( withFilters('method:eq:GET', 'status:eq:401', 'pathname:eq:/customers') ) // Method/pathname filters wrap the if() that picks the gateway or // storage-service attribute key so storage rows match too. expect(sql).toContain( `(if(source = 'storage_logs', log_attributes['req.method'], log_attributes['request.method'])) IN ('GET')` ) // Status filter wraps the CASE that picks HTTP code or Postgres SQLSTATE // so e.g. '00000' matches postgres success rows. expect(sql).toContain(`log_attributes['parsed.sql_state_code']`) expect(sql).toMatch(/END\) IN \('401'\)/) expect(sql).toContain( `(multiIf(source = 'storage_logs', log_attributes['req.url'], source = 'function_edge_logs' AND log_attributes['request.pathname'] != '', log_attributes['request.pathname'], log_attributes['request.path'])) IN ('/customers')` ) }) it('flips IN to NOT IN when the operator is `<>`', () => { const sql = getUnifiedLogsQuery(withFilters('method:neq:GET', 'status:neq:401')) expect(sql).toContain( `(if(source = 'storage_logs', log_attributes['req.method'], log_attributes['request.method'])) NOT IN ('GET')` ) expect(sql).toMatch(/END\) NOT IN \('401'\)/) }) // Auth- and storage-service logs expose their status under their own keys, // not the gateway's `response.status_code`; without this their 4xx/5xx // classify as success and the severity filter returns nothing. it.each([ ['auth', `WHEN source = 'auth_logs' THEN log_attributes['status']`], ['storage', `WHEN source = 'storage_logs' THEN log_attributes['res.statusCode']`], ])('reads the HTTP status from the service-specific key for %s rows', (logType, expected) => { const sql = getUnifiedLogsQuery(withFilters(`log_type:eq:${logType}`)) expect(sql).toContain(expected) }) it('uses NOT IN for pathname and retains NOT LIKE for host with `<>`', () => { const sql = getUnifiedLogsQuery(withFilters('pathname:neq:/health', 'host:neq:cdn.foo')) expect(sql).toContain( `(multiIf(source = 'storage_logs', log_attributes['req.url'], source = 'function_edge_logs' AND log_attributes['request.pathname'] != '', log_attributes['request.pathname'], log_attributes['request.path'])) NOT IN ('/health')` ) expect(sql).toContain(`log_attributes['request.url'] NOT LIKE '%cdn.foo%'`) }) describe('filter groups', () => { const GROUP = 'group:or:status:neq:200,pathname:neq:%2Fhealth' it('joins group conditions with OR inside one parenthesized clause', () => { const sql = getUnifiedLogsQuery(withFilters(GROUP)) expect(sql).toMatch( /END\) NOT IN \('200'\) OR \(multiIf\([\s\S]*?\)\) NOT IN \('\/health'\)\)/ ) }) it('ANDs the group with flat filters instead of folding it into them', () => { const sql = getUnifiedLogsQuery(withFilters('method:eq:GET', GROUP)) const methodIndex = sql.indexOf(`) IN ('GET')`) const groupIndex = sql.indexOf(`NOT IN ('200')`) expect(methodIndex).toBeGreaterThan(-1) expect(groupIndex).toBeGreaterThan(methodIndex) expect(sql.slice(methodIndex, groupIndex)).toContain(' AND ') }) it('applies groups to the count, chart and facet queries', () => { const search = withFilters(GROUP) expect(getLogsCountQuery(search)).toContain(`NOT IN ('200')`) expect(getLogsChartQuery(search)).toContain(`NOT IN ('200')`) expect(getFacetCountQuery({ search, facet: 'level' })).toContain(`NOT IN ('200')`) }) it('drops a group that has a top-level-only column rather than narrowing it', () => { const sql = getUnifiedLogsQuery(withFilters('group:or:log_type:eq:auth,status:neq:200')) expect(sql).not.toContain(`NOT IN ('200')`) }) it('escapes values so they cannot break out of the string literal', () => { const sql = getUnifiedLogsQuery( withFilters(`group:or:status:eq:${encodeURIComponent(`' OR 1=1 --`)}`) ) // The quote is doubled, so the payload stays inside the string literal. expect(sql).toContain(`IN (''' OR 1=1 --')`) }) }) const pathExpr = `(multiIf(source = 'storage_logs', log_attributes['req.url'], source = 'function_edge_logs' AND log_attributes['request.pathname'] != '', log_attributes['request.pathname'], log_attributes['request.path']))` it.each([ ['eq', 'IN'], ['neq', 'NOT IN'], ])('matches complete pathname values for %s', (operator, expected) => { const sql = getUnifiedLogsQuery( withFilters(`pathname:${operator}:/auth/v1/token`, `pathname:${operator}:/auth/v1/user_%`) ) expect(sql).toContain(`${pathExpr} ${expected} ('/auth/v1/token','/auth/v1/user_%')`) expect(sql).not.toContain(`${pathExpr} LIKE`) expect(sql).not.toContain(`${pathExpr} NOT LIKE`) }) it.each([ ['pathname:ilike:Customers', `${pathExpr} ILIKE '%Customers%'`, null], ['pathname:notilike:health', `${pathExpr} NOT ILIKE '%health%'`, null], ['pathname:ilike:foo%', `${pathExpr} ILIKE 'foo%'`, `'%foo%%'`], ['pathname:ilike:fo_bar', `${pathExpr} ILIKE 'fo_bar'`, `'%fo_bar%'`], ['event_message:ilike:Permission Denied', `event_message ILIKE '%Permission Denied%'`, null], ['event_message:notilike:cron', `event_message NOT ILIKE '%cron%'`, null], ['event_message:ilike:error%', `event_message ILIKE 'error%'`, `'%error%%'`], ['event_message:ilike:foo_bar', `event_message ILIKE 'foo_bar'`, `'%foo_bar%'`], ])( 'emits the pattern predicate for %s, auto-wrapping only values without wildcards', (filter, expected, notExpected) => { const sql = getUnifiedLogsQuery(withFilters(filter)) expect(sql).toContain(expected) if (notExpected) expect(sql).not.toContain(notExpected) } ) it.each([ ['pathname', pathExpr], ['event_message', 'event_message'], ])('joins multiple %s NOT ILIKE values with AND (row must match none)', (column, expr) => { const sql = getUnifiedLogsQuery( withFilters(`${column}:notilike:health`, `${column}:notilike:metrics`) ) expect(sql).toContain(`${expr} NOT ILIKE '%health%' AND ${expr} NOT ILIKE '%metrics%'`) }) it('excludes connection log messages when show_connection_logs=false', () => { const sql = getUnifiedLogsQuery({ ...baseSearch, show_connection_logs: false } as any) expect(sql).toContain("source != 'postgres_logs'") expect(sql).toContain("event_message NOT LIKE 'connection received%'") expect(sql).toContain("event_message NOT LIKE 'connection authenticated%'") expect(sql).toContain("event_message NOT LIKE 'connection authorized%'") }) it('includes connection log messages by default (show_connection_logs=true)', () => { const sql = getUnifiedLogsQuery({ ...baseSearch, show_connection_logs: true } as any) expect(sql).not.toContain("event_message NOT LIKE 'connection received%'") }) it.each([ ['edge_auth', '%/auth/%'], ['edge_storage', '%/storage/%'], ['edge_postgrest', '%/rest/%'], ] as const)('excludes %s-pathed requests from edge_logs when %s=false', (key, pathFilter) => { const sql = getUnifiedLogsQuery({ ...baseSearch, [key]: false } as any) expect(sql).toContain("source != 'edge_logs'") expect(sql).toContain(`log_attributes['request.path'] NOT LIKE '${pathFilter}'`) }) it('does not filter edge_logs by service path by default (all edge_* toggles true)', () => { const sql = getUnifiedLogsQuery(baseSearch) expect(sql).not.toContain("log_attributes['request.path'] NOT LIKE '%/auth/%'") expect(sql).not.toContain("log_attributes['request.path'] NOT LIKE '%/storage/%'") expect(sql).not.toContain("log_attributes['request.path'] NOT LIKE '%/rest/%'") }) it('leaves dedicated auth_logs/storage_logs/postgrest_logs rows untouched by the edge_* toggles', () => { // These toggles only hide traffic nested inside the `edge_logs` (API // Gateway) source — the dedicated sources are separate log types now // that log types are mutually exclusive, so they shouldn't be scoped by // a `source != 'edge_logs' OR ...` guard meant for gateway rows. const sql = getUnifiedLogsQuery({ ...baseSearch, edge_auth: false, edge_storage: false, edge_postgrest: false, } as any) expect(sql).toContain( "(source != 'edge_logs' OR log_attributes['request.path'] NOT LIKE '%/auth/%')" ) expect(sql).toContain( "(source != 'edge_logs' OR log_attributes['request.path'] NOT LIKE '%/storage/%')" ) expect(sql).toContain( "(source != 'edge_logs' OR log_attributes['request.path'] NOT LIKE '%/rest/%')" ) }) it('does not emit subqueries or CTEs (rejected by the OTEL endpoint)', () => { const sql = getUnifiedLogsQuery(baseSearch) expect(sql).not.toMatch(/WITH\s+\w+\s+AS\s*\(/i) expect(sql).not.toMatch(/FROM\s*\(\s*SELECT/i) // Single SELECT * FROM logs (not "SELECT *" wildcard usage either). expect(sql).not.toMatch(/SELECT\s+\*/) }) }) describe('getLogsCountQuery', () => { const whereOfBranchContaining = (sql: string, needle: string) => { const branch = sql.split(/\bUNION ALL\b/).find((b) => b.includes(needle)) ?? '' return branch.split(/\bWHERE\b/)[1]?.split(/\bGROUP BY\b/)[0] ?? '' } it('folds facets into single-pass arrayJoin scans with a total row', () => { const sql = getLogsCountQuery(baseSearch) expect(sql).toContain('arrayJoin([') expect(sql).toContain('multiIf(') expect(sql).toContain(`facet = 'total', 'all'`) for (const lt of ['postgrest', 'storage', 'postgres', 'edge function', 'auth']) { expect(sql).toContain(`'${lt}'`) } for (const lvl of ['success', 'warning', 'error']) { expect(sql).toContain(`'${lvl}'`) } }) it('honours an active log_type filter in the total count scan', () => { const sql = getLogsCountQuery(withFilters('log_type:eq:storage')) // Assert on the WHERE only: value expressions mention other sources inline. const totalWhere = whereOfBranchContaining(sql, `'all'`) expect(totalWhere).toContain(`source = 'storage_logs'`) expect(totalWhere).not.toContain(`source = 'edge_logs'`) expect(totalWhere).not.toContain(`source = 'postgres_logs'`) }) it('gives the log_type facet its own scan that excludes the log_type filter', () => { const sql = getLogsCountQuery(withFilters('log_type:eq:postgrest')) const logTypeWhere = whereOfBranchContaining(sql, `'log_type'`) expect(logTypeWhere).not.toContain(`LIKE '%/rest/%'`) }) it('applies the connection-logs filter to every count scan so badges match the list', () => { const sql = getLogsCountQuery({ ...baseSearch, show_connection_logs: false } as any) const scans = sql.split(/\bUNION ALL\b/) expect(scans.length).toBeGreaterThan(1) for (const scan of scans) { expect(scan).toContain("event_message NOT LIKE 'connection received%'") } }) it('applies the edge_* service filters to every count scan so badges match the list', () => { const sql = getLogsCountQuery({ ...baseSearch, edge_postgrest: false } as any) const scans = sql.split(/\bUNION ALL\b/) expect(scans.length).toBeGreaterThan(1) for (const scan of scans) { expect(scan).toContain("log_attributes['request.path'] NOT LIKE '%/rest/%'") } }) }) describe('getLogsChartQuery', () => { it.each([ ['toStartOfMinute', '2026-05-08T09:00:00Z', '2026-05-08T10:00:00Z'], ['toStartOfHour', '2026-05-08T00:00:00Z', '2026-05-08T18:00:00Z'], ['toStartOfDay', '2026-05-01T00:00:00Z', '2026-05-08T00:00:00Z'], ])('buckets with %s for a %s - %s range', (bucketFn, start, end) => { const sql = getLogsChartQuery({ ...baseSearch, date: [new Date(start), new Date(end)], } as any) expect(sql).toContain(`${bucketFn}(timestamp)`) }) it('buckets auth rows by their log_attributes[status] so 4xx/5xx are not counted as success', () => { const sql = getLogsChartQuery(baseSearch) expect(sql).toContain(`WHEN source = 'auth_logs' THEN log_attributes['status']`) }) it('does not classify Compute rows into a severity bucket', () => { const sql = getLogsChartQuery(withFilters('log_type:eq:compute')) const workerCondition = "log_attributes['subservice'] IN ('worker_ingress_logs','worker_guest_logs','worker_api_logs')" expect(sql).toContain(`WHEN ${workerCondition} THEN null`) expect(sql).not.toContain(`WHEN ${workerCondition} THEN 'success'`) }) }) describe('getFacetCountQuery', () => { it('groups by the requested facet and excludes that facet from the WHERE filters', () => { const sql = getFacetCountQuery({ search: withFilters('method:eq:GET', 'status:eq:200'), facet: 'method', }) // Filtered facet is excluded from WHERE; other filters still applied. // For facet='method' the SELECT projection doesn't include STATUS_EXPR, // so SQLSTATE/IN ('200') must come from the WHERE clause. expect(sql).not.toContain(`log_attributes['request.method'] IN ('GET')`) expect(sql).toContain(`log_attributes['parsed.sql_state_code']`) expect(sql).toMatch(/END\) IN \('200'\)/) expect(sql).toContain('GROUP BY value') expect(sql).toContain('LIMIT 20') }) }) describe('user filter', () => { it('restricts to auth_logs/edge_logs and skips the default postgres+edge restriction', () => { const sql = getUnifiedLogsQuery(withUser('user-123')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain( `(source = 'auth_logs' AND log_attributes['auth_event.actor_id'] = 'user-123')` ) expect(where).toContain( `(source = 'edge_logs' AND log_attributes['request.sb.jwt.authorization.payload.subject'] = 'user-123')` ) // The unfiltered default (edge_logs OR postgres_logs) would incorrectly exclude // auth_logs, the primary attributable source, so it must not appear here. expect(where).not.toContain(`(source = 'edge_logs') OR (source = 'postgres_logs')`) }) it('does not restrict sources when the user filter is inactive', () => { const sql = getUnifiedLogsQuery(baseSearch) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).not.toContain(`auth_event.actor_id`) }) it('ANDs an explicit non-attributable log_type filter with the user condition (edge case: always zero rows)', () => { // Locks in the exact shape `isUserFilterUnreachable` detects — `source = 'edge_logs'` // AND `(source = 'auth_logs' ...) OR (source = 'postgres_logs' ...)` can never both hold. const sql = getUnifiedLogsQuery(withUser('user-123', 'log_type:eq:edge')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(`source = 'edge_logs'`) expect(where).toContain(`log_attributes['auth_event.actor_id'] = 'user-123'`) }) }) describe('isUserFilterUnreachable', () => { it('is false when no user filter is active', () => { expect(isUserFilterUnreachable(withFilters('log_type:eq:edge'))).toBe(false) }) it.each([ [[], false], [['log_type:eq:auth'], false], [['log_type:eq:edge'], false], [['log_type:eq:edge', 'log_type:eq:auth'], false], [['log_type:eq:storage'], true], [['log_type:eq:realtime', 'log_type:eq:storage'], true], // Excluding one attributable source leaves the other eligible. [['log_type:neq:edge'], false], [['log_type:neq:auth', 'log_type:neq:edge'], true], ])('with a user filter and log_type filters %j returns %s', (filters, expected) => { expect(isUserFilterUnreachable(withUser('user-123', ...filters))).toBe(expected) }) }) describe('analyticsLiteral escaping', () => { it('emits ClickHouse / BigQuery escape syntax (doubled `\\\\`, no `E` prefix)', () => { // pg-meta's literal() would emit `E'a\\b'` for `a\b` — the `E` prefix is // Postgres-only and rejected by both analytics engines. analyticsLiteral // doubles the backslash inside plain `'…'` delimiters instead. const sql = getUnifiedLogsQuery(withFilters('method:eq:a\\b')) expect(sql).toContain( `(if(source = 'storage_logs', log_attributes['req.method'], log_attributes['request.method'])) IN ('a\\\\b')` ) expect(sql).not.toContain(`E'a`) }) }) }) describe('UnifiedLogs.queries.bq', () => { it.each([ ['eq', 'IN'], ['neq', 'NOT IN'], ])('matches complete pathname values for %s', (operator, expected) => { const sql = getUnifiedLogsQueryBQ( withFilters(`pathname:${operator}:/auth/v1/token`, `pathname:${operator}:/auth/v1/user_%`) ) expect(sql).toContain('`pathname` ' + expected + " ('/auth/v1/token','/auth/v1/user_%')") expect(sql).not.toContain('`pathname` LIKE') expect(sql).not.toContain('`pathname` NOT LIKE') }) it('backtick-quotes column identifiers (BigQuery syntax)', () => { const sql = getUnifiedLogsQueryBQ(withFilters('method:eq:GET')) expect(sql).toContain("`method` IN ('GET')") }) // Keys failing the quotedIdent regex (`[A-Za-z_][A-Za-z0-9_]*`) drop the predicate entirely. it.each([ ['foo; DROP TABLE x:eq:y', ['DROP TABLE', 'foo;']], ['level OR id IS NOT NULL:eq:anything', ['IS NOT NULL', 'level OR']], ])('rejects the non-identifier key in %s', (filter, forbidden) => { const sql = getUnifiedLogsQueryBQ(withFilters(filter)) for (const fragment of forbidden) expect(sql).not.toContain(fragment) }) it('escapes injection attempts in filter values via analyticsLiteral', () => { const sql = getUnifiedLogsQueryBQ(withFilters("method:eq:GET' OR '1'='1")) // The value is single-quote-escaped, so the synthetic OR can't break out // of the string literal. expect(sql).toContain("`method` IN ('GET'' OR ''1''=''1')") expect(sql).not.toMatch(/`method` IN \('GET' OR '1'='1'\)/) }) // BigQuery has no ILIKE keyword. Wildcard handling must match the ClickHouse // builder, otherwise switching the `otelUnifiedLogs` flag would silently // change what a saved/shared filter matches. it.each([ [ 'event_message:ilike:Permission Denied', "LOWER(`event_message`) LIKE LOWER('%Permission Denied%')", ], ['event_message:notilike:cron', "LOWER(`event_message`) NOT LIKE LOWER('%cron%')"], ['pathname:ilike:Customers', "LOWER(`pathname`) LIKE LOWER('%Customers%')"], ['pathname:notilike:health', "LOWER(`pathname`) NOT LIKE LOWER('%health%')"], ['pathname:ilike:foo%', "LOWER(`pathname`) LIKE LOWER('foo%')"], ['pathname:ilike:fo_bar', "LOWER(`pathname`) LIKE LOWER('fo_bar')"], ])('emulates ILIKE with LOWER() for %s', (filter, expected) => { const sql = getUnifiedLogsQueryBQ(withFilters(filter)) expect(sql).toContain(expected) expect(sql).not.toMatch(/\bILIKE\b/) }) }) describe('resource-scoped logs', () => { const FUNCTION_SCOPE_CONDITION = `((source = 'function_edge_logs') OR (source = 'function_logs')) AND log_attributes['function_id'] IN ('fn-123')` describe('ClickHouse', () => { it("restricts rows to the function's invocations and runtime logs instead of the default log types", () => { const sql = getUnifiedLogsQuery(withFunctionScope()) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(FUNCTION_SCOPE_CONDITION) expect(where).not.toContain(`source = 'postgres_logs'`) expect(where).not.toContain(`source = 'edge_logs'`) }) it('keeps the scope when the user narrows to one of its log types', () => { const sql = getUnifiedLogsQuery(withFunctionScope('log_type:eq:edge function runtime')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(`((source = 'function_logs'))`) expect(where).toContain(FUNCTION_SCOPE_CONDITION) }) it('still lists runtime output when the user excludes invocations from a function scope', () => { const sql = getUnifiedLogsQuery(withFunctionScope('log_type:neq:edge function')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(`NOT (source = 'function_edge_logs')`) expect(where).not.toContain(`NOT (source = 'function_logs')`) }) it('keeps rows outside the scope out even when an out-of-scope log type is requested', () => { const sql = getUnifiedLogsQuery(withFunctionScope('log_type:eq:postgres')) const where = sql.split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(`((source = 'postgres_logs'))`) expect(where).toContain(FUNCTION_SCOPE_CONDITION) }) it('keeps every log count within the selected function', () => { const scans = getLogsCountQuery(withFunctionScope()).split(/\bUNION ALL\b/) expect(scans.length).toBeGreaterThan(1) for (const scan of scans) expect(scan).toContain(FUNCTION_SCOPE_CONDITION) }) it('keeps chart and filter counts within the selected function', () => { expect(getLogsChartQuery(withFunctionScope())).toContain(FUNCTION_SCOPE_CONDITION) expect(getFacetCountQuery({ search: withFunctionScope(), facet: 'status' })).toContain( FUNCTION_SCOPE_CONDITION ) }) it('labels runtime logs and preserves error and warning severity', () => { const sql = getUnifiedLogsQuery(withFunctionScope()) expect(sql).toContain(`WHEN source = 'function_logs' THEN 'edge function runtime'`) expect(sql).toContain( `WHEN source = 'function_logs' AND lower(log_attributes['level']) IN ('error','fatal') THEN 'error'` ) expect(sql).toContain( `WHEN source = 'function_logs' AND lower(log_attributes['level']) IN ('warn','warning') THEN 'warning'` ) }) it('does not restrict project-wide searches to a resource', () => { expect(getUnifiedLogsQuery(baseSearch)).not.toContain(`log_attributes['function_id']`) }) it('requires logs to match both bucket inclusion and exclusion filters', () => { const sql = getUnifiedLogsQuery( withScope({ filters: [ { column: 'log_type', operator: '=', value: 'storage' }, { column: 'bucket_id', operator: '=', value: 'avatars' }, { column: 'bucket_id', operator: '<>', value: 'private' }, ], }) ) expect(sql).toContain( `(((source = 'storage_logs')) AND log_attributes['bucket_id'] IN ('avatars') AND log_attributes['bucket_id'] NOT IN ('private'))` ) }) it('matches no rows when the fixed scope has no filters', () => { const where = getUnifiedLogsQuery(withScope({ filters: [] })).split(/\bWHERE\b/)[1] ?? '' expect(where.trim()).toBe('0') }) it('matches no rows when an unvalidated scope filter omits its value', () => { const scope = JSON.parse('{"filters":[{"column":"function_id","operator":"="}]}') const where = getUnifiedLogsQuery({ ...baseSearch, scope }).split(/\bWHERE\b/)[1] ?? '' expect(where.trim()).toBe('0') }) it.each([ { operator: '~~*', label: 'substring inclusion' }, { operator: '!~~*', label: 'substring exclusion' }, ] as const)('matches no rows for unsupported function filters using $label', ({ operator }) => { const where = getUnifiedLogsQuery( withScope({ filters: [{ column: 'function_id', operator, value: 'fn-%' }], }) ).split(/\bWHERE\b/)[1] ?? '' expect(where.trim()).toBe('0') }) it.each([ { scenario: 'includes logs whose messages contain text', filter: { column: 'event_message', operator: '~~*', value: 'permission denied' }, expectedCondition: "event_message ILIKE '%permission denied%'", }, { scenario: 'excludes logs whose messages contain text', filter: { column: 'event_message', operator: '!~~*', value: 'permission denied' }, expectedCondition: "event_message NOT ILIKE '%permission denied%'", }, { scenario: 'includes requests whose paths contain text', filter: { column: 'pathname', operator: '~~*', value: '/functions/v1/example' }, expectedCondition: ") ILIKE '%/functions/v1/example%'", }, { scenario: 'excludes requests whose paths contain text', filter: { column: 'pathname', operator: '!~~*', value: '/functions/v1/example' }, expectedCondition: ") NOT ILIKE '%/functions/v1/example%'", }, ] as const)('$scenario', ({ filter, expectedCondition }) => { const where = getUnifiedLogsQuery(withScope({ filters: [filter] })).split(/\bWHERE\b/)[1] ?? '' expect(where).toContain(expectedCondition) }) }) describe('BigQuery', () => { it('refuses scoped searches rather than return rows from outside the scope', () => { expect(() => getUnifiedLogsQueryBQ(withFunctionScope())).toThrow( 'Scoped unified logs queries are only supported on ClickHouse' ) }) it('leaves unscoped queries on the default log types', () => { const sql = getUnifiedLogsQueryBQ(baseSearch) expect(sql).toContain('from postgres_logs') expect(sql).toContain('from edge_logs') expect(sql).not.toContain('function_id') }) }) }) describe('request timeline', () => { it('reads request and execution IDs from the keys each source sets', () => { expect( getRequestCorrelationIds([ { source: 'edge_logs', attributes: { 'request.headers.cf_ray': '8f00aa-IAD' } }, { source: 'auth_logs', attributes: { request_id: '8f00aa-IAD' } }, { source: 'function_edge_logs', attributes: { execution_id: 'exec-1', 'request.headers.cf_ray': '8f00bb-IAD' }, }, { source: 'postgres_logs', attributes: { request_id: 'ignored' } }, ]) ).toEqual({ requestIds: ['8f00aa-IAD', '8f00bb-IAD'], executionIds: ['exec-1'], nativeRequestIds: [], traceIds: [], }) }) it('ignores IDs that are not plain identifiers', () => { expect( getRequestCorrelationIds([ { source: 'edge_logs', attributes: { 'request.headers.cf_ray': "x' OR 1=1 --" } }, { source: 'auth_logs', attributes: { request_id: 42 } }, { source: 'storage_logs', attributes: null }, ]) ).toEqual({ requestIds: [], executionIds: [], nativeRequestIds: [], traceIds: [] }) }) it('keeps native request IDs, traces, and legacy IDs in separate namespaces', () => { expect( getRequestCorrelationIds([ { source: 'edge_logs', attributes: { request_id: '01a1880e-a158-7005-9fdf-e9ee66e4b6ad', 'request.headers.cf_ray': '01a1880e-a158-7005-9fdf-e9ee66e4b6ad', trace_id: '69110a42ebc24cb5a63d00fc2e8017a4', span_id: '467867d205824e7d', }, }, { source: 'auth_logs', attributes: { request_id: '01a1880e-a158-7005-9fdf-e9ee66e4b6ad' }, }, { source: 'unknown_logs', attributes: { trace_id: 'a'.repeat(32) } }, ]) ).toEqual({ requestIds: [], executionIds: [], nativeRequestIds: ['01a1880e-a158-7005-9fdf-e9ee66e4b6ad'], traceIds: ['69110a42ebc24cb5a63d00fc2e8017a4'], }) }) it('ignores malformed traces, standalone spans, and zero placeholders', () => { expect( getRequestCorrelationIds([ { source: 'edge_logs', attributes: { request_id: '00000000-0000-0000-0000-000000000000', trace_id: '0'.repeat(32), 'request.headers.cf_ray': '0000', }, }, { source: 'function_logs', attributes: { execution_id: '00000000-0000-0000-0000-000000000000', trace_id: 'bad-trace', span_id: '467867d205824e7d', parent_span_id: 'f3addadfe21d5055', }, }, ]) ).toEqual({ requestIds: [], executionIds: [], nativeRequestIds: [], traceIds: [] }) }) it('matches each source on its own key and orders oldest first', () => { const sql = getRequestTimelineQuery({ requestIds: ['8f00aa-IAD'], executionIds: ['exec-1'] }) expect(sql).toContain( `(source = 'edge_logs' AND (log_attributes['request.headers.cf_ray'] IN ('8f00aa-IAD') OR log_attributes['response.headers.cf_ray'] IN ('8f00aa-IAD')))` ) expect(sql).toContain( `(source = 'auth_logs' AND (log_attributes['request_id'] IN ('8f00aa-IAD')))` ) expect(sql).toContain( `(source = 'function_logs' AND (log_attributes['execution_id'] IN ('exec-1')))` ) expect(sql).toContain('log_attributes AS metadata') expect(sql).toContain('ORDER BY timestamp ASC') expect(sql).toMatch(/LIMIT 200\s*$/) }) it('skips execution ID conditions when there are none', () => { const sql = getRequestTimelineQuery({ requestIds: ['8f00aa-IAD'], executionIds: [] }) expect(sql).not.toContain('execution_id') }) it('refuses to build an unbounded query', () => { expect(() => getRequestTimelineQuery({ requestIds: [], executionIds: [], nativeRequestIds: [], traceIds: [], }) ).toThrow() }) }) describe('explicit attribute filters', () => { it.each(['status', 'user', 'date', 'request:header', "key' OR 1=1 --", 'attribute.status'])( 'uses the stored %s key in every query surface', (key) => { const filter = logsFiltersToUrlParams([ { column: logAttributeFilterId(key), operator: '<>', value: "quoted'value" }, ]) const search = createUnifiedLogsSearch({ ...baseSearch, filter }) const escapedKey = key.replaceAll("'", "''") for (const sql of [ getUnifiedLogsQuery(search), getLogsCountQuery(search), getLogsChartQuery(search), getFacetCountQuery({ search, facet: 'pathname' }), ]) { expect(sql).toContain(`log_attributes['${escapedKey}'] NOT IN ('quoted''value')`) } expect(() => getUnifiedLogsQueryBQ(search)).toThrow( 'Log attribute filters are only supported on ClickHouse' ) } ) }) describe('Pipelines logs', () => { const pipelineId = '03dg2o5teb2eucxr9ggh3uie6' it.each([ ['list', getUnifiedLogsQuery], ['counts', getLogsCountQuery], ['chart', getLogsChartQuery], ])('uses only pipeline_id_v2 with the same source for the %s', (_, buildQuery) => { const sql = buildQuery(withFilters('log_type:eq:pipelines', `pipeline_id:eq:${pipelineId}`)) expect(sql).toContain("source = 'etl_replication_logs'") expect(sql).toContain("log_attributes['pipeline_id_v2'] IN ('03dg2o5teb2eucxr9ggh3uie6')") expect(sql).not.toContain("log_attributes['pipeline_id']") }) it('limits an identity-only filter to Pipelines logs', () => { const where = getUnifiedLogsQuery(withFilters('pipeline_id:eq:150')).split('WHERE')[1] expect(where).toContain("source = 'etl_replication_logs'") expect(where).not.toContain("source = 'postgres_logs'") expect(where).not.toContain("source = 'edge_logs'") }) it('searches pipeline ID options using the canonical identity without its own active filter', () => { const sql = getFacetCountQuery({ search: withFilters('log_type:eq:pipelines', 'pipeline_id:eq:150'), facet: 'pipeline_id', facetSearch: '03dg', }) expect(sql).toContain("log_attributes['pipeline_id_v2']") expect(sql).toContain("source = 'etl_replication_logs'") expect(sql).toContain("LIKE '%03dg%'") expect(sql).not.toContain("IN ('150')") }) it('returns pipeline ID choices without restricting them to the selected ID', () => { const sql = getLogsCountQuery(withFilters('log_type:eq:pipelines', 'pipeline_id:eq:150')) const pipelineFacet = sql .split(/\bUNION ALL\b/) .find((branch) => branch.includes("facet = 'pipeline_id'")) expect(pipelineFacet).toBeDefined() expect(pipelineFacet).toContain("log_attributes['pipeline_id_v2']") expect(pipelineFacet).toContain("source = 'etl_replication_logs'") expect(pipelineFacet).not.toContain("IN ('150')") }) it('returns BigQuery pipeline ID choices without their own active filter', () => { const sql = getLogsCountQueryBQ(withFilters('log_type:eq:pipelines', 'pipeline_id:eq:150')) const pipelineFacet = sql.split('pipeline_id_count AS (')[1]?.split('\n)')[0] expect(pipelineFacet).toBeDefined() expect(pipelineFacet).toContain("'pipeline_id' as dimension") expect(pipelineFacet).toContain("`log_type` IN ('pipelines')") expect(pipelineFacet).not.toContain("`pipeline_id` IN ('150')") expect(sql).toContain('SELECT dimension, value, count FROM pipeline_id_count') }) it('projects the identity and process metadata without HTTP fields', () => { const sql = getUnifiedLogsQuery(withFilters('log_type:eq:pipelines')) expect(sql).toContain("WHEN source = 'etl_replication_logs' THEN 'pipelines'") expect(sql).toContain('AS pipeline_id') expect(sql).toContain("WHEN source = 'etl_replication_logs' THEN null") expect(sql).toContain("upper(coalesce(nullIf(log_attributes['level'], ''), severity_text))") expect(sql).toContain( "source IN ('function_logs', 'etl_replication_logs'), log_attributes, map()" ) }) it.each([ ['list', getUnifiedLogsQueryBQ], ['counts', getLogsCountQueryBQ], ['chart', getLogsChartQueryBQ], ])( 'reads only pipeline_id_v2 in the BigQuery %s without requiring a schema column', (_, buildQuery) => { const sql = buildQuery(withFilters('log_type:eq:pipelines', `pipeline_id:eq:${pipelineId}`)) expect(sql).toContain('from etl_replication_logs as pl') expect(sql).toContain("json_value(to_json_string(pl), '$.pipeline_id_v2')") expect(sql).not.toContain('cast(pl.pipeline_id as string)') expect(sql).toContain("`pipeline_id` IN ('03dg2o5teb2eucxr9ggh3uie6')") expect(sql).not.toContain('pl.pipeline_id_v2') } ) it.each([getUnifiedLogsQuery, getUnifiedLogsQueryBQ])( 'quotes an opaque identity safely', (buildQuery) => { expect(buildQuery(withFilters("pipeline_id:eq:opaque' OR '1'='1"))).toContain( "'opaque'' OR ''1''=''1'" ) } ) })