Skip to content

Add totp_track_used_codes_in_keeper server setting: single use of TOTP codes across the cluster - #125664

Merged
vdimir merged 4 commits into
masterfrom
vdimir/totp-strict-mode
Nov 3, 2026
Merged

vdimir merged 4 commits into
masterfrom
vdimir/totp-strict-mode

Conversation

@vdimir

@vdimir vdimir commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Related: #117563

Follow-up to #117563, which made each code of a time-based one-time password accepted at most once per server. The used codes were tracked in process memory, so in a cluster a code accepted by one replica could still be replayed once on every other replica, and again on the same server after a restart.

The new server setting totp_track_used_codes_in_keeper (default false) tracks the accepted codes in Keeper under /clickhouse/access/one_time_passwords (configurable with totp_used_codes_keeper_path): one persistent node per user, named by the SHA-256 hash of the user name, holding the start timestamp of the last accepted time step and advanced with compare-and-set. A code accepted by one server is then rejected by all servers sharing that Keeper, and the record survives restarts. The setting requires a <zookeeper> section (the server refuses to start otherwise), and while Keeper is unavailable, authentication with a one-time password fails instead of falling back to per-server tracking. Keeper holds no secrets and no user names, only hashes and timestamps; an administrator can reset a user by deleting its node, and the node count is bounded by the number of TOTP users, so no TTL or cleanup is needed.

The tracking moves from a static in OneTimePassword.cpp into OneTimePasswordUsageTracker, owned by AccessControl. The code is consumed in AccessControl::authenticate once the whole authentication succeeded, so the access storages stay pure verifiers and a failed attempt still cannot burn a valid code. Entries, local and in Keeper, are keyed by user and store the start of the time step rather than its number, so a change of period cannot lock a user out.

tests/integration/test_totp_auth gets two Keeper-backed servers with the setting enabled and a test that covers: a failed attempt does not consume the code, the code is rejected on the other server and on the same one, an earlier time step is rejected everywhere, the next time step is accepted once, the state survives a restart, and the Keeper node is named hex(SHA256(user)).

Changelog category (leave one):

  • Improvement

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

Added the server setting totp_track_used_codes_in_keeper. When enabled, codes of time-based one-time passwords are accepted at most once across all servers that share the same ZooKeeper or ClickHouse Keeper (previously, at most once per server), and the record of used codes survives server restarts. The accepted codes are tracked in Keeper under the path set by totp_used_codes_keeper_path (default /clickhouse/access/one_time_passwords); while Keeper is unavailable, authentication with a one-time password fails.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/125664]

Version info

  • Merged into: 26.11.1.1238-master (included in 26.11 and later)

@mintlify

mintlify Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 2, 2026, 6:48 PM

@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2aff068]

Summary: ✅


AI Review

Summary

Adds opt-in Keeper-backed tracking of accepted TOTP time steps, enforcing single use across servers and preserving usage records across restarts. Review of head 2aff068415134783a8415840ad2d00656cbf7d89 still requires changes: the concurrent-consumption and Keeper-outage guarantees lack focused regression coverage.

Findings

⚠️ Majors

  • tests/integration/test_totp_auth/test_totp.py:633: The cluster-wide single-use and fail-closed authentication contracts remain untested. Every login is sequential and Keeper stays available, so these assertions would still pass with an unconditional trySet that permits concurrent replay, or with local-only acceptance during an outage. This is the existing, unresolved review finding; no duplicate inline comment was posted.
Tests
  • ⚠️ Reuse the existing cluster for overlapping logins on both servers with the same unused code, asserting exactly one succeeds. Ensure the case exercises competing updates to an existing usage node.
  • ⚠️ Partition a server from Keeper and attempt authentication with a valid, unused code; require rejection, then restore connectivity and verify authentication recovers with a valid code.
Final Verdict

Status: ⚠️ Request changes. Add the two focused tests above to establish the security guarantees promised by totp_track_used_codes_in_keeper.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-authentication Identity verification: users, credentials, auth methods, external auth providers. label Oct 13, 2026
auto component_guard = Coordination::setCurrentComponent("OneTimePasswordUsageTracker::tryConsumeInKeeper");

/// The node is named by a hash of the user name, so that Keeper (and its snapshots and logs) hold no user names.
const auto user_name_digest = AuthenticationData::Util::encodeSHA256(user_name);

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.

This keys the durable usage record by user_name, not by the TOTP secret. Before this PR, the in-memory single-use state was keyed by the secret and its parameters, so the same OTP could not be replayed through a second account that happened to share that secret. With this change, user_a and user_b get independent slots/nodes, so the same code can be accepted once per user. Since ClickHouse does not enforce TOTP-secret uniqueness across users, this weakens the existing single-use guarantee; the key needs to identify the TOTP secret (or another stable secret-specific identifier), not only the user name.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Per user, as long as every user has its own secret, which is what RFC 6238 assumes.

  • The RFC has no accounts. Section 5.2 states single use per prover ("a prover may send the same OTP inside a given time-step window multiple times to a verifier. The verifier MUST NOT accept the second attempt of the OTP ..."), R1 names the token as the prover, and R5 says "There MUST be a unique secret (key) for each prover", so a secret identifies exactly one prover.
  • A ClickHouse user has at most one TOTP secret (time_based_one_time_password is user level only, UsersConfigParser.cpp), and the documented recipe (base32 -w32 < /dev/urandom) makes a random 160-bit one. With distinct secrets, per user and per secret behave identically.
  • They differ only when several users are given the same secret, which ClickHouse does not reject (normalizeOneTimePasswordSecret only checks the alphabet and non-emptiness). That is the case above: the code is accepted once per user, and since TOTP is a second factor, using it for user_b also needs the password of user_b.

Per secret would close that case, but in strict mode the node name would then be derived from the secret: an unsalted SHA-256 of a short secret can be brute forced offline by anyone who can read Keeper (salting it with the user name makes it per user again), and every rotated secret leaves a node that nothing removes, so the node count is no longer bounded by the number of users.

I would keep per user and add one line to the docs that each user needs its own secret (R5).

}
}

/// The local entries are only a cache of the accepts done by this server: they are sound as a pre-filter

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.

This fast path is only sound if the Keeper value never decreases, but the design here also exposes deleting the Keeper node as the way to reset a user. After an operator removes that node, a server that still has a cached last_accepted[user] rejects the OTP locally and never re-reads Keeper, so the reset does not take effect until the cache entry expires. Because future-step codes are accepted, that stale entry can survive for almost 3 * period (up to 360 seconds with the allowed max period). Either strict mode needs to bypass/revalidate local negative hits after external resets, or the reset-by-deletion behavior is not actually implemented.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We do not plan to support manual deletion of keeper nodes.

vdimir and others added 2 commits October 14, 2026 09:45
Each code of a time-based one-time password is accepted at most once
per server since #117563, but the used codes were tracked in process
memory, so a code could still be replayed once on every other replica
and again after a restart.

With the new server setting `totp_strict_mode` the accepted codes are
tracked in Keeper under `/clickhouse/access/one_time_passwords`: one
node per user, named by the SHA-256 hash of the user name, holding the
start of the last accepted time step and advanced with compare-and-set.
A code accepted by one server is then rejected by all servers sharing
that Keeper and after restarts. Keeper must be configured; while it is
unavailable, authentication with a one-time password fails.

The tracking moves from a static in `OneTimePassword.cpp` into
`OneTimePasswordUsageTracker`, owned by `AccessControl`, and the code is
now consumed in `AccessControl::authenticate` once the whole
authentication succeeded, so the storages stay pure verifiers. The
per-server map is kept for the default mode and as a pre-filter in
strict mode. The entries are keyed by user and store the start of the
time step rather than its number, so a change of `period` cannot lock a
user out.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
)

# The code for the next time step is accepted once, on another server
assert f"{user}42\n" == node2.query(

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.

⚠️ Major: cover concurrent consumption and Keeper unavailability

The strict-mode contract includes single use during concurrent logins and rejection when Keeper is unavailable, but every login in this test is sequential and Keeper stays healthy. In particular, replacing the versioned trySet with an unconditional write would still pass these assertions, although two servers could then accept the same code after reading the same previous timestamp. The test also would not detect a fallback to local tracking during an outage.

Please reuse this cluster for two focused cases: overlapping logins on both servers with the same next-step code, asserting exactly one succeeds, and a Keeper partition while presenting a valid, unused code, asserting authentication fails and resumes with a valid code after connectivity is restored. Both security properties need regression coverage before enabling this mode.

@antonio2368

Copy link
Copy Markdown
Member

@vdimir can you resolve conflicts here and I will review the code.

@vdimir

vdimir commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

@antonio2368 Done, conflicts are resolved and master is merged in (6f086a8). Ready for review.

Comment thread src/Core/ServerSettings.cpp Outdated
DECLARE(UInt64, dictionary_background_reconnect_interval, 1000, "Interval in milliseconds for reconnection attempts of failed MySQL and Postgres dictionaries having `background_reconnect` enabled.", 0) \
DECLARE(Bool, show_addresses_in_stack_traces, true, R"(If it is set true will show addresses in stack traces)", 0) \
DECLARE(Bool, shutdown_wait_unfinished_queries, false, R"(If set true ClickHouse will wait for running queries finish before shutdown.)", 0) \
DECLARE(Bool, totp_strict_mode, false, R"(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not sure if strict_mode is a good name. It doesn't tell me that it's shared between Keepers IMO. Maybe make it more descriptive?

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2aff06841 with master f16078f16 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 55e1ca2ea; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

37 object files changed (+182.07 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Access/OneTimePasswordUsageTracker.cpp.o new 180.97 KiB +180.97 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

152 translation units recompiled, 1028 s compile time in total, 150 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.2 s
  • src/Access/OneTimePasswordUsageTracker.cpp: 5.6 s

Job report

The setting enables tracking of accepted TOTP codes in Keeper, shared by
all servers using the same Keeper and surviving restarts. "Strict mode"
did not say that; the new name describes the storage, like the existing
`allow_kafka_offsets_storage_in_keeper` and `series_keeper_path`.
`totp_strict_mode_keeper_path` becomes `totp_used_codes_keeper_path`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vdimir vdimir changed the title Add totp_strict_mode server setting: single use of TOTP codes across the cluster Add totp_track_used_codes_in_keeper server setting: single use of TOTP codes across the cluster Nov 2, 2026
@vdimir
vdimir added this pull request to the merge queue Nov 3, 2026
Merged via the queue into master with commit 2bb0a15 Nov 3, 2026
354 of 355 checks passed
@vdimir
vdimir deleted the vdimir/totp-strict-mode branch November 3, 2026 18:24
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 2aff0684 Deployed Nov 2, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-authentication Identity verification: users, credentials, auth methods, external auth providers. pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants