Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,23 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **Connection timeout log level**: `Database connection timeout` is now logged at `info` level instead of `warn`.
Proxy closes a client connection when no message moves in either direction for `connection_timeout`, and the idle connections of a connection pool are the usual cause, so the message is routine.
With the default `connection_timeout` of 120 seconds, expect one message for each connection that stays idle for that long.
The `PROTOCOL` target defaults to `info`, so the message remains visible with `CS_LOG__LEVEL=warn`.
Set `CS_LOG__PROTOCOL_LEVEL=warn` to suppress it.
The timeout follows the global log level, so `CS_LOG__LEVEL=warn` suppresses it.
- **Connection events**: `Client connected`, `Database connection closed by client` and `Database connection closed after cancel request` use the `PROTOCOL` target at `info`.
Set `CS_LOG__PROTOCOL_LEVEL=warn` to suppress these routine events.
`Database connection error` uses the global log level at `error`.
Each event that ends a connection records its connection number in `client_id`, so you can match it to the corresponding `Client connected` event.
- **Schema and migration log targets**: schema loading and reload messages now use the `SCHEMA` target, and Encryption Migrator dry run and connection error messages now use the `MIGRATE` target, so `CS_LOG__SCHEMA_LEVEL` and `CS_LOG__MIGRATE_LEVEL` control them.
The migrator now logs `Encryption Migrator connection error` in place of `Connection error: …` and records the chain of causes in the `error` field.
Startup and configuration warnings, such as a missing TLS or keyset configuration and the warning that no Encrypt configuration was loaded, still follow `CS_LOG__LEVEL` so that a target level cannot hide them.
The schema warnings `Database schema contains no tables` and `Error reloading committed schema snapshot` use the `SCHEMA` target, so `CS_LOG__SCHEMA_LEVEL` controls them.
With only `CS_LOG__LEVEL=warn`, routine connection and schema snapshot messages remain visible because the targets default to `info`.
With only `CS_LOG__LEVEL=debug`, enable `CS_LOG__SCHEMA_LEVEL=debug` to see `ReloadCommand received`.
- **Encryption Migrator update debug message**: the `Update` debug message now records the number of rows in the batch in `rows`, in place of the batch's SQL, because that SQL contains the plaintext values being encrypted.

### Security

- **Encryption Migrator quoting**: the Encryption Migrator now escapes source values, the target column name and the table name in the `UPDATE` statements it builds.
Before, a source value containing a single quote, such as `O'Brien`, made the batch fail, and a crafted value could run its own SQL statement.

### Fixed

Expand Down
4 changes: 4 additions & 0 deletions packages/cipherstash-proxy/CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ on log lines to correlate one connection's traffic. The **CipherStash client id*
credential UUID from `CS_ENCRYPT__CLIENT_ID`. They share a name and a field spelling and
are otherwise unrelated.

**Log target**:
A named category of log messages, such as `PROTOCOL`, `SCHEMA`, `MAPPER` or `MIGRATE`, whose level an operator sets separately from the global log level.
_Avoid_: module, component, logger.

