From aee964781a367008346c4b0bf82c72c55667cd72 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 22:19:53 +0000 Subject: [PATCH 01/28] Log TURN credential requests under their own turn module (ADR-0871) GET /voip/turnServer logged through the client_server wrapper, so its one diagnostic could only be raised or silenced with every other client-server line, and an issued credential was not logged at all. The route now logs through log_turn_diagnostic under the turn module, set with log_modules.turn: - turn.credentials_issued (info): user_id, credential (static or shared_secret), ttl_seconds and uri_count - turn.credentials_unavailable (error): now also names the user - turn.not_configured (debug): the answer was {} The username, the password and the shared secret are never logged. Four integration scenarios prove the lines are filed under turn (with client_server silenced), that log_modules.turn filters them, and that no credential reaches the log for either kind of credential. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + ...equests-log-under-their-own-turn-module.md | 54 +++++ docs/adr/index.md | 1 + docs/log-filtering.md | 1 + docs/observability-audit.md | 9 + docs/user-manual.md | 5 +- src/homeserver/AGENTS.md | 2 +- src/homeserver/ClientServerRuntime.cpp | 33 ++- .../test_turn_shared_secret_flow.cpp | 210 ++++++++++++++++++ 9 files changed, 311 insertions(+), 6 deletions(-) create mode 100644 docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7808725d9..d8192de85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) which `/versions` lists (ADR-0865). * The account_data extension follows its `lists` and `rooms` scope, whatever the user's membership; receipts send a room's initial receipts on entering scope and those on a new timeline (MSC4548, MSC4551, ADR-0865). +* `GET /voip/turnServer` logs under its own `turn` module, set with `log_modules.turn`: credentials issued (info), + unavailable (error) and no TURN configured (debug), with the user ID and never a credential (ADR-0871). ## Security Fixes diff --git a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md new file mode 100644 index 000000000..f48979457 --- /dev/null +++ b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md @@ -0,0 +1,54 @@ +# TURN credential requests log under their own `turn` module, and never log a credential + +* Status: accepted +* Date: 2026-11-20 + +## Context and Problem Statement + +`GET /_matrix/client/v3/voip/turnServer` is handled inline in `ClientServerRuntime.cpp`, whose file-local +`log_diagnostic` wrapper files every line under the `client_server` module. Its one diagnostic, +`turn.credentials_unavailable`, could therefore be raised or silenced only together with every other client-server +line, and an issued credential was not logged at all. An operator debugging calls ("why does this client get no +relay?") had nothing to filter on. LiveKit already has its own `livekit` module (`log_modules.livekit`). + +## Decision Drivers + +* An operator must be able to turn TURN logging up or down without touching `client_server`. +* The answer holds a working credential: the username (`:` with a shared secret, or the static one) + and the password. Neither may reach a log, and the shared secret never leaves the request's `SecretBuffer` + (ADR-0480). + +## Considered Options + +* Keep the lines under `client_server` and add an issued line there. +* Log the route under a `turn` module through its own wrapper, `log_turn_diagnostic`. +* Move the whole route out of `ClientServerRuntime.cpp` into a TURN service file with its own module constant. + +## Decision Outcome + +Chosen option: "a `turn` module through `log_turn_diagnostic`". The route logs `turn.credentials_issued` (info), +`turn.credentials_unavailable` (error) and `turn.not_configured` (debug), each with `user_id`; the issued line adds +`credential` (`static` or `shared_secret`), `ttl_seconds` and `uri_count`. The username, the password and the shared +secret are never fields of any line. Moving the route out of `ClientServerRuntime.cpp` was not needed to get a module +of its own and would have moved forty lines of unrelated JSON building with it. + +### Positive Consequences + +* `log_modules.turn=debug` shows every TURN request; `log_modules.turn=warning` hides the per-request info line. +* The logging tests run with `client_server` silenced, so a line moved back under `client_server` fails them. + +### Negative Consequences + +* An issued credential is one info line per request at the default level. Clients ask again before the ttl ends, so + this is one line per client per ttl, not per call; an operator who finds it loud sets `log_modules.turn=warning`. +* Changing the module of `turn.credentials_unavailable` means a filter on `client_server` no longer sees it. + +## Rules for future code + +* A new diagnostic of `GET /voip/turnServer` goes through `log_turn_diagnostic`, never the `client_server` wrapper. +* Never add the username or the password as a field, even at debug or trace level: the username is half of a working + credential and, with a shared secret, names the user and the expiry the MAC covers. + +## Links + +* Refines [ADR-0480](0480-turn-credentials-come-from-a-coturn-shared-secret-file-through-an-openssl-hmac-sha1.md) diff --git a/docs/adr/index.md b/docs/adr/index.md index 157616603..cb97d9738 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -744,3 +744,4 @@ * [0868 - The typing and receipts extensions keep their event wrapper](0868-the-typing-and-receipts-extensions-keep-their-event-wrapper.md) * [0869 - A sliding sync long poll wakes only for what its response sends, and a room is sent again when its summary changes](0869-a-sliding-sync-long-poll-wakes-only-for-what-its-response-sends.md) * [0870 - A ranges algorithm takes a typed value, never a bare string literal](0870-a-ranges-algorithm-takes-a-typed-value-never-a-bare-string-literal.md) +* [0871 - TURN credential requests log under their own `turn` module, and never log a credential](0871-turn-credential-requests-log-under-their-own-turn-module.md) diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 9249a455a..87b1d8dea 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -133,6 +133,7 @@ used as the first argument to `observability::log_diagnostic` and `log_diagnosti | `stream_token_epoch` | The database's sync token epoch: created at first start, replaced by `--after-restore`, or refused | | `tls` | TLS context set-up and handshake accept or reject | | `oauth` | OAuth 2.0 client registration, eviction at the cap, and stored metadata that no longer validates | +| `turn` | `GET /voip/turnServer` (ADR-0871): `turn.credentials_issued` (info, with `credential` `static` or `shared_secret`, `ttl_seconds` and `uri_count`), `turn.credentials_unavailable` (error: the shared secret file is unreadable or empty) and `turn.not_configured` (debug: the answer was `{}`). Each names the user; never the username, the password or the shared secret | | `delayed_events` | Delayed events: scheduled, restarted, cancelled, sent, failed, a failed outcome write and a failed prune; never event content or a state key. The count of rows skipped at load is a start-up warning from the process entry point, not this module | | `livekit` | The built-in LiveKit token service: a token issued or refused, to a local user, to another server's user, or relayed from another server; a failed `CreateRoom` call and an unreadable API secret; a delegated delayed leave stored, refused, dropped, sent or failing to restart or send (`livekit.delegation.*`); a refused webhook (`livekit.webhook.refused`, warning, with the reason only) and one that prompted a check (`livekit.webhook.prompted`). Each names the user and room (and the server, for federation); never the token, the API secret, the device or member ID, the slot or the delay ID | diff --git a/docs/observability-audit.md b/docs/observability-audit.md index 847c80ecd..81c960f91 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -655,6 +655,15 @@ The process entry point, not the `delayed_events` module, writes one start-up wa `delayed_events.rows_skipped_at_load:` when the loader skipped rows, with the count only: the loader skips a row it cannot read and never repairs it (ADR-0824). +## TURN credential diagnostics (ADR-0871) + +`GET /_matrix/client/v3/voip/turnServer` logs under the `turn` module, never `client_server`, each line with +`user_id`: `turn.credentials_issued` (info, with `credential` (`static` or `shared_secret`), `ttl_seconds` and +`uri_count`), `turn.credentials_unavailable` (error, with `reason`: the shared secret file is unreadable or empty, and +the request is answered 500) and `turn.not_configured` (debug: no TURN URI is configured and the answer is `{}`). The +username, the password and the shared secret are never logged: the username names an expiry and the user, and is half +of a working credential. + ## Registration token file diagnostics When `security.registration.token_file` is set but yields no token hash, every `POST /register` that needs the token diff --git a/docs/user-manual.md b/docs/user-manual.md index 53c7dab02..8add4fc7d 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -802,7 +802,10 @@ Application-service connect timeout must not exceed its total timeout. Byte size VoIP clients request TURN relay credentials through `GET /_matrix/client/v3/voip/turnServer`. When no TURN server is configured the endpoint returns an empty JSON object so clients gracefully disable relay -support. +support. Each request is logged under the `turn` module (`log_modules.turn`): an +issued credential at info, an unreadable shared secret file at error, and a +request answered `{}` at debug, naming the user and never a credential. See +[log filtering](log-filtering.md#module-names). | Key | Default | When to change | |---|---|---| diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 8d9f27aa9..c04d85ed8 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -84,7 +84,7 @@ This is the largest and most complex module — read this file carefully before | `LiveKitDelegations.cpp` | MSC4195's delegated delayed leave and LiveKit's webhook: `delegate_livekit_delayed_leave` (`POST .../rtc/livekit/delegate_delayed_leave`, ADR-0832: the caller's own scheduled event in a room they are joined to, delay at least 5 min, 20 per user; stores the row, makes no network call), `run_livekit_delegations` (the `livekit-delegations` `PeriodicJob`: drops rows that can no longer be acted on, asks `GetParticipant` about at most 16 due ones with `runtime.mutex` free, then restarts or sends through `manage_delayed_event` only; an unknown answer changes nothing) and `receive_livekit_webhook` (`POST /_merovingian/livekit/webhook`, ADR-0833, before the access-token gate: authenticated as LiveKit signs it, and an authentic event only sets a recorded delegation's next check to now). Never let a webhook restart or send an event. Progress (`livekit_delegation_progress`) and seen webhook IDs are in memory, guarded by `runtime.mutex` | | `LiveKitRequestFields.cpp` | Module-internal: the request-body readers and refusal shared by `LiveKitTokenService.cpp` and `LiveKitDelegations.cpp` (`read_livekit_call_members`, `read_livekit_string`, `livekit_member_of`, `livekit_refusal`). Not public API | | `LiveKitNames.cpp` | `livekit_room_name` and `livekit_participant_identity`: MSC4195's `base64nopad(SHA-256(canonical JSON [a, b]))`, with the legacy slot `m.call#ROOM` hashed as `m.call#room` (ADR-0829). Never send a Matrix ID or room ID to LiveKit any other way | -| `TurnCredentials.cpp` | `make_turn_credentials`: the coturn REST API username and password for `GET /voip/turnServer` (ADR-0480) | +| `TurnCredentials.cpp` | `make_turn_credentials`: the coturn REST API username and password for `GET /voip/turnServer` (ADR-0480). The route logs through `log_turn_diagnostic` in `ClientServerRuntime.cpp`, under the `turn` module, never `client_server` (ADR-0871): `user_id`, the kind of credential, the ttl and the URI count only, never the username, the password or the secret | | `EmailPush.cpp` | Kind `"email"` pushers (ADR-0219, ADR-0220): `owned_email_pusher_address` (the pushkey must be the account's own email 3PID), `remove_email_pushers_for_address`, and `EmailPushJob`, the one thread that sends due digests through `send_due_email_notifications`. It re-reads the pusher, the 3PID, the account and the badge count under `runtime.mutex` (one hold, one `PushBadgeBudget`: rows and glob steps bounded together, ADR-0722), then sends with the mutex released | | `RuntimeSigningKeyStore.cpp` | Production `SigningKeyStore` over the persisted server signing-key rows | | `FederationProxy.cpp` | Forwards inbound federation requests to the out-of-process federation worker over encrypted IPC; `GET /_matrix/key/v2/server` stays local. A room whose reload failed is served by main, and so are its reads while a reload is pending (`federation_room_request_served_by_main`, ADR-0748); so is every request for a room the worker has never loaded (`RoomSyncStatus::held`, ADR-0756), and a `/send` is checked for every room it names (`federation_request_room_ids`), each on the copy held by the shard it is sent to (`room_sync_status(shard, room)`). Every shard reloads every changed room (ADR-0758). Main serves a request only for the selected shard's copy of a room it names (failed, pending read, or never loaded); never route a request to main because its rooms belong to different shards, which a remote server chooses (ADR-0131) | diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index c5761db19..0dc42a5dd 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -259,6 +259,15 @@ namespace observability::log_diagnostic("client_server", event, fields, severity); } + // `GET /voip/turnServer` logs under its own module, so `log_modules.turn` sets its level apart from every other + // client-server line (ADR-0871). Pass the user ID, the kind of credential and the ttl only: never the username, + // the password or the shared secret. + auto log_turn_diagnostic(std::string_view event, std::vector fields, + observability::LogEventSeverity severity) -> void + { + observability::log_diagnostic("turn", event, fields, severity); + } + [[nodiscard]] auto starts_with(std::string_view v, std::string_view p) noexcept -> bool { return v.size() >= p.size() && v.substr(0U, p.size()) == p; @@ -21492,6 +21501,11 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp auto const& turn = rt.homeserver.config.server().turn; if (turn.server.empty() && turn.uris.empty()) { + log_turn_diagnostic("turn.not_configured", + { + {"user_id", *user, false} + }, + observability::LogEventSeverity::debug); return dispatch_resp(req, rt, 200U, "{}"); } auto username = turn.username; @@ -21511,11 +21525,13 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp auto credentials = make_turn_credentials(bytes, *user, now_seconds, turn.ttl_seconds); if (!credentials.has_value()) { - log_diagnostic("turn.credentials_unavailable", - { - {"reason", "shared secret file unreadable or empty", false} + log_turn_diagnostic( + "turn.credentials_unavailable", + { + {"user_id", *user, false}, + {"reason", "shared secret file unreadable or empty", false} }, - observability::LogEventSeverity::error); + observability::LogEventSeverity::error); return dispatch_err(req, rt, 500U, "M_UNKNOWN", "TURN credentials are unavailable"); } username = std::move(credentials->username); @@ -21535,12 +21551,21 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp uris.push_back(json_str(uri)); } } + auto const uri_count = uris.size(); auto const body = json_serialize(json_obj({ json_member("username", json_str(username)), json_member("password", json_str(password)), json_member("ttl", json_int(static_cast(turn.ttl_seconds))), json_member("uris", json_arr(std::move(uris))), })); + log_turn_diagnostic("turn.credentials_issued", + { + {"user_id", *user, false}, + {"credential", turn.shared_secret_file.empty() ? "static" : "shared_secret", false}, + {"ttl_seconds", std::to_string(turn.ttl_seconds), false}, + {"uri_count", std::to_string(uri_count), false}, + }, + observability::LogEventSeverity::info); return dispatch_resp(req, rt, 200U, body); } diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index ffdc24c2b..c999372ff 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -4,6 +4,7 @@ // TURN shared-secret credentials (the coturn REST API, `use-auth-secret`): HMAC-SHA1, the credential format, // the config rules and GET /voip/turnServer. A choice of this server (ADR-0480), so a unit test. +#include "../support/ConsoleLogCapture.hpp" #include "../support/InMemoryDatabaseConfig.hpp" #include "../support/JsonTestSupport.hpp" #include "../support/MasterKey.hpp" @@ -21,7 +22,11 @@ #include "merovingian/homeserver/ClientServerClock.hpp" #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" +#include "merovingian/homeserver/DispatchResult.hpp" +#include "merovingian/homeserver/LocalHttpResponse.hpp" #include "merovingian/homeserver/TurnCredentials.hpp" +#include "merovingian/observability/LogLevel.hpp" +#include "merovingian/observability/SingleLog.hpp" #include @@ -31,10 +36,14 @@ #include #include #include +#include #include +#include #include #include #include +#include +#include #include #include @@ -121,6 +130,57 @@ class SecretFile final return *token; } +// The first captured line at `level` (the logger's name for it, such as "INFO"), filed under `module`, that names +// `event`; nullopt when there is none. +[[nodiscard]] auto module_line(std::string const& text, std::string_view level, std::string_view module, + std::string_view event) -> std::optional +{ + auto const level_tag = "<" + std::string{level} + ">"; + auto const module_tag = " " + std::string{module} + ": "; + auto const event_tag = "event=" + std::string{event}; + auto lines = std::istringstream{text}; + for (auto line = std::string{}; std::getline(lines, line);) + { + if (line.find(level_tag) != std::string::npos && line.find(module_tag) != std::string::npos && + line.find(event_tag) != std::string::npos) + { + return line; + } + } + return std::nullopt; +} + +// Sets one module's log level for the scope, and restores what it was (an absent override stays absent). +class ModuleLogLevel final +{ +public: + ModuleLogLevel(std::string module, merovingian::observability::LogLevel level) + : m_module{std::move(module)} + , m_previous{merovingian::observability::SingleLog::instance().exchange_module_log_level(m_module, level)} + { + } + ~ModuleLogLevel() noexcept + { + std::ignore = merovingian::observability::SingleLog::instance().exchange_module_log_level(m_module, m_previous); + } + ModuleLogLevel(ModuleLogLevel const&) = delete; + auto operator=(ModuleLogLevel const&) -> ModuleLogLevel& = delete; + ModuleLogLevel(ModuleLogLevel&&) = delete; + auto operator=(ModuleLogLevel&&) -> ModuleLogLevel& = delete; + +private: + std::string m_module; + std::optional m_previous; +}; + +[[nodiscard]] auto turn_server(merovingian::homeserver::ClientServerRuntime& runtime, std::string const& token) + -> merovingian::homeserver::LocalHttpResponse +{ + return merovingian::homeserver::handle_client_server_request( + runtime, {"GET", "/_matrix/client/v3/voip/turnServer", token, {}}) + .response; +} + } // namespace SCENARIO("GET /voip/turnServer issues per-user time-limited credentials from a shared secret", @@ -235,3 +295,153 @@ SCENARIO("GET /voip/turnServer lists every server.turn.uris entry in order with } } } + +SCENARIO("The turn log files an issued credential under its own module, naming the user and never a credential", + "[homeserver][turn][logging]") +{ + GIVEN("a server whose TURN shared secret is in an owner-only file, and alice") + { + auto const secret = SecretFile{"north-turn-secret\n"}; + auto started = merovingian::homeserver::start_client_server(secret_turn_config(secret.path(), 3600U)); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const alice = login(runtime, "alice"); + + WHEN("alice is issued credentials with the client_server module silenced and the log captured") + { + auto const quiet_client_server = + ModuleLogLevel{"client_server", merovingian::observability::LogLevel::critical}; + auto const capture = ConsoleLogCapture{}; + auto const response = turn_server(runtime, alice); + auto const text = capture.text(); + + THEN("an info line under turn names the event, alice, the kind of credential and the ttl") + { + REQUIRE(response.status == 200U); + auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); + REQUIRE(line.has_value()); + CHECK(line->find("@alice:example.org") != std::string::npos); + CHECK(line->find("credential=shared_secret") != std::string::npos); + CHECK(line->find("ttl_seconds=3600") != std::string::npos); + } + + THEN("the log holds neither the username, the password nor the shared secret") + { + REQUIRE(response.status == 200U); + auto const body = parse_object(response.body); + auto const* username = string_member(body, "username"); + auto const* password = string_member(body, "password"); + REQUIRE((username != nullptr && password != nullptr)); + CHECK(text.find(*username) == std::string::npos); + CHECK(text.find(*password) == std::string::npos); + CHECK(text.find("north-turn-secret") == std::string::npos); + } + } + + WHEN("alice is issued credentials with the turn module set to error and the log captured") + { + auto const quiet_turn = ModuleLogLevel{"turn", merovingian::observability::LogLevel::error}; + auto const capture = ConsoleLogCapture{}; + auto const response = turn_server(runtime, alice); + auto const text = capture.text(); + + THEN("the credentials are issued and the turn module's level keeps the info line out") + { + REQUIRE(response.status == 200U); + CHECK(text.find("turn.credentials_issued") == std::string::npos); + } + } + } +} + +SCENARIO("The turn log names an unreadable shared secret as an error under its own module", + "[homeserver][turn][logging]") +{ + GIVEN("a shared secret path that does not exist, and alice") + { + auto started = merovingian::homeserver::start_client_server( + secret_turn_config("/nonexistent/merovingian-turn-secret", 3600U)); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const alice = login(runtime, "alice"); + + WHEN("alice asks for credentials with the client_server module silenced and the log captured") + { + auto const quiet_client_server = + ModuleLogLevel{"client_server", merovingian::observability::LogLevel::critical}; + auto const capture = ConsoleLogCapture{}; + auto const response = turn_server(runtime, alice); + auto const text = capture.text(); + + THEN("the answer is 500 and an error line under turn names the event and alice") + { + REQUIRE(response.status == 500U); + auto const line = module_line(text, "ERROR", "turn", "turn.credentials_unavailable"); + REQUIRE(line.has_value()); + CHECK(line->find("@alice:example.org") != std::string::npos); + } + } + } +} + +SCENARIO("The turn log files configured static credentials under its own module and never the password", + "[homeserver][turn][logging]") +{ + GIVEN("a server with a static TURN username and password, and alice") + { + auto config = secret_turn_config({}, 86400U); + config.server().turn.username = "static-turn-user"; + config.server().turn.password = "static-turn-password"; + auto started = merovingian::homeserver::start_client_server(std::move(config)); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const alice = login(runtime, "alice"); + + WHEN("alice is issued credentials with the log captured") + { + auto const capture = ConsoleLogCapture{}; + auto const response = turn_server(runtime, alice); + auto const text = capture.text(); + + THEN("an info line under turn names the static credential, and the log holds neither part of it") + { + REQUIRE(response.status == 200U); + auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); + REQUIRE(line.has_value()); + CHECK(line->find("credential=static") != std::string::npos); + CHECK(text.find("static-turn-user") == std::string::npos); + CHECK(text.find("static-turn-password") == std::string::npos); + } + } + } +} + +SCENARIO("The turn log says at debug level that no TURN server is configured", "[homeserver][turn][logging]") +{ + GIVEN("a server with no TURN server configured, and alice") + { + auto config = secret_turn_config({}, 3600U); + config.server().turn.server.clear(); + auto started = merovingian::homeserver::start_client_server(std::move(config)); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const alice = login(runtime, "alice"); + + WHEN("alice asks for credentials with the turn module at debug and the log captured") + { + auto const verbose_turn = ModuleLogLevel{"turn", merovingian::observability::LogLevel::debug}; + auto const capture = ConsoleLogCapture{merovingian::observability::LogLevel::debug}; + auto const response = turn_server(runtime, alice); + auto const text = capture.text(); + + THEN("the answer is the empty object and a debug line under turn names the event and alice") + { + REQUIRE(response.status == 200U); + REQUIRE(response.body == "{}"); + auto const line = module_line(text, "DEBUG", "turn", "turn.not_configured"); + REQUIRE(line.has_value()); + CHECK(line->find("@alice:example.org") != std::string::npos); + } + } + } +} From 785de5b348897dffc9340fb716cfcbf14fecdffd Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 22:28:23 +0000 Subject: [PATCH 02/28] List every log module in the example configurations The commented log_modules list in both example configurations had fallen behind the sources: twelve modules the server logs under were missing (appservice, connection_parker, crypto, delayed_events, federation_proxy, livekit, oauth, presence, redaction, stream_token_epoch, turn and worker_pool), and it named token, which nothing has ever logged under. The list now holds exactly the 54 names passed as the module to observability::log_diagnostic, log_diagnostic_audit and the SingleLog level methods in src/ and include/. log-filtering.md says the examples hold the full list and that both must be kept in step. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ config/merovingian.conf.bsd.example | 14 +++++++++++++- config/merovingian.conf.example | 14 +++++++++++++- docs/log-filtering.md | 4 +++- 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8192de85..07726f2b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -179,6 +179,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * The Fedora 44 and 45 RPMs build again: GCC 16 refused `std::ranges::find` with a bare string literal under C++26, and `reject-unsafe.sh` now rejects that form in code and tests (ADR-0870). * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. +* The example configurations list every `log_modules` module the server logs under: twelve were missing (`oauth`, + `livekit`, `delayed_events`, `presence` and others), and `token`, which nothing logs under, is gone. ## Release notes diff --git a/config/merovingian.conf.bsd.example b/config/merovingian.conf.bsd.example index 9fc33e9d9..a8eca1568 100644 --- a/config/merovingian.conf.bsd.example +++ b/config/merovingian.conf.bsd.example @@ -911,8 +911,13 @@ appservice.max_queued_events=100000 # every other module sees. Restart is required for changes to take effect. # Merovingian needs to run with the --debug parameter to enable debug logging. # — see docs/log-filtering.md. +# Every module the server logs under: +# log_modules.appservice=info # log_modules.auth=info # log_modules.client_server=info +# log_modules.connection_parker=info +# log_modules.crypto=info +# log_modules.delayed_events=info # log_modules.dispatch_worker=info # log_modules.event=info # log_modules.event_auth=info @@ -920,12 +925,14 @@ appservice.max_queued_events=100000 # log_modules.event_signer=info # log_modules.federation=info # log_modules.federation_policy=info +# log_modules.federation_proxy=info # log_modules.federation_security=info # log_modules.hardening_self_check=info # log_modules.http_server=info # log_modules.identity=info # log_modules.inbound_ingestion=info # log_modules.key_query=info +# log_modules.livekit=info # log_modules.local_router=info # log_modules.local_services=info # log_modules.media_repository=info @@ -933,12 +940,15 @@ appservice.max_queued_events=100000 # log_modules.media_service=info # log_modules.membership_endpoints=info # log_modules.migration=info +# log_modules.oauth=info # log_modules.outbound_client=info # log_modules.outbound_transaction=info # log_modules.persistent_store=info # log_modules.policy_engine=info # log_modules.postgresql_store=info +# log_modules.presence=info # log_modules.rate_limit=info +# log_modules.redaction=info # log_modules.remote_key_resolver=info # log_modules.rooms=info # log_modules.runtime=info @@ -948,12 +958,14 @@ appservice.max_queued_events=100000 # log_modules.signing_service=info # log_modules.sqlite_store=info # log_modules.state_resolution=info +# log_modules.stream_token_epoch=info # log_modules.sync_filter=info # log_modules.sync_notifier=info # log_modules.thread_pool=info # log_modules.tls=info -# log_modules.token=info # log_modules.transactions=info +# log_modules.turn=info +# log_modules.worker_pool=info # All log module config # Setting this to debug on a live server will open the floodgates diff --git a/config/merovingian.conf.example b/config/merovingian.conf.example index 6229408c1..2b5bf95ec 100644 --- a/config/merovingian.conf.example +++ b/config/merovingian.conf.example @@ -884,8 +884,13 @@ appservice.max_queued_events=100000 # every other module sees. Restart is required for changes to take effect. # Merovingian needs to run with the --debug parameter to enable debug logging. # — see docs/log-filtering.md. +# Every module the server logs under: +# log_modules.appservice=info # log_modules.auth=info # log_modules.client_server=info +# log_modules.connection_parker=info +# log_modules.crypto=info +# log_modules.delayed_events=info # log_modules.dispatch_worker=info # log_modules.event=info # log_modules.event_auth=info @@ -893,12 +898,14 @@ appservice.max_queued_events=100000 # log_modules.event_signer=info # log_modules.federation=info # log_modules.federation_policy=info +# log_modules.federation_proxy=info # log_modules.federation_security=info # log_modules.hardening_self_check=info # log_modules.http_server=info # log_modules.identity=info # log_modules.inbound_ingestion=info # log_modules.key_query=info +# log_modules.livekit=info # log_modules.local_router=info # log_modules.local_services=info # log_modules.media_repository=info @@ -906,12 +913,15 @@ appservice.max_queued_events=100000 # log_modules.media_service=info # log_modules.membership_endpoints=info # log_modules.migration=info +# log_modules.oauth=info # log_modules.outbound_client=info # log_modules.outbound_transaction=info # log_modules.persistent_store=info # log_modules.policy_engine=info # log_modules.postgresql_store=info +# log_modules.presence=info # log_modules.rate_limit=info +# log_modules.redaction=info # log_modules.remote_key_resolver=info # log_modules.rooms=info # log_modules.runtime=info @@ -921,12 +931,14 @@ appservice.max_queued_events=100000 # log_modules.signing_service=info # log_modules.sqlite_store=info # log_modules.state_resolution=info +# log_modules.stream_token_epoch=info # log_modules.sync_filter=info # log_modules.sync_notifier=info # log_modules.thread_pool=info # log_modules.tls=info -# log_modules.token=info # log_modules.transactions=info +# log_modules.turn=info +# log_modules.worker_pool=info # All log module config # Setting this to debug on a live server will open the floodgates diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 87b1d8dea..8ce493f36 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -102,7 +102,9 @@ A malformed `category=` value returns 400 with The `log_modules.` keys accept any string — the bootstrap forwards the name to `SingleLog::set_module_log_level(name, level)` -without a registry. This is a non-exhaustive list of common module names +without a registry. The example configurations (`config/merovingian.conf.example` and +`config/merovingian.conf.bsd.example`) list every module the server logs under; keep both in step when a module is +added or removed. This is a non-exhaustive list of common module names used as the first argument to `observability::log_diagnostic` and `log_diagnostic_audit` in `src/` (`rate_limit` is used only with `log_diagnostic_audit`): From 35567e769d0d6757200beb0b11b8dd04a31f1e9b Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 22:32:16 +0000 Subject: [PATCH 03/28] Share the module log-level test helper, and correct the TURN logging docs Review feedback on the turn module: - ModuleLogLevel moves to tests/support/ModuleLogLevel.hpp and replaces the copy in test_turn_shared_secret_flow.cpp and DebugClientServerLog in test_oauth_log_query_flow.cpp, which did the same save and restore. - The turn_server test helper gets its purpose comment. - docs/security-coding-rules.md states the TURN rule under Secrets and logging, with why the username counts as a credential, and the index lists src/homeserver/AGENTS.md for that section. - ADR-0871 and the user manual no longer claim the turn module shows every TURN request: a 401 for a missing or expired token is refused before the handler and logged under client_server. They say the debug line needs --debug too, and that the info line is one per successful request, which the ttl does not bound. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + ...equests-log-under-their-own-turn-module.md | 11 +++-- docs/security-coding-rules.md | 15 ++++++- docs/user-manual.md | 5 ++- .../integration/test_oauth_log_query_flow.cpp | 34 +++------------ .../test_turn_shared_secret_flow.cpp | 28 ++----------- tests/support/AGENTS.md | 1 + tests/support/ModuleLogLevel.hpp | 42 +++++++++++++++++++ 8 files changed, 79 insertions(+), 59 deletions(-) create mode 100644 tests/support/ModuleLogLevel.hpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 07726f2b4..0ae53cee3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) room's initial receipts on entering scope and those on a new timeline (MSC4548, MSC4551, ADR-0865). * `GET /voip/turnServer` logs under its own `turn` module, set with `log_modules.turn`: credentials issued (info), unavailable (error) and no TURN configured (debug), with the user ID and never a credential (ADR-0871). +* Tests set a log module's level through one shared helper, `tests/support/ModuleLogLevel.hpp`, instead of a copy per + file; the security coding rules state the TURN logging rule and why the username counts as a credential. ## Security Fixes diff --git a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md index f48979457..9722f81f1 100644 --- a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md +++ b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md @@ -34,13 +34,18 @@ of its own and would have moved forty lines of unrelated JSON building with it. ### Positive Consequences -* `log_modules.turn=debug` shows every TURN request; `log_modules.turn=warning` hides the per-request info line. +* `log_modules.turn` sets the level of every line the TURN handler writes; `log_modules.turn=warning` hides the + per-request info line. Only requests that reach the handler are logged there: a missing, expired or unknown access + token is refused with 401 before it, and logged as `request.auth.rejected` (debug) under `client_server`, so look + there for authentication failures. `turn.not_configured` is a debug line, which reaches the console only when the + server also runs with `--debug`. * The logging tests run with `client_server` silenced, so a line moved back under `client_server` fails them. ### Negative Consequences -* An issued credential is one info line per request at the default level. Clients ask again before the ttl ends, so - this is one line per client per ttl, not per call; an operator who finds it loud sets `log_modules.turn=warning`. +* An issued credential is one info line per successful request at the default level. The ttl does not bound that: + a client may ask again before its credential expires (for example at the start of each call), and every request + writes a line. An operator who finds it loud sets `log_modules.turn=warning`. * Changing the module of `turn.credentials_unavailable` means a filter on `client_server` no longer sees it. ## Rules for future code diff --git a/docs/security-coding-rules.md b/docs/security-coding-rules.md index d6504389a..501f9c549 100644 --- a/docs/security-coding-rules.md +++ b/docs/security-coding-rules.md @@ -176,6 +176,19 @@ quickly finding everything a given `AGENTS.md` file contributed. Source: `src/crypto/AGENTS.md`, `src/auth/AGENTS.md`, `src/observability/AGENTS.md`, `security/coding-rules.md`. +- **`GET /voip/turnServer` never logs the TURN username, the password or the shared secret, + at any level.** It logs through `log_turn_diagnostic` under the `turn` module, with + `user_id`, the kind of credential, the ttl and the URI count only. + Why: the username is half of a working credential, not an identifier. With a shared + secret it is `:`, the exact text the password's HMAC-SHA1 covers, so the + pair relays traffic through the TURN server as that user until the expiry, and with + static credentials the username and password are the same for every user of the server. + Leaking the username leaves only the password between a log reader and a credential + (CWE-532), and the shared secret would let them mint credentials for any user. + Source: `src/homeserver/AGENTS.md`; + [ADR-0871](adr/0871-turn-credential-requests-log-under-their-own-turn-module.md), + [ADR-0480](adr/0480-turn-credentials-come-from-a-coturn-shared-secret-file-through-an-openssl-hmac-sha1.md). + - **Write log records only through `SingleLog`, and never remove the control-character escaping in `SingleLog::make_log_line`.** Every line is passed through `escape_log_controls`, so `\n`, `\r`, other C0 controls, DEL and UTF-8 C1 controls in a @@ -2067,7 +2080,7 @@ For finding everything a specific file contributed, without re-reading the whole | `src/http/AGENTS.md` | HTTP and network boundary | | `src/net/AGENTS.md` | Memory safety; HTTP and network boundary | | `src/oauth/AGENTS.md` | OAuth 2.0 API | -| `src/homeserver/AGENTS.md` | Authentication and authorization; OAuth 2.0 API; HTTP and network boundary; Federation; Media; Sync; Delayed events | +| `src/homeserver/AGENTS.md` | Secrets and logging; Authentication and authorization; OAuth 2.0 API; HTTP and network boundary; Federation; Media; Sync; Delayed events | | `src/media/AGENTS.md` | HTTP and network boundary; Media | | `src/database/AGENTS.md` | OAuth 2.0 API; Database; Delayed events | | `migrations/AGENTS.md` | Database | diff --git a/docs/user-manual.md b/docs/user-manual.md index 8add4fc7d..d083b222b 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -804,7 +804,10 @@ VoIP clients request TURN relay credentials through endpoint returns an empty JSON object so clients gracefully disable relay support. Each request is logged under the `turn` module (`log_modules.turn`): an issued credential at info, an unreadable shared secret file at error, and a -request answered `{}` at debug, naming the user and never a credential. See +request answered `{}` at debug, naming the user and never a credential. The debug +line needs `--debug` as well as `log_modules.turn=debug`. A request refused for a +missing or expired access token never reaches the handler: it is logged under +`client_server` as `request.auth.rejected`. See [log filtering](log-filtering.md#module-names). | Key | Default | When to change | diff --git a/tests/integration/test_oauth_log_query_flow.cpp b/tests/integration/test_oauth_log_query_flow.cpp index 2963d54ab..d7e6b038d 100644 --- a/tests/integration/test_oauth_log_query_flow.cpp +++ b/tests/integration/test_oauth_log_query_flow.cpp @@ -7,6 +7,7 @@ // level, so the per-request lines (request.received, request.route_not_found, request.rejected) are seen. #include "../support/ConsoleLogCapture.hpp" +#include "../support/ModuleLogLevel.hpp" #include "../support/OAuthAuthorizationSupport.hpp" #include "../support/OAuthRegistrationSupport.hpp" #include "../support/OAuthTokenSupport.hpp" @@ -14,12 +15,10 @@ #include "merovingian/homeserver/ClientServerStartResult.hpp" #include "merovingian/homeserver/LocalHttpRequest.hpp" #include "merovingian/observability/LogLevel.hpp" -#include "merovingian/observability/SingleLog.hpp" #include #include -#include #include #include #include @@ -37,31 +36,6 @@ auto send(hs::ClientServerRuntime& runtime, std::string method, std::string targ std::ignore = hs::handle_client_server_request(runtime, request, /*can_wait=*/false); } -// Lowers a module's log level to debug for the scope (client_server by default), so its per-request lines are written. -class DebugClientServerLog final -{ -public: - explicit DebugClientServerLog(std::string module_name = "client_server") - : module_name_{std::move(module_name)} - , previous_{merovingian::observability::SingleLog::instance().exchange_module_log_level( - module_name_, merovingian::observability::LogLevel::debug)} - { - } - ~DebugClientServerLog() - { - std::ignore = - merovingian::observability::SingleLog::instance().exchange_module_log_level(module_name_, previous_); - } - DebugClientServerLog(DebugClientServerLog const&) = delete; - auto operator=(DebugClientServerLog const&) -> DebugClientServerLog& = delete; - DebugClientServerLog(DebugClientServerLog&&) = delete; - auto operator=(DebugClientServerLog&&) -> DebugClientServerLog& = delete; - -private: - std::string module_name_; - std::optional previous_; -}; - } // namespace SCENARIO("The query of an OAuth 2.0 request is never logged", "[integration][oauth][oauth-log][logging][security]") @@ -74,7 +48,8 @@ SCENARIO("The query of an OAuth 2.0 request is never logged", "[integration][oau WHEN("OAuth 2.0 requests carry a state, a code, a login hint and a session in their query") { - auto const debug_module = DebugClientServerLog{}; + auto const debug_module = + merovingian::tests::ModuleLogLevel{"client_server", merovingian::observability::LogLevel::debug}; auto const capture = merovingian::tests::ConsoleLogCapture{merovingian::observability::LogLevel::debug}; send(runtime, "GET", "/_merovingian/oauth2/authorize?state=SECRETSTATE&login_hint=SECRETHINT"); send(runtime, "POST", "/_merovingian/oauth2/register?code=SECRETCODE", "{}"); @@ -119,7 +94,8 @@ SCENARIO("A refused token or device request logs the client ID only when it name WHEN("an unregistered client ID is sent to every token grant and to the device endpoint, and the registered " "client asks for a grant it does not hold") { - auto const debug_module = DebugClientServerLog{"oauth"}; + auto const debug_module = + merovingian::tests::ModuleLogLevel{"oauth", merovingian::observability::LogLevel::debug}; auto const capture = merovingian::tests::ConsoleLogCapture{merovingian::observability::LogLevel::debug}; constexpr auto probe = std::string_view{"UNREGISTEREDPROBE"}; auto const refresh = merovingian::tests::post_oauth_form( diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index c999372ff..c7c5de10e 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -8,6 +8,7 @@ #include "../support/InMemoryDatabaseConfig.hpp" #include "../support/JsonTestSupport.hpp" #include "../support/MasterKey.hpp" +#include "../support/ModuleLogLevel.hpp" #include "../support/RegistrationToken.hpp" #include "../support/TempDirectory.hpp" #include "merovingian/config/ClientRateLimitsConfig.hpp" @@ -26,7 +27,6 @@ #include "merovingian/homeserver/LocalHttpResponse.hpp" #include "merovingian/homeserver/TurnCredentials.hpp" #include "merovingian/observability/LogLevel.hpp" -#include "merovingian/observability/SingleLog.hpp" #include @@ -42,7 +42,6 @@ #include #include #include -#include #include #include #include @@ -150,29 +149,8 @@ class SecretFile final return std::nullopt; } -// Sets one module's log level for the scope, and restores what it was (an absent override stays absent). -class ModuleLogLevel final -{ -public: - ModuleLogLevel(std::string module, merovingian::observability::LogLevel level) - : m_module{std::move(module)} - , m_previous{merovingian::observability::SingleLog::instance().exchange_module_log_level(m_module, level)} - { - } - ~ModuleLogLevel() noexcept - { - std::ignore = merovingian::observability::SingleLog::instance().exchange_module_log_level(m_module, m_previous); - } - ModuleLogLevel(ModuleLogLevel const&) = delete; - auto operator=(ModuleLogLevel const&) -> ModuleLogLevel& = delete; - ModuleLogLevel(ModuleLogLevel&&) = delete; - auto operator=(ModuleLogLevel&&) -> ModuleLogLevel& = delete; - -private: - std::string m_module; - std::optional m_previous; -}; - +// Asks for TURN credentials as the user `token` belongs to, through the client-server dispatcher, and returns the +// HTTP response. [[nodiscard]] auto turn_server(merovingian::homeserver::ClientServerRuntime& runtime, std::string const& token) -> merovingian::homeserver::LocalHttpResponse { diff --git a/tests/support/AGENTS.md b/tests/support/AGENTS.md index 103a25feb..34498b6de 100644 --- a/tests/support/AGENTS.md +++ b/tests/support/AGENTS.md @@ -31,6 +31,7 @@ Shared test utilities used across unit, conformance, and integration tests. | `CapturedAppserviceRequest.hpp` | `CapturedAppserviceRequest`: one request recorded by `MockAppservice` (method, target, `Authorization`, body, answered status) | | `TestAppservice.hpp` | `TestAppservice`: the fields of one appservice registration written by `appservice_test_config()` | | `ConsoleLogCapture.hpp` | `ConsoleLogCapture`: sends the console log to a string for the scope's lifetime; safe only while the logger's asynchronous writer threads are not running (the unit test binary); `text()` returns everything captured | +| `ModuleLogLevel.hpp` | `ModuleLogLevel`: sets one logger module's level for the scope and restores the previous override (or its absence) on exit. Use it whenever a scenario needs a module raised or silenced, never a file-local copy | | `CrossSigningKeyPair.hpp` | `CrossSigningKeyPair`: a cross-signing public key (unpadded base64) and its secret key | | `CrossSigningSet.hpp` | `CrossSigningSet`: a user's master, self-signing and user-signing keys, the latter two signed by the master key | | `EduRelayChannels.hpp` / `EduRelayContext.hpp` | `EduRelayChannels` and `make_edu_relay_channels()`: a main and a worker `IpcChannel` over a real authenticated transport, for the downstream EDU relay fixtures. Creates a `socketpair`, so it is an I/O exception | diff --git a/tests/support/ModuleLogLevel.hpp b/tests/support/ModuleLogLevel.hpp new file mode 100644 index 000000000..7b47f6f22 --- /dev/null +++ b/tests/support/ModuleLogLevel.hpp @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "merovingian/observability/LogLevel.hpp" +#include "merovingian/observability/SingleLog.hpp" + +#include +#include +#include +#include + +namespace merovingian::tests +{ + +// Sets one logger module's level for the scope's lifetime, and restores what it was when the scope ends: an absent +// override stays absent rather than becoming a copy of the default. Changes process-wide logger state, so a scenario +// that uses it must not run in parallel with another in the same process (Catch2 runs scenarios one at a time). +class ModuleLogLevel final +{ +public: + ModuleLogLevel(std::string module, merovingian::observability::LogLevel level) + : m_module{std::move(module)} + , m_previous{merovingian::observability::SingleLog::instance().exchange_module_log_level(m_module, level)} + { + } + ~ModuleLogLevel() noexcept + { + // Restoring an existing entry or erasing one allocates nothing, so this cannot throw. + std::ignore = merovingian::observability::SingleLog::instance().exchange_module_log_level(m_module, m_previous); + } + ModuleLogLevel(ModuleLogLevel const&) = delete; + auto operator=(ModuleLogLevel const&) -> ModuleLogLevel& = delete; + ModuleLogLevel(ModuleLogLevel&&) = delete; + auto operator=(ModuleLogLevel&&) -> ModuleLogLevel& = delete; + +private: + std::string m_module; + std::optional m_previous; +}; + +} // namespace merovingian::tests From 696b10b03bccad01262702465b99155798acdd13 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 22:35:58 +0000 Subject: [PATCH 04/28] Assert uri_count in the TURN log, and restate why the username is withheld Review feedback on the turn module: - The issued-credential scenario now reads each field whole with a small field_value helper (so uri_count=1 cannot pass for 10) and asserts uri_count: 1 for server.turn.server, and 2 in a new case with two server.turn.uris entries, checked against the answer's uris. - ADR-0871, the security coding rules and observability-audit.md no longer justify withholding the username as "half of a credential": with a shared secret it can be rebuilt from user_id, ttl_seconds and the line's timestamp. The reasons now given hold whatever the line carries: static credentials are one configured pair shared by every user, and one rule keeps every line free of credential text. The ADR says the shared-secret case is accepted and no reason to log it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- ...equests-log-under-their-own-turn-module.md | 12 +++- docs/observability-audit.md | 6 +- docs/security-coding-rules.md | 14 +++-- .../test_turn_shared_secret_flow.cpp | 55 +++++++++++++++++-- 5 files changed, 74 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ae53cee3..70771a47d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,7 +53,7 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * `GET /voip/turnServer` logs under its own `turn` module, set with `log_modules.turn`: credentials issued (info), unavailable (error) and no TURN configured (debug), with the user ID and never a credential (ADR-0871). * Tests set a log module's level through one shared helper, `tests/support/ModuleLogLevel.hpp`, instead of a copy per - file; the security coding rules state the TURN logging rule and why the username counts as a credential. + file; the security coding rules state the TURN logging rule and why the username is withheld. ## Security Fixes diff --git a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md index 9722f81f1..30b51abf6 100644 --- a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md +++ b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md @@ -51,8 +51,16 @@ of its own and would have moved forty lines of unrelated JSON building with it. ## Rules for future code * A new diagnostic of `GET /voip/turnServer` goes through `log_turn_diagnostic`, never the `client_server` wrapper. -* Never add the username or the password as a field, even at debug or trace level: the username is half of a working - credential and, with a shared secret, names the user and the expiry the MAC covers. +* Never add the username or the password as a field, even at debug or trace level. The password is the secret that + matters. The username is withheld for two reasons that hold whatever else the line carries: + * With static credentials (`server.turn.username`) it is a configured value that nothing else in a log reveals, the + same for every user, and one of the two halves of a credential every user of the server may relay with. + * One rule for both kinds keeps every line free of credential text, so a log can be pasted into an issue or a + support thread without first working out which parts of it are safe. +* With a shared secret, withholding the username hides little: it is `:`, and the expiry can be + rebuilt to the second from the line's timestamp and `ttl_seconds`. That is accepted, because the username without the + password, which needs the shared secret, grants nothing. Do not read it as a reason to start logging the username: + the static case still forbids it. ## Links diff --git a/docs/observability-audit.md b/docs/observability-audit.md index 81c960f91..1be107c64 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -661,8 +661,10 @@ cannot read and never repairs it (ADR-0824). `user_id`: `turn.credentials_issued` (info, with `credential` (`static` or `shared_secret`), `ttl_seconds` and `uri_count`), `turn.credentials_unavailable` (error, with `reason`: the shared secret file is unreadable or empty, and the request is answered 500) and `turn.not_configured` (debug: no TURN URI is configured and the answer is `{}`). The -username, the password and the shared secret are never logged: the username names an expiry and the user, and is half -of a working credential. +username, the password and the shared secret are never logged. The password is the secret; the username is withheld +because static credentials are one configured pair shared by every user, and so that no line ever holds credential +text. With a shared secret the username can be rebuilt from `user_id`, `ttl_seconds` and the line's timestamp, which is +accepted: without the password it grants nothing (ADR-0871). ## Registration token file diagnostics diff --git a/docs/security-coding-rules.md b/docs/security-coding-rules.md index 501f9c549..8a2341d88 100644 --- a/docs/security-coding-rules.md +++ b/docs/security-coding-rules.md @@ -179,12 +179,14 @@ quickly finding everything a given `AGENTS.md` file contributed. - **`GET /voip/turnServer` never logs the TURN username, the password or the shared secret, at any level.** It logs through `log_turn_diagnostic` under the `turn` module, with `user_id`, the kind of credential, the ttl and the URI count only. - Why: the username is half of a working credential, not an identifier. With a shared - secret it is `:`, the exact text the password's HMAC-SHA1 covers, so the - pair relays traffic through the TURN server as that user until the expiry, and with - static credentials the username and password are the same for every user of the server. - Leaking the username leaves only the password between a log reader and a credential - (CWE-532), and the shared secret would let them mint credentials for any user. + Why: the password is the secret, and the shared secret would let a log reader mint + credentials for any user (CWE-532). The username is withheld too because with static + credentials it is a configured value nothing else reveals, shared by every user, and one + of the two halves of a credential the whole server relays with. One rule for both kinds + keeps every line free of credential text, so a log is safe to paste into an issue. With + a shared secret the username (`:`) can be rebuilt from `user_id`, + `ttl_seconds` and the line's timestamp, and is useless without the password; that is + accepted, and is no reason to log it. Source: `src/homeserver/AGENTS.md`; [ADR-0871](adr/0871-turn-credential-requests-log-under-their-own-turn-module.md), [ADR-0480](adr/0480-turn-credentials-come-from-a-coturn-shared-secret-file-through-an-openssl-hmac-sha1.md). diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index c7c5de10e..f7999b6c9 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -149,6 +149,21 @@ class SecretFile final return std::nullopt; } +// The value of the ` key=value` field in a diagnostic line, up to the next space; nullopt when the line has no such +// field. Matching the whole value keeps `uri_count=1` from passing for `uri_count=10`. +[[nodiscard]] auto field_value(std::string const& line, std::string_view key) -> std::optional +{ + auto const marker = " " + std::string{key} + "="; + auto const start = line.find(marker); + if (start == std::string::npos) + { + return std::nullopt; + } + auto const value_start = start + marker.size(); + auto const value_end = line.find(' ', value_start); + return line.substr(value_start, value_end == std::string::npos ? std::string::npos : value_end - value_start); +} + // Asks for TURN credentials as the user `token` belongs to, through the client-server dispatcher, and returns the // HTTP response. [[nodiscard]] auto turn_server(merovingian::homeserver::ClientServerRuntime& runtime, std::string const& token) @@ -293,14 +308,15 @@ SCENARIO("The turn log files an issued credential under its own module, naming t auto const response = turn_server(runtime, alice); auto const text = capture.text(); - THEN("an info line under turn names the event, alice, the kind of credential and the ttl") + THEN("an info line under turn names the event, alice, the kind of credential, the ttl and the one URI") { REQUIRE(response.status == 200U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); REQUIRE(line.has_value()); - CHECK(line->find("@alice:example.org") != std::string::npos); - CHECK(line->find("credential=shared_secret") != std::string::npos); - CHECK(line->find("ttl_seconds=3600") != std::string::npos); + CHECK(field_value(*line, "user_id") == "@alice:example.org"); + CHECK(field_value(*line, "credential") == "shared_secret"); + CHECK(field_value(*line, "ttl_seconds") == "3600"); + CHECK(field_value(*line, "uri_count") == "1"); } THEN("the log holds neither the username, the password nor the shared secret") @@ -330,6 +346,37 @@ SCENARIO("The turn log files an issued credential under its own module, naming t } } } + + GIVEN("a server with two server.turn.uris entries and a shared secret file, and alice") + { + auto const secret = SecretFile{"north-turn-secret\n"}; + auto config = secret_turn_config(secret.path(), 3600U); + config.server().turn.server.clear(); + config.server().turn.uris = {"turn:turn.example.org:3478?transport=udp", "turns:turn.example.org:5349"}; + auto started = merovingian::homeserver::start_client_server(std::move(config)); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const alice = login(runtime, "alice"); + + WHEN("alice is issued credentials with the log captured") + { + auto const capture = ConsoleLogCapture{}; + auto const response = turn_server(runtime, alice); + auto const text = capture.text(); + + THEN("the info line counts the two URIs the answer lists") + { + REQUIRE(response.status == 200U); + auto const body = parse_object(response.body); + auto const* uris = object_member_as_array(body, "uris"); + REQUIRE(uris != nullptr); + REQUIRE(uris->size() == 2U); + auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); + REQUIRE(line.has_value()); + CHECK(field_value(*line, "uri_count") == "2"); + } + } + } } SCENARIO("The turn log names an unreadable shared secret as an error under its own module", From 0ddf09e508c5e61769b88029315c9292a91ea04d Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 22:48:11 +0000 Subject: [PATCH 05/28] Test the example configs' log module list, and state every TURN log field Review feedback on the turn module: - tests/tooling/test_example_config.py gains ExampleLogModuleListTests. It scans src/ and include/ for the modules the logger calls name (the qualified log_diagnostic and log_diagnostic_audit calls, the homeserver's log_diagnostic_audit(database, "module", ...) overload, SingleLog level calls, and modules named once in a string constant) and fails when either example's "# log_modules.=" lines are a different set, or list a module twice. A first argument it cannot resolve fails too, so a new call form is noticed rather than missed. - The log_turn_diagnostic comment, src/homeserver/AGENTS.md, the security coding rules and ADR-0871 stated the TURN fields as a list that left out uri_count and reason. Each now states the rule (no field carries credential text) and lists every field. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- ...equests-log-under-their-own-turn-module.md | 4 +- docs/log-filtering.md | 3 +- docs/security-coding-rules.md | 6 +- src/homeserver/AGENTS.md | 2 +- src/homeserver/ClientServerRuntime.cpp | 5 +- tests/tooling/test_example_config.py | 73 +++++++++++++++++++ 7 files changed, 87 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70771a47d..3628d35d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -181,8 +181,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * The Fedora 44 and 45 RPMs build again: GCC 16 refused `std::ranges::find` with a bare string literal under C++26, and `reject-unsafe.sh` now rejects that form in code and tests (ADR-0870). * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. -* The example configurations list every `log_modules` module the server logs under: twelve were missing (`oauth`, - `livekit`, `delayed_events`, `presence` and others), and `token`, which nothing logs under, is gone. +* The example configurations list every `log_modules` module the server logs under (twelve were missing, `token` is + gone), and a tooling test now fails when that list and the modules the sources log under differ. ## Release notes diff --git a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md index 30b51abf6..7b9002b9c 100644 --- a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md +++ b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md @@ -28,8 +28,8 @@ relay?") had nothing to filter on. LiveKit already has its own `livekit` module Chosen option: "a `turn` module through `log_turn_diagnostic`". The route logs `turn.credentials_issued` (info), `turn.credentials_unavailable` (error) and `turn.not_configured` (debug), each with `user_id`; the issued line adds -`credential` (`static` or `shared_secret`), `ttl_seconds` and `uri_count`. The username, the password and the shared -secret are never fields of any line. Moving the route out of `ClientServerRuntime.cpp` was not needed to get a module +`credential` (`static` or `shared_secret`), `ttl_seconds` and `uri_count`, and the unavailable line a fixed `reason`. +No field carries credential text: the username, the password and the shared secret are never fields of any line. Moving the route out of `ClientServerRuntime.cpp` was not needed to get a module of its own and would have moved forty lines of unrelated JSON building with it. ### Positive Consequences diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 8ce493f36..5ce538f07 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -104,7 +104,8 @@ The `log_modules.` keys accept any string — the bootstrap forwards the name to `SingleLog::set_module_log_level(name, level)` without a registry. The example configurations (`config/merovingian.conf.example` and `config/merovingian.conf.bsd.example`) list every module the server logs under; keep both in step when a module is -added or removed. This is a non-exhaustive list of common module names +added or removed. `tests/tooling/test_example_config.py` scans `src/` and `include/` for the modules the logger calls +name and fails when either example lists a different set. This is a non-exhaustive list of common module names used as the first argument to `observability::log_diagnostic` and `log_diagnostic_audit` in `src/` (`rate_limit` is used only with `log_diagnostic_audit`): diff --git a/docs/security-coding-rules.md b/docs/security-coding-rules.md index 8a2341d88..65d2d8e5b 100644 --- a/docs/security-coding-rules.md +++ b/docs/security-coding-rules.md @@ -177,8 +177,10 @@ quickly finding everything a given `AGENTS.md` file contributed. `security/coding-rules.md`. - **`GET /voip/turnServer` never logs the TURN username, the password or the shared secret, - at any level.** It logs through `log_turn_diagnostic` under the `turn` module, with - `user_id`, the kind of credential, the ttl and the URI count only. + at any level.** No field of its lines carries credential text. It logs through + `log_turn_diagnostic` under the `turn` module: `user_id` on every line, `credential`, + `ttl_seconds` and `uri_count` on `turn.credentials_issued`, and a fixed `reason` on + `turn.credentials_unavailable`. Why: the password is the secret, and the shared secret would let a log reader mint credentials for any user (CWE-532). The username is withheld too because with static credentials it is a configured value nothing else reveals, shared by every user, and one diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index c04d85ed8..e3b920f5e 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -84,7 +84,7 @@ This is the largest and most complex module — read this file carefully before | `LiveKitDelegations.cpp` | MSC4195's delegated delayed leave and LiveKit's webhook: `delegate_livekit_delayed_leave` (`POST .../rtc/livekit/delegate_delayed_leave`, ADR-0832: the caller's own scheduled event in a room they are joined to, delay at least 5 min, 20 per user; stores the row, makes no network call), `run_livekit_delegations` (the `livekit-delegations` `PeriodicJob`: drops rows that can no longer be acted on, asks `GetParticipant` about at most 16 due ones with `runtime.mutex` free, then restarts or sends through `manage_delayed_event` only; an unknown answer changes nothing) and `receive_livekit_webhook` (`POST /_merovingian/livekit/webhook`, ADR-0833, before the access-token gate: authenticated as LiveKit signs it, and an authentic event only sets a recorded delegation's next check to now). Never let a webhook restart or send an event. Progress (`livekit_delegation_progress`) and seen webhook IDs are in memory, guarded by `runtime.mutex` | | `LiveKitRequestFields.cpp` | Module-internal: the request-body readers and refusal shared by `LiveKitTokenService.cpp` and `LiveKitDelegations.cpp` (`read_livekit_call_members`, `read_livekit_string`, `livekit_member_of`, `livekit_refusal`). Not public API | | `LiveKitNames.cpp` | `livekit_room_name` and `livekit_participant_identity`: MSC4195's `base64nopad(SHA-256(canonical JSON [a, b]))`, with the legacy slot `m.call#ROOM` hashed as `m.call#room` (ADR-0829). Never send a Matrix ID or room ID to LiveKit any other way | -| `TurnCredentials.cpp` | `make_turn_credentials`: the coturn REST API username and password for `GET /voip/turnServer` (ADR-0480). The route logs through `log_turn_diagnostic` in `ClientServerRuntime.cpp`, under the `turn` module, never `client_server` (ADR-0871): `user_id`, the kind of credential, the ttl and the URI count only, never the username, the password or the secret | +| `TurnCredentials.cpp` | `make_turn_credentials`: the coturn REST API username and password for `GET /voip/turnServer` (ADR-0480). The route logs through `log_turn_diagnostic` in `ClientServerRuntime.cpp`, under the `turn` module, never `client_server` (ADR-0871). No field carries credential text, never the username, the password or the secret: `user_id` on every line, `credential`, `ttl_seconds` and `uri_count` on `turn.credentials_issued`, and a fixed `reason` on `turn.credentials_unavailable` | | `EmailPush.cpp` | Kind `"email"` pushers (ADR-0219, ADR-0220): `owned_email_pusher_address` (the pushkey must be the account's own email 3PID), `remove_email_pushers_for_address`, and `EmailPushJob`, the one thread that sends due digests through `send_due_email_notifications`. It re-reads the pusher, the 3PID, the account and the badge count under `runtime.mutex` (one hold, one `PushBadgeBudget`: rows and glob steps bounded together, ADR-0722), then sends with the mutex released | | `RuntimeSigningKeyStore.cpp` | Production `SigningKeyStore` over the persisted server signing-key rows | | `FederationProxy.cpp` | Forwards inbound federation requests to the out-of-process federation worker over encrypted IPC; `GET /_matrix/key/v2/server` stays local. A room whose reload failed is served by main, and so are its reads while a reload is pending (`federation_room_request_served_by_main`, ADR-0748); so is every request for a room the worker has never loaded (`RoomSyncStatus::held`, ADR-0756), and a `/send` is checked for every room it names (`federation_request_room_ids`), each on the copy held by the shard it is sent to (`room_sync_status(shard, room)`). Every shard reloads every changed room (ADR-0758). Main serves a request only for the selected shard's copy of a room it names (failed, pending read, or never loaded); never route a request to main because its rooms belong to different shards, which a remote server chooses (ADR-0131) | diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index 0dc42a5dd..a16b22363 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -260,8 +260,9 @@ namespace } // `GET /voip/turnServer` logs under its own module, so `log_modules.turn` sets its level apart from every other - // client-server line (ADR-0871). Pass the user ID, the kind of credential and the ttl only: never the username, - // the password or the shared secret. + // client-server line (ADR-0871). No field may carry credential text: never the username, the password or the + // shared secret. Today's fields are `user_id` on every line, `credential`, `ttl_seconds` and `uri_count` on the + // issued line, and a fixed `reason` on the unavailable one. auto log_turn_diagnostic(std::string_view event, std::vector fields, observability::LogEventSeverity severity) -> void { diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index d2a2b4419..e35800372 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -251,5 +251,78 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: self.assertIn("security.registration.token_file=/usr/local/etc/merovingian/registration-token", filled) +# The logger module is the first argument of the qualified free functions, or of a +# SingleLog level method. File-local wrappers (`log_diagnostic(event, fields, ...)`) +# take the event first, so only the qualified calls are read. +QUALIFIED_LOG_CALL = re.compile( + r'observability::log_diagnostic(?:_audit)?\s*\(\s*(?:"([A-Za-z0-9_]+)"|([A-Za-z_][A-Za-z0-9_:]*))' +) +LEVEL_LOG_CALL = re.compile( + r'(?:\.|->)\s*(?:trace|debug|info|notice|warning|error|critical)\s*\(\s*' + r'(?:"([A-Za-z0-9_]+)"|([A-Za-z_][A-Za-z0-9_:]*))\s*,' +) +# The homeserver's `log_diagnostic_audit(database, "module", "event", ...)` takes the module second. +DATABASE_AUDIT_CALL = re.compile(r'\blog_diagnostic_audit\s*\(\s*[A-Za-z_][A-Za-z0-9_.]*\s*,\s*"([A-Za-z0-9_]+)"') +# A module named once in a constant: `auto log_module = std::string_view{"livekit"};` or `name{"livekit"};`. +MODULE_CONSTANT = re.compile( + r'\b([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:std::string_view\s*\{\s*|std::string\s*\{\s*)?"([A-Za-z0-9_]+)"(?:sv|s)?\s*\}?\s*;' +) +MODULE_CONSTANT_INIT = re.compile(r'\b([A-Za-z_][A-Za-z0-9_]*)\s*\{\s*"([A-Za-z0-9_]+)"(?:sv)?\s*\}\s*;') +# Identifiers that forward a caller's module rather than name one. +FORWARDED_MODULE_PARAMETERS = {"__func__", "mod", "logger", "module"} +EXAMPLE_LOG_MODULE_LINE = re.compile(r"^# log_modules\.([A-Za-z0-9_]+)=", re.MULTILINE) + + +def source_log_modules() -> tuple[set[str], set[str]]: + """Every logger module the server's sources name, and any first argument the scan cannot resolve.""" + modules: set[str] = set() + unresolved: set[str] = set() + sources = [path for path in (REPO_ROOT / "src").rglob("*") if path.suffix in {".cpp", ".hpp"}] + sources += list((REPO_ROOT / "include").rglob("*.hpp")) + for path in sources: + text = path.read_text(encoding="utf-8") + constants = dict(MODULE_CONSTANT.findall(text)) + constants.update(MODULE_CONSTANT_INIT.findall(text)) + modules.update(DATABASE_AUDIT_CALL.findall(text)) + for regex in (QUALIFIED_LOG_CALL, LEVEL_LOG_CALL): + for literal, identifier in regex.findall(text): + short = identifier.split("::")[-1] + if literal: + modules.add(literal) + elif short in constants: + modules.add(constants[short]) + elif short not in FORWARDED_MODULE_PARAMETERS: + unresolved.add(f"{path.relative_to(REPO_ROOT).as_posix()}: {identifier}") + return modules, unresolved + + +class ExampleLogModuleListTests(unittest.TestCase): + def test_each_example_lists_exactly_the_modules_the_server_logs_under(self) -> None: + # GIVEN every logger module the server's sources name. + modules, unresolved = source_log_modules() + self.assertEqual( + unresolved, + set(), + "a logger call names its module through an identifier this scan cannot resolve: " + "name it with a literal or a string constant in the same file", + ) + self.assertIn("turn", modules, "the scan no longer finds the modules it is meant to find") + + for path in (EXAMPLE_CONFIG, BSD_EXAMPLE_CONFIG): + with self.subTest(path=path.name): + # WHEN the example's commented `log_modules.=` lines are read. + listed = EXAMPLE_LOG_MODULE_LINE.findall(path.read_text(encoding="utf-8")) + + # THEN it lists each module once, and exactly the modules the server logs + # under: a new module must be added to both examples, a removed one dropped. + self.assertEqual(len(listed), len(set(listed)), f"{path.name} lists a module twice") + self.assertEqual( + set(listed), + modules, + f"{path.name} log_modules list differs from the modules the sources log under " + f"(missing: {sorted(modules - set(listed))}, not logged: {sorted(set(listed) - modules)})", + ) + + if __name__ == "__main__": unittest.main() From 97087904f139b4cc86f9e0dcdc70de6469d130d5 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 23:04:54 +0000 Subject: [PATCH 06/28] Ignore comments in the log module scan, and record its rules in ADR-0872 Review feedback on the example-config log module test: - source_log_modules blanks C++ comments before it reads logger calls, skipping string, character and raw string literals so a "//" or "/*" inside one is kept. A comment that quotes a call no longer adds a module the code never logs under. A new case pins it: a quoted call in a line or block comment counts for nothing, the literals survive whole, and line numbers stay where they were. - ADR-0872 records the decision and the rules the test makes binding: a logger call names its module with a literal or a same-file string constant, a new call form or a shared constant is taught to the scan in the same change, and the examples list every module, never a selection. testing-standards.md gains "Tooling tests that read the sources"; log-filtering.md and the CHANGELOG cite the ADR. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- ...test-reads-the-modules-from-the-sources.md | 57 +++++++++++++++++++ docs/adr/index.md | 1 + docs/log-filtering.md | 3 +- docs/testing-standards.md | 9 +++ tests/tooling/test_example_config.py | 39 ++++++++++++- 6 files changed, 108 insertions(+), 3 deletions(-) create mode 100644 docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 3628d35d4..aebbebef6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -182,7 +182,7 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) and `reject-unsafe.sh` now rejects that form in code and tests (ADR-0870). * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. * The example configurations list every `log_modules` module the server logs under (twelve were missing, `token` is - gone), and a tooling test now fails when that list and the modules the sources log under differ. + gone), and a tooling test fails when that list and the modules the sources log under differ (ADR-0872). ## Release notes diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md new file mode 100644 index 000000000..6fabd7ad2 --- /dev/null +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -0,0 +1,57 @@ +# The example configs list every log module, and a tooling test reads the modules from the sources + +* Status: accepted +* Date: 2026-11-20 + +## Context and Problem Statement + +`log_modules.` accepts any name: the bootstrap passes it to `SingleLog::set_module_log_level` without a registry. +The example configurations (`config/merovingian.conf.example` and its BSD edition) are where an operator learns which +names exist, and their list drifted: twelve modules the server logs under were missing and one, `token`, was logged under +by nothing. How do the examples stay complete without someone remembering to edit them? + +## Decision Drivers + +* A module added to or removed from the sources must fail a test until both examples agree. +* The check must not need a list kept by hand, which would only move the drift into the test. +* It must not miss a module silently when a logger call takes a form the check does not know. + +## Considered Options + +* A hand-kept list of modules in the test, compared with the examples. +* A tooling test that reads the module names from the logger calls in `src/` and `include/`. +* A module registry in C++ that the logger, the config parser and a test all read. + +## Decision Outcome + +Chosen option: "a tooling test that reads the module names from the sources", +`ExampleLogModuleListTests` in `tests/tooling/test_example_config.py`. It blanks C++ comments (a comment that quotes a +call names no module), then reads the first argument of the qualified `observability::log_diagnostic` and +`log_diagnostic_audit` calls and of `SingleLog` level calls, the second argument of the homeserver's +`log_diagnostic_audit(database, "module", ...)` overload, and resolves an identifier through a string constant defined +in the same file. Each example must list exactly that set as `# log_modules.=` lines, each once. A hand-kept list +drifts like the examples did. A registry is the larger change: every logger call site and the config parser would move +to it, for a list that exists to be documented. + +### Positive Consequences + +* A new module fails the test, with its name, until both examples list it; a module nothing logs under any more fails + until it is dropped. +* A first argument the scan cannot resolve fails the test instead of shrinking the expected set. + +### Negative Consequences + +* The scan is text, not a C++ parser: it knows the call forms above, and a new form must be taught to it. +* A module constant shared from another file (a header) is not resolved and fails the test. + +## Rules for future code + +* Name a logger call's module with a string literal, or with a string constant defined in the same file. A parameter + that only forwards a caller's module is named `logger`, `mod` or `module` (or is `__func__`), which the scan skips. +* To share a module constant across files, or to log through a new call form, extend `source_log_modules` in the test + in the same change. Never relax or delete the assertion to get past it. +* The examples list every module the server logs under, not a selection of common ones. Do not trim the list. + +## Links + +* Refines [ADR-0871](0871-turn-credential-requests-log-under-their-own-turn-module.md) diff --git a/docs/adr/index.md b/docs/adr/index.md index cb97d9738..996aaa948 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -745,3 +745,4 @@ * [0869 - A sliding sync long poll wakes only for what its response sends, and a room is sent again when its summary changes](0869-a-sliding-sync-long-poll-wakes-only-for-what-its-response-sends.md) * [0870 - A ranges algorithm takes a typed value, never a bare string literal](0870-a-ranges-algorithm-takes-a-typed-value-never-a-bare-string-literal.md) * [0871 - TURN credential requests log under their own `turn` module, and never log a credential](0871-turn-credential-requests-log-under-their-own-turn-module.md) +* [0872 - The example configs list every log module, and a tooling test reads the modules from the sources](0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md) diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 5ce538f07..a5594dd08 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -105,7 +105,8 @@ forwards the name to `SingleLog::set_module_log_level(name, level)` without a registry. The example configurations (`config/merovingian.conf.example` and `config/merovingian.conf.bsd.example`) list every module the server logs under; keep both in step when a module is added or removed. `tests/tooling/test_example_config.py` scans `src/` and `include/` for the modules the logger calls -name and fails when either example lists a different set. This is a non-exhaustive list of common module names +name and fails when either example lists a different set, or when a call names its module through anything but a +literal or a string constant in the same file (ADR-0872). This is a non-exhaustive list of common module names used as the first argument to `observability::log_diagnostic` and `log_diagnostic_audit` in `src/` (`rate_limit` is used only with `log_diagnostic_audit`): diff --git a/docs/testing-standards.md b/docs/testing-standards.md index db5723f8f..f51814b4d 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -38,6 +38,15 @@ service function: starting a runtime wires config, the store, the signing key an `tests/unit/` names one of those functions (ADR-0593). The directory guides, `tests/unit/AGENTS.md` and `tests/integration/AGENTS.md`, have the rest of the split. +## Tooling tests that read the sources + +A list that documents something in the code (the example configurations' `log_modules` lines, for one) is checked by a +tooling test that reads the code, never against a second list kept by hand in the test. Such a test fails on anything it +cannot read rather than skipping it, so a new form in the code is taught to the test instead of dropping out of the +check, and it ignores comments. `ExampleLogModuleListTests` in `tests/tooling/test_example_config.py` is the model: +a logger call names its module with a literal or a string constant in the same file, and a new call form or a shared +constant is added to the scan in the same change (ADR-0872). + ## Concurrency and locking tests Assert on what a thread holding none of the resource can observe, not on what a diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index e35800372..48acb3e67 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -271,6 +271,23 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: # Identifiers that forward a caller's module rather than name one. FORWARDED_MODULE_PARAMETERS = {"__func__", "mod", "logger", "module"} EXAMPLE_LOG_MODULE_LINE = re.compile(r"^# log_modules\.([A-Za-z0-9_]+)=", re.MULTILINE) +# A C++ comment, or a literal a comment marker may appear inside: raw strings first, since +# their bodies may hold quotes, then ordinary string and character literals. +CPP_COMMENT_OR_LITERAL = re.compile( + r'R"(?P[^()\\\s]{0,16})\(.*?\)(?P=delim)"' + r'|"(?:\\.|[^"\\\n])*"' + r"|'(?:\\.|[^'\\\n])*'" + r"|(?P//[^\n]*|/\*.*?\*/)", + re.DOTALL, +) + + +def without_comments(source: str) -> str: + """The C++ source with its comments blanked, so code a comment quotes is not read as a call.""" + return CPP_COMMENT_OR_LITERAL.sub( + lambda match: re.sub(r"[^\n]", " ", match.group(0)) if match.group("comment") else match.group(0), + source, + ) def source_log_modules() -> tuple[set[str], set[str]]: @@ -280,7 +297,7 @@ def source_log_modules() -> tuple[set[str], set[str]]: sources = [path for path in (REPO_ROOT / "src").rglob("*") if path.suffix in {".cpp", ".hpp"}] sources += list((REPO_ROOT / "include").rglob("*.hpp")) for path in sources: - text = path.read_text(encoding="utf-8") + text = without_comments(path.read_text(encoding="utf-8")) constants = dict(MODULE_CONSTANT.findall(text)) constants.update(MODULE_CONSTANT_INIT.findall(text)) modules.update(DATABASE_AUDIT_CALL.findall(text)) @@ -297,6 +314,26 @@ def source_log_modules() -> tuple[set[str], set[str]]: class ExampleLogModuleListTests(unittest.TestCase): + def test_a_logger_call_quoted_in_a_comment_names_no_module(self) -> None: + # GIVEN source whose comments quote logger calls, beside literals that hold comment markers. + source = ( + '// observability::log_diagnostic("quoted_line", "x", fields, severity);\n' + '/* observability::log_diagnostic("quoted_block", "x",\n fields, severity); */\n' + 'auto const url = std::string_view{"https://example.org/*not-a-comment"};\n' + 'auto const raw = R"json({"a": "//", "b": "*/"})json";\n' + 'observability::log_diagnostic("real", "x", fields, severity); // trailing\n' + ) + + # WHEN the comments are blanked and the calls read. + stripped = without_comments(source) + modules = {literal for literal, _ in QUALIFIED_LOG_CALL.findall(stripped)} + + # THEN only the call in code counts, the literals are kept whole, and the lines stay where they were. + self.assertEqual(modules, {"real"}) + self.assertIn('"https://example.org/*not-a-comment"', stripped) + self.assertIn('R"json({"a": "//", "b": "*/"})json"', stripped) + self.assertEqual(stripped.count("\n"), source.count("\n")) + def test_each_example_lists_exactly_the_modules_the_server_logs_under(self) -> None: # GIVEN every logger module the server's sources name. modules, unresolved = source_log_modules() From 563da3466c3f56ef5f5fc495e95dd8976d8391bb Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 23:22:40 +0000 Subject: [PATCH 07/28] Read a sv or s suffixed module literal in the level-call scan Review feedback: LEVEL_LOG_CALL wanted the comma straight after the closing quote, so `.info("newmod"sv, ...)` matched nothing. The scan then found no module and reported nothing unresolved, and the test passed while both examples left the module out. The literal may now carry `sv` or `s`, as MODULE_CONSTANT already allows. A new case writes the module that way in every call form the scan reads. Co-Authored-By: Claude Opus 5.5 --- tests/tooling/test_example_config.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 48acb3e67..dc17aa11c 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -259,7 +259,7 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: ) LEVEL_LOG_CALL = re.compile( r'(?:\.|->)\s*(?:trace|debug|info|notice|warning|error|critical)\s*\(\s*' - r'(?:"([A-Za-z0-9_]+)"|([A-Za-z_][A-Za-z0-9_:]*))\s*,' + r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))\s*,' ) # The homeserver's `log_diagnostic_audit(database, "module", "event", ...)` takes the module second. DATABASE_AUDIT_CALL = re.compile(r'\blog_diagnostic_audit\s*\(\s*[A-Za-z_][A-Za-z0-9_.]*\s*,\s*"([A-Za-z0-9_]+)"') @@ -334,6 +334,25 @@ def test_a_logger_call_quoted_in_a_comment_names_no_module(self) -> None: self.assertIn('R"json({"a": "//", "b": "*/"})json"', stripped) self.assertEqual(stripped.count("\n"), source.count("\n")) + def test_a_module_literal_with_a_string_suffix_is_read_in_every_call_form(self) -> None: + # GIVEN each call form the scan reads, with its module written as a `sv` or `s` literal. + calls = { + QUALIFIED_LOG_CALL: 'observability::log_diagnostic("qualified"sv, "x", fields, severity);', + LEVEL_LOG_CALL: 'SingleLog::instance().info("level"sv, "x");\nlog.warning("level_s"s, "x");', + DATABASE_AUDIT_CALL: 'log_diagnostic_audit(runtime.database, "audit"sv, "x", fields);', + } + + # WHEN each is read. + found = { + regex.pattern: {match if isinstance(match, str) else match[0] for match in regex.findall(source)} + for regex, source in calls.items() + } + + # THEN the module is found, so a suffixed literal never drops a module from the expected set. + self.assertEqual(found[QUALIFIED_LOG_CALL.pattern], {"qualified"}) + self.assertEqual(found[LEVEL_LOG_CALL.pattern], {"level", "level_s"}) + self.assertEqual(found[DATABASE_AUDIT_CALL.pattern], {"audit"}) + def test_each_example_lists_exactly_the_modules_the_server_logs_under(self) -> None: # GIVEN every logger module the server's sources name. modules, unresolved = source_log_modules() From b7d81f4578a579d01ae68338119c51749f6dc86e Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 23:39:48 +0000 Subject: [PATCH 08/28] Read level calls on the logger only, and name what the module scan skips Review feedback on the example-config log module test: - LEVEL_LOG_CALL matched a level-named method on any receiver, so another type's `.warning("deprecated", detail)` would have become a module the examples had to list. It now reads level calls only on SingleLog::instance() or a reference named log or logger, which are the only receivers the sources use: the real scan still finds all 13 level calls and the same 54 modules. A new case shows the logger's calls counted and other types' level methods not. - log-filtering.md and testing-standards.md said the scan fails on any module it cannot read, but it skips the forwarding parameters module, mod and logger, and __func__, which the legacy LOG_* macros pass. Both now name those four and the receiver rule. ADR-0872 makes the receiver rule binding and records that a level call through another receiver is missed, the price of not reading every .info(). Co-Authored-By: Claude Opus 5.5 --- ...test-reads-the-modules-from-the-sources.md | 11 ++++++++- docs/log-filtering.md | 5 +++- docs/testing-standards.md | 8 ++++--- tests/tooling/test_example_config.py | 24 +++++++++++++++++-- 4 files changed, 41 insertions(+), 7 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index 6fabd7ad2..01faf7781 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -43,11 +43,20 @@ to it, for a list that exists to be documented. * The scan is text, not a C++ parser: it knows the call forms above, and a new form must be taught to it. * A module constant shared from another file (a header) is not resolved and fails the test. +* Level calls are recognised by their receiver, so one through a receiver the rule does not name is missed rather than + failed. Reading every `.info(...)` instead would take other types' methods for modules and demand example lines for + modules that do not exist; the receiver rule is the price of not doing that. ## Rules for future code * Name a logger call's module with a string literal, or with a string constant defined in the same file. A parameter - that only forwards a caller's module is named `logger`, `mod` or `module` (or is `__func__`), which the scan skips. + that only forwards a caller's module is named `logger`, `mod` or `module`, which the scan skips. So is `__func__`: + the legacy `LOG_*` macros log under the calling function's name, which is no module and is not listed in the + examples. These four identifiers are the only first arguments the scan skips; say so wherever the test is described. +* Call a level method (`info`, `warning`, ...) directly only on `SingleLog::instance()` or on a reference named `log` + or `logger`. The scan reads level calls on those receivers only, so a method of another type that happens to be named + `warning` never becomes a module. A level call through any other receiver breaks this rule, and the scan does not + see it. * To share a module constant across files, or to log through a new call form, extend `source_log_modules` in the test in the same change. Never relax or delete the assertion to get past it. * The examples list every module the server logs under, not a selection of common ones. Do not trim the list. diff --git a/docs/log-filtering.md b/docs/log-filtering.md index a5594dd08..4aa0918ce 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -106,7 +106,10 @@ without a registry. The example configurations (`config/merovingian.conf.example `config/merovingian.conf.bsd.example`) list every module the server logs under; keep both in step when a module is added or removed. `tests/tooling/test_example_config.py` scans `src/` and `include/` for the modules the logger calls name and fails when either example lists a different set, or when a call names its module through anything but a -literal or a string constant in the same file (ADR-0872). This is a non-exhaustive list of common module names +literal or a string constant in the same file. The one exception is a parameter that forwards its caller's module +(`module`, `mod`, `logger`), and `__func__`, which the legacy macros pass (see below): the scan skips them, and a +function name is not listed in the examples. A level method (`info`, `warning`, ...) is read only on +`SingleLog::instance()` or a reference named `log` or `logger` (ADR-0872). This is a non-exhaustive list of common module names used as the first argument to `observability::log_diagnostic` and `log_diagnostic_audit` in `src/` (`rate_limit` is used only with `log_diagnostic_audit`): diff --git a/docs/testing-standards.md b/docs/testing-standards.md index f51814b4d..f23ed1296 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -43,9 +43,11 @@ service function: starting a runtime wires config, the store, the signing key an A list that documents something in the code (the example configurations' `log_modules` lines, for one) is checked by a tooling test that reads the code, never against a second list kept by hand in the test. Such a test fails on anything it cannot read rather than skipping it, so a new form in the code is taught to the test instead of dropping out of the -check, and it ignores comments. `ExampleLogModuleListTests` in `tests/tooling/test_example_config.py` is the model: -a logger call names its module with a literal or a string constant in the same file, and a new call form or a shared -constant is added to the scan in the same change (ADR-0872). +check, and it ignores comments. What it skips on purpose it names, in the test and in the documents that describe it. +`ExampleLogModuleListTests` in `tests/tooling/test_example_config.py` is the model: a logger call names its module with +a literal or a string constant in the same file; the only identifiers it skips are the forwarding parameters `module`, +`mod` and `logger`, and `__func__`; a level method is read only on `SingleLog::instance()` or a reference named `log` +or `logger`; and a new call form or a shared constant is added to the scan in the same change (ADR-0872). ## Concurrency and locking tests diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index dc17aa11c..2b28a8cc5 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -253,12 +253,15 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: # The logger module is the first argument of the qualified free functions, or of a # SingleLog level method. File-local wrappers (`log_diagnostic(event, fields, ...)`) -# take the event first, so only the qualified calls are read. +# take the event first, so only the qualified calls are read. A level method is read only +# on `SingleLog::instance()` or a reference named `log` or `logger` (ADR-0872), so another +# type's `.warning("text", ...)` is not taken for a module. QUALIFIED_LOG_CALL = re.compile( r'observability::log_diagnostic(?:_audit)?\s*\(\s*(?:"([A-Za-z0-9_]+)"|([A-Za-z_][A-Za-z0-9_:]*))' ) LEVEL_LOG_CALL = re.compile( - r'(?:\.|->)\s*(?:trace|debug|info|notice|warning|error|critical)\s*\(\s*' + r'(?:\bSingleLog::instance\(\)|(?])(?:log|logger))\s*(?:\.|->)\s*' + r'(?:trace|debug|info|notice|warning|error|critical)\s*\(\s*' r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))\s*,' ) # The homeserver's `log_diagnostic_audit(database, "module", "event", ...)` takes the module second. @@ -353,6 +356,23 @@ def test_a_module_literal_with_a_string_suffix_is_read_in_every_call_form(self) self.assertEqual(found[LEVEL_LOG_CALL.pattern], {"level", "level_s"}) self.assertEqual(found[DATABASE_AUDIT_CALL.pattern], {"audit"}) + def test_a_level_named_method_of_another_type_names_no_module(self) -> None: + # GIVEN level calls on the logger beside level-named methods of other types. + source = ( + '::merovingian::observability::SingleLog::instance().info("on_instance", "x");\n' + 'log.warning("on_log", "x");\n' + 'logger->error("on_logger", "x");\n' + 'result.warning("deprecated", detail);\n' + 'status->error("phantom", detail);\n' + 'catalog.info("catalog", detail);\n' + ) + + # WHEN the level calls are read. + modules = {literal for literal, _ in LEVEL_LOG_CALL.findall(source)} + + # THEN only the logger's calls name a module, so another type's method adds no phantom module. + self.assertEqual(modules, {"on_instance", "on_log", "on_logger"}) + def test_each_example_lists_exactly_the_modules_the_server_logs_under(self) -> None: # GIVEN every logger module the server's sources name. modules, unresolved = source_log_modules() From 7e2c682565f39105e2af2610fa9cc7f7012a2f0b Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 23:45:54 +0000 Subject: [PATCH 09/28] Say why the level-call scan skips a logger reached through another object Review note: the lookbehind in LEVEL_LOG_CALL rejects a member chain such as ctx->logger->info(...). That is deliberate, since ADR-0872's rule names a reference called log or logger, not a member of another object; the comment beside the pattern now says so. Co-Authored-By: Claude Opus 5.5 --- tests/tooling/test_example_config.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 2b28a8cc5..53bb7fdf8 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -255,7 +255,9 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: # SingleLog level method. File-local wrappers (`log_diagnostic(event, fields, ...)`) # take the event first, so only the qualified calls are read. A level method is read only # on `SingleLog::instance()` or a reference named `log` or `logger` (ADR-0872), so another -# type's `.warning("text", ...)` is not taken for a module. +# type's `.warning("text", ...)` is not taken for a module. The lookbehind keeps `log` or +# `logger` a name of its own: a member reached through another object (`ctx->logger->info`, +# `self.log.info`) is not the reference the rule names, and is not read. QUALIFIED_LOG_CALL = re.compile( r'observability::log_diagnostic(?:_audit)?\s*\(\s*(?:"([A-Za-z0-9_]+)"|([A-Za-z_][A-Za-z0-9_:]*))' ) From 4395790fd778f988838dc09d092945f0db25755e Mon Sep 17 00:00:00 2001 From: James Chapman Date: Fri, 20 Nov 2026 23:51:48 +0000 Subject: [PATCH 10/28] Resolve the audit overload's module, and report a constant with two values Review feedback on the example-config log module test: - DATABASE_AUDIT_CALL read only a literal second argument, so log_diagnostic_audit(runtime.database, audit_module, ...) was skipped: no module and nothing unresolved. It now takes a literal or an identifier, resolved like the other call forms, and pins the first argument to an expression ending in `database` (every call passes runtime.database or rt.homeserver.database), so a wrapper's (event, fields) is not read as a module. - Constants were merged into one dict per file, so two functions each defining log_module with a different value resolved both calls to the last one. Each name now keeps every value it is given; a name with two is reported as ambiguous rather than guessed. - The per-file logic is scan_log_modules(source, label), which two new cases drive with snippets. The real scan is unchanged: 54 modules, none unresolved. ADR-0872 and log-filtering.md state the one-value rule. Co-Authored-By: Claude Opus 5.5 --- ...test-reads-the-modules-from-the-sources.md | 4 +- docs/log-filtering.md | 2 +- tests/tooling/test_example_config.py | 89 +++++++++++++++---- 3 files changed, 78 insertions(+), 17 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index 01faf7781..e156fbafd 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -49,7 +49,9 @@ to it, for a list that exists to be documented. ## Rules for future code -* Name a logger call's module with a string literal, or with a string constant defined in the same file. A parameter +* Name a logger call's module with a string literal, or with a string constant defined in the same file under a name + given no other value there: the scan does not know scopes, so a name two functions each define with a different value + is reported as ambiguous. The database audit overload's module argument follows the same rule. A parameter that only forwards a caller's module is named `logger`, `mod` or `module`, which the scan skips. So is `__func__`: the legacy `LOG_*` macros log under the calling function's name, which is no module and is not listed in the examples. These four identifiers are the only first arguments the scan skips; say so wherever the test is described. diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 4aa0918ce..7aeca929a 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -106,7 +106,7 @@ without a registry. The example configurations (`config/merovingian.conf.example `config/merovingian.conf.bsd.example`) list every module the server logs under; keep both in step when a module is added or removed. `tests/tooling/test_example_config.py` scans `src/` and `include/` for the modules the logger calls name and fails when either example lists a different set, or when a call names its module through anything but a -literal or a string constant in the same file. The one exception is a parameter that forwards its caller's module +literal or a string constant in the same file (one the file gives no other value). The one exception is a parameter that forwards its caller's module (`module`, `mod`, `logger`), and `__func__`, which the legacy macros pass (see below): the scan skips them, and a function name is not listed in the examples. A level method (`info`, `warning`, ...) is read only on `SingleLog::instance()` or a reference named `log` or `logger` (ADR-0872). This is a non-exhaustive list of common module names diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 53bb7fdf8..6d49ce967 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -267,7 +267,12 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))\s*,' ) # The homeserver's `log_diagnostic_audit(database, "module", "event", ...)` takes the module second. -DATABASE_AUDIT_CALL = re.compile(r'\blog_diagnostic_audit\s*\(\s*[A-Za-z_][A-Za-z0-9_.]*\s*,\s*"([A-Za-z0-9_]+)"') +# Its first argument is the `LocalDatabase` (`runtime.database`, `rt.homeserver.database`), which +# tells it apart from a file-local wrapper whose first two arguments are the event and its fields. +DATABASE_AUDIT_CALL = re.compile( + r'\blog_diagnostic_audit\s*\(\s*(?:[A-Za-z_][A-Za-z0-9_]*\s*(?:\.|->)\s*)*database\s*,\s*' + r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))' +) # A module named once in a constant: `auto log_module = std::string_view{"livekit"};` or `name{"livekit"};`. MODULE_CONSTANT = re.compile( r'\b([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:std::string_view\s*\{\s*|std::string\s*\{\s*)?"([A-Za-z0-9_]+)"(?:sv|s)?\s*\}?\s*;' @@ -295,26 +300,44 @@ def without_comments(source: str) -> str: ) +def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: + """The logger modules one C++ source names, and each module argument it cannot resolve, prefixed with `label`.""" + modules: set[str] = set() + unresolved: set[str] = set() + text = without_comments(source) + # Every value each name is given in the file: the scan does not know scopes, so a name + # given two values (say, a `log_module` in each of two functions) is ambiguous, never + # silently resolved to whichever definition came last. + constants: dict[str, set[str]] = {} + for regex in (MODULE_CONSTANT, MODULE_CONSTANT_INIT): + for name, value in regex.findall(text): + constants.setdefault(name, set()).add(value) + for regex in (QUALIFIED_LOG_CALL, LEVEL_LOG_CALL, DATABASE_AUDIT_CALL): + for literal, identifier in regex.findall(text): + short = identifier.split("::")[-1] + if literal: + modules.add(literal) + elif short in FORWARDED_MODULE_PARAMETERS: + continue + elif len(constants.get(short, ())) == 1: + modules.update(constants[short]) + elif short in constants: + unresolved.add(f"{label}: {identifier} (given {sorted(constants[short])} in this file)") + else: + unresolved.add(f"{label}: {identifier}") + return modules, unresolved + + def source_log_modules() -> tuple[set[str], set[str]]: - """Every logger module the server's sources name, and any first argument the scan cannot resolve.""" + """Every logger module the server's sources name, and any module argument the scan cannot resolve.""" modules: set[str] = set() unresolved: set[str] = set() sources = [path for path in (REPO_ROOT / "src").rglob("*") if path.suffix in {".cpp", ".hpp"}] sources += list((REPO_ROOT / "include").rglob("*.hpp")) for path in sources: - text = without_comments(path.read_text(encoding="utf-8")) - constants = dict(MODULE_CONSTANT.findall(text)) - constants.update(MODULE_CONSTANT_INIT.findall(text)) - modules.update(DATABASE_AUDIT_CALL.findall(text)) - for regex in (QUALIFIED_LOG_CALL, LEVEL_LOG_CALL): - for literal, identifier in regex.findall(text): - short = identifier.split("::")[-1] - if literal: - modules.add(literal) - elif short in constants: - modules.add(constants[short]) - elif short not in FORWARDED_MODULE_PARAMETERS: - unresolved.add(f"{path.relative_to(REPO_ROOT).as_posix()}: {identifier}") + found, missed = scan_log_modules(path.read_text(encoding="utf-8"), path.relative_to(REPO_ROOT).as_posix()) + modules |= found + unresolved |= missed return modules, unresolved @@ -358,6 +381,42 @@ def test_a_module_literal_with_a_string_suffix_is_read_in_every_call_form(self) self.assertEqual(found[LEVEL_LOG_CALL.pattern], {"level", "level_s"}) self.assertEqual(found[DATABASE_AUDIT_CALL.pattern], {"audit"}) + def test_a_database_audit_call_resolves_its_module_like_the_other_call_forms(self) -> None: + # GIVEN database audit calls that name their module through a constant, an unknown + # identifier and a forwarding parameter, beside a wrapper whose first argument is no database. + source = ( + 'constexpr auto audit_module = std::string_view{"audited"};\n' + 'log_diagnostic_audit(runtime.database, audit_module, "x", fields);\n' + 'log_diagnostic_audit(rt.homeserver.database, unknown_module, "x", fields);\n' + 'log_diagnostic_audit(database, logger, "x", fields);\n' + 'log_diagnostic_audit(event_name, field_list, severity);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN the constant resolves, the unknown identifier is reported, and neither the forwarding + # parameter nor the wrapper's arguments are taken for a module. + self.assertEqual(modules, {"audited"}) + self.assertEqual(unresolved, {"f.cpp: unknown_module"}) + + def test_a_constant_given_two_values_in_one_file_is_reported_not_guessed(self) -> None: + # GIVEN two functions in one file, each with its own `log_module`. + source = ( + 'void a() { constexpr auto log_module = std::string_view{"first"};\n' + ' observability::log_diagnostic(log_module, "x", fields, severity); }\n' + 'void b() { constexpr auto log_module = std::string_view{"second"};\n' + ' observability::log_diagnostic(log_module, "x", fields, severity); }\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN neither value is guessed: the call is reported with both values, so the test fails + # until each function names its module with a literal or a name of its own. + self.assertEqual(modules, set()) + self.assertEqual(unresolved, {"f.cpp: log_module (given ['first', 'second'] in this file)"}) + def test_a_level_named_method_of_another_type_names_no_module(self) -> None: # GIVEN level calls on the logger beside level-named methods of other types. source = ( From e2d1c6c9ee542f7ec4cbbe0d4b387e4aa4c34f09 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 00:05:54 +0000 Subject: [PATCH 11/28] Assert the TURN reason field, read audit calls by shape, and narrow "every module" Review feedback: - The turn.credentials_unavailable scenario now checks user_id with field_value and the whole fixed reason ("shared secret file unreadable or empty"), which field_value cannot read as it holds spaces. Dropping or changing the reason now fails a test. - DATABASE_AUDIT_CALL recognised the homeserver audit overload only when its first argument ended in `database`, so a call through an alias (`auto& db = rt.database; log_diagnostic_audit(db, ...)`) was skipped silently. It now goes by the call's shape: unqualified, with a name or member expression (or *pointer) first. A file-local wrapper takes a literal event first and never has that shape; one called with a variable event does, and is reported unresolved rather than skipped. The real scan still reads the same 26 calls and 54 modules. - "Every module the server logs under" was not true of the legacy LOG_* lines, which log under the calling function's name. Both examples, log-filtering.md, the CHANGELOG and ADR-0872 now say "every module a structured logger call names" and that function names are left out. ADR-0872 records the shape rule. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- config/merovingian.conf.bsd.example | 4 +- config/merovingian.conf.example | 4 +- ...test-reads-the-modules-from-the-sources.md | 7 +++- docs/log-filtering.md | 3 +- .../test_turn_shared_secret_flow.cpp | 6 ++- tests/tooling/test_example_config.py | 39 ++++++++++++++----- 7 files changed, 50 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aebbebef6..29f9052e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -181,8 +181,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * The Fedora 44 and 45 RPMs build again: GCC 16 refused `std::ranges::find` with a bare string literal under C++26, and `reject-unsafe.sh` now rejects that form in code and tests (ADR-0870). * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. -* The example configurations list every `log_modules` module the server logs under (twelve were missing, `token` is - gone), and a tooling test fails when that list and the modules the sources log under differ (ADR-0872). +* The example configurations list every module a structured logger call names (twelve were missing, `token` is + gone), and a tooling test fails when that list and the modules the sources name differ (ADR-0872). ## Release notes diff --git a/config/merovingian.conf.bsd.example b/config/merovingian.conf.bsd.example index a8eca1568..b775d0efa 100644 --- a/config/merovingian.conf.bsd.example +++ b/config/merovingian.conf.bsd.example @@ -911,7 +911,9 @@ appservice.max_queued_events=100000 # every other module sees. Restart is required for changes to take effect. # Merovingian needs to run with the --debug parameter to enable debug logging. # — see docs/log-filtering.md. -# Every module the server logs under: +# Every module a structured logger call names. The legacy LOG_* lines log +# under the calling function's name instead (for example `main`), and a +# function name is a valid key that this list leaves out: # log_modules.appservice=info # log_modules.auth=info # log_modules.client_server=info diff --git a/config/merovingian.conf.example b/config/merovingian.conf.example index 2b5bf95ec..9ba3340ab 100644 --- a/config/merovingian.conf.example +++ b/config/merovingian.conf.example @@ -884,7 +884,9 @@ appservice.max_queued_events=100000 # every other module sees. Restart is required for changes to take effect. # Merovingian needs to run with the --debug parameter to enable debug logging. # — see docs/log-filtering.md. -# Every module the server logs under: +# Every module a structured logger call names. The legacy LOG_* lines log +# under the calling function's name instead (for example `main`), and a +# function name is a valid key that this list leaves out: # log_modules.appservice=info # log_modules.auth=info # log_modules.client_server=info diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index e156fbafd..d1bd49d2e 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -61,7 +61,12 @@ to it, for a list that exists to be documented. see it. * To share a module constant across files, or to log through a new call form, extend `source_log_modules` in the test in the same change. Never relax or delete the assertion to get past it. -* The examples list every module the server logs under, not a selection of common ones. Do not trim the list. +* The examples list every module a structured logger call names, not a selection of common ones, and say that the + legacy `LOG_*` macros' function names are left out. Do not trim the list. +* The homeserver's `log_diagnostic_audit(database, module, ...)` is recognised by its shape (an unqualified call whose + first argument is a name or member expression), never by what the database is called, so an alias such as `db` is + read. Call a file-local wrapper with its event as a literal: one called with a variable event has the same shape and + is reported as unresolved. ## Links diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 7aeca929a..aca5beb86 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -103,7 +103,8 @@ A malformed `category=` value returns 400 with The `log_modules.` keys accept any string — the bootstrap forwards the name to `SingleLog::set_module_log_level(name, level)` without a registry. The example configurations (`config/merovingian.conf.example` and -`config/merovingian.conf.bsd.example`) list every module the server logs under; keep both in step when a module is +`config/merovingian.conf.bsd.example`) list every module a structured logger call names (not the function names the +legacy `LOG_*` macros log under, see below); keep both in step when a module is added or removed. `tests/tooling/test_example_config.py` scans `src/` and `include/` for the modules the logger calls name and fails when either example lists a different set, or when a call names its module through anything but a literal or a string constant in the same file (one the file gives no other value). The one exception is a parameter that forwards its caller's module diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index f7999b6c9..078cb494f 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -398,12 +398,14 @@ SCENARIO("The turn log names an unreadable shared secret as an error under its o auto const response = turn_server(runtime, alice); auto const text = capture.text(); - THEN("the answer is 500 and an error line under turn names the event and alice") + THEN("the answer is 500 and an error line under turn names the event, alice and the fixed reason") { REQUIRE(response.status == 500U); auto const line = module_line(text, "ERROR", "turn", "turn.credentials_unavailable"); REQUIRE(line.has_value()); - CHECK(line->find("@alice:example.org") != std::string::npos); + CHECK(field_value(*line, "user_id") == "@alice:example.org"); + // The reason holds spaces, so it is matched whole rather than through field_value. + CHECK(line->find(" reason=shared secret file unreadable or empty") != std::string::npos); } } } diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 6d49ce967..eaeb276e7 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -267,10 +267,13 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))\s*,' ) # The homeserver's `log_diagnostic_audit(database, "module", "event", ...)` takes the module second. -# Its first argument is the `LocalDatabase` (`runtime.database`, `rt.homeserver.database`), which -# tells it apart from a file-local wrapper whose first two arguments are the event and its fields. +# It is told apart by its shape, never by what the database is called (`runtime.database`, or an +# alias such as `db`): any call not qualified with `observability::` whose first argument is a name +# or member expression, not a literal. A file-local wrapper takes the event first, as a literal, so it +# never has that shape; the qualified `observability::` form is QUALIFIED_LOG_CALL's. DATABASE_AUDIT_CALL = re.compile( - r'\blog_diagnostic_audit\s*\(\s*(?:[A-Za-z_][A-Za-z0-9_]*\s*(?:\.|->)\s*)*database\s*,\s*' + r'(?)\s*[A-Za-z_][A-Za-z0-9_]*)*\s*,\s*' r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))' ) # A module named once in a constant: `auto log_module = std::string_view{"livekit"};` or `name{"livekit"};`. @@ -382,24 +385,42 @@ def test_a_module_literal_with_a_string_suffix_is_read_in_every_call_form(self) self.assertEqual(found[DATABASE_AUDIT_CALL.pattern], {"audit"}) def test_a_database_audit_call_resolves_its_module_like_the_other_call_forms(self) -> None: - # GIVEN database audit calls that name their module through a constant, an unknown - # identifier and a forwarding parameter, beside a wrapper whose first argument is no database. + # GIVEN database audit calls through the database, an alias for it and a pointer, naming their + # module with a literal, a constant, an unknown identifier and a forwarding parameter, beside a + # wrapper called with a literal event and a qualified `observability::` call. source = ( 'constexpr auto audit_module = std::string_view{"audited"};\n' 'log_diagnostic_audit(runtime.database, audit_module, "x", fields);\n' + 'auto& db = rt.database;\n' + 'log_diagnostic_audit(db, "through_alias", "x", fields);\n' + 'log_diagnostic_audit(*database_ptr, "through_pointer", "x", fields);\n' 'log_diagnostic_audit(rt.homeserver.database, unknown_module, "x", fields);\n' 'log_diagnostic_audit(database, logger, "x", fields);\n' - 'log_diagnostic_audit(event_name, field_list, severity);\n' + 'log_diagnostic_audit("event.name", {{"k", "v", false}}, severity);\n' + 'observability::log_diagnostic_audit(logger, event, fields, severity);\n' ) # WHEN the source is scanned. modules, unresolved = scan_log_modules(source, "f.cpp") - # THEN the constant resolves, the unknown identifier is reported, and neither the forwarding - # parameter nor the wrapper's arguments are taken for a module. - self.assertEqual(modules, {"audited"}) + # THEN every call of the database overload is read whatever the database is called, the + # constant resolves, the unknown identifier is reported, and neither the forwarding parameter, + # the wrapper's event nor the qualified call's event is taken for a module. + self.assertEqual(modules, {"audited", "through_alias", "through_pointer"}) self.assertEqual(unresolved, {"f.cpp: unknown_module"}) + def test_a_wrapper_called_with_a_variable_event_is_reported_not_skipped(self) -> None: + # GIVEN a file-local wrapper called with its event in a variable: the database overload's shape. + source = 'log_diagnostic_audit(event_name, field_list, severity);\n' + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN it is reported, never silently skipped: the scan cannot tell it from a database call + # (ADR-0872), and a wrapper is called with a literal event. + self.assertEqual(modules, set()) + self.assertEqual(unresolved, {"f.cpp: field_list"}) + def test_a_constant_given_two_values_in_one_file_is_reported_not_guessed(self) -> None: # GIVEN two functions in one file, each with its own `log_module`. source = ( From 0f67b442f0d2d9cae59dd9ddfee3a605d941ea68 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 00:09:12 +0000 Subject: [PATCH 12/28] Say which first arguments the audit-call scan cannot parse Review note: a database audit call whose first argument is parenthesised or a call expression is skipped rather than reported. The comment beside DATABASE_AUDIT_CALL now says so, and that the database is passed as a name, a member or *pointer. Co-Authored-By: Claude Opus 5.5 --- tests/tooling/test_example_config.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index eaeb276e7..7c2ed2640 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -270,7 +270,9 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: # It is told apart by its shape, never by what the database is called (`runtime.database`, or an # alias such as `db`): any call not qualified with `observability::` whose first argument is a name # or member expression, not a literal. A file-local wrapper takes the event first, as a literal, so it -# never has that shape; the qualified `observability::` form is QUALIFIED_LOG_CALL's. +# never has that shape; the qualified `observability::` form is QUALIFIED_LOG_CALL's. A first +# argument the shape cannot parse, such as `(db)` or a call (`database_of(rt)`), is skipped, not +# reported: pass the database as a name, a member or `*pointer` (ADR-0872). DATABASE_AUDIT_CALL = re.compile( r'(?)\s*[A-Za-z_][A-Za-z0-9_]*)*\s*,\s*' From 28d3badefcc275d6684f752fd65a44ba41702317 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 00:16:01 +0000 Subject: [PATCH 13/28] Accept the s suffix on a brace-initialised module constant Review feedback: MODULE_CONSTANT_INIT allowed only sv, so a constant written log_module{"livekit"s}; was collected under no name and every call using it was reported unresolved. It now accepts sv or s, as the other three patterns do. A new case writes constants with each suffix, by assignment and by brace initialisation; the brace s form failed before. The real scan is unchanged: 54 modules, none unresolved. Co-Authored-By: Claude Opus 5.5 --- tests/tooling/test_example_config.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 7c2ed2640..adc30097a 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -282,7 +282,7 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: MODULE_CONSTANT = re.compile( r'\b([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:std::string_view\s*\{\s*|std::string\s*\{\s*)?"([A-Za-z0-9_]+)"(?:sv|s)?\s*\}?\s*;' ) -MODULE_CONSTANT_INIT = re.compile(r'\b([A-Za-z_][A-Za-z0-9_]*)\s*\{\s*"([A-Za-z0-9_]+)"(?:sv)?\s*\}\s*;') +MODULE_CONSTANT_INIT = re.compile(r'\b([A-Za-z_][A-Za-z0-9_]*)\s*\{\s*"([A-Za-z0-9_]+)"(?:sv|s)?\s*\}\s*;') # Identifiers that forward a caller's module rather than name one. FORWARDED_MODULE_PARAMETERS = {"__func__", "mod", "logger", "module"} EXAMPLE_LOG_MODULE_LINE = re.compile(r"^# log_modules\.([A-Za-z0-9_]+)=", re.MULTILINE) @@ -386,6 +386,27 @@ def test_a_module_literal_with_a_string_suffix_is_read_in_every_call_form(self) self.assertEqual(found[LEVEL_LOG_CALL.pattern], {"level", "level_s"}) self.assertEqual(found[DATABASE_AUDIT_CALL.pattern], {"audit"}) + def test_a_module_constant_with_a_string_suffix_resolves_in_both_forms(self) -> None: + # GIVEN module constants written with an `s` or `sv` suffix, by assignment and by brace + # initialisation, each used by a call. + source = ( + 'auto const assigned_s = "assigned_s"s;\n' + 'constexpr auto assigned_sv = std::string_view{"assigned_sv"sv};\n' + 'constexpr std::string_view braced_sv{"braced_sv"sv};\n' + 'std::string const braced_s{"braced_s"s};\n' + 'observability::log_diagnostic(assigned_s, "x", fields, severity);\n' + 'observability::log_diagnostic(assigned_sv, "x", fields, severity);\n' + 'observability::log_diagnostic(braced_sv, "x", fields, severity);\n' + 'observability::log_diagnostic(braced_s, "x", fields, severity);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN every constant resolves, so a suffix never sends a well-named module to `unresolved`. + self.assertEqual(modules, {"assigned_s", "assigned_sv", "braced_sv", "braced_s"}) + self.assertEqual(unresolved, set()) + def test_a_database_audit_call_resolves_its_module_like_the_other_call_forms(self) -> None: # GIVEN database audit calls through the database, an alias for it and a pointer, naming their # module with a literal, a constant, an unknown identifier and a forwarding parameter, beside a From a61eb43ab1384b251ffb705b054f09b2c1149f45 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 00:30:10 +0000 Subject: [PATCH 14/28] Resolve a same-file constant before skipping a forwarding name Review feedback: scan_log_modules skipped module, mod and logger before looking them up as constants, so a constant named module was dropped and its module fell out of the expected set. A constant the file defines now resolves first; the forwarding names are skipped only when no constant of that name exists. A new case covers both. ADR-0872 states the order. The level-call receiver test also gains m_log, event_log, log_ and logger_, which the lookbehind already rejects (its class includes _). The real scan is unchanged: 54 modules, none unresolved. Co-Authored-By: Claude Opus 5.5 --- ...test-reads-the-modules-from-the-sources.md | 3 +- tests/tooling/test_example_config.py | 31 +++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index d1bd49d2e..c75ec5f2e 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -52,7 +52,8 @@ to it, for a list that exists to be documented. * Name a logger call's module with a string literal, or with a string constant defined in the same file under a name given no other value there: the scan does not know scopes, so a name two functions each define with a different value is reported as ambiguous. The database audit overload's module argument follows the same rule. A parameter - that only forwards a caller's module is named `logger`, `mod` or `module`, which the scan skips. So is `__func__`: + that only forwards a caller's module is named `logger`, `mod` or `module`, which the scan skips, but only when the + file defines no string constant of that name: a constant always resolves first, so the skip goes by role. So is `__func__`: the legacy `LOG_*` macros log under the calling function's name, which is no module and is not listed in the examples. These four identifiers are the only first arguments the scan skips; say so wherever the test is described. * Call a level method (`info`, `warning`, ...) directly only on `SingleLog::instance()` or on a reference named `log` diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index adc30097a..8292d584c 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -320,14 +320,16 @@ def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: for regex in (QUALIFIED_LOG_CALL, LEVEL_LOG_CALL, DATABASE_AUDIT_CALL): for literal, identifier in regex.findall(text): short = identifier.split("::")[-1] + # A constant the file defines comes first, whatever it is called: the forwarding names + # are skipped only when no constant of that name exists, so they skip by role, not name. if literal: modules.add(literal) - elif short in FORWARDED_MODULE_PARAMETERS: - continue elif len(constants.get(short, ())) == 1: modules.update(constants[short]) elif short in constants: unresolved.add(f"{label}: {identifier} (given {sorted(constants[short])} in this file)") + elif short in FORWARDED_MODULE_PARAMETERS: + continue else: unresolved.add(f"{label}: {identifier}") return modules, unresolved @@ -461,6 +463,27 @@ def test_a_constant_given_two_values_in_one_file_is_reported_not_guessed(self) - self.assertEqual(modules, set()) self.assertEqual(unresolved, {"f.cpp: log_module (given ['first', 'second'] in this file)"}) + def test_a_constant_named_like_a_forwarding_parameter_still_resolves(self) -> None: + # GIVEN a file that defines a module constant called `module`, and another file whose + # `module` is only a parameter forwarding its caller's module. + with_constant = ( + 'constexpr auto module = std::string_view{"named_module"};\n' + 'observability::log_diagnostic(module, "x", fields, severity);\n' + ) + forwarding = ( + 'auto log_line(std::string_view module) -> void\n' + '{ observability::log_diagnostic(module, "x", fields, severity); }\n' + ) + + # WHEN each is scanned. + constant_modules, constant_unresolved = scan_log_modules(with_constant, "a.cpp") + forwarded_modules, forwarded_unresolved = scan_log_modules(forwarding, "b.cpp") + + # THEN the constant names its module, and only the bare parameter is skipped: the skip + # is by role, so a constant is never dropped for its name. + self.assertEqual((constant_modules, constant_unresolved), ({"named_module"}, set())) + self.assertEqual((forwarded_modules, forwarded_unresolved), (set(), set())) + def test_a_level_named_method_of_another_type_names_no_module(self) -> None: # GIVEN level calls on the logger beside level-named methods of other types. source = ( @@ -470,6 +493,10 @@ def test_a_level_named_method_of_another_type_names_no_module(self) -> None: 'result.warning("deprecated", detail);\n' 'status->error("phantom", detail);\n' 'catalog.info("catalog", detail);\n' + 'm_log.info("member_prefix", detail);\n' + 'event_log.error("name_prefix", detail);\n' + 'log_.warning("name_suffix", detail);\n' + 'logger_->error("pointer_suffix", detail);\n' ) # WHEN the level calls are read. From 94d24bc78be44eed1c79ca94f71689f28576f530 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 00:50:40 +0000 Subject: [PATCH 15/28] Report a logger call whose arguments the module scan cannot read Review feedback: a call of a known form whose module argument was parenthesised or a call (`(kModule)`, `module_of(rt)`, `SingleLog::instance().info(module_name(), ...)`), or whose database argument the audit pattern could not parse (`database_of(rt)`, `(db)`), matched no pattern and was skipped silently. The docs promise the scan fails on what it cannot read. Each call form now has an opening pattern that finds every call of the form, whatever its arguments, and the full pattern that reads it from there. An opening the full pattern cannot read is reported in `unresolved`, quoting the call. Declarations (`auto log_diagnostic_audit(`) and literal-event wrapper calls are not openings. New cases cover the five unreadable calls and the declarations. The real scan is unchanged: 54 modules, none unresolved. ADR-0872 now states the database argument forms (name, member, *pointer) and that anything else is reported. Co-Authored-By: Claude Opus 5.5 --- ...test-reads-the-modules-from-the-sources.md | 15 ++-- tests/tooling/test_example_config.py | 86 +++++++++++++++---- 2 files changed, 80 insertions(+), 21 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index c75ec5f2e..8c7f91e58 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -37,7 +37,10 @@ to it, for a list that exists to be documented. * A new module fails the test, with its name, until both examples list it; a module nothing logs under any more fails until it is dropped. -* A first argument the scan cannot resolve fails the test instead of shrinking the expected set. +* A first argument the scan cannot resolve fails the test instead of shrinking the expected set, and so does a call + of a known form whose arguments it cannot read (`(kModule)`, `module_of(rt)`, `database_of(rt)`): each form has an + opening pattern that finds every call of that form, and an opening the full pattern cannot read is reported with + the call quoted. ### Negative Consequences @@ -64,10 +67,12 @@ to it, for a list that exists to be documented. in the same change. Never relax or delete the assertion to get past it. * The examples list every module a structured logger call names, not a selection of common ones, and say that the legacy `LOG_*` macros' function names are left out. Do not trim the list. -* The homeserver's `log_diagnostic_audit(database, module, ...)` is recognised by its shape (an unqualified call whose - first argument is a name or member expression), never by what the database is called, so an alias such as `db` is - read. Call a file-local wrapper with its event as a literal: one called with a variable event has the same shape and - is reported as unresolved. +* The homeserver's `log_diagnostic_audit(database, module, ...)` is recognised by its shape (an unqualified call that + is not a declaration and does not open with a literal), never by what the database is called, so an alias such as + `db` is read. Pass the database as a name, a member expression or `*pointer`; any other first argument (`(db)`, + `database_of(rt)`) is reported, and so is the module argument of any call when it is neither a literal nor a name. + Call a file-local wrapper with its event as a literal: one called with a variable event has the same shape and is + reported as unresolved. ## Links diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 8292d584c..97fcecc27 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -258,25 +258,36 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: # type's `.warning("text", ...)` is not taken for a module. The lookbehind keeps `log` or # `logger` a name of its own: a member reached through another object (`ctx->logger->info`, # `self.log.info`) is not the reference the rule names, and is not read. -QUALIFIED_LOG_CALL = re.compile( - r'observability::log_diagnostic(?:_audit)?\s*\(\s*(?:"([A-Za-z0-9_]+)"|([A-Za-z_][A-Za-z0-9_:]*))' -) -LEVEL_LOG_CALL = re.compile( +# +# Each call form has an opening, which finds every call of that form whatever its arguments, +# and the full pattern, which reads the module from it. A call whose opening is found and whose +# arguments the full pattern cannot read (`(kModule)`, `module_of(rt)`, `database_of(rt)`) is +# reported, never skipped (ADR-0872). +MODULE_ARGUMENT = r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))\s*,' +QUALIFIED_LOG_OPENING = re.compile(r'observability::log_diagnostic(?:_audit)?\s*\(') +QUALIFIED_LOG_CALL = re.compile(QUALIFIED_LOG_OPENING.pattern + r'\s*' + MODULE_ARGUMENT) +LEVEL_LOG_OPENING = re.compile( r'(?:\bSingleLog::instance\(\)|(?])(?:log|logger))\s*(?:\.|->)\s*' - r'(?:trace|debug|info|notice|warning|error|critical)\s*\(\s*' - r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))\s*,' + r'(?:trace|debug|info|notice|warning|error|critical)\s*\(' ) +LEVEL_LOG_CALL = re.compile(LEVEL_LOG_OPENING.pattern + r'\s*' + MODULE_ARGUMENT) # The homeserver's `log_diagnostic_audit(database, "module", "event", ...)` takes the module second. # It is told apart by its shape, never by what the database is called (`runtime.database`, or an -# alias such as `db`): any call not qualified with `observability::` whose first argument is a name -# or member expression, not a literal. A file-local wrapper takes the event first, as a literal, so it -# never has that shape; the qualified `observability::` form is QUALIFIED_LOG_CALL's. A first -# argument the shape cannot parse, such as `(db)` or a call (`database_of(rt)`), is skipped, not -# reported: pass the database as a name, a member or `*pointer` (ADR-0872). +# alias such as `db`): any call not qualified with `observability::` and not opening with a literal. +# A file-local wrapper takes the event first, as a literal, so it never has that shape; the +# qualified `observability::` form is QUALIFIED_LOG_CALL's; a declaration (`auto log_diagnostic_audit(`) +# is no call. The database is read as a name, a member expression or `*pointer`; any other first +# argument is reported (ADR-0872). +DATABASE_AUDIT_OPENING = re.compile(r'(?)\s*[A-Za-z_][A-Za-z0-9_]*)*\s*,\s*' - r'(?:"([A-Za-z0-9_]+)"(?:sv|s)?|([A-Za-z_][A-Za-z0-9_:]*))' + DATABASE_AUDIT_OPENING.pattern + + r'\s*\*?\s*[A-Za-z_][A-Za-z0-9_]*(?:\s*(?:\.|->)\s*[A-Za-z_][A-Za-z0-9_]*)*\s*,\s*' + + MODULE_ARGUMENT +) +CALL_FORMS = ( + (QUALIFIED_LOG_OPENING, QUALIFIED_LOG_CALL), + (LEVEL_LOG_OPENING, LEVEL_LOG_CALL), + (DATABASE_AUDIT_OPENING, DATABASE_AUDIT_CALL), ) # A module named once in a constant: `auto log_module = std::string_view{"livekit"};` or `name{"livekit"};`. MODULE_CONSTANT = re.compile( @@ -317,8 +328,14 @@ def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: for regex in (MODULE_CONSTANT, MODULE_CONSTANT_INIT): for name, value in regex.findall(text): constants.setdefault(name, set()).add(value) - for regex in (QUALIFIED_LOG_CALL, LEVEL_LOG_CALL, DATABASE_AUDIT_CALL): - for literal, identifier in regex.findall(text): + for opening, call in CALL_FORMS: + for found in opening.finditer(text): + read = call.match(text, found.start()) + if read is None: + excerpt = " ".join(text[found.start() : found.end() + 40].split()) + unresolved.add(f"{label}: cannot read the module of `{excerpt}`") + continue + literal, identifier = read.group(1), read.group(2) or "" short = identifier.split("::")[-1] # A constant the file defines comes first, whatever it is called: the forwarding names # are skipped only when no constant of that name exists, so they skip by role, not name. @@ -463,6 +480,43 @@ def test_a_constant_given_two_values_in_one_file_is_reported_not_guessed(self) - self.assertEqual(modules, set()) self.assertEqual(unresolved, {"f.cpp: log_module (given ['first', 'second'] in this file)"}) + def test_a_call_whose_module_argument_cannot_be_read_is_reported_not_skipped(self) -> None: + # GIVEN one call of each form whose module, or the audit overload's database, is an + # argument the scan cannot read: parenthesised, or a call. + source = ( + 'observability::log_diagnostic((kTurnModule), "x", fields, severity);\n' + 'observability::log_diagnostic(module_of(rt), "x", fields, severity);\n' + 'SingleLog::instance().info(module_name(), "x");\n' + 'log_diagnostic_audit(database_of(rt), "audited", "x", fields);\n' + 'log_diagnostic_audit((db), "audited", "x", fields);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN no module is read from them, and each one is reported, quoting the call, so the + # failure points at the call rather than at the example configurations. + self.assertEqual(modules, set()) + self.assertEqual(len(unresolved), 5, sorted(unresolved)) + for excerpt in ("(kTurnModule)", "module_of(rt)", "module_name()", "database_of(rt)", "(db)"): + with self.subTest(excerpt=excerpt): + self.assertTrue(any(excerpt in entry for entry in unresolved), sorted(unresolved)) + + def test_a_declaration_of_the_audit_overload_is_not_taken_for_a_call(self) -> None: + # GIVEN the overload's declarations and a literal-event wrapper call. + source = ( + 'auto log_diagnostic_audit(LocalDatabase& database, std::string_view logger, std::string_view event,\n' + ' std::vector fields) -> void;\n' + 'inline auto log_diagnostic_audit(std::string_view logger, std::string_view event) -> void;\n' + 'log_diagnostic_audit("event.name", {{"k", "v", false}}, severity);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.hpp") + + # THEN nothing is read and nothing is reported. + self.assertEqual((modules, unresolved), (set(), set())) + def test_a_constant_named_like_a_forwarding_parameter_still_resolves(self) -> None: # GIVEN a file that defines a module constant called `module`, and another file whose # `module` is only a parameter forwarding its caller's module. From dc0886d2febe9d3b29dd5b67743aaad159716155 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 01:01:04 +0000 Subject: [PATCH 16/28] Find logger calls only outside literals, and skip only bare forwarding names Review feedback on the example-config log module test: - A logger call written inside a string literal, such as R"cpp(observability::log_diagnostic("example_only", ...))cpp", was read as a real call and added a module nothing logs under. Calls and constants are now found in a copy of the source whose literals keep their quotes but have blank contents, the same length as the source, and read from the source at the same position. Text inside a literal is no call and no constant. - The forwarding names were matched on the identifier's last part, so shared::module was skipped like a bare `module` parameter. Only the bare names are skipped now; a qualified one is reported. New cases cover both. The real scan is unchanged: 54 modules, none unresolved. ADR-0872 says calls are found outside literals. Co-Authored-By: Claude Opus 5.5 --- ...test-reads-the-modules-from-the-sources.md | 3 +- tests/tooling/test_example_config.py | 67 +++++++++++++++++-- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index 8c7f91e58..72f0de259 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -26,7 +26,8 @@ by nothing. How do the examples stay complete without someone remembering to edi Chosen option: "a tooling test that reads the module names from the sources", `ExampleLogModuleListTests` in `tests/tooling/test_example_config.py`. It blanks C++ comments (a comment that quotes a -call names no module), then reads the first argument of the qualified `observability::log_diagnostic` and +call names no module) and finds calls and constants only outside string literals (logger-call text inside a string is +no call), then reads the first argument of the qualified `observability::log_diagnostic` and `log_diagnostic_audit` calls and of `SingleLog` level calls, the second argument of the homeserver's `log_diagnostic_audit(database, "module", ...)` overload, and resolves an identifier through a string constant defined in the same file. Each example must list exactly that set as `# log_modules.=` lines, each once. A hand-kept list diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 97fcecc27..6e0118d16 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -316,20 +316,42 @@ def without_comments(source: str) -> str: ) +def without_literal_contents(source: str) -> str: + """The source with each literal replaced by a quote, blanks and a quote, of the same length. + + A string's contents are never code, so nothing inside one is found as a call or a constant; + the quotes stay, so a call that opens with a literal still looks like one. + """ + return CPP_COMMENT_OR_LITERAL.sub( + lambda match: match.group(0) + if match.group("comment") + else '"' + re.sub(r"[^\n]", " ", match.group(0)[1:-1]) + '"', + source, + ) + + def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: """The logger modules one C++ source names, and each module argument it cannot resolve, prefixed with `label`.""" modules: set[str] = set() unresolved: set[str] = set() text = without_comments(source) + # Calls and constants are found in `code`, where every literal's contents are blanked, so a + # logger call written inside a string (`R"cpp(observability::log_diagnostic(...))cpp"`) is no + # call. Their arguments are then read from `text` at the same position: the two are the same + # length, character for character. + code = without_literal_contents(text) # Every value each name is given in the file: the scan does not know scopes, so a name # given two values (say, a `log_module` in each of two functions) is ambiguous, never # silently resolved to whichever definition came last. constants: dict[str, set[str]] = {} for regex in (MODULE_CONSTANT, MODULE_CONSTANT_INIT): - for name, value in regex.findall(text): - constants.setdefault(name, set()).add(value) + for found in regex.finditer(text): + # Its value is a literal, so it is matched in `text`; its name must be code, not the + # inside of some other literal, where `code` holds a blank instead. + if code[found.start()] == text[found.start()]: + constants.setdefault(found.group(1), set()).add(found.group(2)) for opening, call in CALL_FORMS: - for found in opening.finditer(text): + for found in opening.finditer(code): read = call.match(text, found.start()) if read is None: excerpt = " ".join(text[found.start() : found.end() + 40].split()) @@ -345,7 +367,9 @@ def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: modules.update(constants[short]) elif short in constants: unresolved.add(f"{label}: {identifier} (given {sorted(constants[short])} in this file)") - elif short in FORWARDED_MODULE_PARAMETERS: + elif identifier in FORWARDED_MODULE_PARAMETERS: + # Only a bare parameter forwards its caller's module. A qualified name such as + # `shared::module` names a constant defined elsewhere, which the scan cannot read. continue else: unresolved.add(f"{label}: {identifier}") @@ -517,6 +541,41 @@ def test_a_declaration_of_the_audit_overload_is_not_taken_for_a_call(self) -> No # THEN nothing is read and nothing is reported. self.assertEqual((modules, unresolved), (set(), set())) + def test_logger_call_text_inside_a_string_literal_is_not_a_call(self) -> None: + # GIVEN a logger call and a module constant written inside string literals, beside a + # real call that names its module with a literal and one through a real constant. + source = ( + 'auto const sample = R"cpp(observability::log_diagnostic("example_only", "event", fields, severity);)cpp";\n' + 'auto const doc = "log.info(\\"quoted_level\\", x); auto m = std::string_view{\\"in_string\\"};";\n' + 'constexpr auto log_module = std::string_view{"real_constant"};\n' + 'observability::log_diagnostic("real_literal", "event", fields, severity);\n' + 'observability::log_diagnostic(log_module, "event", fields, severity);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN only the real calls count: the text inside the literals names no module and + # defines no constant. + self.assertEqual(modules, {"real_literal", "real_constant"}) + self.assertEqual(unresolved, set()) + + def test_a_qualified_forwarding_name_is_reported_not_skipped(self) -> None: + # GIVEN calls naming their module through `shared::module`, a constant in another file, + # and through a bare `module` parameter. + source = ( + 'observability::log_diagnostic(shared::module, "event", fields, severity);\n' + 'auto log_line(std::string_view module) -> void\n' + '{ observability::log_diagnostic(module, "event", fields, severity); }\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN only the bare parameter is skipped: the qualified name is reported. + self.assertEqual(modules, set()) + self.assertEqual(unresolved, {"f.cpp: shared::module"}) + def test_a_constant_named_like_a_forwarding_parameter_still_resolves(self) -> None: # GIVEN a file that defines a module constant called `module`, and another file whose # `module` is only a parameter forwarding its caller's module. From f06c97a53aa36e10f3218babd2395a090635b3a6 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 08:15:18 +0000 Subject: [PATCH 17/28] Fix the clang-tidy findings on the TURN log: const& fields, checked optional access log_turn_diagnostic took its field vector by value and only passed it on to observability::log_diagnostic, which takes a const reference (performance-unnecessary-value-param). The TURN log scenarios read the found line with *line and line-> after REQUIRE(line.has_value()), which clang-tidy's dataflow cannot see through (bugprone-unchecked-optional-access); they now use line.value(). Co-Authored-By: Claude Opus 5.5 --- src/homeserver/ClientServerRuntime.cpp | 2 +- .../test_turn_shared_secret_flow.cpp | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index a16b22363..66e7f9b5a 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -263,7 +263,7 @@ namespace // client-server line (ADR-0871). No field may carry credential text: never the username, the password or the // shared secret. Today's fields are `user_id` on every line, `credential`, `ttl_seconds` and `uri_count` on the // issued line, and a fixed `reason` on the unavailable one. - auto log_turn_diagnostic(std::string_view event, std::vector fields, + auto log_turn_diagnostic(std::string_view event, std::vector const& fields, observability::LogEventSeverity severity) -> void { observability::log_diagnostic("turn", event, fields, severity); diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index 078cb494f..5cdf54820 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -313,10 +313,10 @@ SCENARIO("The turn log files an issued credential under its own module, naming t REQUIRE(response.status == 200U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); REQUIRE(line.has_value()); - CHECK(field_value(*line, "user_id") == "@alice:example.org"); - CHECK(field_value(*line, "credential") == "shared_secret"); - CHECK(field_value(*line, "ttl_seconds") == "3600"); - CHECK(field_value(*line, "uri_count") == "1"); + CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); + CHECK(field_value(line.value(), "credential") == "shared_secret"); + CHECK(field_value(line.value(), "ttl_seconds") == "3600"); + CHECK(field_value(line.value(), "uri_count") == "1"); } THEN("the log holds neither the username, the password nor the shared secret") @@ -373,7 +373,7 @@ SCENARIO("The turn log files an issued credential under its own module, naming t REQUIRE(uris->size() == 2U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); REQUIRE(line.has_value()); - CHECK(field_value(*line, "uri_count") == "2"); + CHECK(field_value(line.value(), "uri_count") == "2"); } } } @@ -403,9 +403,9 @@ SCENARIO("The turn log names an unreadable shared secret as an error under its o REQUIRE(response.status == 500U); auto const line = module_line(text, "ERROR", "turn", "turn.credentials_unavailable"); REQUIRE(line.has_value()); - CHECK(field_value(*line, "user_id") == "@alice:example.org"); + CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); // The reason holds spaces, so it is matched whole rather than through field_value. - CHECK(line->find(" reason=shared secret file unreadable or empty") != std::string::npos); + CHECK(line.value().find(" reason=shared secret file unreadable or empty") != std::string::npos); } } } @@ -435,7 +435,7 @@ SCENARIO("The turn log files configured static credentials under its own module REQUIRE(response.status == 200U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); REQUIRE(line.has_value()); - CHECK(line->find("credential=static") != std::string::npos); + CHECK(line.value().find("credential=static") != std::string::npos); CHECK(text.find("static-turn-user") == std::string::npos); CHECK(text.find("static-turn-password") == std::string::npos); } @@ -467,7 +467,7 @@ SCENARIO("The turn log says at debug level that no TURN server is configured", " REQUIRE(response.body == "{}"); auto const line = module_line(text, "DEBUG", "turn", "turn.not_configured"); REQUIRE(line.has_value()); - CHECK(line->find("@alice:example.org") != std::string::npos); + CHECK(line.value().find("@alice:example.org") != std::string::npos); } } } From 72acb5592353c928485a7893a00d6ffa7cf072c1 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 08:32:07 +0000 Subject: [PATCH 18/28] Report a qualified log module name instead of matching its last segment The example-config scan resolved `hs::kModule` against any constant of this file named `kModule`, so a constant from another namespace could be taken for this file's module and the other module drop out of the checked set unnoticed. A qualified name is now always reported, as ADR-0872 says; only a bare name is resolved from the file's constants or skipped as a forwarding parameter. A new scenario covers a file with its own `kModule` beside `hs::kModule`. ADR-0871 named the wrong safety net: what fails a line moved back under `client_server` is each test's assertion of the `turn` module tag; two of the four scenarios also silence `client_server`. Co-Authored-By: Claude Opus 5.5 --- ...equests-log-under-their-own-turn-module.md | 4 ++- tests/tooling/test_example_config.py | 34 +++++++++++++++---- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md index 7b9002b9c..eb17c9402 100644 --- a/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md +++ b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md @@ -39,7 +39,9 @@ of its own and would have moved forty lines of unrelated JSON building with it. token is refused with 401 before it, and logged as `request.auth.rejected` (debug) under `client_server`, so look there for authentication failures. `turn.not_configured` is a debug line, which reaches the console only when the server also runs with `--debug`. -* The logging tests run with `client_server` silenced, so a line moved back under `client_server` fails them. +* Each logging test asserts that the line's module tag is `turn`, so a line moved back under `client_server` fails + it. The issued-credential and unreadable-secret scenarios also silence `client_server`, so no client-server line + can stand in for the TURN one either way. ### Negative Consequences diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 6e0118d16..f082ff08c 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -358,18 +358,21 @@ def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: unresolved.add(f"{label}: cannot read the module of `{excerpt}`") continue literal, identifier = read.group(1), read.group(2) or "" - short = identifier.split("::")[-1] # A constant the file defines comes first, whatever it is called: the forwarding names # are skipped only when no constant of that name exists, so they skip by role, not name. if literal: modules.add(literal) - elif len(constants.get(short, ())) == 1: - modules.update(constants[short]) - elif short in constants: - unresolved.add(f"{label}: {identifier} (given {sorted(constants[short])} in this file)") + elif "::" in identifier: + # A qualified name such as `shared::module` names a constant in some namespace, and + # the scan knows no scopes: a constant of this file that shares its last segment may + # be another one, so it is reported, never resolved and never skipped. + unresolved.add(f"{label}: {identifier}") + elif len(constants.get(identifier, ())) == 1: + modules.update(constants[identifier]) + elif identifier in constants: + unresolved.add(f"{label}: {identifier} (given {sorted(constants[identifier])} in this file)") elif identifier in FORWARDED_MODULE_PARAMETERS: - # Only a bare parameter forwards its caller's module. A qualified name such as - # `shared::module` names a constant defined elsewhere, which the scan cannot read. + # Only a bare parameter forwards its caller's module. continue else: unresolved.add(f"{label}: {identifier}") @@ -576,6 +579,23 @@ def test_a_qualified_forwarding_name_is_reported_not_skipped(self) -> None: self.assertEqual(modules, set()) self.assertEqual(unresolved, {"f.cpp: shared::module"}) + def test_a_qualified_name_is_not_resolved_to_a_constant_sharing_its_last_segment(self) -> None: + # GIVEN a file that defines its own `kModule` constant and also names `hs::kModule`, a + # constant of another namespace that only shares the last segment. + source = ( + 'constexpr auto kModule = std::string_view{"rooms"};\n' + 'observability::log_diagnostic(kModule, "event", fields, severity);\n' + 'observability::log_diagnostic(hs::kModule, "event", fields, severity);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN the bare name resolves to this file's constant and the qualified one is reported, + # not taken for `rooms`. + self.assertEqual(modules, {"rooms"}) + self.assertEqual(unresolved, {"f.cpp: hs::kModule"}) + def test_a_constant_named_like_a_forwarding_parameter_still_resolves(self) -> None: # GIVEN a file that defines a module constant called `module`, and another file whose # `module` is only a parameter forwarding its caller's module. From 1d0e3cf2be300235e77772931522463191d88af2 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 08:50:32 +0000 Subject: [PATCH 19/28] Skip a forwarding module name only where the file declares it a parameter The example-config scan skipped any bare `module`, `mod` or `logger` by name, so a local holding a computed module (`module = module_for(kind)`) dropped out of the checked set without a report. A name is now skipped only when the file declares it as a string parameter or gives it a value only by copying one (`auto const mod = std::string{logger};`, as SingleLog.hpp does); anything else, or a name the file never declares, is reported. `__func__` is still skipped on its name. Two new scenarios cover the computed local, the copied parameter and an undeclared name; the database-audit fixture now declares its `logger`. The user manual said every turnServer request logs under `turn`; it is each answer the handler writes, since a request refused at the token gate never reaches it. ADR-0872, testing-standards and log-filtering say how the skip goes. Co-Authored-By: Claude Opus 5.5 --- ...test-reads-the-modules-from-the-sources.md | 5 +- docs/log-filtering.md | 4 +- docs/testing-standards.md | 4 +- docs/user-manual.md | 2 +- tests/tooling/test_example_config.py | 71 ++++++++++++++++++- 5 files changed, 77 insertions(+), 9 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index 72f0de259..9f4aa3582 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -57,7 +57,10 @@ to it, for a list that exists to be documented. given no other value there: the scan does not know scopes, so a name two functions each define with a different value is reported as ambiguous. The database audit overload's module argument follows the same rule. A parameter that only forwards a caller's module is named `logger`, `mod` or `module`, which the scan skips, but only when the - file defines no string constant of that name: a constant always resolves first, so the skip goes by role. So is `__func__`: + file defines no string constant of that name (a constant always resolves first) and declares the name as a string + parameter or gives it a value only by copying one (`auto const mod = std::string{logger};`). So the skip goes by + role: a local holding a computed module (`module = module_for(kind)`), or a name the file never declares, is + reported. `__func__` is skipped on its name alone: the legacy `LOG_*` macros log under the calling function's name, which is no module and is not listed in the examples. These four identifiers are the only first arguments the scan skips; say so wherever the test is described. * Call a level method (`info`, `warning`, ...) directly only on `SingleLog::instance()` or on a reference named `log` diff --git a/docs/log-filtering.md b/docs/log-filtering.md index aca5beb86..0f453adc6 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -107,8 +107,8 @@ without a registry. The example configurations (`config/merovingian.conf.example legacy `LOG_*` macros log under, see below); keep both in step when a module is added or removed. `tests/tooling/test_example_config.py` scans `src/` and `include/` for the modules the logger calls name and fails when either example lists a different set, or when a call names its module through anything but a -literal or a string constant in the same file (one the file gives no other value). The one exception is a parameter that forwards its caller's module -(`module`, `mod`, `logger`), and `__func__`, which the legacy macros pass (see below): the scan skips them, and a +literal or a string constant in the same file (one the file gives no other value). The one exception is a string parameter that forwards its caller's module +(`module`, `mod`, `logger`, declared as a parameter in that file or copied from one there), and `__func__`, which the legacy macros pass (see below): the scan skips them, and a function name is not listed in the examples. A level method (`info`, `warning`, ...) is read only on `SingleLog::instance()` or a reference named `log` or `logger` (ADR-0872). This is a non-exhaustive list of common module names used as the first argument to `observability::log_diagnostic` and `log_diagnostic_audit` in `src/` diff --git a/docs/testing-standards.md b/docs/testing-standards.md index f23ed1296..d4aceb1bd 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -45,8 +45,8 @@ tooling test that reads the code, never against a second list kept by hand in th cannot read rather than skipping it, so a new form in the code is taught to the test instead of dropping out of the check, and it ignores comments. What it skips on purpose it names, in the test and in the documents that describe it. `ExampleLogModuleListTests` in `tests/tooling/test_example_config.py` is the model: a logger call names its module with -a literal or a string constant in the same file; the only identifiers it skips are the forwarding parameters `module`, -`mod` and `logger`, and `__func__`; a level method is read only on `SingleLog::instance()` or a reference named `log` +a literal or a string constant in the same file; the only identifiers it skips are `module`, `mod` and `logger` where the +file declares them as string parameters (or copies one into them), and `__func__`; a level method is read only on `SingleLog::instance()` or a reference named `log` or `logger`; and a new call form or a shared constant is added to the scan in the same change (ADR-0872). ## Concurrency and locking tests diff --git a/docs/user-manual.md b/docs/user-manual.md index d083b222b..724be355f 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -802,7 +802,7 @@ Application-service connect timeout must not exceed its total timeout. Byte size VoIP clients request TURN relay credentials through `GET /_matrix/client/v3/voip/turnServer`. When no TURN server is configured the endpoint returns an empty JSON object so clients gracefully disable relay -support. Each request is logged under the `turn` module (`log_modules.turn`): an +support. Each answer the handler writes is logged under the `turn` module (`log_modules.turn`): an issued credential at info, an unreadable shared secret file at error, and a request answered `{}` at debug, naming the user and never a credential. The debug line needs `--debug` as well as `log_modules.turn=debug`. A request refused for a diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index f082ff08c..6a254a855 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -294,8 +294,37 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: r'\b([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:std::string_view\s*\{\s*|std::string\s*\{\s*)?"([A-Za-z0-9_]+)"(?:sv|s)?\s*\}?\s*;' ) MODULE_CONSTANT_INIT = re.compile(r'\b([A-Za-z_][A-Za-z0-9_]*)\s*\{\s*"([A-Za-z0-9_]+)"(?:sv|s)?\s*\}\s*;') -# Identifiers that forward a caller's module rather than name one. +# Identifiers that may forward a caller's module rather than name one. Only `__func__` is +# skipped on its name alone; the others only where `forwards_callers_module` finds them to be +# a string parameter, or a local copied straight from one. FORWARDED_MODULE_PARAMETERS = {"__func__", "mod", "logger", "module"} +# A string parameter of that name: `std::string_view logger,` or `std::string const& module)`. +STRING_PARAMETER = r"\b(?:std::)?string(?:_view)?\s*(?:const\s*)?&?\s*\b{name}\s*[,)]" +# Where a name is given a value: `name = ...` or `name{...}`, never a comparison. +NAME_INITIALISED = r"\b{name}\s*(?:=(?!=)|\{{)" +# What a local that only copies a name is given, up to its `;`: `logger`, `std::string{logger}`, +# `std::string(logger)`, or for `mod{logger};` the `logger}` after the brace. +COPY_OF_NAME = re.compile(r"\s*(?:(?:std::)?string(?:_view)?\s*[{(]\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*[})]?\s*\}?\s*") + + +def forwards_callers_module(name: str, code: str) -> bool: + """Whether `name` in this file only carries the module its caller passed. + + True for `__func__`, and for a name the file declares as a string parameter or gives a value + only by copying such a parameter (`auto const mod = std::string{logger};`). A name given any + other value, or declared nowhere in the file, is not: the scan cannot read what it holds. + `code` is the file without comments and with every literal's contents blanked. + """ + if name == "__func__": + return True + initialised = list(re.finditer(NAME_INITIALISED.format(name=re.escape(name)), code)) + for found in initialised: + statement_end = code.find(";", found.end()) + copied = COPY_OF_NAME.fullmatch(code, found.end(), statement_end if statement_end >= 0 else len(code)) + source = copied.group(1) if copied else "" + if not source or source == name or not re.search(STRING_PARAMETER.format(name=re.escape(source)), code): + return False + return bool(initialised) or re.search(STRING_PARAMETER.format(name=re.escape(name)), code) is not None EXAMPLE_LOG_MODULE_LINE = re.compile(r"^# log_modules\.([A-Za-z0-9_]+)=", re.MULTILINE) # A C++ comment, or a literal a comment marker may appear inside: raw strings first, since # their bodies may hold quotes, then ordinary string and character literals. @@ -371,8 +400,9 @@ def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: modules.update(constants[identifier]) elif identifier in constants: unresolved.add(f"{label}: {identifier} (given {sorted(constants[identifier])} in this file)") - elif identifier in FORWARDED_MODULE_PARAMETERS: - # Only a bare parameter forwards its caller's module. + elif identifier in FORWARDED_MODULE_PARAMETERS and forwards_callers_module(identifier, code): + # Only a parameter, or a local copied straight from one, forwards its caller's + # module; a local such as `module = module_for(kind)` holds a module of its own. continue else: unresolved.add(f"{label}: {identifier}") @@ -458,6 +488,7 @@ def test_a_database_audit_call_resolves_its_module_like_the_other_call_forms(sel # module with a literal, a constant, an unknown identifier and a forwarding parameter, beside a # wrapper called with a literal event and a qualified `observability::` call. source = ( + "auto audit_line(std::string_view logger, std::string_view event) -> void;\n" 'constexpr auto audit_module = std::string_view{"audited"};\n' 'log_diagnostic_audit(runtime.database, audit_module, "x", fields);\n' 'auto& db = rt.database;\n' @@ -596,6 +627,40 @@ def test_a_qualified_name_is_not_resolved_to_a_constant_sharing_its_last_segment self.assertEqual(modules, {"rooms"}) self.assertEqual(unresolved, {"f.cpp: hs::kModule"}) + def test_a_forwarding_name_given_a_computed_value_is_reported(self) -> None: + # GIVEN a file whose `module` is a local holding a computed module, not a parameter. + source = ( + "std::string_view const module = module_for(kind);\n" + 'observability::log_diagnostic(module, "event", fields, severity);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN it is reported: the scan cannot read what the local holds. + self.assertEqual(modules, set()) + self.assertEqual(unresolved, {"f.cpp: module"}) + + def test_a_local_copied_from_a_forwarding_parameter_is_skipped(self) -> None: + # GIVEN a function that copies its `logger` parameter into `mod` and logs through it, + # and a file that names `logger` without ever declaring it. + forwarding = ( + "auto log_line(std::string_view logger, std::string_view event) -> void\n" + "{\n" + " auto const mod = std::string{logger};\n" + " SingleLog::instance().debug(mod, std::string{event});\n" + "}\n" + ) + undeclared = 'observability::log_diagnostic(logger, "event", fields, severity);\n' + + # WHEN both are scanned. + forwarded, forwarded_unresolved = scan_log_modules(forwarding, "a.hpp") + stray, stray_unresolved = scan_log_modules(undeclared, "b.cpp") + + # THEN the copy forwards its caller's module and names none; the undeclared name is reported. + self.assertEqual((forwarded, forwarded_unresolved), (set(), set())) + self.assertEqual((stray, stray_unresolved), (set(), {"b.cpp: logger"})) + def test_a_constant_named_like_a_forwarding_parameter_still_resolves(self) -> None: # GIVEN a file that defines a module constant called `module`, and another file whose # `module` is only a parameter forwarding its caller's module. From 87fc45d73ebb8eb3fb56b5ed1f32b2375a1f91bc Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:08:34 +0000 Subject: [PATCH 20/28] Say what the source-reading tooling tests guarantee, and how ADR-0872 relates to ADR-0871 testing-standards promised that such a test fails on anything it cannot read, but ADR-0872 records that a call form the scan does not recognise is missed, not failed. The rule now says a found argument that cannot be resolved fails, a form the test does not name is missed, and a change that adds a form adds it to the scan. ADR-0872 listed itself as refining ADR-0871, which it does not amend; the link now says how the two meet: the turn module ADR-0871 adds is one the examples must list. Co-Authored-By: Claude Opus 5.5 --- ...nd-a-tooling-test-reads-the-modules-from-the-sources.md | 3 ++- docs/testing-standards.md | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index 9f4aa3582..b93933777 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -80,4 +80,5 @@ to it, for a list that exists to be documented. ## Links -* Refines [ADR-0871](0871-turn-credential-requests-log-under-their-own-turn-module.md) +* See [ADR-0871](0871-turn-credential-requests-log-under-their-own-turn-module.md): the `turn` module it adds is one of + the modules the examples must list. diff --git a/docs/testing-standards.md b/docs/testing-standards.md index d4aceb1bd..632e03ce6 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -41,9 +41,10 @@ service function: starting a runtime wires config, the store, the signing key an ## Tooling tests that read the sources A list that documents something in the code (the example configurations' `log_modules` lines, for one) is checked by a -tooling test that reads the code, never against a second list kept by hand in the test. Such a test fails on anything it -cannot read rather than skipping it, so a new form in the code is taught to the test instead of dropping out of the -check, and it ignores comments. What it skips on purpose it names, in the test and in the documents that describe it. +tooling test that reads the code, never against a second list kept by hand in the test. Such a test fails on an argument +it finds but cannot resolve rather than skipping it, and it ignores comments. A form it does not recognise at all is +missed, not failed (ADR-0872), so a change that adds a new form adds it to the scan too; a green run never proves a form +the test does not name was checked. What it skips on purpose it names, in the test and in the documents that describe it. `ExampleLogModuleListTests` in `tests/tooling/test_example_config.py` is the model: a logger call names its module with a literal or a string constant in the same file; the only identifiers it skips are `module`, `mod` and `logger` where the file declares them as string parameters (or copies one into them), and `__func__`; a level method is read only on `SingleLog::instance()` or a reference named `log` From 9e226c75ec612bb9eb42d84548f406a862174c13 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:20:36 +0000 Subject: [PATCH 21/28] Read a TURN log field up to the next field, not the first space field_value ended a value at the first space, so a multi-word value such as `reason=shared secret file unreadable or empty` read as `shared`, and a short expected token would pass. It now ends the value where the next ` name=` field opens, or at the end of the line, and the unreadable-secret scenario checks `reason` through it instead of a raw substring search. Co-Authored-By: Claude Opus 5.5 --- .../test_turn_shared_secret_flow.cpp | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index 5cdf54820..4388a9b8d 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -149,8 +149,21 @@ class SecretFile final return std::nullopt; } -// The value of the ` key=value` field in a diagnostic line, up to the next space; nullopt when the line has no such -// field. Matching the whole value keeps `uri_count=1` from passing for `uri_count=10`. +// Whether a ` name=` field opens at `position` of a diagnostic line: a space, then a field name, then `=`. +[[nodiscard]] auto field_opens_at(std::string const& line, std::size_t position) -> bool +{ + auto const is_name_char = [](char c) { return std::isalnum(static_cast(c)) != 0 || c == '_'; }; + auto name_end = position + 1U; + while (name_end < line.size() && is_name_char(line[name_end])) + { + ++name_end; + } + return line[position] == ' ' && name_end > position + 1U && name_end < line.size() && line[name_end] == '='; +} + +// The value of the ` key=value` field in a diagnostic line, up to where the next ` name=` field opens or the line +// ends, so a value holding spaces (`reason=shared secret file unreadable or empty`) is read whole; nullopt when the +// line has no such field. Matching the whole value keeps `uri_count=1` from passing for `uri_count=10`. [[nodiscard]] auto field_value(std::string const& line, std::string_view key) -> std::optional { auto const marker = " " + std::string{key} + "="; @@ -160,7 +173,11 @@ class SecretFile final return std::nullopt; } auto const value_start = start + marker.size(); - auto const value_end = line.find(' ', value_start); + auto value_end = line.find(' ', value_start); + while (value_end != std::string::npos && !field_opens_at(line, value_end)) + { + value_end = line.find(' ', value_end + 1U); + } return line.substr(value_start, value_end == std::string::npos ? std::string::npos : value_end - value_start); } @@ -405,7 +422,7 @@ SCENARIO("The turn log names an unreadable shared secret as an error under its o REQUIRE(line.has_value()); CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); // The reason holds spaces, so it is matched whole rather than through field_value. - CHECK(line.value().find(" reason=shared secret file unreadable or empty") != std::string::npos); + CHECK(field_value(line.value(), "reason") == "shared secret file unreadable or empty"); } } } From a62d8bd397f586ae418bab61cf3b01974be3bc58 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:32:56 +0000 Subject: [PATCH 22/28] Report a module constant the file also reassigns from a non-literal The example-config scan resolved a name as soon as the file gave it one literal module, even when another statement reassigned it (`log_module = federation_module(kind);`), so the modules that call could return dropped out of the check. A constant is now resolved only when every place the file gives the name a value is one of its literal definitions, as ADR-0872 already says; otherwise it is reported. A new scenario covers the reassignment beside a constant that is only compared. The comment above the unreadable-secret reason check said it avoids field_value, which it now uses; it says why field_value reads the value whole. Co-Authored-By: Claude Opus 5.5 --- .../test_turn_shared_secret_flow.cpp | 3 +- tests/tooling/test_example_config.py | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index 4388a9b8d..93f360698 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -421,7 +421,8 @@ SCENARIO("The turn log names an unreadable shared secret as an error under its o auto const line = module_line(text, "ERROR", "turn", "turn.credentials_unavailable"); REQUIRE(line.has_value()); CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); - // The reason holds spaces, so it is matched whole rather than through field_value. + // field_value stops only where the next ` name=` field opens, so the reason, which holds spaces, is + // read whole. CHECK(field_value(line.value(), "reason") == "shared secret file unreadable or empty"); } } diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index 6a254a855..bc047e11b 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -373,12 +373,24 @@ def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: # given two values (say, a `log_module` in each of two functions) is ambiguous, never # silently resolved to whichever definition came last. constants: dict[str, set[str]] = {} + # Where each constant is defined, so a name also given some other value is told apart. + defined_at: dict[str, set[int]] = {} for regex in (MODULE_CONSTANT, MODULE_CONSTANT_INIT): for found in regex.finditer(text): # Its value is a literal, so it is matched in `text`; its name must be code, not the # inside of some other literal, where `code` holds a blank instead. if code[found.start()] == text[found.start()]: constants.setdefault(found.group(1), set()).add(found.group(2)) + defined_at.setdefault(found.group(1), set()).add(found.start()) + + def given_another_value(name: str) -> bool: + # A constant reassigned anything but a literal (`log_module = federation_module(kind);`) + # may hold a module the scan cannot read, so it is reported rather than resolved. + return any( + found.start() not in defined_at[name] + for found in re.finditer(NAME_INITIALISED.format(name=re.escape(name)), code) + ) + for opening, call in CALL_FORMS: for found in opening.finditer(code): read = call.match(text, found.start()) @@ -396,6 +408,8 @@ def scan_log_modules(source: str, label: str) -> tuple[set[str], set[str]]: # the scan knows no scopes: a constant of this file that shares its last segment may # be another one, so it is reported, never resolved and never skipped. unresolved.add(f"{label}: {identifier}") + elif identifier in constants and given_another_value(identifier): + unresolved.add(f"{label}: {identifier} (also given a value that is not a literal in this file)") elif len(constants.get(identifier, ())) == 1: modules.update(constants[identifier]) elif identifier in constants: @@ -641,6 +655,26 @@ def test_a_forwarding_name_given_a_computed_value_is_reported(self) -> None: self.assertEqual(modules, set()) self.assertEqual(unresolved, {"f.cpp: module"}) + def test_a_constant_also_given_a_computed_value_is_reported(self) -> None: + # GIVEN a module constant that one branch reassigns from a call, beside one compared only. + source = ( + 'auto log_module = std::string_view{"rate_limit"};\n' + "if (fed) { log_module = federation_module(kind); }\n" + 'observability::log_diagnostic(log_module, "event", fields, severity);\n' + 'constexpr auto kept_module = std::string_view{"kept"};\n' + "if (kept_module == other) { }\n" + 'observability::log_diagnostic(kept_module, "event", fields, severity);\n' + ) + + # WHEN the source is scanned. + modules, unresolved = scan_log_modules(source, "f.cpp") + + # THEN the reassigned one is reported, not taken for `rate_limit`; a comparison is no value. + self.assertEqual(modules, {"kept"}) + self.assertEqual( + unresolved, {"f.cpp: log_module (also given a value that is not a literal in this file)"} + ) + def test_a_local_copied_from_a_forwarding_parameter_is_skipped(self) -> None: # GIVEN a function that copies its `logger` parameter into `mod` and logs through it, # and a file that names `logger` without ever declaring it. From 677258052d33b7a89251fee78207049737e169d1 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:38:30 +0000 Subject: [PATCH 23/28] Describe the turn module's diagnostics in the debug-logging guide docs/AGENTS.md pairs debug-logging.md with log-filtering.md for a new logger module, and only log-filtering.md named `turn`. The guide now lists its three lines, their levels and fields, that `turn.not_configured` needs `log_modules.turn=debug` (and `--debug` for the console), that no line carries credential text, and where a token refusal is logged instead. Co-Authored-By: Claude Opus 5.5 --- docs/debug-logging.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/debug-logging.md b/docs/debug-logging.md index 76e2020d2..03154da0b 100644 --- a/docs/debug-logging.md +++ b/docs/debug-logging.md @@ -133,6 +133,16 @@ The `persistent_store` module logs `sync_stream.watermark_persist_failed` (error the sync stream high-water mark could not be written. The id is still issued (ADR-0540), and the next write that succeeds covers it; only a restart before any write succeeds can reissue it. +## TURN credential diagnostics (1.1.3) + +`GET /_matrix/client/v3/voip/turnServer` logs under the `turn` module, never `client_server` (ADR-0871), so +`log_modules.turn` sets its level alone. `turn.credentials_issued` is an info line (`user_id`, `credential`, which is +`shared_secret` or `static`, `ttl_seconds` and `uri_count`) and needs no `--debug`; `turn.credentials_unavailable` is an +error line (`user_id` and a fixed `reason`) when the shared secret file cannot be read. `turn.not_configured` (`user_id`) +is a debug line for a request answered `{}`: it is written only with `log_modules.turn=debug`, and reaches the console +only with `--debug` as well. No line carries the username, the password or the shared secret. A request refused for its +access token never reaches the handler and is logged under `client_server` as `request.auth.rejected`. + ## Per-module level overrides (0.5.0) `--debug` lowers the **console sink** threshold to `debug`. It does not change From 45853cb5fc6a6b91958794dfb027a79d4f959718 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:43:52 +0000 Subject: [PATCH 24/28] Report a copy of a forwarding parameter the file reassigns The example-config scan accepted `auto const mod = std::string{logger};` as forwarding whenever `logger` was declared a string parameter, even after `logger = module_for(kind);`, so the computed module was skipped. A parameter counts as forwarding only while the file never gives it another value, both for a copy's source and for the parameter itself; the copied-parameter scenario gains the reassigned case, and ADR-0872 says so. Co-Authored-By: Claude Opus 5.5 --- ...test-reads-the-modules-from-the-sources.md | 3 +- tests/tooling/test_example_config.py | 38 +++++++++++++++---- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md index b93933777..698989bfb 100644 --- a/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md +++ b/docs/adr/0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md @@ -58,7 +58,8 @@ to it, for a list that exists to be documented. is reported as ambiguous. The database audit overload's module argument follows the same rule. A parameter that only forwards a caller's module is named `logger`, `mod` or `module`, which the scan skips, but only when the file defines no string constant of that name (a constant always resolves first) and declares the name as a string - parameter or gives it a value only by copying one (`auto const mod = std::string{logger};`). So the skip goes by + parameter or gives it a value only by copying one (`auto const mod = std::string{logger};`), a parameter the file + never gives another value (`logger = module_for(kind);` makes a copy of it reported). So the skip goes by role: a local holding a computed module (`module = module_for(kind)`), or a name the file never declares, is reported. `__func__` is skipped on its name alone: the legacy `LOG_*` macros log under the calling function's name, which is no module and is not listed in the diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index bc047e11b..a5dc334c2 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -310,21 +310,33 @@ def test_bsd_example_fill_is_the_sed_the_scripts_run(self) -> None: def forwards_callers_module(name: str, code: str) -> bool: """Whether `name` in this file only carries the module its caller passed. - True for `__func__`, and for a name the file declares as a string parameter or gives a value - only by copying such a parameter (`auto const mod = std::string{logger};`). A name given any - other value, or declared nowhere in the file, is not: the scan cannot read what it holds. + True for `__func__`, and for a name the file declares as a string parameter it never gives a + value, or gives a value only by copying such a parameter (`auto const mod = std::string{logger};`). + A name given any other value, a copy of a parameter the file reassigns (`logger = module_for(kind);`), + or a name declared nowhere in the file is not: the scan cannot read what it holds. `code` is the file without comments and with every literal's contents blanked. """ if name == "__func__": return True + + def unchanged_string_parameter(parameter: str) -> bool: + # A parameter declaration ends in `,` or `)`, so it never matches NAME_INITIALISED: any + # match is a statement giving the parameter another value. + escaped = re.escape(parameter) + return re.search(STRING_PARAMETER.format(name=escaped), code) is not None and not re.search( + NAME_INITIALISED.format(name=escaped), code + ) + initialised = list(re.finditer(NAME_INITIALISED.format(name=re.escape(name)), code)) for found in initialised: statement_end = code.find(";", found.end()) copied = COPY_OF_NAME.fullmatch(code, found.end(), statement_end if statement_end >= 0 else len(code)) source = copied.group(1) if copied else "" - if not source or source == name or not re.search(STRING_PARAMETER.format(name=re.escape(source)), code): + if not source or source == name or not unchanged_string_parameter(source): return False - return bool(initialised) or re.search(STRING_PARAMETER.format(name=re.escape(name)), code) is not None + return bool(initialised) or unchanged_string_parameter(name) + + EXAMPLE_LOG_MODULE_LINE = re.compile(r"^# log_modules\.([A-Za-z0-9_]+)=", re.MULTILINE) # A C++ comment, or a literal a comment marker may appear inside: raw strings first, since # their bodies may hold quotes, then ordinary string and character literals. @@ -686,14 +698,26 @@ def test_a_local_copied_from_a_forwarding_parameter_is_skipped(self) -> None: "}\n" ) undeclared = 'observability::log_diagnostic(logger, "event", fields, severity);\n' + # AND a function that reassigns its `logger` parameter before copying it. + reassigned = ( + "auto log_line(std::string_view logger, std::string_view event) -> void\n" + "{\n" + " logger = module_for(kind);\n" + " auto const mod = std::string{logger};\n" + " SingleLog::instance().debug(mod, std::string{event});\n" + "}\n" + ) - # WHEN both are scanned. + # WHEN each is scanned. forwarded, forwarded_unresolved = scan_log_modules(forwarding, "a.hpp") stray, stray_unresolved = scan_log_modules(undeclared, "b.cpp") + computed, computed_unresolved = scan_log_modules(reassigned, "c.hpp") - # THEN the copy forwards its caller's module and names none; the undeclared name is reported. + # THEN the copy forwards its caller's module and names none; the undeclared name, and the + # copy of a parameter the function reassigns, are reported. self.assertEqual((forwarded, forwarded_unresolved), (set(), set())) self.assertEqual((stray, stray_unresolved), (set(), {"b.cpp: logger"})) + self.assertEqual((computed, computed_unresolved), (set(), {"c.hpp: mod"})) def test_a_constant_named_like_a_forwarding_parameter_still_resolves(self) -> None: # GIVEN a file that defines a module constant called `module`, and another file whose From 3b9223c113ce064a7425685342fd8f61a1d7e984 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:55:12 +0000 Subject: [PATCH 25/28] Check every turn line's user_id field, and say what the module table is The static-credential and not-configured scenarios found the user and the credential kind by substring, so a renamed or dropped `user_id` field, or a `credential=static_x`, would still pass. Both now read the fields whole through field_value, as the other two scenarios do. log-filtering.md called the module table a non-exhaustive list right after saying the example configs hold the complete, test-checked list. The table now has its own paragraph saying it is not complete, no test checks it, and the examples are the complete list. Co-Authored-By: Claude Opus 5.5 --- docs/log-filtering.md | 9 ++++++--- tests/integration/test_turn_shared_secret_flow.cpp | 5 +++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 0f453adc6..cd0798218 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -110,9 +110,12 @@ name and fails when either example lists a different set, or when a call names i literal or a string constant in the same file (one the file gives no other value). The one exception is a string parameter that forwards its caller's module (`module`, `mod`, `logger`, declared as a parameter in that file or copied from one there), and `__func__`, which the legacy macros pass (see below): the scan skips them, and a function name is not listed in the examples. A level method (`info`, `warning`, ...) is read only on -`SingleLog::instance()` or a reference named `log` or `logger` (ADR-0872). This is a non-exhaustive list of common module names -used as the first argument to `observability::log_diagnostic` and `log_diagnostic_audit` in `src/` -(`rate_limit` is used only with `log_diagnostic_audit`): +`SingleLog::instance()` or a reference named `log` or `logger` (ADR-0872). + +The table below describes the common modules, the first argument to `observability::log_diagnostic` and +`log_diagnostic_audit` in `src/` (`rate_limit` is used only with `log_diagnostic_audit`). It is not complete and no test +checks it: the complete list is the one in the example configurations, which the tooling test keeps in step with the +sources. | Module | What it logs | |--------|--------------| diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index 93f360698..54efbb9e3 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -453,7 +453,8 @@ SCENARIO("The turn log files configured static credentials under its own module REQUIRE(response.status == 200U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); REQUIRE(line.has_value()); - CHECK(line.value().find("credential=static") != std::string::npos); + CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); + CHECK(field_value(line.value(), "credential") == "static"); CHECK(text.find("static-turn-user") == std::string::npos); CHECK(text.find("static-turn-password") == std::string::npos); } @@ -485,7 +486,7 @@ SCENARIO("The turn log says at debug level that no TURN server is configured", " REQUIRE(response.body == "{}"); auto const line = module_line(text, "DEBUG", "turn", "turn.not_configured"); REQUIRE(line.has_value()); - CHECK(line.value().find("@alice:example.org") != std::string::npos); + CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); } } } From e73af278f7016016ed11807571663ad0b202ee7c Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 10:20:24 +0000 Subject: [PATCH 26/28] Include for std::size_t in the TURN log test helpers field_opens_at and field_value use std::size_t, which reached the file only through other standard headers; , for std::isalnum, was already there. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_turn_shared_secret_flow.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index 54efbb9e3..55068a790 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include From 00a3ff579f6e98b6fb17f96e4f8aea21b4b52d85 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 10:59:37 +0000 Subject: [PATCH 27/28] Return the found TURN log line as a string, so no optional is unwrapped bugprone-unchecked-optional-access flags line.value() as it does *line: its dataflow does not see Catch2's REQUIRE(line.has_value()) as a guard, so the earlier switch to value() still failed clang-tidy. module_line now returns the line, empty when none matches, and the scenarios check REQUIRE_FALSE(line.empty()) before reading its fields. clang-tidy-diff 18 over the file reports only the EnumCastOutOfRange note in Catch2's own header that CI's clang-tidy 21 does not. Co-Authored-By: Claude Opus 5.5 --- .../test_turn_shared_secret_flow.cpp | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/tests/integration/test_turn_shared_secret_flow.cpp b/tests/integration/test_turn_shared_secret_flow.cpp index 55068a790..af816be72 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -131,9 +131,10 @@ class SecretFile final } // The first captured line at `level` (the logger's name for it, such as "INFO"), filed under `module`, that names -// `event`; nullopt when there is none. +// `event`; empty when there is none. A string rather than an optional, so the scenarios read it after +// `REQUIRE_FALSE(line.empty())` with no access clang-tidy's optional-access check cannot see guarded. [[nodiscard]] auto module_line(std::string const& text, std::string_view level, std::string_view module, - std::string_view event) -> std::optional + std::string_view event) -> std::string { auto const level_tag = "<" + std::string{level} + ">"; auto const module_tag = " " + std::string{module} + ": "; @@ -147,7 +148,7 @@ class SecretFile final return line; } } - return std::nullopt; + return {}; } // Whether a ` name=` field opens at `position` of a diagnostic line: a space, then a field name, then `=`. @@ -330,11 +331,11 @@ SCENARIO("The turn log files an issued credential under its own module, naming t { REQUIRE(response.status == 200U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); - REQUIRE(line.has_value()); - CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); - CHECK(field_value(line.value(), "credential") == "shared_secret"); - CHECK(field_value(line.value(), "ttl_seconds") == "3600"); - CHECK(field_value(line.value(), "uri_count") == "1"); + REQUIRE_FALSE(line.empty()); + CHECK(field_value(line, "user_id") == "@alice:example.org"); + CHECK(field_value(line, "credential") == "shared_secret"); + CHECK(field_value(line, "ttl_seconds") == "3600"); + CHECK(field_value(line, "uri_count") == "1"); } THEN("the log holds neither the username, the password nor the shared secret") @@ -390,8 +391,8 @@ SCENARIO("The turn log files an issued credential under its own module, naming t REQUIRE(uris != nullptr); REQUIRE(uris->size() == 2U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); - REQUIRE(line.has_value()); - CHECK(field_value(line.value(), "uri_count") == "2"); + REQUIRE_FALSE(line.empty()); + CHECK(field_value(line, "uri_count") == "2"); } } } @@ -420,11 +421,11 @@ SCENARIO("The turn log names an unreadable shared secret as an error under its o { REQUIRE(response.status == 500U); auto const line = module_line(text, "ERROR", "turn", "turn.credentials_unavailable"); - REQUIRE(line.has_value()); - CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); + REQUIRE_FALSE(line.empty()); + CHECK(field_value(line, "user_id") == "@alice:example.org"); // field_value stops only where the next ` name=` field opens, so the reason, which holds spaces, is // read whole. - CHECK(field_value(line.value(), "reason") == "shared secret file unreadable or empty"); + CHECK(field_value(line, "reason") == "shared secret file unreadable or empty"); } } } @@ -453,9 +454,9 @@ SCENARIO("The turn log files configured static credentials under its own module { REQUIRE(response.status == 200U); auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); - REQUIRE(line.has_value()); - CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); - CHECK(field_value(line.value(), "credential") == "static"); + REQUIRE_FALSE(line.empty()); + CHECK(field_value(line, "user_id") == "@alice:example.org"); + CHECK(field_value(line, "credential") == "static"); CHECK(text.find("static-turn-user") == std::string::npos); CHECK(text.find("static-turn-password") == std::string::npos); } @@ -486,8 +487,8 @@ SCENARIO("The turn log says at debug level that no TURN server is configured", " REQUIRE(response.status == 200U); REQUIRE(response.body == "{}"); auto const line = module_line(text, "DEBUG", "turn", "turn.not_configured"); - REQUIRE(line.has_value()); - CHECK(field_value(line.value(), "user_id") == "@alice:example.org"); + REQUIRE_FALSE(line.empty()); + CHECK(field_value(line, "user_id") == "@alice:example.org"); } } } From 3f468a31add0ea06ffcc49a4d3ecfc9203dec5a2 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 15:20:14 +0000 Subject: [PATCH 28/28] Mark GCC's braced-list cleanup in the TURN log calls excluded from coverage GCC labels the loop that destroys an already-built StructuredLogField, run only when building a later one throws, as an ordinary decision branch, so --exclude-throw-branches keeps it and the first field's line reads 0 hits. The three TURN log calls mark the call line GCOVR_EXCL_BR_LINE and the first field's row GCOVR_EXCL_START/STOP, with no decision on either. ADR-0874 records the rule and the rejected alternatives; the testing standards point to it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + ...cleanup-branches-excluded-from-coverage.md | 78 +++++++++++++++++++ docs/adr/index.md | 1 + docs/testing-standards.md | 4 +- src/homeserver/ClientServerRuntime.cpp | 14 +++- 5 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 docs/adr/0874-a-braced-log-field-list-may-mark-gcc-s-cleanup-branches-excluded-from-coverage.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 29f9052e3..7b198c094 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -183,6 +183,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. * The example configurations list every module a structured logger call names (twelve were missing, `token` is gone), and a tooling test fails when that list and the modules the sources name differ (ADR-0872). +* The TURN log calls mark GCC's cleanup of their braced field lists excluded from coverage, a compiler path no test + can reach; the testing standards say when such a marker is allowed (ADR-0874). ## Release notes diff --git a/docs/adr/0874-a-braced-log-field-list-may-mark-gcc-s-cleanup-branches-excluded-from-coverage.md b/docs/adr/0874-a-braced-log-field-list-may-mark-gcc-s-cleanup-branches-excluded-from-coverage.md new file mode 100644 index 000000000..3982be472 --- /dev/null +++ b/docs/adr/0874-a-braced-log-field-list-may-mark-gcc-s-cleanup-branches-excluded-from-coverage.md @@ -0,0 +1,78 @@ +# A braced log-field list may mark GCC's cleanup branches excluded from coverage + +* Status: accepted +* Date: 2026-11-21 + +## Context and Problem Statement + +A structured log call takes its fields as a braced list, `log_diagnostic(event, {{"user_id", *user, false}, ...})`. +For such a list of `StructuredLogField` (two `std::string`s each), GCC emits a loop that destroys the fields already +built when building a later one throws. gcov labels that loop's test as an ordinary decision branch, not an exception +edge, so `--exclude-throw-branches` ([ADR-0217](0217-branch-coverage-excludes-compiler-exception-edges.md)) keeps it, and +it gives the first field's line, which only that cleanup path reaches, a count of zero. Every braced field list in +`ClientServerRuntime.cpp` shows the call line with 4 of 6 conditions covered and, in a list of two or more fields, the +first field's line uncovered; `request.auth.accepted`, written on every authenticated request, is one. No test can reach +the path without failing an allocation. A change whose new code is mostly such calls cannot reach SonarQube Cloud's 80% +coverage on new code: pull request 611 added 12 coverable lines, three of them TURN log calls, and stood at 74.2%. How is +that told apart from code a test should cover? + +## Decision Drivers + +* The testing standards allow an exclusion marker only for code that is genuinely unreachable, with the reason beside it. +* A real decision on a field's line (a `cond ? a : b` value) must stay measured. +* The quality gate is the built-in "Sonar way", which cannot be edited, and a project-wide change weakens every pull + request. + +## Considered Options + +* Mark the call line `GCOVR_EXCL_BR_LINE` and the first field's line `GCOVR_EXCL_START`/`GCOVR_EXCL_STOP`, where the + artefact shows +* Write the calls another way (an `initializer_list` parameter, a typed helper per line, `push_back`) +* A custom quality gate with a lower coverage threshold +* Exclude `ClientServerRuntime.cpp` from coverage (`sonar.coverage.exclusions`) + +## Decision Outcome + +Chosen option: mark the call line and the first field's line, because it removes only what GCC generated: the call's own +line still counts as covered, every other field's line and its decisions are still measured, and nothing outside the +marked call changes. A call whose fields gcov reports fully covered needs no marker. + +The markers are written as `ClientServerRuntime.cpp`'s TURN calls show them: a comment above the call naming this ADR, a +trailing `// GCOVR_EXCL_BR_LINE` on the line that opens the call, and, for a list of two or more fields, `// +GCOVR_EXCL_START` and `// GCOVR_EXCL_STOP` on their own lines around the first field only. clang-format leaves that +layout as it is. A trailing `// GCOVR_EXCL_LINE` on the field would do the same, but pushes a long aligned row past the +120-column limit. + +### Positive Consequences + +* The TURN log calls reach full coverage on the lines gcov can count, and the gate passes without being loosened. +* The reason for every marker is one ADR away. + +### Negative Consequences + +* A marker hides a real untested branch if one is ever written on the marked line. Never put a decision (`?:`, `&&`, + `||`) on the line that opens the call, nor in the first field of a marked list: put it in a later field. +* Only new calls that need it are marked; the many unmarked braced lists in older code keep the artefact, which a change + that adds enough other covered lines absorbs. + +## Pros and Cons of the Options + +### Write the calls another way + +* Bad, because each shape measured with `gcc-14 -O2 --coverage` and gcovr kept a partial branch, or moved it into the + helper: an `initializer_list` parameter still builds an array of fields at the call, and `push_back` has the vector's + growth branch. + +### A custom quality gate + +* Bad, because it lowers the bar for every pull request to pass one, and may need a paid plan. + +### Exclude the file from coverage + +* Bad, because `ClientServerRuntime.cpp` holds most of the client-server API and would no longer be measured at all. + +## Links + +* Refines [ADR-0217](0217-branch-coverage-excludes-compiler-exception-edges.md): a compiler exception path gcov does not + label as one is marked by hand, call by call. +* See [ADR-0871](0871-turn-credential-requests-log-under-their-own-turn-module.md): the TURN log calls are the first marked. diff --git a/docs/adr/index.md b/docs/adr/index.md index 996aaa948..5743f5ca4 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -746,3 +746,4 @@ * [0870 - A ranges algorithm takes a typed value, never a bare string literal](0870-a-ranges-algorithm-takes-a-typed-value-never-a-bare-string-literal.md) * [0871 - TURN credential requests log under their own `turn` module, and never log a credential](0871-turn-credential-requests-log-under-their-own-turn-module.md) * [0872 - The example configs list every log module, and a tooling test reads the modules from the sources](0872-the-example-configs-list-every-log-module-and-a-tooling-test-reads-the-modules-from-the-sources.md) +* [0874 - A braced log-field list may mark GCC's cleanup branches excluded from coverage](0874-a-braced-log-field-list-may-mark-gcc-s-cleanup-branches-excluded-from-coverage.md) diff --git a/docs/testing-standards.md b/docs/testing-standards.md index 632e03ce6..86ab6c4f6 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -458,7 +458,9 @@ label those edges), so the coverage job alone builds with `gcc-14` and reads its `gcov-14`; every other job builds with clang. Every decision branch still counts, so a partial line means a condition went one way only. Cover it with a test of the other outcome, not an exclusion marker; `LCOV_EXCL`/`GCOVR_EXCL` are for code that is genuinely unreachable, with the reason -beside them. +beside them. One such case is GCC's cleanup of a braced list of log fields, which gcov labels a decision branch: a call +may mark it as the TURN log calls in `ClientServerRuntime.cpp` do, with no decision on the marked lines +([ADR-0874](adr/0874-a-braced-log-field-list-may-mark-gcc-s-cleanup-branches-excluded-from-coverage.md)). ## CI job order diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index 66e7f9b5a..f38cbd32e 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -21502,7 +21502,9 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp auto const& turn = rt.homeserver.config.server().turn; if (turn.server.empty() && turn.uris.empty()) { - log_turn_diagnostic("turn.not_configured", + // The coverage markers below drop only GCC's cleanup of the braced field list, which runs when building a + // field throws and so no test reaches (ADR-0874). + log_turn_diagnostic("turn.not_configured", // GCOVR_EXCL_BR_LINE { {"user_id", *user, false} }, @@ -21526,10 +21528,13 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp auto credentials = make_turn_credentials(bytes, *user, now_seconds, turn.ttl_seconds); if (!credentials.has_value()) { - log_turn_diagnostic( + // GCC's cleanup of the braced field list is unreachable by any test (ADR-0874). + log_turn_diagnostic( // GCOVR_EXCL_BR_LINE "turn.credentials_unavailable", { + // GCOVR_EXCL_START {"user_id", *user, false}, + // GCOVR_EXCL_STOP {"reason", "shared secret file unreadable or empty", false} }, observability::LogEventSeverity::error); @@ -21559,9 +21564,12 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp json_member("ttl", json_int(static_cast(turn.ttl_seconds))), json_member("uris", json_arr(std::move(uris))), })); - log_turn_diagnostic("turn.credentials_issued", + // GCC's cleanup of the braced field list is unreachable by any test (ADR-0874). + log_turn_diagnostic("turn.credentials_issued", // GCOVR_EXCL_BR_LINE { + // GCOVR_EXCL_START {"user_id", *user, false}, + // GCOVR_EXCL_STOP {"credential", turn.shared_secret_file.empty() ? "static" : "shared_secret", false}, {"ttl_seconds", std::to_string(turn.ttl_seconds), false}, {"uri_count", std::to_string(uri_count), false},