From 0de495395cfae66bb4b3bda04b46aff58c48db1d Mon Sep 17 00:00:00 2001 From: Toby Hede Date: Wed, 2 Dec 2026 15:25:54 +1100 Subject: [PATCH 1/2] perf(proxy): track the first reply to each simple query Track forwarded simple queries in wire order so unrelated replies avoid the protocol-state write lock. Exercise a query discarded after an extended error and document the model's batch boundary. Signed-off-by: Toby Hede --- CHANGELOG.md | 20 ++++--- .../src/postgresql/context/mod.rs | 27 +-------- .../src/postgresql/middleware/backend.rs | 47 +++++++++++++-- .../src/postgresql/middleware/frontend.rs | 3 - .../src/postgresql/middleware/mod.rs | 59 ++++++++++++------- .../middleware/tests/connection_model.rs | 52 ++++++++++++++-- 6 files changed, 139 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7008b6dea..7275a5f43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. @@ -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. diff --git a/packages/cipherstash-proxy/src/postgresql/context/mod.rs b/packages/cipherstash-proxy/src/postgresql/context/mod.rs index fb1665bbf..43cbff5a7 100644 --- a/packages/cipherstash-proxy/src/postgresql/context/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/context/mod.rs @@ -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, - /// 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`. @@ -823,33 +820,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 { diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs index 750f2bed4..ad8b53fb3 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs @@ -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; @@ -66,6 +67,8 @@ use tracing::debug; pub struct Backend { /// Session context with portal and statement metadata context: Context, + /// Forwarded simple Queries awaiting their first reply, in wire order. + pending_queries: VecDeque, encrypted_rows: Vec, encrypted_rows_operation: Option, encrypted_rows_bytes: usize, @@ -138,6 +141,7 @@ impl Backend { pub fn new(context: Context) -> Self { Backend { context, + pending_queries: VecDeque::new(), encrypted_rows: Vec::new(), encrypted_rows_operation: None, encrypted_rows_bytes: 0, @@ -145,6 +149,24 @@ impl Backend { } } + pub(super) fn query_forwarded(&mut self, operation: OperationId) { + self.pending_queries.push_back(operation); + } + + fn first_query_reply(&mut self, operation: OperationId) -> bool { + while let Some(&query) = self.pending_queries.front() { + if query > operation { + 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, @@ -160,11 +182,8 @@ impl Backend { ) -> Result { 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.first_query_reply(operation)) { + self.context.release_unnamed_statement(query)?; } if let (BackendMessage::CommandComplete(tag), Some(operation)) = @@ -850,6 +869,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.first_query_reply(earlier)); + assert!(backend.first_query_reply(first)); + assert!(!backend.first_query_reply(first)); + assert!(backend.first_query_reply(second)); + assert!(!backend.first_query_reply(second)); + } + #[test] fn decryption_failure_is_returned_as_a_postgresql_error() { let mut backend = create_backend(); diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs b/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs index 80c2a6bc7..4a06f83de 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/frontend.rs @@ -185,9 +185,6 @@ impl Frontend { 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 { diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs b/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs index 4d70e5ee6..88a9f22a1 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs @@ -40,6 +40,25 @@ impl CipherStashMiddleware { backend: Backend::new(context), } } + + async fn intercept_frontend( + &mut self, + operation: super::OperationId, + message: FrontendMessage, + ) -> Result { + 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 IntermediaryMiddleware<(), ServerContext, ClientContext> @@ -59,7 +78,7 @@ where operation: OperationId, message: FrontendMessage, ) -> Result { - self.frontend.intercept(operation.into(), message).await + self.intercept_frontend(operation.into(), message).await } async fn backend_operation( @@ -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, @@ -137,8 +156,7 @@ mod tests { } struct Connection { - frontend: Frontend, - backend: Backend, + middleware: CipherStashMiddleware, context: Context, /// SQL the tests prepare: it reads an encrypted column when the schema has one select: &'static str, @@ -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, @@ -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) } @@ -239,7 +260,8 @@ mod tests { operation: OperationId, message: BackendMessage, ) -> BackendMiddlewareOutput { - self.backend + self.middleware + .backend .intercept(Some(operation), message) .await .unwrap() @@ -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 { @@ -2583,8 +2598,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!( @@ -2603,8 +2618,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, @@ -2932,8 +2947,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!( diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs b/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs index 0c28ed1d2..df7bc10c5 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs @@ -9,7 +9,7 @@ //! - agrees on whether the connection's temporary table exists. //! //! The model covers less than PostgreSQL does: -//! - a pipelined run holds back PostgreSQL's replies until the next Sync or Query, and +//! - a pipelined run holds back replies within one extended batch until Sync, and //! any other run delivers each reply before the client sends its next message, //! - Execute always runs a portal to completion, and there is no Describe or Flush, //! - each simple Query holds one statement, @@ -426,7 +426,7 @@ struct Run { /// SQL text Proxy may forward, and what PostgreSQL runs for it sql: HashMap, batch_open: bool, - /// Whether PostgreSQL's replies wait for the next Sync or Query + /// Whether extended-protocol replies wait for the next Sync pipelined: bool, replies: Vec<(OperationId, BackendMessage)>, } @@ -570,8 +570,10 @@ impl Run { async fn step(&mut self, step: Step) { match step { - // pg-proto refuses a Query while an extended batch is open - Step::Query { .. } if self.batch_open => { + // pg-proto accepts a Query in an open extended batch only after it sees an error. + Step::Query { .. } + if self.batch_open && (self.pipelined || !self.postgres.skipping) => + { Box::pin(self.step(Step::Sync)).await; Box::pin(self.step(step)).await; } @@ -664,11 +666,17 @@ impl Run { let text = self.simple_text(sql); let (operation, forwarded) = self.send(FrontendMessage::Query(Bytes::from(text))).await; + if self.postgres.skipping { + assert!( + forwarded.is_none(), + "Proxy must suppress a Query after an extended error, got {forwarded:?}" + ); + return; + } let Some(FrontendMessage::Query(query)) = forwarded else { panic!("Query forwarded as {forwarded:?}"); }; let sql = self.classify(&query, true); - self.deliver_replies().await; for message in self.postgres.query(sql, fails) { self.connection.server(operation, message).await; } @@ -738,6 +746,40 @@ fn run(connect: fn() -> Connection, pipelined: bool, steps: Vec) { }); } +#[tokio::test] +async fn query_after_an_extended_error_preserves_the_unnamed_statement() { + let mut run = Run::new(Connection::encrypted(), false); + run.step(Step::Parse { + statement: 0, + sql: ExtendedSql::Select, + }) + .await; + run.step(Step::Sync).await; + run.step(Step::Bind { + statement: 1, + portal: 0, + }) + .await; + assert!( + run.postgres.skipping, + "the missing statement must fail Bind" + ); + run.step(Step::Query { + sql: SimpleSql::Select, + fails: false, + }) + .await; + assert!( + run.postgres.skipping, + "a Query after an extended error must leave the batch waiting for Sync" + ); + run.step(Step::Sync).await; + assert!( + run.connection.holds_statement(b""), + "the ignored Query must preserve the unnamed statement" + ); +} + proptest! { #![proptest_config(ProptestConfig::with_cases(256))] From e61d0d79255e856df01e522a561ba3432dbee513 Mon Sep 17 00:00:00 2001 From: Toby Hede Date: Wed, 2 Dec 2026 17:42:49 +1100 Subject: [PATCH 2/2] Cover pending simple queries in connection and rollback tests --- .../src/postgresql/context/mod.rs | 4 +- .../src/postgresql/middleware/backend.rs | 19 +-- .../src/postgresql/middleware/mod.rs | 5 +- .../middleware/settings_rollback_tests.rs | 119 ++++++++++++------ .../middleware/tests/connection_model.rs | 6 +- .../cipherstash-proxy/src/postgresql/mod.rs | 3 + 6 files changed, 105 insertions(+), 51 deletions(-) diff --git a/packages/cipherstash-proxy/src/postgresql/context/mod.rs b/packages/cipherstash-proxy/src/postgresql/context/mod.rs index 43cbff5a7..bea91c3f4 100644 --- a/packages/cipherstash-proxy/src/postgresql/context/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/context/mod.rs @@ -141,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, @@ -963,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(), diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs index ad8b53fb3..833e2d39d 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs @@ -153,7 +153,12 @@ impl Backend { self.pending_queries.push_back(operation); } - fn first_query_reply(&mut self, operation: OperationId) -> bool { + #[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 { break; @@ -182,7 +187,7 @@ impl Backend { ) -> Result { let mut outbound_message = protocol_message.clone(); - if let Some(query) = operation.filter(|&operation| self.first_query_reply(operation)) { + if let Some(query) = operation.filter(|&operation| self.take_first_query_reply(operation)) { self.context.release_unnamed_statement(query)?; } @@ -880,11 +885,11 @@ mod tests { backend.query_forwarded(skipped); backend.query_forwarded(second); - assert!(!backend.first_query_reply(earlier)); - assert!(backend.first_query_reply(first)); - assert!(!backend.first_query_reply(first)); - assert!(backend.first_query_reply(second)); - assert!(!backend.first_query_reply(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] diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs b/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs index 88a9f22a1..48731245a 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/mod.rs @@ -325,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()) } } @@ -668,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; diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/settings_rollback_tests.rs b/packages/cipherstash-proxy/src/postgresql/middleware/settings_rollback_tests.rs index 5cacf5e46..974b5dcc9 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/settings_rollback_tests.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/settings_rollback_tests.rs @@ -1,6 +1,6 @@ //! Behavioral transaction-setting tests at the PostgreSQL message boundary. -use super::{Backend, Frontend}; +use super::CipherStashMiddleware; use crate::postgresql::{test_operation_id as operation_id, OperationId}; use crate::{ config::TandemConfig, @@ -58,8 +58,7 @@ impl EncryptionService for Cipher { } struct Client { - frontend: Frontend, - backend: Backend, + middleware: CipherStashMiddleware, cipher: Cipher, context: Context, } @@ -101,8 +100,7 @@ impl Client { sender, ); Self { - frontend: Frontend::new(context.clone()), - backend: Backend::new(context.clone()), + middleware: CipherStashMiddleware::new(context.clone()), cipher, context, } @@ -110,21 +108,23 @@ impl Client { async fn command(&mut self, sql: &str, tag: &str, status: TransactionStatus) { let operation = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( operation, FrontendMessage::Query(Bytes::copy_from_slice(sql.as_bytes())), ) .await .unwrap(); - self.backend + self.middleware + .backend .intercept( Some(operation), BackendMessage::CommandComplete(Bytes::copy_from_slice(tag.as_bytes())), ) .await .unwrap(); - self.backend + self.middleware + .backend .intercept(Some(operation), BackendMessage::ReadyForQuery(status)) .await .unwrap(); @@ -132,8 +132,8 @@ impl Client { async fn encrypted_insert_uses(&mut self, expected: Option) { self.cipher.selected.lock().unwrap().clear(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( operation_id(), FrontendMessage::Query(Bytes::from_static( b"INSERT INTO encrypted(secret) VALUES ('value')", @@ -146,8 +146,8 @@ impl Client { async fn prepare(&mut self, sql: &str) { let operation = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( operation, FrontendMessage::Parse(pg_proto::Parse { statement: Bytes::from_static(b"setting"), @@ -157,7 +157,8 @@ impl Client { ) .await .unwrap(); - self.backend + self.middleware + .backend .intercept(Some(operation), BackendMessage::ParseComplete) .await .unwrap(); @@ -165,8 +166,8 @@ impl Client { async fn execute_prepared(&mut self) { let operation = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( operation, FrontendMessage::Bind(pg_proto::Bind { portal: Bytes::new(), @@ -178,13 +179,14 @@ impl Client { ) .await .unwrap(); - self.backend + self.middleware + .backend .intercept(Some(operation), BackendMessage::BindComplete) .await .unwrap(); let operation = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( operation, FrontendMessage::Execute(pg_proto::Execute { portal: Bytes::new(), @@ -193,7 +195,8 @@ impl Client { ) .await .unwrap(); - self.backend + self.middleware + .backend .intercept( Some(operation), BackendMessage::CommandComplete(Bytes::from_static(b"SET")), @@ -224,8 +227,8 @@ impl Client { let mut failed = false; for (sql, tag) in statements { let parse = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( parse, FrontendMessage::Parse(pg_proto::Parse { statement: Bytes::new(), @@ -236,8 +239,8 @@ impl Client { .await .unwrap(); let bind = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( bind, FrontendMessage::Bind(pg_proto::Bind { portal: Bytes::new(), @@ -250,8 +253,8 @@ impl Client { .await .unwrap(); let execute = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( execute, FrontendMessage::Execute(pg_proto::Execute { portal: Bytes::new(), @@ -283,8 +286,8 @@ impl Client { } } let sync = operation_id(); - self.frontend - .intercept(sync, FrontendMessage::Sync) + self.middleware + .intercept_frontend(sync, FrontendMessage::Sync) .await .unwrap(); replies.push((sync, BackendMessage::ReadyForQuery(status))); @@ -294,7 +297,8 @@ impl Client { /// Delivers PostgreSQL's queued replies to the backend, in order async fn reply(&mut self, replies: &mut Vec<(OperationId, BackendMessage)>) { for (operation, message) in replies.drain(..) { - self.backend + self.middleware + .backend .intercept(Some(operation), message) .await .unwrap(); @@ -303,11 +307,12 @@ impl Client { async fn sync(&mut self, status: TransactionStatus) { let operation = operation_id(); - self.frontend - .intercept(operation, FrontendMessage::Sync) + self.middleware + .intercept_frontend(operation, FrontendMessage::Sync) .await .unwrap(); - self.backend + self.middleware + .backend .intercept(Some(operation), BackendMessage::ReadyForQuery(status)) .await .unwrap(); @@ -315,14 +320,15 @@ impl Client { async fn fail_query(&mut self, status: TransactionStatus) { let operation = operation_id(); - self.frontend - .intercept( + self.middleware + .intercept_frontend( operation, FrontendMessage::Query(Bytes::from_static(b"SELECT 1 / 0")), ) .await .unwrap(); - self.backend + self.middleware + .backend .intercept( Some(operation), BackendMessage::ErrorResponse( @@ -335,7 +341,8 @@ impl Client { .unwrap(); // The Query boundary, not ReadyForQuery, ends the discard state. assert!(!self.context.discarding_extended_messages().unwrap()); - self.backend + self.middleware + .backend .intercept(Some(operation), BackendMessage::ReadyForQuery(status)) .await .unwrap(); @@ -344,8 +351,8 @@ impl Client { async fn query_is_forwarded(&mut self) { assert!(!self.context.discarding_extended_messages().unwrap()); let output = self - .frontend - .intercept( + .middleware + .intercept_frontend( operation_id(), FrontendMessage::Query(Bytes::from_static(b"SELECT 1")), ) @@ -365,6 +372,29 @@ fn named(name: &str) -> Option { Some(KeysetIdentifier(IdentifiedBy::Name(name.to_owned().into()))) } +#[tokio::test] +async fn simple_command_releases_the_unnamed_statement_from_an_extended_command() { + let mut client = Client::new(); + let unnamed = Bytes::new(); + client + .run(true, "BEGIN", "BEGIN", TransactionStatus::InTransaction) + .await; + assert!(client + .context + .test_statement_metrics_scope(&unnamed) + .unwrap() + .is_some()); + + client + .command("ROLLBACK", "ROLLBACK", TransactionStatus::Idle) + .await; + assert!(client + .context + .test_statement_metrics_scope(&unnamed) + .unwrap() + .is_none()); +} + #[tokio::test] async fn rollback_to_savepoint_restores_keyset_used_for_encryption() { let mut client = Client::new(); @@ -675,8 +705,8 @@ async fn decryption_failure_keeps_later_settings_in_step_with_postgresql() { .store(true, std::sync::atomic::Ordering::Relaxed); let query = operation_id(); client - .frontend - .intercept( + .middleware + .intercept_frontend( query, FrontendMessage::Query(Bytes::from_static( b"SELECT secret FROM encrypted; SET CIPHERSTASH.KEYSET_NAME = 'a'; SET CIPHERSTASH.KEYSET_NAME = 'b'", @@ -706,6 +736,7 @@ async fn decryption_failure_keeps_later_settings_in_step_with_postgresql() { BackendMessage::ReadyForQuery(TransactionStatus::Idle), ] { client + .middleware .backend .intercept(Some(query), message) .await @@ -766,7 +797,11 @@ async fn failed_pipelined_execute_with_mapping_disabled_does_not_suppress_next_q ), (sync, FrontendMessage::Sync), ] { - client.frontend.intercept(operation, message).await.unwrap(); + client + .middleware + .intercept_frontend(operation, message) + .await + .unwrap(); } for (operation, message) in [ (parse, BackendMessage::ParseComplete), @@ -779,6 +814,7 @@ async fn failed_pipelined_execute_with_mapping_disabled_does_not_suppress_next_q ), ] { client + .middleware .backend .intercept(Some(operation), message) .await @@ -788,6 +824,7 @@ async fn failed_pipelined_execute_with_mapping_disabled_does_not_suppress_next_q // The driver pipelined this Query, so it can arrive before ReadyForQuery. client.query_is_forwarded().await; client + .middleware .backend .intercept( Some(sync), diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs b/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs index df7bc10c5..9dde45f89 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/tests/connection_model.rs @@ -703,6 +703,10 @@ impl Run { } if postgres.status() == TransactionStatus::Idle { let sizes = self.connection.sizes(); + assert_eq!( + sizes.pending_queries, 0, + "queries awaiting a reply at idle: {sizes:?}" + ); assert_eq!(sizes.operations, 0, "operations held at idle: {sizes:?}"); assert_eq!(sizes.portals, 0, "portals held at idle: {sizes:?}"); assert_eq!( @@ -747,7 +751,7 @@ fn run(connect: fn() -> Connection, pipelined: bool, steps: Vec) { } #[tokio::test] -async fn query_after_an_extended_error_preserves_the_unnamed_statement() { +async fn suppressing_a_query_after_an_extended_error_preserves_the_unnamed_statement() { let mut run = Run::new(Connection::encrypted(), false); run.step(Step::Parse { statement: 0, diff --git a/packages/cipherstash-proxy/src/postgresql/mod.rs b/packages/cipherstash-proxy/src/postgresql/mod.rs index 6f0297956..288a6a2a2 100644 --- a/packages/cipherstash-proxy/src/postgresql/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/mod.rs @@ -17,6 +17,9 @@ pub use driver::handler; pub(crate) use rewrite::Name; /// Proxy-owned identity for correlating PostgreSQL protocol operations. +/// +/// Within one connection, Proxy relies on pg-proto assigning increasing IDs in +/// frontend wire order to distinguish earlier operations from later ones. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct OperationId(OperationIdInner);