Skip to content
Merged
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 `<redacted>` 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 `<redacted>` in their place in every build.

## [3.1.0] - 2026-11-04

### Added
Expand Down
21 changes: 21 additions & 0 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<redacted>` 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:
Expand Down Expand Up @@ -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 `<redacted>` unless a development build enables the `log-plaintext` feature.

Debug logging is very verbose, and targets allow configuration of granular log levels.

Expand Down Expand Up @@ -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

```
Expand Down
13 changes: 13 additions & 0 deletions docs/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<redacted>` 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):
Expand Down
19 changes: 16 additions & 3 deletions mise.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
"""

Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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 = """
Expand Down
1 change: 1 addition & 0 deletions packages/cipherstash-proxy-integration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
150 changes: 150 additions & 0 deletions packages/cipherstash-proxy-integration/src/log_redaction.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<String>> {
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!(
Comment thread
tobyhede marked this conversation as resolved.
Resolved
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"
);
}
}
6 changes: 6 additions & 0 deletions packages/cipherstash-proxy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
5 changes: 5 additions & 0 deletions packages/cipherstash-proxy/build.rs
Original file line number Diff line number Diff line change
@@ -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={}",
Expand Down
8 changes: 4 additions & 4 deletions packages/cipherstash-proxy/src/cli/migrate/mod.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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() {
{
Expand Down
Loading
Loading