**Keyset**:
The ZeroKMS collection of keys a workspace encrypts against. Addressed by UUID or by
name, and selectable per connection via `SET CIPHERSTASH.KEYSET_ID` / `KEYSET_NAME`.
Expand Down
213 changes: 171 additions & 42 deletions packages/cipherstash-proxy/src/cli/migrate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl Migrate {
info!(target: MIGRATE, msg = "Encrypting table", table = self.table, columns = ?self.columns);

if !self.commit() {
warn!(msg = "Dry run is enabled");
warn!(target: MIGRATE, msg = "Dry run is enabled");
}

let mut batch_count = 0;
Expand Down Expand Up @@ -143,9 +143,7 @@ impl Migrate {

let row_count = rows.len() - 1; // Last row is always CommandComplete

// Batch by building a single statement string
let mut update_sql = String::from("");
let mut records = vec![];
let mut batch = vec![];

for row in rows {
match row {
Expand All @@ -164,38 +162,8 @@ impl Migrate {
row.get(source_col.as_str()).unwrap_or("").to_owned()
})
.collect::<Vec<String>>();
// Set the col to update to the encrypted column
// And set the plaintext value to the p value
let update_str = self
.columns
.iter()
.zip(column_vals.iter())
.map(|((_source_col, target_col), val)| {
format!("\"{target_col}\"='{val}'")
})
.collect::<Vec<String>>()
.join(", ");

let where_str = self
.primary_key
.iter()
.zip(primary_key_vals.iter())
.map(|(col, val)| {
let col = escape_identifier(col);
let val = escape_literal(val);
format!("{col}={val}")
})
.collect::<Vec<String>>()
.join(" AND ");

let sql = format!(
"UPDATE {} SET {update_str} WHERE {where_str};\n",
self.table
);

updated_count += 1;
update_sql.push_str(&sql);
records.extend(primary_key_vals.to_owned());
batch.push((primary_key_vals, column_vals));
}
tokio_postgres::SimpleQueryMessage::CommandComplete(..) => {}
tokio_postgres::SimpleQueryMessage::RowDescription(..) => {}
Expand All @@ -206,11 +174,8 @@ impl Migrate {
}
}

if self.verbose {
info!(target: MIGRATE, msg = "Encrypting", records = ?Sensitive(&records));
}

debug!(target: MIGRATE, msg = "Update", update_sql = %Sensitive(&update_sql));
updated_count += batch.len();
let update_sql = self.build_update_batch(&batch);

if self.commit() {
{
Expand Down Expand Up @@ -238,6 +203,78 @@ impl Migrate {
}
}

impl Migrate {
///
/// Build one multi-statement string that updates every row in the batch.
/// Each batch row is `(primary_key_values, source_column_values)`.
///
fn build_update_batch(&self, batch: &[(Vec<String>, Vec<String>)]) -> String {
// Batch by building a single statement string
let mut update_sql = String::from("");
let mut records = vec![];

for (primary_key_vals, column_vals) in batch {
let sql = build_update_statement(
&self.table,
&self.columns,
column_vals,
&self.primary_key,
primary_key_vals,
);
update_sql.push_str(&sql);
records.extend(primary_key_vals.to_owned());
}

if self.verbose {
info!(target: MIGRATE, msg = "Encrypting", records = ?Sensitive(&records));
}

// The statements carry plaintext source values, so log only the row count.
debug!(target: MIGRATE, msg = "Update", rows = batch.len());

update_sql
}
}

///
/// Build the UPDATE statement for one row.
/// Sets each target column to the row's source column value, matched by primary key.
///
fn build_update_statement(
table: &str,
columns: &[(String, String)],
column_vals: &[String],
primary_key: &[String],
primary_key_vals: &[String],
) -> String {
// Set the col to update to the encrypted column
// And set the plaintext value to the p value
let update_str = columns
.iter()
.zip(column_vals.iter())
.map(|((_source_col, target_col), val)| {
let col = escape_identifier(target_col);
let val = escape_literal(val);
format!("{col}={val}")
})
.collect::<Vec<String>>()
.join(", ");

let where_str = primary_key
.iter()
.zip(primary_key_vals.iter())
.map(|(col, val)| {
let col = escape_identifier(col);
let val = escape_literal(val);
format!("{col}={val}")
})
.collect::<Vec<String>>()
.join(" AND ");

let table = escape_identifier(table);
format!("UPDATE {table} SET {update_str} WHERE {where_str};\n")
}

/// Parse a single key-value pair - copied from clap example https://github.com/clap-rs/clap/blob/master/examples/typed-derive.rs#L25
fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn ClapError + Send + Sync + 'static>>
where
Expand Down Expand Up @@ -270,7 +307,7 @@ pub async fn connect_with_tls(

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

}
});
Ok(client)
Expand All @@ -285,8 +322,100 @@ pub async fn connect_with_no_tls(connection_string: &str) -> Result<Client, Erro

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));
}
});
Ok(client)
}

