Skip to content

fix(proxy): use log targets for connection events - #533

Merged
tobyhede merged 9 commits into
mainfrom
tobyhede/use-proxy-log-targets-for-connection-events
Dec 3, 2026
Merged

tobyhede merged 9 commits into
mainfrom
tobyhede/use-proxy-log-targets-for-connection-events

Conversation

@tobyhede

@tobyhede tobyhede commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Operators can quiet routine connects and closes with CS_LOG__PROTOCOL_LEVEL=warn and still see why a connection timed out or failed.
Timeouts follow the global level at info, and unexpected connection failures follow it at error.
The connection number in client_id links each ending event to its connection.
The Encryption Migrator, the command that encrypts the existing rows of a table, now escapes the values it writes, so a value containing a single quote no longer breaks a batch or runs as SQL, and its debug log no longer contains plaintext.

Changes

  • Route routine connection events to PROTOCOL, schema diagnostics to SCHEMA, and Encryption Migrator diagnostics to MIGRATE.
  • Escape source values, the target column name and the table name in the Encryption Migrator's UPDATE statements.
  • Log the row count instead of the batch's SQL in the Encryption Migrator's Update debug message.
  • Document which messages operators see at global warn and debug and how to adjust individual targets, and define "log target" in the Proxy glossary.

Verification

  • After rebasing onto main, cargo nextest run -p cipherstash-proxy --lib: 620 passed, 1 skipped, with and without the log-plaintext feature.
  • The three migrator quoting tests and the migrator debug-log test failed before the fix and pass after it.
  • The two timeout regression tests failed before the routing fix and passed afterward.
  • mise run test:format, test:check and test:clippy passed.
  • Integration tests run in CI.

Related

CIP-5750

Refs #527 (moved Database connection timeout to the PROTOCOL target).

Review notes

Start with packages/cipherstash-proxy/src/postgresql/connection_events.rs, then build_update_statement in packages/cipherstash-proxy/src/cli/migrate/mod.rs.
The migrator quoting bug predates this pull request; it is fixed here because it sits in the same migrator code this pull request changes.
Other warnings and errors still use a log target, so a quiet target level can hide them; changing that for every target is deferred to separate work.
The type-conversion debug message's MAPPER target and plaintext redaction came from #534, so this pull request no longer changes it.

Acknowledgment

By submitting this pull request, I confirm that CipherStash can use, modify, copy, and redistribute this contribution, under the terms of CipherStash's choice.

@tobyhede
tobyhede marked this pull request as ready for review December 2, 2026 08:46

@cipherstash-agent cipherstash-agent left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review attestation

Reviewed 03114f4 · posted from Claude Code · claude-opus-5-5 · effort medium
Sources: code-review · claude-opus-5-5; standards and spec reviews (mattpocock code-review) · claude-opus-5-5; rust-security agent · claude-opus-5-5
Skills: code-review, mattpocock-skills:code-review, company-skills:rust-security, company-skills:review-cross-check, company-skills:review-post

Findings (10): 3 major, 7 minor. 8 inline, 2 below.

  • packages/cipherstash-proxy/src/cli/migrate/mod.rs:174 (outside diff, already in the code) major format!("\"{target_col}\"='{val}'") puts the source value into the UPDATE without escape_literal, unlike the primary key values at lines 181-183. A value such as O'Brien breaks the batch, and x'; DELETE FROM users; -- runs as SQL in the multi-statement simple_query. Use escape_identifier(target_col) and escape_literal(val), and use quoted_table in the UPDATE (line 191).
    Source: code-review · claude-opus-5-5
  • packages/cipherstash-proxy/src/cli/migrate/mod.rs:213 (outside diff, already in the code) minor With CS_LOG__MIGRATE_LEVEL=debug, update_sql logs every plaintext value in the batch, dry runs included. This PR removes the plaintext from the MAPPER event for the same reason. Log the row count instead.
    Source: code-review · claude-opus-5-5

