diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b32be10c..0c3e79c99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/packages/cipherstash-proxy/CONTEXT.md b/packages/cipherstash-proxy/CONTEXT.md index ab51f6542..c1fc61287 100644 --- a/packages/cipherstash-proxy/CONTEXT.md +++ b/packages/cipherstash-proxy/CONTEXT.md @@ -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`. diff --git a/packages/cipherstash-proxy/src/cli/migrate/mod.rs b/packages/cipherstash-proxy/src/cli/migrate/mod.rs index ac729b785..3b7010a7a 100644 --- a/packages/cipherstash-proxy/src/cli/migrate/mod.rs +++ b/packages/cipherstash-proxy/src/cli/migrate/mod.rs @@ -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; @@ -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 { @@ -164,38 +162,8 @@ impl Migrate { row.get(source_col.as_str()).unwrap_or("").to_owned() }) .collect::>(); - // 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::>() - .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::>() - .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(..) => {} @@ -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() { { @@ -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, Vec)]) -> 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::>() + .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::>() + .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(s: &str) -> Result<(T, U), Box> where @@ -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)); } }); Ok(client) @@ -285,8 +322,100 @@ pub async fn connect_with_no_tls(connection_string: &str) -> Result Vec<(String, String)> { + vec![("name".to_string(), "encrypted_name".to_string())] + } + + fn primary_key() -> Vec { + 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}" + ); + } +} diff --git a/packages/cipherstash-proxy/src/main.rs b/packages/cipherstash-proxy/src/main.rs index 3f51f73e1..313d732e9 100644 --- a/packages/cipherstash-proxy/src/main.rs +++ b/packages/cipherstash-proxy/src/main.rs @@ -90,28 +90,26 @@ fn main() -> Result<(), Box> { } } - 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! { + _ = 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. @@ -119,28 +117,11 @@ fn main() -> Result<(), Box> { 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); } }); }, diff --git a/packages/cipherstash-proxy/src/postgresql/connection_events.rs b/packages/cipherstash-proxy/src/postgresql/connection_events.rs new file mode 100644 index 000000000..a68fc3703 --- /dev/null +++ b/packages/cipherstash-proxy/src/postgresql/connection_events.rs @@ -0,0 +1,152 @@ +//! Log events for the lifecycle of a client connection. +//! +//! Routine connects and closes use `PROTOCOL`. Timeouts and unexpected errors follow the global log level. + +use crate::error::{Error, ErrorChain}; +use crate::log::PROTOCOL; +use tracing::{error, info}; + +/// Logs a client connection to Proxy. +pub fn client_connected(database: &str, client_id: i32) { + info!(target: PROTOCOL, msg = "Client connected", database, client_id); +} + +/// Logs the end of a client connection that stopped with an error. +pub fn connection_ended(err: &Error, client_id: i32) { + match err { + Error::ConnectionClosed => { + info!(target: PROTOCOL, msg = "Database connection closed by client", client_id); + } + Error::CancelRequest => { + info!(target: PROTOCOL, msg = "Database connection closed after cancel request", client_id); + } + Error::ConnectionTimeout { .. } => { + // Proxy closes the connection when no message moves either way for `connection_timeout`, usually a pool's idle connection. + // A timeout reports a problem, so it has no target: it follows the global log level and `CS_LOG__PROTOCOL_LEVEL` cannot hide it. + info!( + msg = "Database connection timeout", + client_id, + error = err.to_string() + ); + } + _ => { + error!(msg = "Database connection error", client_id, error = %ErrorChain(err)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{LogConfig, LogLevel}; + use crate::log::SCHEMA; + use crate::test_helpers::capture_logs; + use std::time::Duration; + use tracing::debug; + + #[test] + fn client_connected_logs_the_database_and_client_id_on_the_protocol_target() { + 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}" + ); + } + + #[test] + fn protocol_warn_suppresses_informational_connection_events() { + let mut config = LogConfig::with_level(LogLevel::Info); + config.targets.protocol_level = LogLevel::Warn; + let output = capture_logs(&config, || { + client_connected("localhost:5432", 1); + connection_ended(&Error::ConnectionClosed, 1); + connection_ended(&Error::CancelRequest, 1); + }); + assert_eq!(output, ""); + + let output = capture_logs(&config, || { + connection_ended( + &Error::ConnectionTimeout { + duration: Duration::from_secs(120), + }, + 1, + ); + }); + + assert!(output.contains("Database connection timeout"), "{output}"); + } + + #[test] + fn global_warn_hides_timeouts_and_keeps_errors_visible() { + let config = LogConfig { + level: LogLevel::Warn, + ..LogConfig::default() + }; + let output = capture_logs(&config, || { + connection_ended( + &Error::ConnectionTimeout { + duration: Duration::from_secs(120), + }, + 1, + ); + connection_ended(&Error::Unknown, 1); + }); + + assert!(output.contains("Database connection error"), "{output}"); + assert!(!output.contains("Database connection timeout"), "{output}"); + assert!(!output.contains(r#""target":"PROTOCOL""#), "{output}"); + assert!(output.contains(r#""level":"ERROR""#), "{output}"); + } + + #[test] + fn protocol_warn_leaves_unrelated_events_on_their_own_levels() { + let mut config = LogConfig::with_level(LogLevel::Info); + config.targets.protocol_level = LogLevel::Warn; + config.targets.schema_level = LogLevel::Debug; + let output = capture_logs(&config, || { + info!(msg = "Untargeted info event"); + debug!(msg = "Untargeted debug event"); + debug!(target: SCHEMA, msg = "Schema debug event"); + }); + + assert!( + output.contains("Untargeted info event"), + "untargeted info should follow the global info level: {output}" + ); + assert!( + !output.contains("Untargeted debug event"), + "untargeted debug should follow the global info level: {output}" + ); + assert!( + output.contains("Schema debug event"), + "SCHEMA debug should follow the SCHEMA debug level: {output}" + ); + } + + #[test] + fn connection_ended_events_record_the_client_id() { + let config = LogConfig::with_level(LogLevel::Info); + let errors = [ + Error::ConnectionClosed, + Error::CancelRequest, + Error::ConnectionTimeout { + duration: Duration::from_secs(120), + }, + Error::Unknown, + ]; + + for err in errors { + let output = capture_logs(&config, || connection_ended(&err, 42)); + + assert!( + output.contains(r#""client_id":42"#), + "{err:?} should record the client_id: {output}" + ); + } + } +} diff --git a/packages/cipherstash-proxy/src/postgresql/data/mod.rs b/packages/cipherstash-proxy/src/postgresql/data/mod.rs index 1f709624d..51b0259f6 100644 --- a/packages/cipherstash-proxy/src/postgresql/data/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/data/mod.rs @@ -65,11 +65,31 @@ pub fn to_type(plaintext: Plaintext, postgres_type: &Type) -> Plaintext { mod tests { use super::to_type; use crate::test_helpers::{ - assert_secret_logged_only_with_log_plaintext, capture_trace_logs, SECRET, + assert_secret_logged_only_with_log_plaintext, capture_logs, capture_trace_logs, SECRET, }; use cipherstash_client::encryption::Plaintext; use postgres_types::Type; + #[test] + fn global_debug_with_default_mapper_level_hides_conversion_details() { + crate::test_helpers::with_no_cs_vars(|| { + temp_env::with_var("CS_LOG__LEVEL", Some("debug"), || { + let config = + crate::TandemConfig::build_path("tests/config/cipherstash-proxy-test.toml") + .unwrap(); + let output = capture_logs(&config.log, || { + tracing::debug!(msg = "Global debug event"); + to_type(Plaintext::Int(Some(42)), &Type::INT8); + }); + assert!(output.contains("Global debug event"), "{output}"); + assert!( + !output.contains("Convert plaintext to postgres_type"), + "{output}" + ); + }); + }); + } + #[test] fn converted_plaintext_is_logged_only_with_log_plaintext() { let logs = capture_trace_logs(|| to_type(Plaintext::new(SECRET.to_owned()), &Type::TEXT)); diff --git a/packages/cipherstash-proxy/src/postgresql/driver.rs b/packages/cipherstash-proxy/src/postgresql/driver.rs index e9420d1f7..958b9223d 100644 --- a/packages/cipherstash-proxy/src/postgresql/driver.rs +++ b/packages/cipherstash-proxy/src/postgresql/driver.rs @@ -19,7 +19,6 @@ use std::{ sync::{Arc, LazyLock}, }; use tokio::net::TcpStream; -use tracing::info; /// Cancellation requests arrive on a new connection, so every intermediary /// must share the registry that maps client cancellation keys to upstream keys. @@ -310,11 +309,7 @@ where }}; } - info!( - msg = "Client connected", - database = address, - client_id = context.client_id - ); + super::connection_events::client_connected(&address, context.client_id); if let Some(tls_config) = context.tls_config() { let (config, leaf) = tls::configure_server_with_leaf(tls_config)?; let identity = DownstreamIdentity(ServerIdentity::new(Arc::new(config), leaf)); diff --git a/packages/cipherstash-proxy/src/postgresql/mod.rs b/packages/cipherstash-proxy/src/postgresql/mod.rs index 288a6a2a2..5556b1031 100644 --- a/packages/cipherstash-proxy/src/postgresql/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/mod.rs @@ -1,4 +1,5 @@ mod column_mapper; +pub mod connection_events; mod context; mod data; mod diagnostics; diff --git a/packages/cipherstash-proxy/src/proxy/mod.rs b/packages/cipherstash-proxy/src/proxy/mod.rs index 9731bc6d1..64c146310 100644 --- a/packages/cipherstash-proxy/src/proxy/mod.rs +++ b/packages/cipherstash-proxy/src/proxy/mod.rs @@ -4,6 +4,7 @@ use crate::{ config::TandemConfig, connect, error::{ConfigError, Error, ErrorChain, TlsConfigError}, + log::SCHEMA, postgresql::{Column, Context, KeysetIdentifier}, proxy::schema::SchemaManager, tls, @@ -115,7 +116,7 @@ impl Proxy { pub fn receive(mut reload_receiver: ReloadReceiver, schema_manager: SchemaManager) { tokio::task::spawn(async move { while let Some(command) = reload_receiver.recv().await { - debug!(msg = "ReloadCommand received", ?command); + debug!(target: SCHEMA, msg = "ReloadCommand received", ?command); match command { ReloadCommand::DatabaseSchema(responder) => { let schema_manager = schema_manager.clone(); diff --git a/packages/cipherstash-proxy/src/proxy/schema/manager.rs b/packages/cipherstash-proxy/src/proxy/schema/manager.rs index 9ff56acfc..8d9882831 100644 --- a/packages/cipherstash-proxy/src/proxy/schema/manager.rs +++ b/packages/cipherstash-proxy/src/proxy/schema/manager.rs @@ -213,6 +213,7 @@ where } Err(err) => { warn!( + target: SCHEMA, msg = "Error reloading committed schema snapshot", error = %ErrorChain(&err) ); @@ -242,7 +243,7 @@ async fn init_reloader(config: DatabaseConfig) -> Result { warn!(msg = "No active Encrypt configuration found in database."); warn!(msg = "Data is not protected with encryption"); } - info!(msg = "Loaded committed schema snapshot"); + info!(target: SCHEMA, msg = "Loaded committed schema snapshot"); let snapshot = Arc::new(ArcSwap::new(Arc::new(CommittedSchemaSnapshot::new( 1, @@ -470,7 +471,7 @@ async fn load_snapshot(config: &DatabaseConfig) -> Result<(Schema, EncryptConfig let tables = client.query(SCHEMA_QUERY, &[]).await?; if tables.is_empty() { - warn!(msg = "Database schema contains no tables"); + warn!(target: SCHEMA, msg = "Database schema contains no tables"); } let (mut schema, encrypt_config) = build_snapshot(tables.into_iter().map(|table| TableRow { diff --git a/packages/cipherstash-proxy/src/test_helpers.rs b/packages/cipherstash-proxy/src/test_helpers.rs index abee7d440..df4ac46fa 100644 --- a/packages/cipherstash-proxy/src/test_helpers.rs +++ b/packages/cipherstash-proxy/src/test_helpers.rs @@ -105,3 +105,18 @@ pub(crate) fn assert_secret_logged_only_with_log_plaintext(logs: &str) { "plaintext in logs must match the log-plaintext feature:\n{logs}" ); } + +pub(crate) fn capture_logs(config: &crate::config::LogConfig, emit: impl FnOnce()) -> String { + use crate::config::{LogConfig, LogFormat}; + use crate::log::{set_format, subscriber}; + use tracing_subscriber::fmt::writer::BoxMakeWriter; + + let config = LogConfig { + format: LogFormat::Structured, + ..config.clone() + }; + let writer = MockMakeWriter::default(); + let builder = subscriber::builder(&config).with_writer(BoxMakeWriter::new(writer.clone())); + tracing::dispatcher::with_default(&set_format(&config, builder).into(), emit); + writer.get_string() +}