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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [Unreleased]

### Security
## [2.2.7] - 2026-12-04

- **Statements and portals after a failed batch**: Proxy now refuses a Bind, Describe or Execute that names a prepared statement or portal a failed batch would have changed, until PostgreSQL confirms a later change to it.
Proxy applied a Parse, Bind or Close when it read it, but PostgreSQL skips the rest of a batch after an error and keeps the statement or portal such a message would have replaced.
So after a batch failed before its `Close` or re-`Parse` of a statement, values bound to that statement could be sent to PostgreSQL without being encrypted, and rows could be returned without being decrypted, for every later use of that statement name.
Proxy also refuses such a message when it is sent before PostgreSQL has answered the batch that made the change.
The refusal uses PostgreSQL's `26000` error for a statement and `34000` for a portal, and the connection stays open; drivers that cache statements prepare them again on `26000`.
See [Unconfirmed prepared statement](docs/errors.md#mapping-unconfirmed-prepared-statement) and [Unconfirmed portal](docs/errors.md#mapping-unconfirmed-portal).
### Changed

- **Database errors are no longer logged at `error` level**: When PostgreSQL returns an error, Proxy now logs only its SQLSTATE code, as `Database returned an error` at `debug` level on the `PROTOCOL` target.
Previously Proxy logged every database error at `error` level with all of its fields, followed by an `info` message.
Those fields can contain values from the statement, such as the input in an `invalid input syntax` error or the key in a unique violation, so they reached the logs at the default log level.
The client still receives the full error.
The `PROTOCOL` target at `debug` level also logs the raw protocol messages, which include statement values such as bound parameters, so use it only in local development.

### Fixed

Expand All @@ -24,8 +25,26 @@ Previously it went down only when a connection ended with an error, so the value

### Security

- **Encryption Migrator escapes the values it writes**: The `migrate` command, which encrypts the existing rows of a table, now escapes each source value, the target column name and the table name in the `UPDATE` statements it sends.
Previously a source value was inserted into the statement unescaped, so a value containing a single quote, such as `O'Brien`, made the whole batch fail.
A value written to look like SQL, such as `x'; DELETE FROM users; --`, ran as SQL with the migrating database user's privileges.
Upgrade before running `migrate` on a column whose values come from users or other untrusted sources.

- **Statements and portals after a failed batch**: Proxy now refuses a Bind, Describe or Execute that names a prepared statement or portal a failed batch would have changed, until PostgreSQL confirms a later change to it.
Proxy applied a Parse, Bind or Close when it read it, but PostgreSQL skips the rest of a batch after an error and keeps the statement or portal such a message would have replaced.
So after a batch failed before its `Close` or re-`Parse` of a statement, values bound to that statement could be sent to PostgreSQL without being encrypted, and rows could be returned without being decrypted, for every later use of that statement name.
Proxy also refuses such a message when it is sent before PostgreSQL has answered the batch that made the change.
The refusal uses PostgreSQL's `26000` error for a statement and `34000` for a portal, and the connection stays open; drivers that cache statements prepare them again on `26000`.
See [Unconfirmed prepared statement](docs/errors.md#mapping-unconfirmed-prepared-statement) and [Unconfirmed portal](docs/errors.md#mapping-unconfirmed-portal).

- **Dependency updates**: Updated `quinn-proto` to 0.11.19, `quinn-udp` to 0.5.16, `rkyv` to 0.7.46 and `url` to 2.5.9 (with `idna` 1.1.0, `percent-encoding` 2.3.2 and `form_urlencoded` 1.2.3), to pick up the fixes for published security advisories in those crates. No configuration change is required.

- **Advisories that do not affect Proxy**: Some dependency scanners report two advisories against Proxy 2.2.7 that do not affect it.
- `jsonwebtoken` 9.3.1 ([GHSA-h395-gr6q-cpjc](https://github.com/advisories/GHSA-h395-gr6q-cpjc), CVE-2026-25537): a claim with the wrong type can skip the `exp` and `nbf` checks.
Proxy uses `jsonwebtoken` only to read claims from access tokens it has already obtained, with signature and expiry checks turned off, and never uses it to decide access.
The fix is in `jsonwebtoken` 10.3, which requires a major upgrade of the CipherStash client library.
- `rkyv` 0.7 (RUSTSEC-2026-0235): `rkyv` is listed in `Cargo.lock` but is not compiled into Proxy.

## [2.2.6] - 2026-11-19

### Changed
Expand Down
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ members = ["packages/*"]
exclude = ["vendor/stack-auth"]

[workspace.package]
version = "2.2.6"
version = "2.2.7"
edition = "2021"

[profile.dev]
Expand Down
149 changes: 122 additions & 27 deletions packages/cipherstash-proxy/src/cli/migrate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,33 +164,12 @@ impl Migrate {
row.get(source_col.as_str()).unwrap_or("").to_owned()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor Existing code: unwrap_or("") turns a SQL NULL into '', so a NULL source value is written as an encrypted empty string instead of NULL, and a NULL key column gives WHERE "col"='', which matches the wrong rows or none. Keep Option<String> and emit NULL in SET, and IS NULL in WHERE (or refuse a NULL key).

Source: code-review · claude-opus-5-5


Generated by Claude Code

})
.collect::<Vec<String>>();
// Set the col to update to the encrypted column
// And set the plaintext value to the p value
let update_str = self
.columns
.iter()
.zip(column_vals.iter())
.map(|((_source_col, target_col), val)| {
format!("\"{target_col}\"='{val}'")
})
.collect::<Vec<String>>()
.join(", ");

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

let sql = format!(
"UPDATE {} SET {update_str} WHERE {where_str};\n",
self.table
let sql = build_update_statement(
&self.table,
&self.columns,
&column_vals,
&self.primary_key,
&primary_key_vals,
);

updated_count += 1;
Expand Down Expand Up @@ -238,6 +217,43 @@ impl Migrate {
}
}

///
/// 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 {
let update_str = columns
.iter()
.zip(column_vals.iter())
.map(|((_source_col, target_col), val)| {
let col = escape_identifier(target_col);
let val = escape_literal(val);
format!("{col}={val}")
})
.collect::<Vec<String>>()
.join(", ");

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

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

/// Parse a single key-value pair - copied from clap example https://github.com/clap-rs/clap/blob/master/examples/typed-derive.rs#L25
fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn ClapError + Send + Sync + 'static>>
where
Expand Down Expand Up @@ -290,3 +306,82 @@ pub async fn connect_with_no_tls(connection_string: &str) -> Result<Client, Erro
});
Ok(client)
}