#[cfg(test)]
mod tests {
use super::*;
use crate::config::{LogConfig, LogLevel};
use crate::test_helpers::capture_logs;

fn columns() -> Vec<(String, String)> {
vec![("name".to_string(), "encrypted_name".to_string())]
}

fn primary_key() -> Vec<String> {
vec![ID.to_string()]
}

#[test]
fn update_statement_escapes_quote_in_source_value() {
let sql = build_update_statement(
"users",
&columns(),
&["O'Brien".to_string()],
&primary_key(),
&["1".to_string()],
);

assert_eq!(
sql,
"UPDATE \"users\" SET \"encrypted_name\"='O''Brien' WHERE \"id\"='1';\n"
);
}

#[test]
fn update_statement_keeps_injected_sql_inside_the_literal() {
let sql = build_update_statement(
"users",
&columns(),
&["x'; DELETE FROM users; --".to_string()],
&primary_key(),
&["1".to_string()],
);

assert_eq!(
sql,
"UPDATE \"users\" SET \"encrypted_name\"='x''; DELETE FROM users; --' WHERE \"id\"='1';\n"
);
}

#[test]
fn update_statement_quotes_table_and_target_column() {
let columns = vec![("name".to_string(), "encrypted \"name\"".to_string())];

let sql = build_update_statement(
"user accounts",
&columns,
&["Alice".to_string()],
&primary_key(),
&["1".to_string()],
);

assert_eq!(
sql,
"UPDATE \"user accounts\" SET \"encrypted \"\"name\"\"\"='Alice' WHERE \"id\"='1';\n"
);
}

#[test]
fn update_debug_event_does_not_log_source_values() {
let migrate = Migrate {
table: "users".to_string(),
columns: columns(),
primary_key: primary_key(),
batch_size: 100,
dry_run: true,
verbose: false,
};

let mut config = LogConfig::with_level(LogLevel::Info);
config.targets.migrate_level = LogLevel::Debug;

let batch = vec![(vec!["1".to_string()], vec!["plaintext-5f3a9c".to_string()])];

let output = capture_logs(&config, || {
migrate.build_update_batch(&batch);
});

assert!(output.contains(r#""msg":"Update""#), "{output}");
assert!(
!output.contains("plaintext-5f3a9c"),
"source value leaked: {output}"
);
}
}
55 changes: 18 additions & 37 deletions packages/cipherstash-proxy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,57 +90,38 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}

loop {
tokio::select! {
_ = sigint() => {
info!(msg = "Received SIGINT");
break;
},
_ = sighup() => {
info!(msg = "Received SIGHUP. Reloading application configuration");
proxy = reload_application_config(&proxy.config, &args).await.unwrap_or(proxy);
},
_ = sigterm() => {
info!(msg = "Received SIGTERM");
break;
},
Ok(client_stream) = connect::accept(&listener) => {

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

_ = sigint() => {
info!(msg = "Received SIGINT");
break;
},
_ = sighup() => {
info!(msg = "Received SIGHUP. Reloading application configuration");
proxy = reload_application_config(&proxy.config, &args).await.unwrap_or(proxy);
},
_ = sigterm() => {
info!(msg = "Received SIGTERM");
break;
},
Ok(client_stream) = connect::accept(&listener) => {
client_id += 1;

let context = proxy.context(client_id);

tracker.spawn(async move {

gauge!(CLIENTS_ACTIVE_CONNECTIONS).increment(1);
// Decrements even if the handler panics or the task
// is dropped, so the gauge cannot drift upwards.
let active_connection = DropGuard::new((), |()| {
gauge!(CLIENTS_ACTIVE_CONNECTIONS).decrement(1);
});

let result = pg::handler(client_stream,context).await;
let result = pg::handler(client_stream, context).await;
drop(active_connection);

match result {
Ok(_) => (),
Err(err) => {
match err {
Error::ConnectionClosed => {
info!(msg = "Database connection closed by client");
}
Error::CancelRequest => {
info!(msg = "Database connection closed after cancel request");
}
Error::ConnectionTimeout{..} => {
// No message moved either way for the connection timeout, usually a pool's idle connection
info!(target: log::PROTOCOL, msg = "Database connection timeout", error = err.to_string());
}
_ => {
error!(msg = "Database connection error", error = %ErrorChain(&err));
}
}
},
if let Err(err) = result {
pg::connection_events::connection_ended(&err, client_id);
}
});
},
Expand Down
Loading
Loading