diff --git a/CHANGELOG.md b/CHANGELOG.md index 7808725d9..7b198c094 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,10 @@ 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). +* 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 is withheld. ## Security Fixes @@ -177,6 +181,10 @@ 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 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/config/merovingian.conf.bsd.example b/config/merovingian.conf.bsd.example index 9fc33e9d9..b775d0efa 100644 --- a/config/merovingian.conf.bsd.example +++ b/config/merovingian.conf.bsd.example @@ -911,8 +911,15 @@ 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 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 +# 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 +927,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 +942,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 +960,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..9ba3340ab 100644 --- a/config/merovingian.conf.example +++ b/config/merovingian.conf.example @@ -884,8 +884,15 @@ 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 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 +# 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 +900,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 +915,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 +933,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/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..eb17c9402 --- /dev/null +++ b/docs/adr/0871-turn-credential-requests-log-under-their-own-turn-module.md @@ -0,0 +1,69 @@ +# 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`, 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 + +* `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`. +* 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 + +* 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 + +* 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 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 + +* Refines [ADR-0480](0480-turn-credentials-come-from-a-coturn-shared-secret-file-through-an-openssl-hmac-sha1.md) 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..698989bfb --- /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,85 @@ +# 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) 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 +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, 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 + +* 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 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, 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};`), 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 + 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 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 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 + +* 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/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 157616603..5743f5ca4 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -744,3 +744,6 @@ * [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) +* [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/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 diff --git a/docs/log-filtering.md b/docs/log-filtering.md index 9249a455a..cd0798218 100644 --- a/docs/log-filtering.md +++ b/docs/log-filtering.md @@ -102,9 +102,20 @@ 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 -used as the first argument to `observability::log_diagnostic` and `log_diagnostic_audit` in `src/` -(`rate_limit` is used only with `log_diagnostic_audit`): +without a registry. The example configurations (`config/merovingian.conf.example` and +`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 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). + +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 | |--------|--------------| @@ -133,6 +144,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..1be107c64 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -655,6 +655,17 @@ 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 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 When `security.registration.token_file` is set but yields no token hash, every `POST /register` that needs the token diff --git a/docs/security-coding-rules.md b/docs/security-coding-rules.md index d6504389a..65d2d8e5b 100644 --- a/docs/security-coding-rules.md +++ b/docs/security-coding-rules.md @@ -176,6 +176,23 @@ 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.** 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 + 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). + - **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 +2084,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/testing-standards.md b/docs/testing-standards.md index db5723f8f..86ab6c4f6 100644 --- a/docs/testing-standards.md +++ b/docs/testing-standards.md @@ -38,6 +38,18 @@ 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 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` +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 Assert on what a thread holding none of the resource can observe, not on what a @@ -446,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/docs/user-manual.md b/docs/user-manual.md index 53c7dab02..724be355f 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -802,7 +802,13 @@ 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 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 +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/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 8d9f27aa9..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) | +| `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 c5761db19..f38cbd32e 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -259,6 +259,16 @@ 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). 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 const& 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 +21502,13 @@ 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()) { + // 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} + }, + observability::LogEventSeverity::debug); return dispatch_resp(req, rt, 200U, "{}"); } auto username = turn.username; @@ -21511,11 +21528,16 @@ 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} + // 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); + observability::LogEventSeverity::error); return dispatch_err(req, rt, 500U, "M_UNKNOWN", "TURN credentials are unavailable"); } username = std::move(credentials->username); @@ -21535,12 +21557,24 @@ 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))), })); + // 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}, + }, + observability::LogEventSeverity::info); return dispatch_resp(req, rt, 200U, body); } 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 ffdc24c2b..af816be72 100644 --- a/tests/integration/test_turn_shared_secret_flow.cpp +++ b/tests/integration/test_turn_shared_secret_flow.cpp @@ -4,9 +4,11 @@ // 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" +#include "../support/ModuleLogLevel.hpp" #include "../support/RegistrationToken.hpp" #include "../support/TempDirectory.hpp" #include "merovingian/config/ClientRateLimitsConfig.hpp" @@ -21,20 +23,27 @@ #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 #include #include #include +#include #include #include #include +#include #include +#include #include #include #include +#include #include #include @@ -121,6 +130,69 @@ 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`; 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::string +{ + 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 {}; +} + +// 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} + "="; + auto const start = line.find(marker); + if (start == std::string::npos) + { + return std::nullopt; + } + auto const value_start = start + marker.size(); + 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); +} + +// 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 +{ + 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 +307,189 @@ 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, the ttl and the one URI") + { + REQUIRE(response.status == 200U); + auto const line = module_line(text, "INFO", "turn", "turn.credentials_issued"); + 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") + { + 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); + } + } + } + + 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_FALSE(line.empty()); + CHECK(field_value(line, "uri_count") == "2"); + } + } + } +} + +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, alice and the fixed reason") + { + REQUIRE(response.status == 500U); + auto const line = module_line(text, "ERROR", "turn", "turn.credentials_unavailable"); + 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, "reason") == "shared secret file unreadable or empty"); + } + } + } +} + +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_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); + } + } + } +} + +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_FALSE(line.empty()); + CHECK(field_value(line, "user_id") == "@alice:example.org"); + } + } + } +} 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 diff --git a/tests/tooling/test_example_config.py b/tests/tooling/test_example_config.py index d2a2b4419..a5dc334c2 100644 --- a/tests/tooling/test_example_config.py +++ b/tests/tooling/test_example_config.py @@ -251,5 +251,542 @@ 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. 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. 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. +# +# 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*\(' +) +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::` 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*' + + 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( + 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 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 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 unchanged_string_parameter(source): + return False + 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. +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 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]] = {} + # 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()) + 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 "" + # 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 "::" 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 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: + unresolved.add(f"{label}: {identifier} (given {sorted(constants[identifier])} in this file)") + 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}") + return modules, unresolved + + +def source_log_modules() -> tuple[set[str], set[str]]: + """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: + 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 + + +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_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_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 + # 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' + '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", {{"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 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 = ( + '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_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_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_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_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_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. + 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' + # 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 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, 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 + # `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 = ( + '::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' + '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. + 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() + 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()