Repository navigation
Add configurable audit logging - #95355
Libao-Yang wants to merge 114 commits into
Conversation
|
ClickHouse loggers also support JSON format for it's logs. May be make sense to have it's support for audit log as well? |
Thanks for the suggestion. The audit log is implemented in the same way as other log channels (such as For example: <logger>
<formatting>
<type>json</type>
<channel>auditlog</channel>
<names>
<date_time>date_time</date_time>
<date_time_utc>date_time_utc</date_time_utc>
<thread_name>thread_name</thread_name>
<thread_id>thread_id</thread_id>
<level>level</level>
<query_id>query_id</query_id>
<logger_name>logger_name</logger_name>
<message>message</message>
<source_file>source_file</source_file>
<source_line>source_line</source_line>
</names>
</formatting>
</logger>This produces audit log entries in JSON format, for example: {"date_time_utc":"2026-01-28T10:09:56Z","date_time":"1769594996.240493","thread_name":"TCPServerConnection ([#1])","thread_id":"753159","level":"Notice","query_id":"","logger_name":"AUDIT","message":"User, default, 127.0.0.1, LoginSuccess","source_file":"src/Interpreters/Session.cpp; void DB::Session::recordLoginSuccess(ContextPtr) const","source_line":"766"}
{"date_time_utc":"2026-01-28T10:09:56Z","date_time":"1769594996.242095","thread_name":"TCPServerConnection ([#1])","thread_id":"753159","level":"Notice","query_id":"02674082-f925-4b5f-96b9-241663719fe6","logger_name":"AUDIT","message":"DML, Select, 0, default, 127.0.0.1, system.one, select 1;","source_file":"src/Interpreters/executeQuery.cpp; void DB::auditLog(const QueryLogElement &, const ContextPtr)","source_line":"1062"}You are right that this was not mentioned in the configuration documentation. I will add a note to |
|
Workflow [PR], commit [6038c6c] Summary: ✅
AI ReviewSummaryReviewed PR #95355 at Final VerdictStatus: ✅ Approve |
ab72046 to
b0f0e8a
Compare
9d37841 to
cc92dea
Compare
cc92dea to
1a2c01f
Compare
1a2c01f to
0a00998
Compare
7c9c69d to
ac6ac54
Compare
d3fe2f4 to
f024c91
Compare
Conflicts: renumbered `UNEXPECTED_AUDIT_TYPE` to 1023 since master took 1021/1022; kept the `audit` capture/argument in the exception callback together with master's new `query_pipeline` parameter.
`CREATE TOKEN` reports `QueryKind::Create` but adds an authentication method to the current user, so it is an access-control statement. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…erts With `wait_for_async_insert = 0` the original `INSERT` is audited when the data is queued, so a failed flush left only a successful record. Audit the flush itself in that case so the audit trail reflects whether the rows were written. The setting is part of the batching key, so the whole batch shares it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ert flush Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict resolutions: - `ErrorCodes.cpp`: master took 1023 and 1024, so `UNEXPECTED_AUDIT_TYPE` moves to 1025. - `InterpreterExecuteAsQuery`, `InterpreterParallelWithQuery`: keep master's new `parse_server_owned_query_without_limits` flag and add `audit_internal`. - `DistributedPlanExecutor`: `query_plan_hash` is now computed earlier on master. - `TCPHandler`: master removed the up-front authentication-type check of the SSH handshake (user enumeration oracle); keep that removal and keep the audit try/catch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The deferred flush of an async insert reports the query kind `AsyncInsertFlush`, not `Insert`, so `test_audit_log_fire_and_forget_async_insert_flush_failure` never found the audit record of the failed flush. Match the right kind and give slow (sanitizer) builds more time to write the record. `test_audit_log_reload_records_the_statement_that_disables_its_own_type` failed with TSan: the periodic config reload could apply the edited config before the `SYSTEM RELOAD CONFIG` whose own audit record is checked is admitted. Disable the periodic reload on that node; all its tests reload the config explicitly. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95355&sha=8f3bfa06872d8765f1b68c62de36460d9783a054&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%20targeted%29 ClickHouse#95355 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lush The decision whether the flush of a fire-and-forget (`wait_for_async_insert = 0`) async insert writes its own audit record is now taken when the insert is queued, from the audit policy in effect then, and kept in the batching key, so a `SYSTEM RELOAD CONFIG` between enqueue and flush neither drops nor adds the record, and inserts with different decisions are not coalesced. A flush that fails before its query logging is set up (shutdown, an expired authentication method, a user that can no longer be restored) is now audited too, so the audit trail does not show only the successful enqueue of the `INSERT`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Common/ErrorCodes.cpp
The `broken_links` style check rejects `https://clickhouse.com/docs/operations/audit-log` because the page is only added by this pull request. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95355&sha=b1723e0fb93d8a4e45d2b0da46c7188bacb7bf65&name_0=PR&name_1=Style%20check ClickHouse#95355 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed
|
# Conflicts: # src/Interpreters/executeQuery.cpp # src/QueryPipeline/DistributedPlanExecutor.cpp # src/Server/MySQLHandler.cpp
The formatter writes the query ID verbatim into the prefix of each audit record. A native client can send a query ID with `CR`/`LF`, which would split the record and let it forge a separate audit line. Escape it with `escapeForAuditField` like the other free-form fields. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`BlockIO::onCancelOrConnectionLoss` resets the pipeline without running the finish or exception callbacks. Arrow Flight uses it for `CancelFlightInfo` and expired poll descriptors, so a query that had already returned rows left no audit record. Add `BlockIO::cancel_callbacks`, which run only on that path (they are dropped by `onFinish` and `onException`), and register one in `executeQuery` that writes the audit record with `QUERY_WAS_CANCELLED`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An entry that fails parsing (`processEntriesWithParsing`) or conversion (`processPreprocessedEntries`) is isolated from the batch, so the flush itself succeeds, possibly with zero rows, and only the successful flush was audited. Write an audit record with the error code of each such entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
For `LocalConnection` (interactive `clickhouse-local`) the whole suggestion
query runs in-process in `Suggest::loading_thread`: analyzer, planner, and the
regexp JIT that `extractAll(word, '[\\w_]{2,}')` triggers during header
evaluation. The thread was a plain `std::thread`, which macOS gives a 512 KiB
stack, and LLVM codegen does not cooperate with `checkStackSize`, so it ran
into the guard page (`EXC_BAD_ACCESS "Thread stack size exceeded"` in thread
`Suggest`). This killed the `clickhouse-local` under test in
`Fast test (arm_darwin)` for `05024_local_listener_survives_handler_exception`
(curl rc 56) and `04892_client_dialect_command` (`spawn id not open`) on
PRs ClickHouse#95355, ClickHouse#88234, ClickHouse#117004 and ClickHouse#117636: 26 of 26 macOS crash reports of those
jobs show this stack.
ClickHouse#107033 gave the global thread pool and the server pools
`DEFAULT_THREAD_STACK_SIZE` via `ThreadWithStackSize`, and 3510173 did
the same for the `clickhouse-local` listener pool; the suggestion loader was
missed. Use `ThreadWithStackSize` for it on Darwin; other platforms keep
`std::thread`, whose default stack follows `RLIMIT_STACK`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve conflict in `src/Common/ErrorCodes.cpp`: master took error code 1026 for `ICEBERG_CATALOG_CONCURRENT_UPDATE`, so `UNEXPECTED_AUDIT_TYPE` moves to 1027.
…ibling fails When a statement of `PARALLEL WITH` throws before `executeCombinedPipeline`, the `BlockIO` of statements that already returned a pipeline (e.g. `CREATE TABLE ... AS SELECT`, which publishes the table first) was destroyed without its finish, exception or cancellation callbacks, so the audit log had no record of the created table. Now the workers are joined and those statements are reported through `onException`. Add `test_audit_log_parallel_with_prepared_statement_of_failed_query`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict resolutions: - `ErrorCodes.cpp`: master took 1027 for `AMBER_ERROR`; `UNEXPECTED_AUDIT_TYPE` moves to 1028. - `logQueryException` / `logExceptionBeforeStart`: keep both the `audit` parameter and master's quota-charging parameter (`audit` first, the quota flag keeps its default). - `AsynchronousInsertQueue::InsertQuery`: keep both `audit_flush` and master's quota address/hash fields. - `executeQueryImpl`: keep both the audit cancel callback and master's quota cancel callback. - `BlockIO::onCancelOrConnectionLoss`: take the cancel callbacks out first (so they run at most once), but invoke them after the pipeline is stopped, as master requires for the quota accounting.
…sync insert entry errors, fix early flush failures - A query plan received from a native client (`QueryProcessingStage::QueryPlan`) has no AST. `logQueryStart` logs it as `Select`, but `decideAuditLog` classified it as `MISC`, so with `auditlog_types = DML` the read was not audited, and with `MISC` alone it produced a `DML` record. The kind of a query without an AST is now passed to `decideAuditLog` and `logExceptionBeforeStart`, so the decision and the record agree. - An entry of an asynchronous insert batch that fails on its own is now audited with the query ID and the client address of the request that submitted it (kept in the entry only when the flush is audited), instead of the ID of the flush and `Unknown Host`. `AuditLog::write` accepts the query ID to put in the record prefix. - `InsertData::flush_outcome_audited` is set only after `logExceptionBeforeStart` / `logQueryException` has recorded the outcome of the flush, so a failure in the allocations before the audited `try` (e.g. `MEMORY_LIMIT_EXCEEDED` in `log_elements.reserve`) is still audited by `auditFlushFailureBeforeStartSafe`. Fix `test_audit_log_parallel_with_prepared_statement_of_failed_query`: master now populates `CREATE TABLE ... AS SELECT` in databases with UUIDs inside the interpreter and publishes the table afterwards, so it returns no pipeline and really succeeds before the sibling `DROP` fails. Run the test in a `Memory` database, which still takes the lazy fill path. Extend the mixed-batch async insert test to check the query ID and address of the failed entry. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95355&sha=ae72205aca67a6ee02608f6891537afdff7ad14d&name_0=PR PR: ClickHouse#95355 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Interpreters/AsynchronousInsertQueue.cpp # src/Interpreters/AsynchronousInsertQueue.h # src/Interpreters/executeQuery.cpp
Remove the duplicate include of `ASTExecuteAsQuery.h` from `executeQuery.cpp` (it failed the `readability-duplicate-include` check of clang-tidy) and the declaration of the `snappy_mode` setting in `AsynchronousInsertQueue.cpp`, which is not used there after the merge. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=95355&sha=b084b3edd7706c7fb28566f33df599910ccc5f78&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29 PR: ClickHouse#95355 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ons, keep the query ID of cancelled queries - Fire-and-forget asynchronous inserts that are discarded without a flush (a graceful shutdown with `async_insert_queue_flush_on_shutdown = 0`, or a flush that cannot be scheduled on the pool) now get an audit record per entry, under the query ID and the address of the request that queued it (`AsynchronousInsertQueue::auditDiscardedEntriesSafe`). - A MySQL connection rejected right after the handshake response (missing `CLIENT_PROTOCOL_41`, or plaintext with `mysql_require_secure_transport`) is recorded as `LoginFailure`. - `auditLog` identifies the query by `elem.client_info.current_query_id` when no ID is passed, so a record written by another thread (a cancellation callback of Arrow Flight) carries the ID of the cancelled query. - Do not dereference a null AST when checking whether the query result cache can be used: a query plan received from a native client has no AST. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add configurable audit logging via
logger.auditlogandlogger.auditlog_types.Documentation entry for user-facing changes
Motivation
Audit logging enables administrators to track user activities and SQL statement execution in ClickHouse. This is useful for security auditing, incident investigation, and compliance scenarios by providing a dedicated audit trail for sensitive operations.
Parameters
The following settings are added under the
<logger>section (Core implementation looks coherent and guarded byallow_experimental_audit_log):logger.auditlog: Specifies the file path where audit log records are written.logger.auditlog_types: Specifies which categories of statements are recorded in the audit log.Supported values:
USERDDLCREATE,ALTER,DROP,RENAME,ATTACH,DETACH, used to create, modify, or remove database objects (tables, indexes, views, users, roles, etc.)DMLSELECT,SHOW,DELETE,UPDATE,INSERT,TRUNCATE,OPTIMIZE,EXPLAIN, used to query or modify dataDCLGRANTandREVOKE, related to privilege and access controlMISCSET,USE,SYSTEM, andKILLMultiple values can be specified as a comma-separated list.
Audit Log Format
Log Prefix Format
The audit log follows the same logging mechanism as standard ClickHouse logs. Each audit log entry is prefixed with common log metadata, in the following format:
Log Entries Format
The current audit logging implementation is based on existing system logs:
session_log— auditsUSER-related activitiesquery_log— audits SQL statements (DDL,DML,DCL, andMISC)USER Audit Log
USER audit logs record user activity events such as login, logout, and authentication failures.
Format:
TYPE, USER_NAME, IP_ADDRESS, ACTIVITYExample:
Fields
TYPEUserfor user activity eventsUSER_NAMEIP_ADDRESSACTIVITYPossible values for
ACTIVITYfield:LoginSuccessLoginFailureLogoutSQL Audit Log
SQL audit logs record execution of SQL statements, including both successful and failed queries.
Format:
TYPE, COMMAND, EXCEPTION_CODE, USER_NAME, CLIENT_IP, OBJECT_NAMES, QUERYExample:
Fields
TYPEDML,DDL,DCL, orMISCCOMMANDSelect,Insert,Create, etc.EXCEPTION_CODE0indicates success; non-zero values represent ClickHouse error codesUSER_NAMECLIENT_IPOBJECT_NAMESdb.table). Applicable to DML and DDL statementsQUERYquery_log, and is controlled by thelog_queries_cut_to_lengthsettingExample use
Configuration example:
The audit log file content in
/var/log/clickhouse-server/clickhouse-server.audit.log:Note
Medium Risk
Adds a new audit logging path integrated into core query execution, session authentication, and the logging pipeline; misconfiguration or filtering logic bugs could drop or misroute logs and slightly impact performance.
Overview
Adds an experimental audit logging facility controlled by
allow_experimental_audit_log,logger.auditlog, andlogger.auditlog_types, writing Notice-level messages to a dedicatedAUDITlogger/channel.The server now parses and hot-reloads enabled audit categories (USER/DDL/DML/DCL/MISC/ALL), emits audit records for query completion/failures (
auditLog()inexecuteQuery) and for login/logout/auth failures (Session), and routesAUDIT-sourced messages exclusively to the new audit file channel with separate async logging profile counters.Includes integration tests and sample configs validating type filtering and object-name capture, plus a new error code (
UNEXPECTED_AUDIT_TYPE) for invalidauditlog_types.Reviewed by Cursor Bugbot for commit bdcbc3e. Bugbot is set up for automated code reviews on this repo. Configure here.
Workflow [PR]
Sync PR [sync-upstream/pr/95355]