Skip to content

Add configurable audit logging - #95355

Open
Libao-Yang wants to merge 114 commits into
ClickHouse:masterfrom
Libao-Yang:support-audit-log
Open

Libao-Yang wants to merge 114 commits into
ClickHouse:masterfrom
Libao-Yang:support-audit-log

Conversation

@Libao-Yang

@Libao-Yang Libao-Yang commented Jan 28, 2026 •

Copy link
Copy Markdown

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add configurable audit logging via logger.auditlog and logger.auditlog_types.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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 by allow_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:

    Type Description
    USER User activity events, including user login and logout (session-level operations)
    DDL Data Definition Language statements such as CREATE, ALTER, DROP, RENAME, ATTACH, DETACH, used to create, modify, or remove database objects (tables, indexes, views, users, roles, etc.)
    DML Data Manipulation Language statements such as SELECT, SHOW, DELETE, UPDATE, INSERT, TRUNCATE, OPTIMIZE, EXPLAIN, used to query or modify data
    DCL Data Control Language statements such as GRANT and REVOKE, related to privilege and access control
    MISC Other system or session-level statements such as SET, USE, SYSTEM, and KILL

    Multiple values can be specified as a comma-separated list.

    <logger>
        <auditlog_types>DDL,DCL</auditlog_types>
    </logger>
    

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:

timestamp [ thread_id ] {query_id} <Notice> AUDIT: ...
Log Entries Format

The current audit logging implementation is based on existing system logs:

  • session_log — audits USER-related activities
  • query_log — audits SQL statements (DDL, DML, DCL, and MISC)
USER Audit Log

USER audit logs record user activity events such as login, logout, and authentication failures.

  • Format: TYPE, USER_NAME, IP_ADDRESS, ACTIVITY

    Example:

    User, default, ::ffff:127.0.0.1, LoginSuccess
    
  • Fields

    Field Description
    TYPE Audit type. Always User for user activity events
    USER_NAME Name of the database user
    IP_ADDRESS IP address used for login or logout
    ACTIVITY User activity type
  • Possible values for ACTIVITY field:

    Value Description
    LoginSuccess User successfully logged in
    LoginFailure User login failed
    Logout User logged out
SQL 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, QUERY

    Example:

    DML, Select, 0, user1, ::ffff:127.0.0.1, test.t, select id from test.t
    
  • Fields

    Field Description
    TYPE Audit type: DML, DDL, DCL, or MISC
    COMMAND SQL command type, such as Select, Insert, Create, etc.
    EXCEPTION_CODE Execution result of the SQL statement. 0 indicates success; non-zero values represent ClickHouse error codes
    USER_NAME Name of the user executing the SQL statement
    CLIENT_IP IP address of the client issuing the SQL statement
    OBJECT_NAMES Names of database objects involved in the statement (e.g., db.table). Applicable to DML and DDL statements
    QUERY Executed SQL statement. The query text may be truncated, consistent with query_log, and is controlled by the log_queries_cut_to_length setting

Example use

Configuration example:

<allow_experimental_audit_log>true</allow_experimental_audit_log>

<logger>
    <auditlog>/var/log/clickhouse-server/clickhouse-server.audit.log</auditlog>
    <auditlog_types>USER,DDL,DCL</auditlog_types>
</logger>

The audit log file content in /var/log/clickhouse-server/clickhouse-server.audit.log:

2026.01.28 17:12:11.510430 [ 711963 ] {} <Notice> AUDIT: User, default, 127.0.0.1, LoginSuccess
2026.01.28 17:12:25.032659 [ 711963 ] {e79d8fb3-a2b3-4af9-baec-5da73004ed29} <Notice> AUDIT: DML, Select, 0, default, 127.0.0.1, system.build_options, SELECT * FROM system.build_options
2026.01.28 17:12:31.583912 [ 711963 ] {} <Notice> AUDIT: User, default, 127.0.0.1, Logout

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, and logger.auditlog_types, writing Notice-level messages to a dedicated AUDIT logger/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() in executeQuery) and for login/logout/auth failures (Session), and routes AUDIT-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 invalid auditlog_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]

@CLAassistant

CLAassistant commented Jan 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@UnamedRus

Copy link
Copy Markdown
Contributor

ClickHouse loggers also support JSON format for it's logs. May be make sense to have it's support for audit log as well?

@Libao-Yang

Copy link
Copy Markdown
Author

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 errorlog and console), by adding a dedicated channel to the logger.
Therefore, it already supports JSON output when logger.formatting.type = json is enabled.

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 config.xml to clarify this.

@Fgrtue Fgrtue added the can be tested Allows running workflows for external contributors label Jan 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6038c6c]

Summary: ✅


AI Review

Summary

Reviewed PR #95355 at 6038c6c30a32c71bff79e44b432068f512e62f28. It adds experimental audit logging for authentication events and SQL statements, with category filtering, runtime configuration, and a dedicated synchronous writer. The current code addresses the prior findings, including discarded asynchronous inserts, native query-plan cache eligibility, early MySQL handshake rejections, and cancellation query IDs. No remaining actionable findings were identified. The current CI reports 15,345 passed tests and zero failures; no local build or tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jan 28, 2026
@zhangjmruc
zhangjmruc force-pushed the support-audit-log branch 3 times, most recently from 9d37841 to cc92dea Compare March 2, 2026 07:00
Comment thread src/Interpreters/Session.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/Session.cpp Resolved
Comment thread programs/server/Server.cpp Resolved

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Submitting stale pending review to unblock fresh inline comments.

Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Common/Logger.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
@zhangjmruc
zhangjmruc force-pushed the support-audit-log branch 2 times, most recently from d3fe2f4 to f024c91 Compare April 2, 2026 10:39
Comment thread src/Loggers/Loggers.h Resolved
alexey-milovidov and others added 4 commits October 9, 2026 13:21
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]>
alexey-milovidov and others added 5 commits October 17, 2026 18:48
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
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed b1723e0fb93..da04100fd8f (2 commits):

  • Merged master to resolve the conflict in src/Common/ErrorCodes.cpp: master took code 1025 for GPU_ERROR, so UNEXPECTED_AUDIT_TYPE is now 1026.
  • Fixed the broken_links style check: the config.xml comment linked to https://clickhouse.com/docs/operations/audit-log, but that page only exists once this PR is merged. The comment now points to the "Audit log" guide in the docs without a URL.

clickhouse builds locally after the merge.

Comment thread src/Loggers/AuditLog.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 4 commits October 28, 2026 02:30
# 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]>
@mintlify

mintlify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 6038c6c.

Approve preview

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
wilkermichael pushed a commit to Shopify/ClickHouse that referenced this pull request Nov 3, 2026
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]>
alexey-milovidov and others added 2 commits November 5, 2026 08:51
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]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 2 commits November 14, 2026 16:54
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]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Server/MySQLHandler.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 3 commits November 23, 2026 16:20
# 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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants