Encryption Proxy
src/proxy contains a PostgreSQL wire-protocol proxy that sits between an application and a PostgreSQL-compatible backend. It encrypts configured columns in SQL statements on the way in and decrypts them in result rows on the way out, with optional access control and column masking. This page describes what the code does and how much of it is wired and tested.
It is unrelated to SynergyDB's own encryption at rest, which encrypts the storage engine's files; see Encryption at rest internals.
Status: compiled, but never started
| Fact | Source |
|---|---|
Cargo.toml declares a feature encryption-proxy = []. It is not in default, but it gates nothing: no cfg(feature = "encryption-proxy") exists in the source |
Cargo.toml, [features]
|
src/lib.rs declares pub mod proxy; unconditionally, so the module is compiled into every build |
src/lib.rs |
No binary, CLI command or configuration file creates a ProxyServer. Nothing outside src/proxy refers to it |
src/main.rs; src/proxy/mod.rs, ProxyServer
|
Not wired: in practice the proxy is off: it exists as a library type that code embedding the synergydb crate could start, and nothing in this repository does. The module's own doc comment describes it in terms this book does not repeat; the sections below describe what the code does.
The module doc also says the proxy speaks the MySQL protocol. Only a PostgreSQL handler exists (source: src/proxy/handler.rs, PostgresProxyHandler).
Components
| Module | Role |
|---|---|
mod.rs |
ProxyConfig, ProxyServer (key setup, accept loop) |
handler.rs |
PostgresProxyHandler: one client connection; startup, authentication, message rewriting |
crypto/engine.rs |
EncryptionEngine: per-column AES-256-GCM plus HMAC |
crypto/key_derivation.rs |
KeyDerivation: PBKDF2 per-column keys |
crypto/kms.rs |
KmsClient, AWS KMS provider (feature aws-kms), local and mock providers |
crypto/rotation.rs |
KeyRotationManager, BackgroundReencryptor (library only) |
schema/mod.rs |
SchemaRegistry, ColumnConfig, PiiDetector
|
query/mod.rs |
QueryAnalyzer, QueryRewriter
|
masking/mod.rs |
FieldMasker, MaskingPattern
|
access.rs |
AccessControlEngine: roles, grants, row-level security predicates, column masks |
audit/ |
ProxyAuditLogger; persistence.rs with file, SQLite and S3 back ends |
pool.rs, pg_auth.rs
|
Backend connection pool; MD5 and SCRAM client authentication to the backend |
tls.rs, rate_limit.rs, query_rate_limit.rs
|
TLS config helpers and rate limiters |
(source: src/proxy/mod.rs)
Third-party crates used: aes-gcm, hmac, sha2, pbkdf2, subtle (constant-time compare), zeroize, base64, tokio, and with feature aws-kms: aws-config, aws-sdk-kms, aws-types, aws-smithy-runtime, aws-smithy-types (source: Cargo.toml).
Configuration
ProxyConfig field |
Default | Notes |
|---|---|---|
listen_addr |
0.0.0.0:5432 |
|
backend_addr |
127.0.0.1:5433 |
|
database, username
|
postgres |
Backend database and user |
password |
empty | Backend password |
customer_id |
default |
Mixed into every key derivation salt |
kms_config |
none | See key sources below |
local_master_key |
none | Hex string |
pool_size |
100 | Backend connection pool |
audit_enabled |
true | |
auto_detect_pii |
true | Not wired: never read |
access_control |
none | Access control is off unless set |
(source: src/proxy/mod.rs, ProxyConfig::default)
Master key sources
ProxyServer::new picks the master key in this order (source: src/proxy/mod.rs, ProxyServer::new, ProxyServer::master_key_from_kms, dev_insecure_opt_in):
| Configuration | Result |
|---|---|
local_master_key set |
Hex-decoded and used |
kms_config set, built with aws-kms
|
KmsClient::new then get_master_key
|
kms_config set, no aws-kms, fallback configured |
Local fallback provider (passphrase, environment variable or file) |
kms_config set, no aws-kms, no fallback, SYNERGYDB_DEV_INSECURE_AUTH=1 or true
|
Mock provider whose key is a constant from the source code |
kms_config set, no aws-kms, no fallback, no opt-in |
Start-up error |
| nothing set, opt-in set | Random 64-byte key, lost on restart |
| nothing set, no opt-in | Start-up error |
Tested by test_kms_config_without_real_provider_fails_closed, test_no_master_key_fails_closed_without_opt_in, test_dev_opt_in_allows_insecure_paths, test_local_master_key_path and test_access_control_off_by_default_and_built_when_configured in src/proxy/mod.rs.
KeyDerivation::new asserts that the master key is at least 64 bytes. local_master_key is not length-checked before that, so a shorter hex key panics at start-up instead of returning a configuration error (source: src/proxy/crypto/key_derivation.rs, KeyDerivation::new; src/proxy/mod.rs, ProxyServer::new). Not verified: no test covers a short key.
Column encryption
Key derivation
For each (customer_id, table, column) the engine derives 96 bytes with PBKDF2-HMAC-SHA-512, 100,000 iterations: 32 bytes for AES-256 and 64 bytes for HMAC-SHA-512. The salt is SHA-512(customer_id || "||" || table || "||" || column). A separate search-hash key uses the salt suffix ||__synergydb_search_hash_key_v1__. Derived keys are cached per table.column and wiped on drop (zeroize) (source: src/proxy/crypto/key_derivation.rs, KeyDerivation, PBKDF2_ITERATIONS, SecureVec, DerivedKey; src/proxy/crypto/engine.rs, EncryptionEngine).
Tested by test_derive_column_key, test_deterministic_key_derivation, test_different_columns_different_keys, test_different_customers_different_keys, test_deterministic_iv, test_derive_search_hash_key, test_search_hash, the test_secure_vec_* tests, test_derived_key_debug_redacts and test_key_derivation_no_master_key_exposure in key_derivation.rs.
Token format
EncryptionEngine::encrypt(plaintext, table, column) returns an EncryptedValue with a token and a search_hash (source: src/proxy/crypto/engine.rs, EncryptionEngine::encrypt, EncryptedValue):
token = base64( AES-256-GCM ciphertext || GCM tag (16) || HMAC-SHA-512 (64) || IV (12) )
- The IV is random (
OsRng) unless the column was opted in withenable_searchable_encryption, in which case it is the first 12 bytes ofSHA-512(column AES key || plaintext), so equal plaintexts give equal tokens. - The HMAC-SHA-512 covers ciphertext and IV and uses the column's HMAC key.
- Table and column are not in the GCM associated data; tokens are separated by the per-column keys.
-
decryptchecks the decoded length (at least 1 + 64 + 12 bytes), verifies the HMAC with a constant-time compare (subtle), then decrypts. -
search_hashis hexHMAC-SHA-256(search key, lowercase(plaintext)).
Tested by test_encrypt_decrypt, test_default_encryption_is_randomized, test_deterministic_encryption_requires_opt_in, test_search_hash_is_keyed_prf, test_different_columns_different_ciphertext, test_search_hash, test_integrity_verification, test_wrong_column_fails, test_batch_operations, test_unicode_support, test_empty_string, test_large_value, test_key_caching in engine.rs.
Connection flow
(source: src/proxy/handler.rs, PostgresProxyHandler::handle_startup, handle_simple_query, handle_parse, handle_bind, forward_backend_response_with_decryption)
Client side. The handler answers an SSL request with N, so client connections are plain TCP; tls.rs has helpers that nothing in the handler uses. If the access-control engine has a role with a password hash (Argon2id) for the startup user, the proxy asks for a cleartext password and verifies it. With no such role it rejects the connection with SQLSTATE 28000, unless SYNERGYDB_DEV_INSECURE_AUTH is set, which accepts without a password (source: src/proxy/handler.rs, handle_startup, startup_auth_decision). Tested by test_startup_auth_fails_closed_without_dev_flag. Because TLS is declined, that cleartext password crosses the network unencrypted.
Backend side. Backend connections come from ConnectionPool, which authenticates with the configured user and password using MD5 or SCRAM from pg_auth.rs (source: src/proxy/pool.rs, ConnectionPool; src/proxy/pg_auth.rs, PgAuthenticator). Unit tests: 5 in pool.rs, 10 in pg_auth.rs. Not verified: no test connects to a real PostgreSQL server.
Query rewriting
Encrypted columns must be registered in the SchemaRegistry, which starts empty; ProxyServer::schema_registry gives embedding code access to it. A ColumnConfig created with ColumnConfig::new defaults to deterministic mode, searchable = true and hash column <column>_hash; with_randomized turns searchability off (source: src/proxy/schema/mod.rs, SchemaRegistry, ColumnConfig; src/proxy/mod.rs, ProxyServer::schema_registry).
QueryAnalyzer::analyze is string-based, not a SQL parser. It detects the statement type from the leading keyword (SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, ALTER TABLE, DROP TABLE), extracts table names, insert and update columns, and simple column op 'value' conditions (source: src/proxy/query/mod.rs, QueryAnalyzer::analyze, detect_query_type, extract_tables). QueryRewriter::rewrite then:
- replaces the first occurrence of each quoted literal
'value'for an encrypted column in anINSERTorUPDATEwith'token'; - replaces a
WHEREcondition on a searchable, deterministic column with the same condition on its hash column.
(source: src/proxy/query/mod.rs, QueryRewriter::rewrite)
Parameters of extended-protocol Bind messages are encrypted in place by encrypt_bind_parameters. In result rows, decrypt_data_row decrypts the columns the analysis marked, applies the FieldMasker rule for the column, and passes the original bytes through unchanged if decryption fails (source: src/proxy/handler.rs, encrypt_bind_parameters, decrypt_data_row).
Tests: test_query_type_detection, test_table_extraction, test_insert_column_extraction, test_where_condition_extraction, test_query_analysis in query/mod.rs; 8 tests in schema/mod.rs; 16 in masking/mod.rs.
Two gaps in the searchable path (source: src/proxy/query/mod.rs, QueryAnalyzer::analyze, QueryRewriter::rewrite; src/proxy/crypto/key_derivation.rs, KeyDerivation::search_hash; src/proxy/crypto/engine.rs, EncryptionEngine::search_hash):
- The
WHERErewrite computes the hash withKeyDerivation::search_hash, an unkeyed SHA-256 that the code itself marks as legacy, whileEncryptionEngine::encryptproduces the keyed HMAC-SHA-256 hash. The two never match. - The
INSERTrewrite collects the hash values but does not add them to the statement, and the handler does not use them, so the proxy never fills the hash column.
Not verified: no test runs a searchable query end to end through the rewriter. The healthcare tests (healthcare_test.rs, healthcare_migration_demo.rs, test-only modules) call the engine's keyed search_hash directly, not the rewriter.
Also, ColumnConfig's encryption mode is not passed to the engine: the engine encrypts with a random IV unless enable_searchable_encryption was called for the column, and ProxyServer never calls it (source: src/proxy/crypto/engine.rs, EncryptionEngine::enable_searchable_encryption; src/proxy/mod.rs, ProxyServer::new).
Access control, masking and audit
When access_control is set, the handler checks privileges before forwarding a statement, injects row-level-security predicates into the SQL, and masks configured columns in DataRow messages; a denied Parse is answered with SQLSTATE 42501 and never reaches the backend (source: src/proxy/handler.rs, handle_parse, mask_data_row; src/proxy/access.rs, AccessControlEngine). Tested by test_no_access_control_engine_passes_queries_unchanged, test_access_control_allows_granted_denies_ungranted, test_access_control_superuser_bypass, test_access_control_engine_without_context_denies, test_access_control_rls_predicate_injection, test_inject_rls_predicate_shapes, test_mask_data_row_masks_configured_columns, test_compute_result_masks in handler.rs, and 19 tests in access.rs.
MaskingPattern |
|
|---|---|
LastN(n), FirstN(n)
|
Show only the last or first n characters |
Ssn, CreditCard, Email, Phone, IpAddress
|
Format-specific masks |
FullMask, Redact, Hash, Tokenize
|
Hide the whole value |
Custom { .. } |
User pattern |
(source: src/proxy/masking/mod.rs, MaskingPattern)
ProxyServer creates ProxyAuditLogger::new(audit_enabled), which sends events as JSON to tracing under the target audit (for example connection, authentication, query rewrite, encryption and decryption errors, access granted or denied). The persistence back ends in audit/persistence.rs (rotating JSON files, SQLite with feature migrate-sqlite, S3) with an HMAC-SHA-256 hash chain are not attached by ProxyServer (source: src/proxy/audit/mod.rs, ProxyAuditLogger::new, ProxyAuditEventType; src/proxy/audit/persistence.rs, PersistenceManager). Unit tests: 6 in audit/mod.rs, 10 in audit/persistence.rs.
KMS integration (feature aws-kms)
KmsClient wraps a provider chosen at construction (source: src/proxy/crypto/kms.rs, KmsClient, AwsKmsProvider, LocalKeyProvider, MockKmsProvider):
| Provider | Behaviour |
|---|---|
AwsKmsProvider (aws-kms only) |
GenerateDataKey, Encrypt, Decrypt, EnableKeyRotation, DescribeKey through aws-sdk-kms, with retries |
LocalKeyProvider |
Fallback from a passphrase (PBKDF2, 100,000 iterations), a hex environment variable (at least 64 bytes) or a file. Its data key is derived from its own key, so it is the same on every start |
MockKmsProvider |
Key is SHA-512 of a constant string in the source; its encrypt is XOR. Dev opt-in only |
| Setting | Default |
|---|---|
| region | us-east-1 |
| key spec |
Bits512 (64-byte data key) |
| data-key cache TTL | 300 s |
| request timeout | 30 s |
| retry policy | 3 attempts, 100 ms initial back-off, doubling, 10 s cap |
(source: src/proxy/crypto/kms.rs, KmsConfigBuilder, KeySpec, RetryPolicy, FallbackConfig)
Credential sources are Environment, File { profile }, InstanceProfile, Explicit, Sso and WebIdentity; only Explicit and File are configured specially, the rest use the AWS SDK's default chain. validate_key_id accepts any non-empty string. On start, KmsClient::new calls DescribeKey; if that fails and a fallback is configured, it switches to the fallback. A failing data-key request also switches to the fallback (source: src/proxy/crypto/kms.rs, CredentialsSource, KmsClient::new, KmsClient::generate_data_key_with_spec).
get_master_key returns the plaintext of a freshly generated data key. With AWS KMS, GenerateDataKey returns a new random key each time, and ProxyServer does not store the wrapped (encrypted) data key anywhere. So each restart, and each new KmsClient, yields a different master key, and values encrypted before the restart can no longer be decrypted (source: src/proxy/crypto/kms.rs, KmsClient::get_master_key; src/proxy/mod.rs, ProxyServer::master_key_from_kms). unwrap_data_key exists for reloading a stored wrapped key, but nothing calls it.
Tests in kms.rs: test_mock_kms_provider, test_local_key_provider_passphrase, test_local_key_provider_encrypt_decrypt, test_kms_client_with_mock, test_kms_config_builder, test_key_spec, test_retry_policy_backoff, test_dek_expiration, test_fallback_without_aws, test_key_id_validation. Not verified: no test exercises AwsKmsProvider or a real KMS.
Key rotation
-
EncryptionEngine::rotate_key_via_kmsbuilds a new engine from a new KMS data key.ProxyServercreates its engine withEncryptionEngine::new, which sets no KMS client, so this call always fails there (source:src/proxy/crypto/engine.rs,EncryptionEngine::new,EncryptionEngine::rotate_key_via_kms). -
with_new_key_internal(key, acknowledge_risk)swaps the master key directly and refuses unlessacknowledge_riskis true (source:src/proxy/crypto/engine.rs,EncryptionEngine::with_new_key_internal). -
KeyRotationManagerkeeps several key versions, each with its own engine, and writes versioned tokens of the formbase64("SDBV" || version as u32 big-endian) ":" token.BackgroundReencryptorre-encrypts items from aReencryptionDataSourcein batches, with pause, resume, cancel, rollback and progress callbacks (source:src/proxy/crypto/rotation.rs,KeyRotationManager,VersionedEncryptedValue,BackgroundReencryptor).
Not wired: the handler writes unversioned tokens from EncryptionEngine::encrypt and never uses KeyRotationManager; the only ReencryptionDataSource is InMemoryDataSource, so there is no way to re-encrypt rows in a real database. Tested at library level by test_versioned_token_serialization, test_versioned_token_detection, test_key_rotation_manager_creation, test_rotate_key, test_encrypt_decrypt_with_version, test_rotation_config_builder, test_rotation_progress, test_in_memory_data_source, test_background_reencryptor_pause_resume, test_multiple_active_versions_during_rotation, test_rollback_rotation in rotation.rs.
Summary of what is and is not verified
| Area | State |
|---|---|
| Column crypto (derivation, token, HMAC, search hash) | Unit-tested |
| Master-key selection and fail-closed start-up | Unit-tested |
| Client authentication decision, access control, masking | Unit-tested |
| Query analysis and rewriting | Unit-tested on strings; searchable WHERE and hash-column fill do not work as described above |
| Proxy against a real PostgreSQL backend | Not verified |
| AWS KMS | Not verified; data key not persisted |
| Key rotation of stored data | Not wired |
| Starting the proxy from SynergyDB | Not wired |
Feature flag encryption-proxy
|
Gates nothing |