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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions docs/features/audit-log.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
title: Audit Log
---

pgconsole emits audit logs as JSON lines to stdout, allowing you to capture and process them with your existing log infrastructure. It also keeps connection-scoped audit entries in memory so admins can inspect recent activity from the `/audit-log` page.
pgconsole emits audit logs as JSON lines to stdout, allowing you to capture and process them with your existing log infrastructure. It also keeps audit entries in memory so they can be inspected from the `/audit-log` page.

## In-App Audit Log

The `/audit-log` page shows SQL execution and data export entries for the selected connection, newest first. Viewing entries requires `admin` permission on that connection.
The `/audit-log` page has two tabs:

- **Connection** — SQL execution and data export entries for the selected connection, newest first. Requires `admin` permission on that connection.
- **System** — instance-level events that aren't tied to a connection (`auth.login` / `auth.logout`), including the auth provider and source IP. Only visible to an instance **owner**, since these events span all users.

Entries are stored in memory only. They are lost when the server restarts. By default, pgconsole retains entries indefinitely while the process is running, so memory usage grows with audit volume. For high-traffic deployments, set `retention_days` to prune older entries:

Expand Down
13 changes: 13 additions & 0 deletions proto/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ service QueryService {
rpc GetActiveSessions(GetActiveSessionsRequest) returns (GetActiveSessionsResponse);
rpc TerminateSession(TerminateSessionRequest) returns (TerminateSessionResponse);
rpc GetAuditLogEntries(GetAuditLogEntriesRequest) returns (GetAuditLogEntriesResponse);
rpc GetSystemAuditLogEntries(GetSystemAuditLogEntriesRequest) returns (GetSystemAuditLogEntriesResponse);
rpc AuditExport(AuditExportRequest) returns (AuditExportResponse);
}

Expand Down Expand Up @@ -356,6 +357,15 @@ message GetAuditLogEntriesResponse {
repeated AuditLogEntry entries = 1;
}

// System-level (non-connection-scoped) audit events, e.g. auth.login / auth.logout.
message GetSystemAuditLogEntriesRequest {
int32 limit = 1;
}

message GetSystemAuditLogEntriesResponse {
repeated AuditLogEntry entries = 1;
}

message AuditLogEntry {
string timestamp = 1;
string actor = 2;
Expand All @@ -371,6 +381,9 @@ message AuditLogEntry {
string source = 12;
string tool = 13;
string agent = 14;
// Auth-event fields (auth.login); blank for other actions.
string provider = 15;
string ip = 16;
}

message AuditExportRequest {
Expand Down
16 changes: 16 additions & 0 deletions server/lib/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,22 @@ export function listAuditEvents(connectionId: string, limit: number): AuditEvent
return entries
}

// System-level audit events — instance-wide auth events not scoped to a connection,
// surfaced in the instance-owner-only "System" tab. Newest first, bounded by limit.
// Match by explicit action (not the absence of a `connection` field) so a future
// connection-less event can't silently leak into the System tab.
export function listSystemAuditEvents(limit: number): AuditEvent[] {
pruneRetainedEvents('all')
const entries: AuditEvent[] = []
for (let i = auditEvents.length - 1; i >= 0 && entries.length < limit; i--) {
const event = auditEvents[i]
if (event.action === 'auth.login' || event.action === 'auth.logout') {
entries.push(event)
}
}
return entries
}

export function clearAuditEventsForTest(): void {
auditEvents.length = 0
}
62 changes: 44 additions & 18 deletions server/services/query-service.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,41 @@
import { ConnectError, Code } from "@connectrpc/connect";
import type { ServiceImpl } from "@connectrpc/connect";
import { QueryService } from "../../src/gen/query_connect";
import { getConnectionById } from "../lib/config";
import { getConnectionById, isOwner } from "../lib/config";
import { createClient, formatAppName, buildConnectionDetails, type ConnectionDetails } from "../lib/db";
import type postgres from "postgres";
import { getUserFromContext } from "../connect";
import { hasPermission, requirePermission, requirePermissions, requireAnyPermission } from "../lib/iam";
import { detectRequiredPermissions } from "../lib/sql-permissions";
import { buildExecutableSql, formatExecutionError } from "../lib/execute-sql";
import { auditSQL, auditExport, listAuditEvents } from "../lib/audit";
import { auditSQL, auditExport, listAuditEvents, listSystemAuditEvents, type AuditEvent } from "../lib/audit";

// Track active queries by queryId -> { pid, connectionDetails, email }
const activeQueries = new Map<string, { pid: number; details: ConnectionDetails; email: string }>();

// Map an in-memory audit event to the wire AuditLogEntry. Fields absent on a given
// event kind map to undefined (numbers, so presence is preserved) or '' (strings).
function toAuditLogEntry(event: AuditEvent) {
return {
timestamp: event.ts,
actor: event.actor,
action: event.action,
connection: 'connection' in event ? event.connection : '',
database: 'database' in event ? event.database : '',
sql: 'sql' in event ? event.sql : '',
success: 'success' in event ? event.success : true,
durationMs: 'duration_ms' in event ? event.duration_ms : undefined,
rowCount: 'row_count' in event && event.row_count !== undefined ? event.row_count : undefined,
error: 'error' in event && event.error ? event.error : '',
format: 'format' in event ? event.format : '',
source: 'source' in event && event.source ? event.source : '',
tool: 'tool' in event && event.tool ? event.tool : '',
agent: 'agent' in event && event.agent ? event.agent : '',
provider: 'provider' in event ? event.provider : '',
ip: 'ip' in event ? event.ip : '',
};
}

function getConnectionDetails(connectionId: string): ConnectionDetails {
const details = buildConnectionDetails(connectionId);
if (!details) {
Expand Down Expand Up @@ -1201,22 +1224,25 @@ export const queryServiceHandlers: ServiceImpl<typeof QueryService> = {
getConnectionDetails(req.connectionId);

const limit = req.limit > 0 ? Math.min(req.limit, 500) : 100;
const entries = listAuditEvents(req.connectionId, limit).map((event) => ({
timestamp: event.ts,
actor: event.actor,
action: event.action,
connection: 'connection' in event ? event.connection : '',
database: 'database' in event ? event.database : '',
sql: 'sql' in event ? event.sql : '',
success: 'success' in event ? event.success : true,
durationMs: 'duration_ms' in event ? event.duration_ms : undefined,
rowCount: 'row_count' in event && event.row_count !== undefined ? event.row_count : undefined,
error: 'error' in event && event.error ? event.error : '',
format: 'format' in event ? event.format : '',
source: 'source' in event && event.source ? event.source : '',
tool: 'tool' in event && event.tool ? event.tool : '',
agent: 'agent' in event && event.agent ? event.agent : '',
}));
const entries = listAuditEvents(req.connectionId, limit).map(toAuditLogEntry);

return { entries };
},

async getSystemAuditLogEntries(req, context) {
// System-level audit (auth.login/logout) is instance-wide, not connection-scoped,
// so it is gated on the instance owner rather than per-connection admin — this avoids
// leaking everyone's login/IP activity to an admin of a single connection.
const user = await getUserFromContext(context.values);
if (!user) {
throw new ConnectError("Authentication required", Code.Unauthenticated);
}
if (!isOwner(user.email)) {
throw new ConnectError("Permission denied: viewing the system audit log requires instance owner", Code.PermissionDenied);
}

const limit = req.limit > 0 ? Math.min(req.limit, 500) : 100;
const entries = listSystemAuditEvents(limit).map(toAuditLogEntry);

return { entries };
},
Expand Down
15 changes: 15 additions & 0 deletions src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const queryKeys = {
functionDependencies: (connectionId: string, schema: string, name: string, args?: string) => [...queryKeys.all, 'functionDependencies', connectionId, schema, name, args] as const,
processes: (connectionId: string) => [...queryKeys.all, 'processes', connectionId] as const,
auditLog: (connectionId: string) => [...queryKeys.all, 'auditLog', connectionId] as const,
systemAuditLog: () => [...queryKeys.all, 'systemAuditLog'] as const,
};

export function invalidateSchemaQueries(qc: QueryClient, connectionId: string) {
Expand Down Expand Up @@ -339,6 +340,20 @@ export function useAuditLogEntries(connectionId: string, enabled = true) {
});
}

// System-level audit entries (auth.login / auth.logout). Owner-gated server-side, so
// only enable the query for instance owners.
export function useSystemAuditLogEntries(enabled = true) {
return useQuery({
queryKey: queryKeys.systemAuditLog(),
queryFn: async () => {
const response = await queryClient.getSystemAuditLogEntries({ limit: 100 });
return response.entries;
},
enabled,
refetchInterval: 5000,
});
}

// Refresh AI schema cache
export function useRefreshSchemaCache() {
return useMutation({
Expand Down
Loading
Loading