Repository navigation
fix(proxy): use log targets for connection events - #533
Conversation
cipherstash-agent
left a comment
There was a problem hiding this comment.
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) majorformat!("\"{target_col}\"='{val}'")puts the source value into the UPDATE withoutescape_literal, unlike the primary key values at lines 181-183. A value such asO'Brienbreaks the batch, andx'; DELETE FROM users; --runs as SQL in the multi-statementsimple_query. Useescape_identifier(target_col)andescape_literal(val), and usequoted_tablein the UPDATE (line 191).
Source: code-review · claude-opus-5-5packages/cipherstash-proxy/src/cli/migrate/mod.rs:213(outside diff, already in the code) minor WithCS_LOG__MIGRATE_LEVEL=debug,update_sqllogs every plaintext value in the batch, dry runs included. This PR removes the plaintext from theMAPPERevent 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); |
There was a problem hiding this comment.
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!( |
There was a problem hiding this comment.
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! { |
There was a problem hiding this comment.
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
| let builder = | ||
| subscriber::builder(&config).with_writer(BoxMakeWriter::new(make_writer.clone())); | ||
| let subscriber = set_format(&config, builder); | ||
| let _default = set_default(&subscriber.into()); |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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
| 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. |
There was a problem hiding this comment.
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; | |||
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
9c9bcd5 to
372ee5b
Compare
|
Rebased onto main after #534. Conflicts resolved:
Unit tests pass with and without |
Summary
Operators can quiet routine connects and closes with
CS_LOG__PROTOCOL_LEVEL=warnand still see why a connection timed out or failed.Timeouts follow the global level at
info, and unexpected connection failures follow it aterror.The connection number in
client_idlinks 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
PROTOCOL, schema diagnostics toSCHEMA, and Encryption Migrator diagnostics toMIGRATE.UPDATEstatements.Updatedebug message.warnanddebugand how to adjust individual targets, and define "log target" in the Proxy glossary.Verification
cargo nextest run -p cipherstash-proxy --lib: 620 passed, 1 skipped, with and without thelog-plaintextfeature.mise run test:format,test:checkandtest:clippypassed.Related
CIP-5750
Refs #527 (moved
Database connection timeoutto thePROTOCOLtarget).Review notes
Start with
packages/cipherstash-proxy/src/postgresql/connection_events.rs, thenbuild_update_statementinpackages/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
MAPPERtarget 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.