Every finding was checked against 03114f4 before posting. Also checked and refuted: using err.to_string() for the timeout arm prints the same text as ErrorChain, and the client_connected wrapper is fine. The rust-security review found no secret or plaintext left in the changed log lines, and the new test does prove the MAPPER value is gone.
Not posted, because they need a decision: should Database schema contains no tables and Error reloading committed schema snapshot follow only CS_LOG__LEVEL, like the other startup warnings? Should connect/mod.rs:100 (Connection error on Proxy's own schema connection) move to a target?


Generated by Claude Code


/// Logs a client connection to Proxy.
pub fn client_connected(database: &str, client_id: i32) {
info!(target: PROTOCOL, msg = "Client connected", database, client_id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

major With CS_LOG__LEVEL=warn or error and no target levels set, this now prints Client connected and both connection-closed events at info. Before, the global level hid them. for_startup keeps unset target levels at Info when a level is explicit (config/log.rs:110), and subscriber.rs adds a PROTOCOL=info directive. The same change works the other way: CS_LOG__LEVEL=debug no longer shows ReloadCommand received (proxy/mod.rs:119) or Convert plaintext to postgres_type (data/mod.rs:28), and Loaded committed schema snapshot (manager.rs:246) now shows under warn. Say so in the CHANGELOG entries, the way the #527 entry does, or make target levels that were never set follow an explicitly set global level.

Source: code-review, spec review (mattpocock code-review) · claude-opus-5-5


Generated by Claude Code

for err in errors {
let output = capture(&config, || connection_ended(&err, 42));

assert!(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

major LogConfig::with_level picks default_log_format(), which is Pretty when stdout is a terminal (config/log.rs:146-152), but these assertions expect JSON. Running cargo test -p cipherstash-proxy --lib under a pty fails 3 tests: this one, protocol_warn_keeps_connection_errors_visible (line 91) and plaintext_conversion_event_omits_the_plaintext_value (data/mod.rs:91). They pass only when stdout is piped, as in CI. Set config.format = LogFormat::Structured in capture and in the data/mod.rs test, as log/mod.rs:194 does.

Source: code-review · claude-opus-5-5


Generated by Claude Code

loop {
tokio::select! {
loop {
tokio::select! {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor Only loop { and tokio::select! { moved. The arms from line 95 on keep their old indentation, so they now sit level with tokio::select! {. rustfmt does not format inside select!, so cargo fmt --check will not catch it. Re-indent lines 95-129 by hand, or revert these two lines.

Source: standards review, spec review (mattpocock code-review) · claude-opus-5-5


Generated by Claude Code

Comment on lines +79 to +82
let builder =
subscriber::builder(&config).with_writer(BoxMakeWriter::new(make_writer.clone()));
let subscriber = set_format(&config, builder);
let _default = set_default(&subscriber.into());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor This repeats the capture setup that connection_events.rs puts in capture (lines 53-61). capture is private to that test module. Move capture(&LogConfig, impl FnOnce()) -> String into test_helpers.rs next to MockMakeWriter and call it from both tests.

Source: standards review (mattpocock code-review) · claude-opus-5-5


Generated by Claude Code

tokio::spawn(async move {
if let Err(err) = connection.await {
error!("Connection error: {}", ErrorChain(&err));
error!(target: MIGRATE, msg = "Encryption Migrator connection error", error = %ErrorChain(&err));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor The message text also changes, from Connection error: <chain> to Encryption Migrator connection error, and the chain moves into an error field. The CHANGELOG only says the target changed, so a log search or alert on the old text stops matching without warning. Add the new message name to the CHANGELOG entry. Line 288 has the same change.

Source: spec review (mattpocock code-review) · claude-opus-5-5


Generated by Claude Code

Comment thread CHANGELOG.md Outdated
Set `CS_LOG__PROTOCOL_LEVEL=warn` to suppress it.
- **Connection event log target**: `Client connected`, `Database connection closed by client`, `Database connection closed after cancel request` and `Database connection error` now use the `PROTOCOL` target at their existing levels, like `Database connection timeout`.
Set `CS_LOG__PROTOCOL_LEVEL=warn` to suppress the informational connection events while connection errors stay visible.
The events that end a connection now record its `client_id`, so you can match them to the `Client connected` event.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor packages/cipherstash-proxy/CONTEXT.md ("Client id") says always qualify this term, because readers can take it for the CipherStash client id, a credential UUID. Write "now record the connection number in the client_id field".

Source: standards review (mattpocock code-review) · claude-opus-5-5


Generated by Claude Code

@@ -1,5 +1,6 @@
use std::sync::Arc;

use crate::log::SCHEMA;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor Put log::SCHEMA inside the use crate::{…} group below, as manager.rs:9 does in this PR.

Source: standards review (mattpocock code-review) · claude-opus-5-5


Generated by Claude Code

use tracing_subscriber::fmt::writer::BoxMakeWriter;

/// Captures log output with the global level at `info`, the `PROTOCOL` target at `warn` and the `SCHEMA` target at `debug`.
fn capture_with_protocol_warn(f: impl FnOnce()) -> String {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

minor The name does not say that this helper also sets SCHEMA to debug. Only protocol_warn_leaves_unrelated_events_on_their_own_levels needs that setting. Set it in that test, or rename the helper.

Source: standards review (mattpocock code-review) · claude-opus-5-5


Generated by Claude Code

@cipherstash-bot cipherstash-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Recommendation: 🟡 merge after changes

Nothing blocks this change except one small test gap. Add a test that checks the Client connected event before merging. The comment cleanup on the timeout arm can wait.


Other findings not posted as comments

  • packages/cipherstash-proxy/src/postgresql/connection_events.rs:24 — Optional: the comment on the timeout arm does not say who closes the connection or why the event has no target.
How this review was made
Agent Model Review type Result
claude claude-opus-5-5 test-gap 1 found, 1 posted
claude claude-opus-5-5 rust 1 found, 0 posted
codex gpt-5.6-terra test-gap 1 found, 1 posted
codex gpt-5.6-terra rust 0 found, 0 posted

Synthesis: claude-sonnet-5-5 merged the findings, removed duplicates and dropped findings it could not confirm in the code. 1 posted finding(s) were raised by two or more models.

Plain language: claude-sonnet-5-5 read every comment as a new reader would. 1 comment(s) had a problem that stopped the reader acting; it rewrote 1.

Stack: not part of a stack.

Context loaded: the description, 0 linked issue(s) and 9 discussion entries.


/// Logs a client connection to Proxy.
pub fn client_connected(database: &str, client_id: i32) {
info!(target: PROTOCOL, msg = "Client connected", database, client_id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Change before merge: no test checks that client_connected emits its event with the PROTOCOL target, database and client_id.

Impact: Operators use client_id to link each ending event to its connection. Someone could remove this log call, the database field or the client_id field, and no test would fail. Operators then cannot match a connection number to its database.

Evidence: The test protocol_warn_suppresses_informational_connection_events calls this function only with PROTOCOL set to warn. It checks that the output is empty. That check also passes when the function emits nothing.

Fix: Add the test below to the same tests module, and run it at the default info level. The test uses LogConfig::with_level and LogLevel::Info to build a log configuration at that level. It uses capture_logs to collect the log output of the call as output. This comment does not show where these three names are defined. Check that the tests module can use them.

#[test]
fn client_connected_records_the_client_id_and_database() {
    let config = LogConfig::with_level(LogLevel::Info);
    let output = capture_logs(&config, || client_connected("localhost:5432", 42));

    assert!(output.contains("Client connected"), "{output}");
    assert!(output.contains(r#""target":"PROTOCOL""#), "{output}");
    assert!(output.contains(r#""client_id":42"#), "{output}");
    assert!(output.contains(r#""database":"localhost:5432""#), "{output}");
}

Found by 2 models: claude, codex

@auxesis auxesis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @tobyhede!

Definitely worth fixing the issues raised by @cipherstash-agent and @cipherstash-bot, but I'm approving in anticipation of that.

…from mapper logs

Route client connection, disconnect, cancel-request closure and connection
error events to the PROTOCOL target at their existing levels, through a new
postgresql::connection_events module shared by main.rs and the driver.

The plaintext conversion debug event used `target = MAPPER` as a field, so
it ignored the mapper level and recorded the plaintext value. It now uses
the MAPPER target and records only the PostgreSQL type.

Schema loading and reload events now use SCHEMA, and Encryption Migrator
dry run and connection errors use MIGRATE. Startup and configuration
warnings stay untargeted so a target level cannot hide safety warnings
such as missing TLS, missing keyset or no loaded Encrypt configuration.

Refs CIP-5750
Show that untargeted and SCHEMA events follow their own levels when
PROTOCOL is set to warn, and narrow the CHANGELOG security entry to the
one debug message that changed.

Refs CIP-5750
Debug logging is for development environments only, so dropping the
plaintext from one debug message is not a security fix.

Refs CIP-5750
The closed, cancel-request, timeout and error events now include the
client_id, so they can be matched to the Client connected event.

Refs CIP-5750
The Encryption Migrator built each row's UPDATE by placing the source value, the target column name and the table name straight into the SQL text. Only the primary key values were escaped. The batch runs as one multi-statement simple query, so a value such as O'Brien made the batch fail, and a crafted value could end the string literal and run a statement of its own.

Building one row's statement now lives in its own function, which escapes the value as a literal and the column and table names as identifiers, the same way the WHERE clause already did. The function needs no database, so unit tests now cover a quote, an injected statement, and names that need quoting.

The batch's Update debug message also logged the whole batch's SQL, which carries every plaintext value being encrypted, including on dry runs. It now records only the number of rows.
…'s level

No test showed that client_connected logs its event. The only test that called it set the PROTOCOL target to warn and expected no output, which would also pass if the log call or its fields were removed. A new test checks the event, its PROTOCOL target, and its database and client_id fields at the default level.

The comment on the timeout case now says that Proxy closes the connection after connection_timeout passes with no traffic, and that the event has no log target because it reports a problem, so the PROTOCOL level cannot hide it.
The changelog now lists the Encryption Migrator quoting fix under Security and the change to its Update debug message under Changed. It also says that the two schema warnings use the SCHEMA target, so the line about startup warnings following the global level does not read as covering them.

The Proxy glossary gains an entry for log target, a term operators meet through settings such as CS_LOG__PROTOCOL_LEVEL.
After rebasing onto the log redaction change, the plaintext conversion event keeps its plaintext field behind Sensitive, so it is redacted rather than removed. The Fixed entry from that change already describes the MAPPER target, so this entry was both duplicated and inaccurate.
@tobyhede
tobyhede force-pushed the tobyhede/use-proxy-log-targets-for-connection-events branch from 9c9bcd5 to 372ee5b Compare December 3, 2026 22:57
@tobyhede tobyhede changed the title fix(proxy): use log targets for connection events and drop plaintext from mapper logs fix(proxy): use log targets for connection events Dec 3, 2026
@tobyhede

tobyhede commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main after #534. Conflicts resolved:

  • postgresql/data/mod.rs: kept main's Sensitive plaintext field and redaction test, and kept this branch's test that a global debug level with the default mapper level hides the conversion event. Dropped this branch's test that the value is omitted.
  • cli/migrate/mod.rs: kept the build_update_statement refactor, and carried main's Sensitive wrapping of the record keys into build_update_batch.
  • test_helpers.rs: kept both log-capture helpers.
  • CHANGELOG.md: removed the type-conversion entry, because fix(proxy): redact plaintext in logs unless built with log-plaintext #534's Fixed entry covers it.

Unit tests pass with and without log-plaintext; fmt and clippy are clean.

@tobyhede
tobyhede merged commit d29edc2 into main Dec 3, 2026
10 checks passed
@tobyhede
tobyhede deleted the tobyhede/use-proxy-log-targets-for-connection-events branch December 3, 2026 23:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants