diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 109237192..7f1432802 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -119,6 +119,7 @@ jobs: exit 1 fi cargo build --locked --release --package cipherstash-proxy + cargo test --locked --release --all-features --package cipherstash-proxy --lib log::sensitive::tests::release_with_all_features_redacts_values -- --ignored --exact # Latest stable: early warning that a new Rust release breaks the build or # adds Clippy lints, before the pinned toolchain is bumped to it. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7275a5f43..2b32be10c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **Statement restored after `DEALLOCATE ALL` in a failed pipeline**: when a pipeline ran `DEALLOCATE ALL` and then failed before a `Close` or `Parse` of a statement it removed, Proxy brought that statement back. Proxy now forgets every statement `DEALLOCATE ALL` removes, including those a pipelined `Close` or `Parse` had already replaced. +- **Mapper log level applies to plaintext conversion**: The `Convert plaintext to postgres_type` debug event now follows `CS_LOG__MAPPER_LEVEL`. + Before this change, the mapper log level did not control this event. + ### Security - **Bind or Describe after an unanswered batch that changed its statement**: Proxy now refuses a Bind or Describe that names a prepared statement an earlier batch changed with a Parse or Close, when PostgreSQL has not yet answered that batch. @@ -40,6 +43,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). PostgreSQL rejected the Bind and stored nothing, but the values crossed the connection between Proxy and the database. This applied to every Bind that Proxy refuses, such as one that names an unknown prepared statement or a value that cannot be encrypted. +- **Debug logs no longer contain plaintext**: Release builds and the published Docker images redact values in log events at every log level, and print `` in their place. + Before this change, setting a target such as `CS_LOG__MAPPER_LEVEL` or `CS_LOG__ENCODING_LEVEL` to `debug` could write plaintexts, bound parameters, literals and SQL statements to your logs. + Proxy now logs a warning at startup when any target is at `debug` or `trace`, because those levels are for development only. + Developers using the development profile can enable the `log-plaintext` Cargo feature to see the values; never run such a build in production. +- **Migrate no longer logs credentials**: The `migrate` command's debug logging no longer writes the client access key, the client key or an inline TLS private key. + Proxy now prints `` in their place in every build. + ## [3.1.0] - 2026-11-04 ### Added diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 8feb403f6..937cb7a8f 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -300,6 +300,21 @@ SLOW_STATEMENTS | CS_LOG__SLOW_STATEMENTS_LEVEL > The application code must use the 'target' parameter for the per-target log level to work. > An example: `debug!(target: AUTHENTICATION, "SASL authentication successful");` +#### Debug logging and plaintext + +Debug and trace logging are for development only. + +Values that can carry customer data are redacted in logs unless a development build enables the `log-plaintext` Cargo feature. +`mise run proxy` enables the feature, so a local Proxy shows plaintexts, bound parameters, literals, SQL text and protocol messages at `debug` and `trace`. +Release builds, the binary that `mise run build:binary` builds, and the published Docker images print `` even if all Cargo features are selected. +To run Proxy by hand with plaintext logging, pass the feature to Cargo: + +```shell +cargo run --package cipherstash-proxy --features log-plaintext +``` + +Proxy logs a warning at startup when any target is at `debug` or `trace`, and says whether the build logs plaintext. + ### Running Proxy locally There are two ways to run Proxy locally: @@ -591,6 +606,9 @@ These are read directly by `cipherstash-client` and do not require proxy configu - Use structured logging - Use the appropriate targets - Include the `client_id` where appropriate +- Wrap every field that can carry a value in `log::Sensitive`, such as `debug!(target: MAPPER, plaintexts = ?Sensitive(&plaintexts))`. + Values include plaintexts, bound parameters, literals, SQL text, and protocol messages with row or parameter data. + `Sensitive` prints `` unless a development build enables the `log-plaintext` feature. Debug logging is very verbose, and targets allow configuration of granular log levels. @@ -631,6 +649,9 @@ This automatically: - Creates the environment variable `CS_LOG__NEW_TARGET_LEVEL` - Adds the target to all logging functions and validation +Add `CS_LOG__NEW_TARGET_LEVEL` to the `proxy-tls` service in `tests/docker-compose.yml` and give `PROXY_LOG_FORCE_LEVEL` precedence, as the other targets do. +The integration run sets every target to `trace` to check that release builds log no plaintext, and docker compose passes only the variables it lists. + ### Available targets ``` diff --git a/docs/reference/index.md b/docs/reference/index.md index 71194ad09..48ea05c96 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -305,6 +305,19 @@ CS_LOG__ENCRYPT_LEVEL="debug" CS_LOG__ZEROKMS_LEVEL="debug" ``` +#### Debug and trace logging are for development only + +Debug and trace logs are verbose and are meant for developing Proxy, not for running it. +Do not leave any target at `debug` or `trace` in production. + +Debug and trace events can describe values that pass through Proxy, such as plaintexts, bound parameters, literals, SQL statements and protocol messages. +Release builds and the published Docker images always redact those values and print `` in their place, whatever the log level. +Only a development build of Proxy compiled with the `log-plaintext` Cargo feature shows them. +That feature is for developing Proxy, and the published binaries and images never include it. + +When any target is at `debug` or `trace`, Proxy logs a warning at startup. +The warning says whether the build logs plaintext. + ### Docker-specific configuration As a convenience for local development, if you use [Proxy's Docker container](../proxy.Dockerfile) with its default entrypoint and the below environment variables set, the EQL SQL will be applied to the database, and an example schema (for example, with the `users` table, from the [README Getting Started example](../README.md#getting-started)) will be loaded. These are turned on by default in the [development `docker-compose.yml`](../docker-compose.yml): diff --git a/mise.toml b/mise.toml index 86c722a91..80ef048c0 100644 --- a/mise.toml +++ b/mise.toml @@ -46,8 +46,8 @@ CS_EQL_VERSION = "eql-3.0.4" # Proxy Tasks [tasks.proxy] alias = 'p' -description = "Run the proxy (with `cargo run`)" -run = 'pwd && env | grep CS_ && echo cargo run --package cipherstash-proxy {{option(name="extra-args",default="")}} | bash' +description = "Run the proxy (with `cargo run`), logging plaintext at debug and trace" +run = 'pwd && env | grep CS_ && echo cargo run --package cipherstash-proxy --features log-plaintext {{option(name="extra-args",default="")}} | bash' [tasks."proxy:kill"] alias = 'k' @@ -139,6 +139,7 @@ mise run test:check mise run test:format mise run test:clippy mise run test:unit +mise run test:unit:log-plaintext mise run test:integration """ @@ -424,11 +425,19 @@ echo '# Test: Integration' echo '###############################################' echo +# Every log target at trace, so the log redaction test sees every debug and trace event. +# tests/docker-compose.yml gives PROXY_LOG_FORCE_LEVEL precedence over every CS_LOG__*_LEVEL in the proxy-tls service. +# The CS_LOG__* variables themselves would not work here: each child `mise run` reloads them from mise.local.toml. +export PROXY_LOG_FORCE_LEVEL=trace +export PROXY_LOG_FORCE_FORMAT=structured + mise --env tls run proxy:up proxy-tls --extra-args "--detach --wait" mise --env tls run test:wait_for_postgres_to_quack --port 6432 --max-retries 20 --tls -mise --env tls run test:integration:without_multitenant +PROXY_LOG_CONTAINER=proxy-tls mise --env tls run test:integration:without_multitenant mise --env tls run proxy:down +unset PROXY_LOG_FORCE_LEVEL PROXY_LOG_FORCE_FORMAT + echo echo '###############################################' echo '# Test: Multitenant Integration' @@ -479,6 +488,10 @@ mise run test:integration:lang:python description = "Runs cargo nextest, skipping integration tests" run = 'cargo nextest run --no-fail-fast --nocapture -E "not package(cipherstash-proxy-integration)" {{arg(name="test",default="")}}' +[tasks."test:unit:log-plaintext"] +description = "Runs the log redaction unit tests with the log-plaintext feature, which shows the values" +run = 'cargo nextest run --no-fail-fast -p cipherstash-proxy --features log-plaintext -E "test(/log_plaintext|plaintext_logging/)"' + [tasks."rust:version"] description = "Outputs rust toolchain version info" run = """ diff --git a/packages/cipherstash-proxy-integration/src/lib.rs b/packages/cipherstash-proxy-integration/src/lib.rs index f94941a78..5a8294f67 100644 --- a/packages/cipherstash-proxy-integration/src/lib.rs +++ b/packages/cipherstash-proxy-integration/src/lib.rs @@ -11,6 +11,7 @@ mod extended_protocol_error_messages; mod inbound_ciphertext; mod insert; mod legacy_v2_column; +mod log_redaction; mod map_concat; mod map_literals; mod map_match_index; diff --git a/packages/cipherstash-proxy-integration/src/log_redaction.rs b/packages/cipherstash-proxy-integration/src/log_redaction.rs new file mode 100644 index 000000000..2141f1feb --- /dev/null +++ b/packages/cipherstash-proxy-integration/src/log_redaction.rs @@ -0,0 +1,150 @@ +//! A release build of Proxy must never log plaintext, whatever the log level. +//! +//! This test sends a distinctive value through Proxy and then reads the Proxy container's logs. +//! It needs a Proxy built without the `log-plaintext` feature, running in a container named by `PROXY_LOG_CONTAINER`, with structured logging and every log target at `trace`. +//! `mise run test:integration` sets that up for the main integration run, by setting `PROXY_LOG_FORCE_LEVEL=trace` for `tests/docker-compose.yml`. +//! The test checks that the startup warning lists every log target, which proves each one is at `debug` or `trace`. +//! Without `PROXY_LOG_CONTAINER` the test is skipped locally, because a Proxy started with `mise run proxy` includes `log-plaintext`. +//! In CI, where `CI` is set, a missing `PROXY_LOG_CONTAINER` fails the test instead, so the check cannot stop running unnoticed. + +#[cfg(test)] +mod tests { + use crate::common::{connect_with_tls, random_id, PROXY}; + use std::process::Command; + use std::time::Duration; + + const CONTAINER_ENV: &str = "PROXY_LOG_CONTAINER"; + + fn container_logs(container: &str) -> String { + let output = Command::new("docker") + .args(["logs", container]) + .output() + .unwrap(); + assert!( + output.status.success(), + "docker logs {container} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + // Proxy logs to stdout, and docker keeps stderr separately + let mut logs = String::from_utf8_lossy(&output.stdout).into_owned(); + logs.push_str(&String::from_utf8_lossy(&output.stderr)); + logs + } + + fn redacted_startup_targets(logs: &str) -> Option> { + logs.lines().find_map(|line| { + let event: serde_json::Value = serde_json::from_str(line).ok()?; + let fields = &event["fields"]; + if event["target"] == "CONFIG" + && event["level"] == "WARN" + && fields["msg"] + .as_str()? + .starts_with("Debug or trace logging is enabled") + && fields["plaintext_logging"] == false + { + // tracing serializes a Debug field as a string in structured output. + serde_json::from_str(fields["targets"].as_str()?).ok() + } else { + None + } + }) + } + + #[test] + fn reads_verbose_targets_only_from_the_startup_warning() { + let logs = r#"{"target":"CONFIG","level":"WARN","fields":{"msg":"Debug or trace logging is enabled.","plaintext_logging":false,"targets":"[\"default\", \"MAPPER\"]"}} +{"target":"MIGRATE","level":"INFO","fields":{"msg":"Select"}}"#; + + assert_eq!( + redacted_startup_targets(logs).unwrap(), + ["default", "MAPPER"] + ); + } + + #[tokio::test] + async fn release_build_logs_no_plaintext_at_trace() { + let Ok(container) = std::env::var(CONTAINER_ENV) else { + // A skip reports as a pass, so CI must never skip: the check would + // stop running without anyone noticing. + assert!( + std::env::var_os("CI").is_none(), + "{CONTAINER_ENV} must be set in CI; `mise run test:integration` sets it" + ); + println!("Skipping: set {CONTAINER_ENV} to the name of a Proxy container built without log-plaintext"); + return; + }; + + // Other tests clear the table concurrently, so this test checks the logs, + // not the rows each query returns. + let client = connect_with_tls(*PROXY).await; + + let canary = format!("log-canary-{}", uuid::Uuid::new_v4().simple()); + + // Extended protocol, with bound parameters + let extended_id = random_id(); + client + .query( + "INSERT INTO encrypted (id, encrypted_text) VALUES ($1, $2)", + &[&extended_id, &canary], + ) + .await + .unwrap(); + client + .query( + "SELECT encrypted_text FROM encrypted WHERE id = $1", + &[&extended_id], + ) + .await + .unwrap(); + client + .query( + "SELECT id FROM encrypted WHERE encrypted_text = $1", + &[&canary], + ) + .await + .unwrap(); + + // Simple protocol, with literals + let simple_id = random_id(); + client + .simple_query(&format!( + "INSERT INTO encrypted (id, encrypted_text) VALUES ({simple_id}, '{canary}')" + )) + .await + .unwrap(); + client + .simple_query(&format!( + "SELECT encrypted_text FROM encrypted WHERE id = {simple_id}" + )) + .await + .unwrap(); + client + .simple_query(&format!( + "SELECT encrypted_text FROM encrypted WHERE encrypted_text = '{canary}'" + )) + .await + .unwrap(); + + // Give the container a moment to flush its log output + tokio::time::sleep(Duration::from_secs(2)).await; + let logs = container_logs(&container); + + let targets = redacted_startup_targets(&logs) + .expect("expected a structured CONFIG startup warning with plaintext logging disabled"); + for target in cipherstash_proxy::log::targets::log_targets() { + assert!( + targets.iter().any(|name| name == target), + "missing verbose target {target}" + ); + } + assert!( + logs.contains("Rewrite Bind") && logs.contains("Rewrite Query"), + "expected the mapper debug events in the {container} logs" + ); + assert!( + !logs.contains(&canary), + "{container} logged a plaintext value" + ); + } +} diff --git a/packages/cipherstash-proxy/Cargo.toml b/packages/cipherstash-proxy/Cargo.toml index 8c620ade8..eb2603c82 100644 --- a/packages/cipherstash-proxy/Cargo.toml +++ b/packages/cipherstash-proxy/Cargo.toml @@ -4,6 +4,12 @@ version.workspace = true edition = "2021" rust-version.workspace = true +[features] +# Log the values that `log::Sensitive` wraps (plaintexts, parameters, literals, +# SQL text). For local development only: release builds and published images +# must never enable it. +log-plaintext = [] + [dependencies] async-trait = "0.1" bigdecimal = { version = "0.4.6", features = ["serde-json"] } diff --git a/packages/cipherstash-proxy/build.rs b/packages/cipherstash-proxy/build.rs index 7c297d21f..daaf4e416 100644 --- a/packages/cipherstash-proxy/build.rs +++ b/packages/cipherstash-proxy/build.rs @@ -1,6 +1,11 @@ use std::env; fn main() { + println!("cargo:rustc-check-cfg=cfg(proxy_dev_profile)"); + if env::var("PROFILE").as_deref() == Ok("debug") { + println!("cargo:rustc-cfg=proxy_dev_profile"); + } + if let Ok(eql_version) = env::var("CS_EQL_VERSION") { println!( "cargo:rustc-env=EQL_VERSION_AT_BUILD_TIME={}", diff --git a/packages/cipherstash-proxy/src/cli/migrate/mod.rs b/packages/cipherstash-proxy/src/cli/migrate/mod.rs index f82b50e21..ac729b785 100644 --- a/packages/cipherstash-proxy/src/cli/migrate/mod.rs +++ b/packages/cipherstash-proxy/src/cli/migrate/mod.rs @@ -1,5 +1,5 @@ use crate::error::{Error, ErrorChain}; -use crate::log::MIGRATE; +use crate::log::{Sensitive, MIGRATE}; use crate::tls::NoCertificateVerification; use crate::TandemConfig; use postgres_protocol::escape::{escape_identifier, escape_literal}; @@ -131,7 +131,7 @@ impl Migrate { if self.verbose { info!(target: MIGRATE, msg = "Fetch records to encrypt", table = self.table, columns = ?self.columns); } - debug!(target: MIGRATE, msg = "Select", sql); + debug!(target: MIGRATE, msg = "Select", sql = %Sensitive(&sql)); let rows = match client.simple_query(&sql).await { Ok(rows) => rows, @@ -207,10 +207,10 @@ impl Migrate { } if self.verbose { - info!(target: MIGRATE, msg = "Encrypting", ?records); + info!(target: MIGRATE, msg = "Encrypting", records = ?Sensitive(&records)); } - debug!(target: MIGRATE, msg = "Update", update_sql = update_sql); + debug!(target: MIGRATE, msg = "Update", update_sql = %Sensitive(&update_sql)); if self.commit() { { diff --git a/packages/cipherstash-proxy/src/config/tandem.rs b/packages/cipherstash-proxy/src/config/tandem.rs index 33a1febe7..be0399096 100644 --- a/packages/cipherstash-proxy/src/config/tandem.rs +++ b/packages/cipherstash-proxy/src/config/tandem.rs @@ -34,19 +34,43 @@ pub struct TandemConfig { pub development: Option, } -#[derive(Clone, Debug, Deserialize)] +/// Placeholder printed in place of a credential in `Debug` output. +pub(crate) const REDACTED_CREDENTIAL: &str = ""; + +#[derive(Clone, Deserialize)] pub struct AuthConfig { pub workspace_crn: Crn, pub client_access_key: String, } -#[derive(Debug, Deserialize, Clone, PartialEq)] +/// Never prints `client_access_key`, in any build: it is a credential. +impl std::fmt::Debug for AuthConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AuthConfig") + .field("workspace_crn", &self.workspace_crn) + .field("client_access_key", &REDACTED_CREDENTIAL) + .finish() + } +} + +#[derive(Deserialize, Clone, PartialEq)] pub struct EncryptConfig { pub client_id: Uuid, pub client_key: String, pub default_keyset_id: Option, } +/// Never prints `client_key`, in any build: it is a credential. +impl std::fmt::Debug for EncryptConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EncryptConfig") + .field("client_id", &self.client_id) + .field("client_key", &REDACTED_CREDENTIAL) + .field("default_keyset_id", &self.default_keyset_id) + .finish() + } +} + #[derive(Clone, Debug, Deserialize)] pub struct PrometheusConfig { #[serde(default)] @@ -1549,4 +1573,31 @@ mod tests { assert_eq!(std::env::var("CS_DATABASE__PORT").unwrap(), "6543"); }); } + + /// `migrate` logs the whole `TandemConfig` with `?config` at debug, so its + /// `Debug` output must never contain the ZeroKMS credentials. + #[test] + fn debug_output_redacts_credentials() { + let auth = super::AuthConfig { + workspace_crn: "crn:us-west-1.aws:E4UMRN47WJNSMAKR".parse().unwrap(), + client_access_key: "secret-client-access-key".to_string(), + }; + let encrypt = super::EncryptConfig { + client_id: Uuid::new_v4(), + client_key: "secret-client-key".to_string(), + default_keyset_id: None, + }; + + let auth_debug = format!("{auth:?}"); + let encrypt_debug = format!("{encrypt:?}"); + + assert!( + !auth_debug.contains("secret-client-access-key"), + "client_access_key leaked into Debug output: {auth_debug}" + ); + assert!( + !encrypt_debug.contains("secret-client-key"), + "client_key leaked into Debug output: {encrypt_debug}" + ); + } } diff --git a/packages/cipherstash-proxy/src/config/tls.rs b/packages/cipherstash-proxy/src/config/tls.rs index 9585cff65..d5bc6ecf4 100644 --- a/packages/cipherstash-proxy/src/config/tls.rs +++ b/packages/cipherstash-proxy/src/config/tls.rs @@ -4,13 +4,14 @@ use rustls_pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer}; use serde::Deserialize; use tracing::debug; +use super::tandem::REDACTED_CREDENTIAL; use crate::{error::TlsConfigError, log::CONFIG}; /// /// Server TLS Configuration /// This is listener/inbound connection config /// -#[derive(Clone, Debug, Deserialize, PartialEq)] +#[derive(Clone, Deserialize, PartialEq)] #[serde(untagged)] pub enum TlsConfig { Pem { @@ -23,6 +24,29 @@ pub enum TlsConfig { }, } +/// Never prints an inline `private_key_pem`, in any build: it is a credential. +impl std::fmt::Debug for TlsConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + TlsConfig::Pem { + certificate_pem, .. + } => f + .debug_struct("Pem") + .field("certificate_pem", certificate_pem) + .field("private_key_pem", &REDACTED_CREDENTIAL) + .finish(), + TlsConfig::Path { + certificate_path, + private_key_path, + } => f + .debug_struct("Path") + .field("certificate_path", certificate_path) + .field("private_key_path", private_key_path) + .finish(), + } + } +} + impl TlsConfig { pub fn check_cert(&self) -> Result<(), TlsConfigError> { match self { @@ -184,4 +208,25 @@ B+qwsnNEiDoJhgYj+cQ= assert!(test_config_with_pem().check_private_key().is_ok()); assert!(test_config_with_invalid_pem().check_private_key().is_err()); } + + /// `migrate` logs the whole `TandemConfig` with `?config` at debug, so an + /// inline PEM private key must never appear in `Debug` output. + #[test] + fn debug_output_redacts_inline_private_key() { + let config = test_config_with_pem(); + let TlsConfig::Pem { + private_key_pem, .. + } = &config + else { + unreachable!() + }; + let key_body = private_key_pem.lines().nth(1).unwrap().to_owned(); + + let debug = format!("{config:?}"); + + assert!( + !debug.contains(&key_body), + "private_key_pem leaked into Debug output: {debug}" + ); + } } diff --git a/packages/cipherstash-proxy/src/log/mod.rs b/packages/cipherstash-proxy/src/log/mod.rs index 21cbdf5a3..9f408cdaa 100644 --- a/packages/cipherstash-proxy/src/log/mod.rs +++ b/packages/cipherstash-proxy/src/log/mod.rs @@ -1,8 +1,10 @@ +pub mod sensitive; pub mod subscriber; pub mod targets; use crate::config::{LogConfig, LogFormat}; use std::sync::Once; +use tracing::warn; use tracing_subscriber::{ fmt::{ format::{DefaultFields, Format}, @@ -19,6 +21,8 @@ pub use targets::{ MAPPER, MIGRATE, PROTOCOL, SCHEMA, SLOW_STATEMENTS, ZEROKMS, }; +pub use sensitive::{Sensitive, PLAINTEXT_LOGGING}; + static INIT: Once = Once::new(); type Subscriber = Box; @@ -30,9 +34,48 @@ pub fn init(config: LogConfig) { tracing::subscriber::set_global_default(subscriber) .expect("Could not set the tracing subscriber"); + + warn_if_verbose(&config); }); } +/// The log targets set to `debug` or `trace`, with `default` for the default level. +pub(crate) fn verbose_targets(config: &LogConfig) -> Vec<&'static str> { + let default = subscriber::is_debug(&config.level).then_some("default"); + let targets = targets::log_targets() + .into_iter() + .filter(|&target| subscriber::is_debug(&targets::log_level_for(config, target))); + default.into_iter().chain(targets).collect() +} + +/// Warns when any log target is at `debug` or `trace`, which are for development only. +/// The warning says whether this build logs plaintext. +/// +/// The warning goes to stderr instead when the `CONFIG` target would filter it out, so that it is never lost. +pub(crate) fn warn_if_verbose(config: &LogConfig) { + let targets = verbose_targets(config); + if targets.is_empty() { + return; + } + + let message = if PLAINTEXT_LOGGING { + "Debug or trace logging is enabled, and this build logs plaintext. Debug and trace logging are for development only. Never run a build with the log-plaintext feature in production." + } else { + "Debug or trace logging is enabled. Debug and trace logging are for development only. Values are redacted in this build." + }; + + if tracing::enabled!(target: CONFIG, tracing::Level::WARN) { + warn!( + target: CONFIG, + msg = message, + ?targets, + plaintext_logging = PLAINTEXT_LOGGING, + ); + } else { + eprintln!("WARN {message} targets={targets:?} plaintext_logging={PLAINTEXT_LOGGING}"); + } +} + pub fn set_format( config: &LogConfig, builder: SubscriberBuilder, @@ -188,6 +231,64 @@ mod tests { assert!(log_contents.contains("info/schema")); } + mod given_startup { + use super::super::{verbose_targets, warn_if_verbose, PLAINTEXT_LOGGING}; + use crate::config::{LogConfig, LogLevel}; + use crate::test_helpers::capture_trace_logs; + + #[test] + fn warns_when_a_target_is_at_debug() { + let mut config = LogConfig::with_level(LogLevel::Info); + config.targets.mapper_level = LogLevel::Debug; + + let logs = capture_trace_logs(|| warn_if_verbose(&config)); + + assert!(logs.contains("WARN"), "{logs}"); + assert!(logs.contains("for development only"), "{logs}"); + assert!(logs.contains("MAPPER"), "{logs}"); + assert!( + logs.contains(&format!("plaintext_logging={PLAINTEXT_LOGGING}")), + "{logs}" + ); + } + + #[test] + fn says_whether_plaintext_logging_is_compiled_in() { + let config = LogConfig::with_level(LogLevel::Trace); + + let logs = capture_trace_logs(|| warn_if_verbose(&config)); + + assert_eq!( + logs.contains("this build logs plaintext"), + PLAINTEXT_LOGGING, + "{logs}" + ); + assert_eq!( + logs.contains("Values are redacted"), + !PLAINTEXT_LOGGING, + "{logs}" + ); + } + + #[test] + fn does_not_warn_at_info() { + let config = LogConfig::with_level(LogLevel::Info); + + let logs = capture_trace_logs(|| warn_if_verbose(&config)); + + assert_eq!(logs, ""); + } + + #[test] + fn lists_the_default_level_and_each_verbose_target() { + let mut config = LogConfig::with_level(LogLevel::Info); + config.level = LogLevel::Trace; + config.targets.encoding_level = LogLevel::Debug; + + assert_eq!(verbose_targets(&config), vec!["default", "ENCODING"]); + } + } + #[test] fn test_log_format_structured() { let make_writer = MockMakeWriter::default(); diff --git a/packages/cipherstash-proxy/src/log/sensitive.rs b/packages/cipherstash-proxy/src/log/sensitive.rs new file mode 100644 index 000000000..54854e840 --- /dev/null +++ b/packages/cipherstash-proxy/src/log/sensitive.rs @@ -0,0 +1,79 @@ +//! Redaction for log fields that can carry customer data. +//! +//! Debug logs are useful during development because they show the values flowing through Proxy. +//! The same logs in production would put plaintext into an operator's log pipeline, so redaction is the default. +//! +//! Wrap any log field that can carry a value (a plaintext, a bound parameter, a literal, SQL text, or a protocol message with row or parameter data) in [`Sensitive`]: +//! +//! ```ignore +//! debug!(target: MAPPER, plaintexts = ?Sensitive(&plaintexts)); +//! ``` +//! +//! Its `Debug` and `Display` print `` unless the `log-plaintext` Cargo feature is enabled in a development build. +//! Release builds always redact these fields, including when all features are enabled. +//! +//! Vitamin C's `Redacted` and `OpaqueDebug` always redact, so they cannot be switched on for development builds. + +use std::fmt; + +/// Whether this build logs the values that [`Sensitive`] wraps. +pub const PLAINTEXT_LOGGING: bool = cfg!(all(proxy_dev_profile, feature = "log-plaintext")); + +const REDACTED: &str = ""; + +/// A log field that can carry customer data. +/// +/// Prints `` unless the `log-plaintext` feature is enabled in a development build. +#[derive(Clone, Copy)] +pub struct Sensitive(pub T); + +impl fmt::Debug for Sensitive { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if PLAINTEXT_LOGGING { + self.0.fmt(f) + } else { + f.write_str(REDACTED) + } + } +} + +impl fmt::Display for Sensitive { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if PLAINTEXT_LOGGING { + self.0.fmt(f) + } else { + f.write_str(REDACTED) + } + } +} + +#[cfg(test)] +mod tests { + use super::Sensitive; + + // CI runs this test explicitly under --release --all-features. + #[test] + #[ignore = "requires the release profile with all features"] + fn release_with_all_features_redacts_values() { + assert_eq!(format!("{:?}", Sensitive("hunter2")), ""); + assert_eq!(format!("{}", Sensitive("hunter2")), ""); + } + + #[cfg(not(all(proxy_dev_profile, feature = "log-plaintext")))] + #[test] + fn redacts_debug_and_display_when_plaintext_logging_is_disabled() { + let value = Sensitive("hunter2"); + + assert_eq!(format!("{value:?}"), ""); + assert_eq!(format!("{value}"), ""); + } + + #[cfg(all(proxy_dev_profile, feature = "log-plaintext"))] + #[test] + fn shows_debug_and_display_with_log_plaintext() { + let value = Sensitive("hunter2"); + + assert_eq!(format!("{value:?}"), "\"hunter2\""); + assert_eq!(format!("{value}"), "hunter2"); + } +} diff --git a/packages/cipherstash-proxy/src/log/subscriber.rs b/packages/cipherstash-proxy/src/log/subscriber.rs index 4e37d960f..e189642ea 100644 --- a/packages/cipherstash-proxy/src/log/subscriber.rs +++ b/packages/cipherstash-proxy/src/log/subscriber.rs @@ -1,11 +1,19 @@ use crate::config::{LogConfig, LogLevel, LogOutput}; use crate::log::targets::{log_level_for, log_targets}; +use crate::log::PLAINTEXT_LOGGING; use tracing_subscriber::filter::EnvFilter; use tracing_subscriber::fmt::format::{DefaultFields, Format}; use tracing_subscriber::fmt::writer::BoxMakeWriter; use tracing_subscriber::fmt::SubscriberBuilder; use tracing_subscriber::FmtSubscriber; +/// Log targets of dependencies whose debug and trace events carry values. +/// +/// EQL Mapper's trace spans and events print SQL statements and AST nodes, literals included. +/// +/// tokio-postgres is not listed: it logs through the `log` crate, which Proxy does not bridge into tracing, so its records are discarded. +const PLAINTEXT_DEPENDENCY_TARGETS: [&str; 3] = ["eql_mapper", "eql-mapper", "eqlmapper"]; + pub fn builder( config: &LogConfig, ) -> SubscriberBuilder { @@ -26,6 +34,15 @@ pub fn builder( env_filter = env_filter.add_directive(format!("{target}={level}").parse().unwrap()); } + // Dependencies cannot wrap their fields in `Sensitive`, so cap the ones + // whose debug and trace output carries values, unless this build logs + // plaintext. + if is_debug(&log_level) && !PLAINTEXT_LOGGING { + for target in PLAINTEXT_DEPENDENCY_TARGETS { + env_filter = env_filter.add_directive(format!("{target}=info").parse().unwrap()); + } + } + let writer = match config.output { LogOutput::Stderr => BoxMakeWriter::new(std::io::stderr), LogOutput::Stdout => BoxMakeWriter::new(std::io::stdout), @@ -46,6 +63,44 @@ pub fn builder( builder } -fn is_debug(level: &LogLevel) -> bool { +pub(crate) fn is_debug(level: &LogLevel) -> bool { matches!(level, LogLevel::Debug | LogLevel::Trace) } + +#[cfg(test)] +mod tests { + use crate::test_helpers::{ + assert_secret_logged_only_with_log_plaintext, capture_trace_logs, SECRET, + }; + + #[test] + fn dependency_debug_and_trace_are_logged_only_with_log_plaintext() { + let logs = capture_trace_logs(|| { + tracing::debug!(target: "eql_mapper::inference", "{SECRET}"); + tracing::trace!(target: "eql_mapper::inference", "{SECRET}"); + tracing::trace!(target: "eql-mapper::DUMP_NODE", "{SECRET}"); + tracing::trace!(target: "eqlmapper::spans", "{SECRET}"); + tracing::info!(target: "eql_mapper::inference", "mapper info"); + }); + + assert!(logs.contains("mapper info"), "{logs}"); + assert_secret_logged_only_with_log_plaintext(&logs); + } + + #[test] + fn eql_mapper_span_fields_are_logged_only_with_log_plaintext() { + let logs = capture_trace_logs(|| { + let span = tracing::span!( + target: "eqlmapper::spans", + tracing::Level::TRACE, + "resolve", + statement = SECRET + ); + let _guard = span.enter(); + tracing::info!(target: "MAPPER", "inside the span"); + }); + + assert!(logs.contains("inside the span"), "{logs}"); + assert_secret_logged_only_with_log_plaintext(&logs); + } +} diff --git a/packages/cipherstash-proxy/src/postgresql/context/statement.rs b/packages/cipherstash-proxy/src/postgresql/context/statement.rs index a07699651..2aac9bce8 100644 --- a/packages/cipherstash-proxy/src/postgresql/context/statement.rs +++ b/packages/cipherstash-proxy/src/postgresql/context/statement.rs @@ -1,11 +1,12 @@ use super::Column; +use crate::log::Sensitive; use eql_mapper::{JsonSelectorSegment, ParamPlan}; /// Where one step of the path half of a fused JSON value selector comes from. /// /// The proxy's copy of [`eql_mapper::JsonSelectorSegment`], with param numbers /// converted to 0-based bind indexes. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub enum JsonSelectorStep { /// A literal selector in the SQL, known at Parse time. Literal(String), @@ -14,6 +15,21 @@ pub enum JsonSelectorStep { Param(usize), } +/// A literal selector is a key into an encrypted JSON column, so it is redacted +/// like any other value. Every `Debug` that contains a statement, portal or +/// execute context prints through here. +impl std::fmt::Debug for JsonSelectorStep { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Literal(selector) => f + .debug_tuple("Literal") + .field(&Sensitive(selector)) + .finish(), + Self::Param(index) => f.debug_tuple("Param").field(index).finish(), + } + } +} + /// The path half of a fused JSON value selector: the steps of the accessor /// chain, outermost last. /// @@ -197,3 +213,24 @@ fn to_selector_path(path: &eql_mapper::JsonSelectorSource) -> JsonSelectorPath { .collect(), } } + +#[cfg(test)] +mod tests { + use super::{JsonSelectorPath, JsonSelectorStep}; + use crate::test_helpers::{assert_secret_logged_only_with_log_plaintext, SECRET}; + + #[test] + fn literal_selector_debug_follows_log_plaintext() { + let path = JsonSelectorPath { + steps: vec![ + JsonSelectorStep::Literal(SECRET.to_owned()), + JsonSelectorStep::Param(1), + ], + }; + + let debug = format!("{path:?}"); + + assert!(debug.contains("Param(1)"), "{debug}"); + assert_secret_logged_only_with_log_plaintext(&debug); + } +} diff --git a/packages/cipherstash-proxy/src/postgresql/data/from_sql.rs b/packages/cipherstash-proxy/src/postgresql/data/from_sql.rs index 9ee51d606..424826eab 100644 --- a/packages/cipherstash-proxy/src/postgresql/data/from_sql.rs +++ b/packages/cipherstash-proxy/src/postgresql/data/from_sql.rs @@ -1,6 +1,6 @@ use crate::{ error::{Error, MappingError}, - log::ENCODING, + log::{Sensitive, ENCODING}, postgresql::{format_code::FormatCode, rewrite::bind::BindParam}, }; use bigdecimal::BigDecimal; @@ -21,7 +21,7 @@ pub fn bind_param_from_sql( eql_term: EqlTermVariant, col_type: ColumnType, ) -> Result, Error> { - debug!(target: ENCODING, ?param, ?postgres_type, ?eql_term, ?col_type); + debug!(target: ENCODING, param = ?Sensitive(param), ?postgres_type, ?eql_term, ?col_type); if param.is_null() { return Ok(None); @@ -44,7 +44,7 @@ pub fn literal_from_sql( eql_term: EqlTermVariant, col_type: ColumnType, ) -> Result, MappingError> { - debug!(target: ENCODING, ?literal, ?eql_term, ?col_type); + debug!(target: ENCODING, literal = ?Sensitive(literal), ?eql_term, ?col_type); let pt = match literal { // All string literal variants Value::SingleQuotedString(s) @@ -182,8 +182,8 @@ pub fn json_value_selector_plaintext( debug!( target: ENCODING, msg = "Encrypted JSON equality requires a scalar value", - ?path, - ?value + path = ?Sensitive(path), + value = ?Sensitive(&value) ); return Err(MappingError::CouldNotParseParameter); } @@ -338,7 +338,7 @@ fn text_from_sql( eql_term: EqlTermVariant, col_type: ColumnType, ) -> Result { - debug!(target: ENCODING, ?val, ?eql_term, ?col_type); + debug!(target: ENCODING, val = ?Sensitive(val), ?eql_term, ?col_type); match (eql_term, col_type) { (EqlTermVariant::Full | EqlTermVariant::Partial, ColumnType::Text) => { @@ -765,6 +765,60 @@ mod tests { } } + mod given_every_log_target_at_trace { + use crate::{ + postgresql::{ + data::{ + bind_param_from_sql, from_sql::json_value_selector_plaintext, literal_from_sql, + }, + format_code::FormatCode, + rewrite::bind::BindParam, + }, + test_helpers::{ + assert_secret_logged_only_with_log_plaintext, capture_trace_logs, SECRET, + }, + }; + use bytes::BytesMut; + use cipherstash_client::schema::ColumnType; + use eql_mapper::EqlTermVariant; + use postgres_types::Type; + use sqltk::parser::ast::Value; + + #[test] + fn bind_param_value_is_logged_only_with_log_plaintext() { + let param = BindParam::new(FormatCode::Text, BytesMut::from(SECRET)); + + let logs = capture_trace_logs(|| { + bind_param_from_sql(¶m, &Type::TEXT, EqlTermVariant::Full, ColumnType::Text) + .unwrap(); + }); + + assert_secret_logged_only_with_log_plaintext(&logs); + } + + #[test] + fn literal_value_is_logged_only_with_log_plaintext() { + let literal = Value::SingleQuotedString(SECRET.to_owned()); + + let logs = capture_trace_logs(|| { + literal_from_sql(&literal, EqlTermVariant::Full, ColumnType::Text).unwrap(); + }); + + assert_secret_logged_only_with_log_plaintext(&logs); + } + + #[test] + fn rejected_json_selector_value_is_logged_only_with_log_plaintext() { + let value = serde_json::json!({ "nested": SECRET }); + + let logs = capture_trace_logs(|| { + json_value_selector_plaintext(&["key"], value).unwrap_err(); + }); + + assert_secret_logged_only_with_log_plaintext(&logs); + } + } + #[test] pub fn bind_param_to_plaintext_i64() { log::init(LogConfig::default()); diff --git a/packages/cipherstash-proxy/src/postgresql/data/mod.rs b/packages/cipherstash-proxy/src/postgresql/data/mod.rs index 651994e19..1f709624d 100644 --- a/packages/cipherstash-proxy/src/postgresql/data/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/data/mod.rs @@ -1,7 +1,7 @@ mod from_sql; mod to_sql; -use crate::log::MAPPER; +use crate::log::{Sensitive, MAPPER}; use cipherstash_client::encryption::Plaintext; pub use from_sql::bind_param_from_sql; use postgres_types::Type; @@ -25,7 +25,7 @@ pub use to_sql::to_sql; /// /// pub fn to_type(plaintext: Plaintext, postgres_type: &Type) -> Plaintext { - debug!(target = MAPPER, msg = "Convert plaintext to postgres_type", plaintext = ?plaintext, postgres_type = ?postgres_type ); + debug!(target: MAPPER, msg = "Convert plaintext to postgres_type", plaintext = ?Sensitive(&plaintext), ?postgres_type); match (plaintext, postgres_type) { (Plaintext::SmallInt(Some(val)), &Type::INT4) => Plaintext::Int(Some(val as i32)), @@ -60,3 +60,24 @@ pub fn to_type(plaintext: Plaintext, postgres_type: &Type) -> Plaintext { } } } + +#[cfg(test)] +mod tests { + use super::to_type; + use crate::test_helpers::{ + assert_secret_logged_only_with_log_plaintext, capture_trace_logs, SECRET, + }; + use cipherstash_client::encryption::Plaintext; + use postgres_types::Type; + + #[test] + fn converted_plaintext_is_logged_only_with_log_plaintext() { + let logs = capture_trace_logs(|| to_type(Plaintext::new(SECRET.to_owned()), &Type::TEXT)); + + assert!( + logs.contains("Convert plaintext to postgres_type"), + "{logs}" + ); + assert_secret_logged_only_with_log_plaintext(&logs); + } +} diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs index 833e2d39d..08e41c2d5 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs @@ -4,7 +4,7 @@ use super::super::error_handler::PostgreSqlErrorHandler; use super::super::rewrite::UNSPECIFIED_TYPE_OID; use super::super::Column; use crate::error::{EncryptError, Error, ProtocolError}; -use crate::log::{CONTEXT, DEVELOPMENT, MAPPER, PROTOCOL}; +use crate::log::{Sensitive, CONTEXT, DEVELOPMENT, MAPPER, PROTOCOL}; use crate::postgresql::context::Portal; use crate::postgresql::rewrite::data_row; use crate::postgresql::OperationId; @@ -394,7 +394,7 @@ impl Backend { debug!(target: PROTOCOL, client_id = self.context.client_id, msg = "Passthrough", - message = ?protocol_message, + message = ?Sensitive(&protocol_message), ); } } @@ -451,7 +451,7 @@ impl Backend { client_id = self.context.client_id, msg = "Database returned an error", code = %field(b'C').unwrap_or_default(), - error = %field(b'M').unwrap_or_default(), + error = %Sensitive(field(b'M').unwrap_or_default()), ); } diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs b/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs index 4a06f83de..51f487d38 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs @@ -5,7 +5,7 @@ use super::super::parser::SqlParser; use super::super::rewrite::bind::Bind; use super::super::rewrite::Name; use crate::error::{EncryptError, Error, MappingError}; -use crate::log::{ENCRYPT, MAPPER, PROTOCOL}; +use crate::log::{Sensitive, ENCRYPT, MAPPER, PROTOCOL}; use crate::postgresql::context::column::Column; use crate::postgresql::context::statement::{ output_params_from_plan, OutputParam, OutputParamSource, @@ -224,7 +224,7 @@ impl Frontend { warn!( client_id = self.context.client_id, msg = "Query Handler Error", - error = ?err.to_string(), + error = %Sensitive(&err), ); let response = self.error_to_response(err); self.context @@ -282,7 +282,7 @@ impl Frontend { warn!( client_id = self.context.client_id, msg = "Parse Handler Error", - error = ?err.to_string(), + error = %Sensitive(&err), ); let response = self.error_to_response(err); self.context.refuse_parse(operation, response.clone())?; @@ -341,7 +341,7 @@ impl Frontend { FrontendMessage::Sync => { debug!(target: PROTOCOL, client_id = self.context.client_id, - message = ?protocol_message, + message = ?Sensitive(&protocol_message), ); self.context.sync(operation)?; } @@ -355,7 +355,7 @@ impl Frontend { debug!(target: PROTOCOL, client_id = self.context.client_id, msg = "Passthrough", - message = ?protocol_message, + message = ?Sensitive(&protocol_message), ); } } @@ -528,7 +528,7 @@ impl Frontend { { debug!(target: MAPPER, client_id = self.context.client_id, - transformed_statement = ?transformed_statement.statement, + transformed_statement = ?Sensitive(&transformed_statement.statement), ); // The simple protocol has no params, so the plan is @@ -599,9 +599,9 @@ impl Frontend { target: MAPPER, client_id = self.context.client_id, msg = "Rewrite Query", - transformed_statement = transformed_statement.to_string(), + transformed_statement = %Sensitive(&transformed_statement), duration_ms = handler_duration.as_millis(), - ?message, + message = ?Sensitive(&message), ); if handler_duration.as_millis() > 100 { warn!( @@ -706,7 +706,7 @@ impl Frontend { debug!(target: MAPPER, client_id = self.context.client_id, ?literal_columns, - ?encrypted + encrypted = ?Sensitive(&encrypted) ); let duration = Instant::now().duration_since(start); @@ -869,8 +869,8 @@ impl Frontend { { debug!(target: MAPPER, client_id = self.context.client_id, - transformed_statement = ?transformed_statement.statement, - param_plan = ?transformed_statement.params, + transformed_statement = ?Sensitive(&transformed_statement.statement), + param_plan = ?Sensitive(&transformed_statement.params), ); // The rewrite may have reshaped the params, so the @@ -911,7 +911,7 @@ impl Frontend { debug!(target: MAPPER, client_id = self.context.client_id, msg = "Rewrite Parse", - ?message); + message = ?Sensitive(&message)); Ok(Some(message)) } else { @@ -1065,7 +1065,7 @@ impl Frontend { self.context .with_metrics_scope(session_id, |m| m.metadata.set_param_bytes(param_bytes))?; - debug!(target: PROTOCOL, client_id = self.context.client_id, bind = ?bind); + debug!(target: PROTOCOL, client_id = self.context.client_id, bind = ?Sensitive(&bind)); let mut portal = Portal::passthrough(session_id); @@ -1096,7 +1096,7 @@ impl Frontend { target: MAPPER, client_id = self.context.client_id, msg = "Rewrite Bind", - ?message + message = ?Sensitive(&message) ); Ok(Some(message)) @@ -1138,7 +1138,7 @@ impl Frontend { .map(|output| output.column.to_owned()) .collect::>(); - debug!(target: MAPPER, client_id = self.context.client_id, plaintexts = ?plaintexts); + debug!(target: MAPPER, client_id = self.context.client_id, plaintexts = ?Sensitive(&plaintexts)); let start = Instant::now(); @@ -1339,7 +1339,7 @@ impl Frontend { let typed_statement = eql_mapper::type_check(resolver.clone(), statement)?; debug!(target: MAPPER, client_id = self.context.client_id, - typed_statement = ?typed_statement + typed_statement = ?Sensitive(&typed_statement) ); Ok(typed_statement) } @@ -1616,9 +1616,9 @@ fn literals_to_plaintext_skipping( debug!( target: MAPPER, msg = "Could not convert literal value", - value = ?val, + value = ?Sensitive(&val), cast_type = ?col.cast_type(), - error = err.to_string() + error = %Sensitive(&err) ); MappingError::InvalidParameter(Box::new(col.to_owned())).into() }) @@ -1660,7 +1660,7 @@ fn json_value_selector_literal_plaintext( debug!( target: MAPPER, msg = "Encrypted JSON equality needs a literal selector when the value is a literal", - value = ?literal, + value = ?Sensitive(literal), ); return Err(MappingError::CouldNotParseParameter); }; @@ -1707,7 +1707,7 @@ fn json_accessor_path_literal_plaintext( target: MAPPER, msg = "An encrypted JSON path with a placeholder step must end in a placeholder, \ so that the whole path can be resolved when the params are bound", - value = ?literal, + value = ?Sensitive(literal), ); return Err(MappingError::CouldNotParseParameter); }; @@ -3566,6 +3566,44 @@ mod tests { assert_eq!(deallocation("DISCARD PLANS"), None); assert_eq!(deallocation("SELECT 1"), None); } + + /// Runs `future` on a fresh runtime while capturing every log event at trace level. + fn capture_async_trace_logs(future: F) -> String { + crate::test_helpers::capture_trace_logs(|| { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(future) + }) + } + + /// A SQL syntax error echoes the unexpected token, which can be a literal, + /// and the Query and Parse handler warnings log the error. + #[test] + fn handler_error_warnings_log_sql_literals_only_with_log_plaintext() { + use crate::test_helpers::{assert_secret_logged_only_with_log_plaintext, SECRET}; + + let sql = format!("SELECT * FROM users WHERE id IN '{SECRET}'"); + for message in [ + FrontendMessage::Query(bytes::Bytes::from(sql.clone())), + FrontendMessage::Parse(Parse { + statement: bytes::Bytes::from_static(b"syntax_error"), + query: bytes::Bytes::from(sql.clone()), + parameter_types: vec![], + }), + ] { + let (mut frontend, _) = settings_frontend(); + let logs = capture_async_trace_logs(async { + frontend.intercept(operation_id(), message).await.unwrap(); + }); + + // With log-plaintext, the secret in the warning also shows the + // handler failed on the syntax error rather than a later check. + assert!(logs.contains("Handler Error"), "{logs}"); + assert_secret_logged_only_with_log_plaintext(&logs); + } + } } #[cfg(test)] @@ -3919,6 +3957,66 @@ mod unresolvable_table_tests { (Frontend::new(context), counter) } + /// The MAPPER debug event for a transformed statement prints its param plan, + /// which carries the literal steps of a JSON selector. + #[test] + fn param_plan_json_selector_is_logged_only_with_log_plaintext() { + use crate::test_helpers::{assert_secret_logged_only_with_log_plaintext, SECRET}; + + let mut schema = eql_mapper::Schema::new("public"); + let mut table = eql_mapper::Table::new(sqltk::parser::ast::Ident::new("patients")); + table.add_column(Arc::new(eql_mapper::Column::native( + sqltk::parser::ast::Ident::new("id"), + ))); + table.add_column(Arc::new(eql_mapper::Column::eql( + sqltk::parser::ast::Ident::new("notes"), + eql_mapper::EqlTraits::all(), + eql_mapper::DomainIdentity::from_domain_name("eql_v3_json_search").unwrap(), + ))); + schema.add_table(table); + let mut encrypt_config = EncryptConfig::new(); + encrypt_config.insert( + crate::Identifier::new("patients", "notes"), + cipherstash_client::schema::ColumnConfig::build("notes".to_owned()) + .casts_as(cipherstash_client::schema::ColumnType::Json), + ); + let (reload_sender, _) = tokio::sync::mpsc::unbounded_channel(); + let context = Context::new( + 1, + Arc::new(TandemConfig::for_testing()), + Arc::new(encrypt_config), + Arc::new(schema), + Arc::new(rustls::RootCertStore::empty()), + Counter::default(), + reload_sender, + ); + let mut frontend = Frontend::new(context); + let sql = format!("SELECT id FROM patients WHERE notes -> '{SECRET}' = $1"); + + let logs = crate::test_helpers::capture_trace_logs(|| { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + frontend + .intercept( + operation_id(), + FrontendMessage::Parse(Parse { + statement: Bytes::from_static(b"json_selector"), + query: Bytes::from(sql), + parameter_types: vec![], + }), + ) + .await + .unwrap(); + }) + }); + + assert!(logs.contains("param_plan"), "{logs}"); + assert_secret_logged_only_with_log_plaintext(&logs); + } + fn encrypted_client() -> (Frontend, Counter) { client(TandemConfig::for_testing(), true) } diff --git a/packages/cipherstash-proxy/src/postgresql/rewrite/bind.rs b/packages/cipherstash-proxy/src/postgresql/rewrite/bind.rs index 569830ff0..409a02b97 100644 --- a/packages/cipherstash-proxy/src/postgresql/rewrite/bind.rs +++ b/packages/cipherstash-proxy/src/postgresql/rewrite/bind.rs @@ -1,7 +1,7 @@ //! CipherStash Bind parameter rewriting. use super::{maybe_json, maybe_jsonb, Name, NULL}; use crate::error::{Error, MappingError, ProtocolError}; -use crate::log::MAPPER; +use crate::log::{Sensitive, MAPPER}; use crate::postgresql::context::column::Column; use crate::postgresql::context::statement::{ params_are_positional, JsonSelectorPath, JsonSelectorStep, OutputParam, OutputParamSource, @@ -187,8 +187,8 @@ impl Bind { debug!( target: MAPPER, msg = "Fused JSON value selector", - path = ?steps, - ?value + path = ?Sensitive(&steps), + value = ?Sensitive(&value) ); let steps: Vec<&str> = steps.iter().map(String::as_str).collect(); @@ -221,8 +221,8 @@ impl Bind { debug!( target: MAPPER, msg = "Composed JSON accessor path", - path = ?steps, - ?composed + path = ?Sensitive(&steps), + composed = ?Sensitive(&composed) ); Ok(Some(Plaintext::new(composed))) diff --git a/packages/cipherstash-proxy/src/postgresql/rewrite/data_row.rs b/packages/cipherstash-proxy/src/postgresql/rewrite/data_row.rs index b06c13774..cb42e2f39 100644 --- a/packages/cipherstash-proxy/src/postgresql/rewrite/data_row.rs +++ b/packages/cipherstash-proxy/src/postgresql/rewrite/data_row.rs @@ -2,7 +2,7 @@ use crate::EqlCiphertext; use crate::{ error::{EncryptError, Error, ProtocolError}, - log::DECRYPT, + log::{Sensitive, DECRYPT}, postgresql::Column, }; use bytes::{Bytes, BytesMut}; @@ -151,7 +151,7 @@ fn json_entry_into_ste_vec_document(value: &mut serde_json::Value) -> Result<(), } fn log_deserialise_error(err: serde_json::Error) -> Error { - debug!(target: DECRYPT, error = err.to_string()); + debug!(target: DECRYPT, error = %Sensitive(&err)); err.into() } diff --git a/packages/cipherstash-proxy/src/test_helpers.rs b/packages/cipherstash-proxy/src/test_helpers.rs index 8a0881da3..abee7d440 100644 --- a/packages/cipherstash-proxy/src/test_helpers.rs +++ b/packages/cipherstash-proxy/src/test_helpers.rs @@ -75,3 +75,33 @@ impl<'a> MakeWriter<'a> for MockMakeWriter { MockWriter::new(self.buf.clone()) } } + +/// Runs `f` with every log target at `trace` and returns what it logged. +pub(crate) fn capture_trace_logs R, R>(f: F) -> String { + use crate::config::{LogConfig, LogFormat, LogLevel}; + use tracing_subscriber::fmt::writer::BoxMakeWriter; + + let make_writer = MockMakeWriter::default(); + let mut config = LogConfig::with_level(LogLevel::Trace); + config.format = LogFormat::Text; + config.ansi_enabled = false; + let subscriber = crate::log::subscriber::builder(&config) + .with_writer(BoxMakeWriter::new(make_writer.clone())); + let subscriber = crate::log::set_format(&config, subscriber); + + tracing::subscriber::with_default(subscriber, f); + make_writer.get_string() +} + +/// A distinctive value for checking whether plaintext reaches the logs. +pub(crate) const SECRET: &str = "zebra-unicorn-4242"; + +/// Asserts that `logs` contains [`SECRET`] exactly when the `log-plaintext` feature is compiled in. +pub(crate) fn assert_secret_logged_only_with_log_plaintext(logs: &str) { + assert!(!logs.is_empty(), "expected a log event"); + assert_eq!( + logs.contains(SECRET), + crate::log::PLAINTEXT_LOGGING, + "plaintext in logs must match the log-plaintext feature:\n{logs}" + ); +} diff --git a/tests/docker-compose.yml b/tests/docker-compose.yml index 27977d6bc..9c3e606bb 100644 --- a/tests/docker-compose.yml +++ b/tests/docker-compose.yml @@ -120,11 +120,22 @@ services: - CS_WORKSPACE_CRN=${CS_WORKSPACE_CRN} - CS_CTS_HOST=${CS_CTS_HOST:-} - CS_ZEROKMS_HOST=${CS_ZEROKMS_HOST:-} - - CS_LOG__FORMAT=${CS_LOG__FORMAT:-pretty} - - CS_LOG__LEVEL=${CS_LOG__LEVEL:-debug} - - CS_LOG__PROTOCOL_LEVEL=${CS_LOG__PROTOCOL_LEVEL:-debug} - - CS_LOG__MAPPER_LEVEL=${CS_LOG__MAPPER_LEVEL:-debug} - - CS_LOG__CONTEXT_LEVEL=${CS_LOG__CONTEXT_LEVEL:-debug} + - CS_LOG__FORMAT=${PROXY_LOG_FORCE_FORMAT:-${CS_LOG__FORMAT:-pretty}} + - CS_LOG__LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__LEVEL:-debug}} + - CS_LOG__PROTOCOL_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__PROTOCOL_LEVEL:-debug}} + - CS_LOG__MAPPER_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__MAPPER_LEVEL:-debug}} + - CS_LOG__CONTEXT_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__CONTEXT_LEVEL:-debug}} + - CS_LOG__DEVELOPMENT_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__DEVELOPMENT_LEVEL:-info}} + - CS_LOG__AUTHENTICATION_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__AUTHENTICATION_LEVEL:-info}} + - CS_LOG__CONFIG_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__CONFIG_LEVEL:-info}} + - CS_LOG__ENCODING_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__ENCODING_LEVEL:-info}} + - CS_LOG__ENCRYPT_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__ENCRYPT_LEVEL:-info}} + - CS_LOG__DECRYPT_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__DECRYPT_LEVEL:-info}} + - CS_LOG__ENCRYPT_CONFIG_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__ENCRYPT_CONFIG_LEVEL:-info}} + - CS_LOG__ZEROKMS_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__ZEROKMS_LEVEL:-info}} + - CS_LOG__MIGRATE_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__MIGRATE_LEVEL:-info}} + - CS_LOG__SCHEMA_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__SCHEMA_LEVEL:-info}} + - CS_LOG__SLOW_STATEMENTS_LEVEL=${PROXY_LOG_FORCE_LEVEL:-${CS_LOG__SLOW_STATEMENTS_LEVEL:-info}} - CS_LOG__SLOW_STATEMENTS=${CS_LOG__SLOW_STATEMENTS:-true} volumes: - ./tls/server.cert:/etc/cipherstash-proxy/server.cert