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
20 changes: 11 additions & 9 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
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.

### Fixed

- **Unnamed prepared statement after a simple Query**: PostgreSQL drops a client's unnamed prepared statement whenever it runs a simple Query, but Proxy kept its copy.
Proxy now releases it when PostgreSQL answers the Query, so the statements Proxy tracks match PostgreSQL's.

- **Statement metrics after a pipelined re-Parse**: when a client prepared a name again in the same pipeline as a SQL `DEALLOCATE` of that name, Proxy never finished the metrics of the deallocated statement.
They are now finished when PostgreSQL confirms the `DEALLOCATE`.

- **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.

### 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 Down Expand Up @@ -82,15 +93,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
`DISCARD ALL`, the default reset query of PgBouncer, and `DISCARD TEMP` now end that refusal once their transaction commits, so the next client of a pooled connection is not refused.
If the transaction rolls back, the table and the refusal both come back.

- **Unnamed prepared statement after a simple Query**: PostgreSQL drops a client's unnamed prepared statement whenever it runs a simple Query, but Proxy kept its copy.
Proxy now releases it when PostgreSQL answers the Query, so the statements Proxy tracks match PostgreSQL's.

- **Statement metrics after a pipelined re-Parse**: when a client prepared a name again in the same pipeline as a SQL `DEALLOCATE` of that name, Proxy never finished the metrics of the deallocated statement.
They are now finished when PostgreSQL confirms the `DEALLOCATE`.

- **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.

- **`--db-user`**: the flag now sets the database username. It previously set an unused variable, so it had no effect.

- **Unknown column error message**: the type-checking error for a column a table does not have now names the column and the table the right way round, for example `Column: email not found for table: users`. It previously swapped them.
Expand Down
31 changes: 5 additions & 26 deletions packages/cipherstash-proxy/src/postgresql/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,6 @@ struct OperationContext {
/// SQL deallocations in a simple Query or an executed portal, applied in order as
/// PostgreSQL confirms each one
deallocations: VecDeque<Deallocation>,
/// A simple Query releases the unnamed statement once PostgreSQL runs it, which it
/// does not while it skips messages until Sync
releases_unnamed_statement: bool,
}