#[cfg(test)]
mod tests {
use super::*;

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

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

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

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

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

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

#[test]
fn update_statement_quotes_table_and_target_column() {
Comment thread
tobyhede marked this conversation as resolved.
Resolved
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_statement_escapes_backslash_and_compound_primary_key() {
let sql = build_update_statement(
"users",
&columns(),
&["a\\b".to_string()],
&["id".to_string(), "user_id".to_string()],
&["1".to_string(), "O'x\\".to_string()],
);

assert_eq!(
sql,
"UPDATE \"users\" SET \"encrypted_name\"= E'a\\\\b' WHERE \"id\"='1' AND \"user_id\"= E'O''x\\\\';\n"
);
}
}
67 changes: 60 additions & 7 deletions packages/cipherstash-proxy/src/postgresql/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::context::Context;
use super::data::to_sql;
use super::error_handler::PostgreSqlErrorHandler;
use super::message_buffer::MessageBuffer;
use super::messages::error_response::ErrorResponse;
use super::messages::error_response::{ErrorResponse, ErrorResponseCode};
use super::messages::row_description::RowDescription;
use super::messages::BackendCode;
use super::Column;
Expand All @@ -25,7 +25,7 @@ use cipherstash_client::eql::EqlCiphertext;
use metrics::{counter, histogram};
use std::time::Instant;
use tokio::io::AsyncRead;
use tracing::{debug, error, info, warn};
use tracing::{debug, error, warn};

/// The PostgreSQL proxy backend that handles server-to-client message processing.
///
Expand Down Expand Up @@ -363,18 +363,31 @@ where
///
/// # Logging and Monitoring
///
/// All errors are logged at ERROR level for debugging and recorded in
/// monitoring systems. This helps track both application-level issues
/// and proxy-specific problems.
/// A database error forwarded to the client is normal proxy operation, and
/// the client surfaces it, so only its SQLSTATE code is logged, at DEBUG
/// level. The message and other fields can contain values from the
/// statement, so they are never logged.
///
/// # Returns
///
/// Always returns `Some(bytes)` containing the original error response
/// to forward to the client unchanged.
fn error_response_handler(&mut self, bytes: &BytesMut) -> Result<Option<BytesMut>, Error> {
let error_response = ErrorResponse::try_from(bytes)?;
error!(msg = "PostgreSQL Error", error = ?error_response);
info!(msg = "PostgreSQL Errors originate in the database");
let field = |code: ErrorResponseCode| {
error_response
.fields
.iter()
.find(|field| field.code == code)
.map(|field| field.value.as_str())
.unwrap_or_default()
};
debug!(
target: PROTOCOL,
client_id = self.context.client_id,
msg = "Database returned an error",
code = field(ErrorResponseCode::Code),
);
Ok(Some(bytes.to_owned()))
}

Expand Down Expand Up @@ -1055,6 +1068,46 @@ mod tests {
assert_eq!(backend.context.session_metrics_queue_len(), 0);
}

/// The `Message` field of an ErrorResponse can carry a value from the statement,
/// such as the input in an `invalid input syntax` error.
/// The database error log must not write it, even at `debug` level.
#[test]
fn error_response_log_omits_values_from_the_message() {
use crate::test_helpers::MockMakeWriter;

let make_writer = MockMakeWriter::default();
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_ansi(false)
.with_writer(make_writer.clone())
.finish();
let _default = tracing::subscriber::set_default(subscriber);

let (client_sender, _client_receiver) = mpsc::unbounded_channel();
let reader = Cursor::new(Vec::new());
let mut backend = Backend::new(client_sender, reader, passthrough_context());

let bytes = backend_message(
b'E',
b"SERROR\0C22P02\0Minvalid input syntax for type integer: \"123-45-678X\"\0\0",
);
backend.error_response_handler(&bytes).unwrap();

let log_contents = make_writer.get_string();
assert!(
log_contents.contains("Database returned an error"),
"database error was not logged: {log_contents}"
);
assert!(
log_contents.contains("22P02"),
"SQLSTATE was not logged: {log_contents}"
);
assert!(
!log_contents.contains("123-45-678X"),
"statement value was logged: {log_contents}"
);
}

#[test]
fn deallocation_command_tags() {
assert!(super::is_deallocation(&command_complete("DEALLOCATE")));
Expand Down
Loading