/// A prepared-statement removal requested with SQL rather than a protocol `Close`.
Expand All @@ -144,6 +141,7 @@ struct DescribeContext {
#[cfg(test)]
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct ProtocolStateSizes {
pub pending_queries: usize,
pub operations: usize,
pub statement_metrics: usize,
pub suspended_executions: usize,
Expand Down Expand Up @@ -823,33 +821,13 @@ where
Ok(())
}

/// PostgreSQL runs a simple Query in the unnamed statement, so it releases the client's
/// once it runs the Query.
pub fn query_releases_unnamed_statement(&self, operation: OperationId) -> Result<(), Error> {
self.protocol_state
.write()
.map_err(|_| crate::error::ContextError::ProtocolStateUnavailable)?
.operations
.entry(operation)
.or_default()
.releases_unnamed_statement = true;
Ok(())
}

/// PostgreSQL answered `operation`, so a simple Query has released the unnamed statement
pub fn operation_answered(&self, operation: OperationId) -> Result<(), Error> {
/// PostgreSQL releases the unnamed statement when it starts running a simple Query.
pub fn release_unnamed_statement(&self, operation: OperationId) -> Result<(), Error> {
let finished = {
let mut state = self
.protocol_state
.write()
.map_err(|_| crate::error::ContextError::ProtocolStateUnavailable)?;
let releases = state
.operations
.get_mut(&operation)
.is_some_and(|context| std::mem::take(&mut context.releases_unnamed_statement));
if !releases {
return Ok(());
}
state.deallocate_statements(operation, &[Name::new()])
};
for metrics in finished {
Expand Down Expand Up @@ -986,9 +964,10 @@ where
///
/// Test-only accessor used to assert per-connection state stays bounded.
#[cfg(test)]
pub(crate) fn protocol_state_sizes(&self) -> ProtocolStateSizes {
pub(crate) fn protocol_state_sizes(&self, pending_queries: usize) -> ProtocolStateSizes {
let state = self.protocol_state.read().unwrap();
ProtocolStateSizes {
pending_queries,
operations: state.operations.len(),
statement_metrics: state.statement_metrics.len(),
suspended_executions: state.suspended_executions.len(),
Expand Down
52 changes: 47 additions & 5 deletions packages/cipherstash-proxy/src/postgresql/middleware/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use crate::proxy::EncryptionService;
use crate::EqlCiphertext;
use metrics::{counter, histogram};
use pg_proto::{BackendMessage, BackendMiddlewareOutput, DataRow, DiagnosticResponse};
use std::collections::VecDeque;
use std::time::Instant;
use tracing::debug;

Expand Down Expand Up @@ -66,6 +67,8 @@ use tracing::debug;
pub struct Backend<S: EncryptionService> {
/// Session context with portal and statement metadata
context: Context<S>,
/// Forwarded simple Queries awaiting their first reply, in wire order.
pending_queries: VecDeque<OperationId>,
Comment thread
tobyhede marked this conversation as resolved.
Resolved
encrypted_rows: Vec<DataRow>,
encrypted_rows_operation: Option<OperationId>,
encrypted_rows_bytes: usize,
Expand Down Expand Up @@ -138,13 +141,37 @@ impl<S: EncryptionService> Backend<S> {
pub fn new(context: Context<S>) -> Self {
Backend {
context,
pending_queries: VecDeque::new(),
encrypted_rows: Vec::new(),
encrypted_rows_operation: None,
encrypted_rows_bytes: 0,
discard_execution: false,
}
}

pub(super) fn query_forwarded(&mut self, operation: OperationId) {
self.pending_queries.push_back(operation);
}

#[cfg(test)]
pub(super) fn pending_query_count(&self) -> usize {
self.pending_queries.len()
}

fn take_first_query_reply(&mut self, operation: OperationId) -> bool {
while let Some(&query) = self.pending_queries.front() {
if query > operation {
Comment thread
tobyhede marked this conversation as resolved.
Resolved
break;
}
// A reply to a later operation means PostgreSQL skipped the earlier Query.
self.pending_queries.pop_front();
if query == operation {
return true;
}
}
false
}

pub async fn intercept(
&mut self,
operation: Option<OperationId>,
Expand All @@ -160,11 +187,8 @@ impl<S: EncryptionService> Backend<S> {
) -> Result<BackendMiddlewareOutput, Error> {
let mut outbound_message = protocol_message.clone();

// A row is never the first answer to an operation, so skip the lock for it
if let Some(operation) =
operation.filter(|_| !matches!(protocol_message, BackendMessage::DataRow(_)))
{
self.context.operation_answered(operation)?;
if let Some(query) = operation.filter(|&operation| self.take_first_query_reply(operation)) {
self.context.release_unnamed_statement(query)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Optional: No test forwards an unnamed Parse after a simple Query and before that Query's first reply.

Impact: release_unnamed_statement now runs when the Query's first reply arrives. By then, Proxy may already track a new unnamed statement from a pipelined Parse "". If deallocate_statements stops comparing operation order, Proxy deletes the new statement. No test would fail. The next Bind to "" would then use missing metadata.

Evidence: reparse_pipelined_after_deallocate_finishes_the_old_metrics in middleware/mod.rs covers the same order for a named statement after DEALLOCATE. No test covers a Parse "" after the Query.

Fix: Add a test next to reparse_pipelined_after_deallocate_finishes_the_old_metrics in middleware/mod.rs. It sends a Query, then Parse "", then Sync. It then delivers the Query replies, the ParseComplete and the Sync reply. It asserts connection.holds_statement(b"") and connection.sizes().pending_queries == 0.

Found by 1 model: claude

}

if let (BackendMessage::CommandComplete(tag), Some(operation)) =
Expand Down Expand Up @@ -850,6 +874,24 @@ mod tests {
(Backend::new(context.clone()), context)
}

#[test]
fn only_the_first_reply_to_each_forwarded_query_releases_the_unnamed_statement() {
let mut backend = create_backend();
let earlier = operation_id();
let first = operation_id();
let skipped = operation_id();
let second = operation_id();
backend.query_forwarded(first);
backend.query_forwarded(skipped);
backend.query_forwarded(second);

assert!(!backend.take_first_query_reply(earlier));
assert!(backend.take_first_query_reply(first));
assert!(!backend.take_first_query_reply(first));
assert!(backend.take_first_query_reply(second));
assert!(!backend.take_first_query_reply(second));
}

#[test]
fn decryption_failure_is_returned_as_a_postgresql_error() {
let mut backend = create_backend();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,6 @@ impl<S: EncryptionService> Frontend<S> {
self.context.discard_operation(operation)?;
return Ok(FrontendMiddlewareOutput::Suppress(protocol_message));
}
if matches!(protocol_message, FrontendMessage::Query(_)) {
self.context.query_releases_unnamed_statement(operation)?;
}

if self.context.mapping_disabled() {
match &protocol_message {
Expand Down
64 changes: 41 additions & 23 deletions packages/cipherstash-proxy/src/postgresql/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,25 @@ impl<S: EncryptionService + Clone> CipherStashMiddleware<S> {
backend: Backend::new(context),
}
}

async fn intercept_frontend(
&mut self,
operation: super::OperationId,
message: FrontendMessage,
) -> Result<FrontendMiddlewareOutput, Error> {
let query = matches!(message, FrontendMessage::Query(_));
let output = self.frontend.intercept(operation, message).await?;
if query
&& matches!(
output,
FrontendMiddlewareOutput::Forward(FrontendMessage::Query(_))
| FrontendMiddlewareOutput::ForwardThenFlush(FrontendMessage::Query(_))
)
{
self.backend.query_forwarded(operation);
}
Ok(output)
}
}

impl<S, ServerContext, ClientContext> IntermediaryMiddleware<(), ServerContext, ClientContext>
Expand All @@ -59,7 +78,7 @@ where
operation: OperationId,
message: FrontendMessage,
) -> Result<FrontendMiddlewareOutput, Error> {
self.frontend.intercept(operation.into(), message).await
self.intercept_frontend(operation.into(), message).await
}

async fn backend_operation(
Expand All @@ -82,7 +101,7 @@ where
/// PostgreSQL exchange for one pattern, many times over on one connection.
#[cfg(test)]
mod tests {
use super::{Backend, Frontend};
use super::CipherStashMiddleware;
use crate::{
config::TandemConfig,
error::Error,
Expand Down Expand Up @@ -137,8 +156,7 @@ mod tests {
}

struct Connection {
frontend: Frontend<TestService>,
backend: Backend<TestService>,
middleware: CipherStashMiddleware<TestService>,
context: Context<TestService>,
/// SQL the tests prepare: it reads an encrypted column when the schema has one
select: &'static str,
Expand Down Expand Up @@ -195,8 +213,7 @@ mod tests {
encrypted: bool,
) -> Self {
Self {
frontend: Frontend::new(context.clone()),
backend: Backend::new(context.clone()),
middleware: CipherStashMiddleware::new(context.clone()),
context,
select,
encrypted,
Expand Down Expand Up @@ -229,7 +246,11 @@ mod tests {
message: FrontendMessage,
) -> (OperationId, FrontendMiddlewareOutput) {
let operation = test_operation_id();
let output = self.frontend.intercept(operation, message).await.unwrap();
let output = self
.middleware
.intercept_frontend(operation, message)
.await
.unwrap();
(operation, output)
}

Expand All @@ -239,7 +260,8 @@ mod tests {
operation: OperationId,
message: BackendMessage,
) -> BackendMiddlewareOutput {
self.backend
self.middleware
.backend
.intercept(Some(operation), message)
.await
.unwrap()
Expand Down Expand Up @@ -286,14 +308,7 @@ mod tests {
}

async fn bind(&mut self, statement: Bytes, portal: Bytes) -> OperationId {
self.client(FrontendMessage::Bind(Bind {
portal,
statement,
parameter_formats: vec![],
parameters: vec![],
result_formats: vec![],
}))
.await
self.client(bind_message(statement, portal)).await
}

async fn execute(&mut self, portal: Bytes) -> OperationId {
Expand All @@ -310,7 +325,8 @@ mod tests {
}

fn sizes(&self) -> ProtocolStateSizes {
self.context.protocol_state_sizes()
self.context
.protocol_state_sizes(self.middleware.backend.pending_query_count())
}
}

Expand Down Expand Up @@ -653,9 +669,11 @@ mod tests {

// PostgreSQL runs a simple Query in the unnamed statement, dropping the client's
let query = connection.query(select).await;
assert_eq!(connection.sizes().pending_queries, 1);
connection
.server(query, command_complete(b"SELECT 1"))
.await;
assert_eq!(connection.sizes().pending_queries, 0);
connection
.server(query, ready(TransactionStatus::Idle))
.await;
Expand Down Expand Up @@ -2583,8 +2601,8 @@ mod tests {
b"SET CIPHERSTASH.KEYSET_ID = 'not-a-uuid'",
));
let output = connection
.frontend
.intercept(test_operation_id(), message.clone())
.middleware
.intercept_frontend(test_operation_id(), message.clone())
.await;
// Refused, as with mapping enabled, rather than forwarded
assert!(!matches!(
Expand All @@ -2603,8 +2621,8 @@ mod tests {
parameter_types: vec![],
});
let output = connection
.frontend
.intercept(test_operation_id(), message.clone())
.middleware
.intercept_frontend(test_operation_id(), message.clone())
.await;
assert!(!matches!(
output,
Expand Down Expand Up @@ -2932,8 +2950,8 @@ mod tests {
b"SET CIPHERSTASH.KEYSET_NAME TO DEFAULT",
));
let output = connection
.frontend
.intercept(test_operation_id(), message.clone())
.middleware
.intercept_frontend(test_operation_id(), message.clone())
.await
.unwrap();
assert!(
Expand Down
Loading
Loading