From e7b2b9c5ea808f483b8fa9236f3fbf4e47ee0797 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Thu, 8 Oct 2026 07:34:12 -0400 Subject: [PATCH] feat(encryption): bind ciphertexts to their job, config section, scheduled purge (#38) - Job payloads are encrypted with AEAD associated data covering the job id, queue name, key id, algorithm, PII fields and encrypted fields, so swapped ciphertexts or a job moved to another queue fail to decrypt. The format is recorded as `format_version` in `encryption_metadata`; payloads without it (written before this change) still decrypt without associated data. - `[encryption]` section in HammerworkConfig (PayloadEncryptionConfig), consumed by JobQueue::from_config. Keys are only referenced (env://, aws://, gcp://, vault://, azure://), never stored, printed or saved. Fails closed on invalid sections. JobQueue::with_encrypted_queues encrypts whole queues. - WorkerPool::with_encrypted_job_purge / from_hammerwork_config schedule the retention purge. Maintenance passes (purge and stale-job reaper) run in their own task so shutdown never cancels one mid-transaction. - TestQueue applies the same sealing, redaction and decryption semantics. - Archived encrypted jobs must be restored to decrypt; decrypt_job says so. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + docs/encryption.md | 91 ++++- src/config.rs | 570 ++++++++++++++++++++++++++++++ src/encryption.rs | 29 ++ src/encryption/engine.rs | 73 +++- src/encryption/job_payload.rs | 245 ++++++++++++- src/lib.rs | 4 +- src/queue/mod.rs | 191 ++++++---- src/queue/mysql.rs | 4 + src/queue/payload_encryption.rs | 139 ++++++++ src/queue/postgres.rs | 4 + src/queue/test.rs | 367 ++++++++++++++++++- src/worker.rs | 225 ++++++++++-- tests/payload_encryption_tests.rs | 471 +++++++++++++++++++++++- 14 files changed, 2308 insertions(+), 112 deletions(-) create mode 100644 src/queue/payload_encryption.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ace5f9..38f687c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Retention is enforced** by the new `DatabaseQueue::purge_expired_encrypted_jobs()` (returns `EncryptedJobPurge`): it deletes finished (`Completed`, `Failed`, `Dead`, `TimedOut`) encrypted jobs whose `retention_delete_at` has passed, and expired encrypted jobs in the archive. Pending and running jobs are never deleted. Default implementation returns an error, so custom `DatabaseQueue` implementations keep compiling. - `EncryptionEngine::with_decryption_key(key_id, &source)` adds a decrypt-only key, so jobs encrypted under a previous key id stay readable after switching keys. New `EncryptionEngine::config()`, `key_id()` and `algorithm()`. - CLI: `cargo hammerwork maintenance purge-encrypted [--dry-run | --confirm]`; `cargo hammerwork job show` prints the key id, algorithm and retention of encrypted jobs. +- **🔐 Encryption follow-ups** ([#38](https://github.com/CodingAnarchy/hammerwork/issues/38)) + - **Ciphertexts are bound to their job.** Job payloads are encrypted with AEAD associated data covering the job id, queue name, key id, algorithm, PII fields and encrypted fields, so swapping `encrypted_payload` / nonce / tag between rows, moving a row to another queue, or changing its key id or PII fields makes decryption fail (the worker fails the run without calling the handler). `encryption_metadata` records the new `format_version` (`EncryptionMetadata::FORMAT_JOB_BOUND`); payloads without it (written before this change) still decrypt without associated data and are not re-encrypted. Archive and restore keep every bound value. New `EncryptionEngine::encrypt_payload_with_associated_data` / `decrypt_payload_with_associated_data` and `encryption::job_payload::job_associated_data`. No migration. + - **`[encryption]` configuration section** (`HammerworkConfig::encryption`, `PayloadEncryptionConfig`): algorithm, key source, key id, compression, default retention, purge interval, `encrypted_queues` and decrypt-only `decryption_keys`. `JobQueue::from_config` (new `JobQueue::apply_encryption_config`) builds the engine with `new_with_pool`, so a configured queue encrypts without code. Keys are only referenced (`KeySourceRef`: `env://VAR`, `aws://`, `gcp://`, `vault://`, `azure://`), never written in the file, printed by `Debug` or saved by `save_to_file`. Fails closed on unknown fields, invalid key sources or algorithms, unloadable keys, and an enabled section without the `encryption` feature. `HammerworkConfig::from_env` reads `HAMMERWORK_ENCRYPTION_*` and rejects invalid values. The section is optional, so existing files still load. + - `JobQueue::with_encrypted_queues(["payments"])` (`"*"`: all) encrypts every job on those queues, also jobs without `with_encryption`. + - **Scheduled retention purge**: `WorkerPool::with_encrypted_job_purge(interval)` / `without_encrypted_job_purge()` (off by default) and `WorkerPool::from_hammerwork_config(worker, &config)` (uses `encryption.purge_interval_secs`). Each purge runs in its own task, so shutdown never cancels one mid-transaction; the stale job reaper now runs the same way. + - **`TestQueue` encryption**: `TestQueue::with_encryption`, `with_encrypted_queues`, `encryption_engine` and `decrypt_job` apply the same sealing, redaction, fail-closed and decryption semantics as the database backends; `purge_expired_encrypted_jobs` is implemented against the `MockClock`. + - **Archived encrypted jobs** must be restored to be decrypted (documented in `docs/encryption.md`); `decrypt_job` on an archived job now says so instead of reporting a missing ciphertext. - **⚙️ `HammerworkConfig` is now consumed by the library** ([#3](https://github.com/CodingAnarchy/hammerwork/issues/3)) - `JobQueue::::from_config` builds the connection pool from `database` (URL, pool size, connection timeout), runs migrations when `auto_migrate` is set, and registers per-queue throttles from `rate_limiting` - `Worker::with_config(&WorkerConfig)` applies poll interval, job timeout, priority weights and retry strategy diff --git a/docs/encryption.md b/docs/encryption.md index a7f75e3..27b81a4 100644 --- a/docs/encryption.md +++ b/docs/encryption.md @@ -224,12 +224,91 @@ How it works: - **The engine decides.** The queue's engine sets the algorithm, key and compression. A job whose config names another algorithm, or a `key_id` other than the engine's, is rejected. Jobs without an encryption config are stored unchanged, also on a queue with an engine. - **Fail closed.** Enqueueing a job that has an encryption config on a queue without an engine fails with `HammerworkError::Encryption`. - **Dequeue and reads.** `dequeue`, `get_job`, `get_batch_jobs` and the other reads return jobs as stored: `is_encrypted` is `true`, `payload` is redacted and `encrypted_payload` holds the ciphertext. The web dashboard and `cargo hammerwork job show` therefore show the redacted payload (`job show` also prints the key id, algorithm and retention). They never need a key. -- **Workers.** A worker decrypts the job (`JobQueue::decrypt_job`) just before it calls the handler; only the handler sees the plaintext. Event hooks, webhooks and the recorded outcome keep using the redacted job. If the payload cannot be decrypted (the worker's queue has no engine, the engine does not have the job's key, or the data was tampered with) the run fails with `Cannot decrypt the payload of job ...` and goes through the normal retry / dead path; the handler is not called. +- **Workers.** A worker decrypts the job (`JobQueue::decrypt_job`) just before it calls the handler; only the handler sees the plaintext. Event hooks, webhooks and the recorded outcome keep using the redacted job. If the payload cannot be decrypted (the worker's queue has no engine, the engine does not have the job's key, the data was tampered with, or the ciphertext belongs to another job; see [Binding the ciphertext to its job](#binding-the-ciphertext-to-its-job)) the run fails with `Cannot decrypt the payload of job ...` and goes through the normal retry / dead path; the handler is not called. - **Reading the plaintext yourself.** `queue.decrypt_job(job).await?` returns the job with its plaintext payload. - **Without the `encryption` feature** a build cannot encrypt or decrypt. It still reads `is_encrypted`, so its workers fail encrypted jobs instead of running them with the redacted payload, and archiving and restoring still carry the ciphertext. The payload hash stored with the ciphertext is an HMAC-SHA256 keyed by the data key (`hmac-sha256:`), not a plain SHA-256, so a low-entropy value (an SSN, a card number) cannot be recovered from it by brute force. Payloads encrypted by earlier versions with a plain SHA-256 still decrypt. +### Binding the ciphertext to its job + +The ciphertext of a job is bound to that job. It is encrypted with AEAD associated data made of the job's id, queue name, key id, algorithm, PII field list and the list of fields that were encrypted (`encryption::job_payload::job_associated_data`). Decryption recomputes the associated data from the stored row, so with write access to the database, an attacker who: + +- swaps the `encrypted_payload` / `encryption_nonce` / `encryption_tag` of two jobs, +- moves a job to another queue (`queue_name`), or +- changes its key id, algorithm or `pii_fields` + +gets a job that fails to decrypt (the worker fails the run without calling the handler) instead of one that decrypts as another job's data. The associated data is not stored; only the format is recorded, as `format_version` in `encryption_metadata`: + +| `format_version` | Meaning | +|---|---| +| missing or `0` | No associated data. Payloads written before this change (and payloads encrypted directly with `EncryptionEngine::encrypt_payload`). They still decrypt, and are not re-encrypted. | +| `1` | Bound to the job as described above. Written by `JobQueue` and `TestQueue` for every newly encrypted job. | +| anything else | Written by a newer version: refused. | + +Resetting `format_version` to `0` on a bound payload does not get around the binding: the ciphertext then fails authentication without the associated data it was encrypted with. Payloads written in the old format can still be swapped among themselves; re-enqueue those jobs if that matters. The retention columns are not covered: anyone who can write to the table can also delete or keep rows. + +Archiving and restoring keep the job id, queue name and encryption columns, so restored jobs decrypt. `EncryptionEngine::encrypt_payload_with_associated_data` / `decrypt_payload_with_associated_data` expose the same mechanism for payloads you encrypt yourself. + +### Archived encrypted jobs + +Archiving moves the ciphertext to `hammerwork_jobs_archive` without decrypting it. `get_job` of an archived job returns it with `status == Archived`, `is_encrypted`, `pii_fields` and the redacted payload, but not the ciphertext, so `decrypt_job` on it fails with an error that says to restore it. To read the plaintext of an archived job, restore it first: + +```rust +let job = queue.restore_archived_job(job_id).await?; // back in hammerwork_jobs, ciphertext unchanged +let job = queue.get_job(job_id).await?.unwrap(); +let plaintext = queue.decrypt_job(job).await?.payload; +``` + +There is no decrypt-on-read for the archive: archived jobs are cold data, and keeping the plaintext path to the live table keeps one place (restore) where an archived payload comes back. Retention still applies to archived jobs (see [Enforcing Retention](#enforcing-retention)). + +### Encrypting whole queues + +`JobQueue::with_encrypted_queues(["payments"])` (or `["*"]` for every queue) encrypts every job enqueued to those queues, also jobs created without `with_encryption`: they get the engine's algorithm and key id, and their PII fields (if any) or whole payload is encrypted. Jobs with their own encryption config are unaffected. This is how a queue configured from `hammerwork.toml` encrypts without code changes. + +### Configuration file + +`JobQueue::from_config` reads an optional `[encryption]` section of `HammerworkConfig` (`PayloadEncryptionConfig`) and sets up the engine itself: + +```toml +[encryption] +enabled = true +algorithm = "AES256GCM" # or "ChaCha20Poly1305" +key_source = "env://HAMMERWORK_ENCRYPTION_KEY" # or aws://, gcp://, vault://, azure:// +key_id = "payments-2027" # default "default" +compression = false +default_retention_secs = 2592000 # retention of UseDefault jobs (30 days) +purge_interval_secs = 3600 # WorkerPool::from_hammerwork_config purges hourly +encrypted_queues = ["payments"] # encrypt these queues' jobs ("*": all) + +[encryption.decryption_keys] # decrypt-only keys of earlier key ids +"payments-2026" = "env://HAMMERWORK_KEY_2026" +``` + +```rust +let config = HammerworkConfig::from_file("hammerwork.toml")?; +let queue = Arc::new(JobQueue::::from_config(&config).await?); +let pool = WorkerPool::from_hammerwork_config(worker, &config)?; +``` + +- **Keys are referenced, never written in the file.** `key_source` and the `decryption_keys` values are `KeySourceRef`s: `env://VAR` (a base64 key in that environment variable) or a KMS URI (`aws://`, `gcp://`, `vault://`, `azure://`, each needing its cargo feature). Static keys and anything else are rejected when the file is loaded, and the error does not repeat the value. `Debug` output and `save_to_file` only ever contain these references. +- **Fails closed.** Unknown fields (for example a key under a guessed name) and unknown algorithms are load errors. `from_config` fails if the section is enabled but the key cannot be loaded, if `encrypted_queues` is set while `enabled = false`, if a decryption key reuses the encryption key id, or if the build lacks the `encryption` feature. +- **Environment.** `HammerworkConfig::from_env` reads `HAMMERWORK_ENCRYPTION_ENABLED`, `_ALGORITHM`, `_KEY_SOURCE`, `_KEY_ID`, `_COMPRESSION`, `_DEFAULT_RETENTION_SECS`, `_PURGE_INTERVAL_SECS`, `_ENCRYPTED_QUEUES` (comma-separated) and `_DECRYPTION_KEYS` (`id=source,id=source`). Invalid values are errors. `HAMMERWORK_ENCRYPTION_KEY` itself is the default key source (the key), not a setting. +- `aws://` and `gcp://` sources work: the engine is created with `EncryptionEngine::new_with_pool` on the queue's pool. + +### Testing with `TestQueue` + +The in-memory `TestQueue` (feature `test`) applies the same semantics when given an engine, so unit tests exercise the real redaction and decryption paths: + +```rust +let queue = TestQueue::new().with_encryption(EncryptionEngine::new(config.clone()).await?); +let id = queue.enqueue(Job::new("payments".into(), json!({"card": "4111"})).with_encryption(config)).await?; +let stored = queue.get_job(id).await?.unwrap(); // {"encrypted": true}, is_encrypted +let opened = queue.decrypt_job(stored).await?; // what a handler sees +``` + +It seals jobs in `enqueue`, `enqueue_batch`, `enqueue_workflow` and `enqueue_cron_job`, rejects jobs with an encryption config when it has no engine, binds ciphertexts to their jobs, supports `with_encrypted_queues`, hides the ciphertext of archived jobs until they are restored, and implements `purge_expired_encrypted_jobs` against its `MockClock`. + ### Key Rotation for Job Payloads Each encrypted job records the id of the key it was encrypted with. To switch to a new key, give the engine a new `key_id` and keep the previous key for decryption: @@ -383,7 +462,15 @@ let policy = RetentionPolicy::UseDefault; ### Enforcing Retention -When a job is encrypted, its retention policy (`Job::with_retention_policy`, or `UseDefault`, which uses the engine's `default_retention`) is stored in `retention_policy` and the deletion time in `retention_delete_at`. Nothing is deleted automatically; run the purge periodically: +When a job is encrypted, its retention policy (`Job::with_retention_policy`, or `UseDefault`, which uses the engine's `default_retention`) is stored in `retention_policy` and the deletion time in `retention_delete_at`. Expired jobs are deleted by a purge, which you run periodically. The simplest way is to let a `WorkerPool` schedule it: + +```rust +let mut pool = WorkerPool::new() + .with_encrypted_job_purge(Duration::from_secs(3600)); // off by default +// or WorkerPool::from_hammerwork_config(worker, &config)? with encryption.purge_interval_secs +``` + +The pool runs the first purge when it starts and then every interval, on its first worker's queue. Each purge runs in its own task, so shutting the pool down never cancels one part-way through its transaction. Several pools or processes purging at once is safe. Without a pool purge, call it yourself: ```rust let purge = queue.purge_expired_encrypted_jobs().await?; diff --git a/src/config.rs b/src/config.rs index 852fd07..a2164af 100644 --- a/src/config.rs +++ b/src/config.rs @@ -241,6 +241,11 @@ pub struct HammerworkConfig { /// Logging and tracing configuration pub logging: LoggingConfig, + + /// Job payload encryption (`[encryption]`). Optional in TOML files; disabled by + /// default. + #[serde(default)] + pub encryption: PayloadEncryptionConfig, } impl HammerworkConfig { @@ -325,6 +330,8 @@ impl HammerworkConfig { buffer_size.parse().unwrap_or(config.events.max_buffer_size); } + config.encryption.apply_env()?; + Ok(config) } } @@ -674,6 +681,337 @@ impl Default for LoggingConfig { } } +/// Encryption algorithm named in [`PayloadEncryptionConfig`]. +/// +/// The same names as [`EncryptionAlgorithm`](crate::encryption::EncryptionAlgorithm), +/// which is only available with the `encryption` feature. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PayloadEncryptionAlgorithm { + /// AES-256-GCM + #[default] + AES256GCM, + /// ChaCha20-Poly1305 + ChaCha20Poly1305, +} + +impl std::str::FromStr for PayloadEncryptionAlgorithm { + type Err = crate::HammerworkError; + + fn from_str(s: &str) -> crate::Result { + match s { + "AES256GCM" => Ok(Self::AES256GCM), + "ChaCha20Poly1305" => Ok(Self::ChaCha20Poly1305), + other => Err(crate::HammerworkError::Config(format!( + "Unknown encryption algorithm '{other}' (expected AES256GCM or ChaCha20Poly1305)" + ))), + } + } +} + +/// Where an encryption key is loaded from, as a reference that never contains the key. +/// +/// Accepted forms: +/// +/// - `env://VAR`: a base64 key in environment variable `VAR` +/// ([`KeySource::Environment`](crate::encryption::KeySource::Environment)) +/// - `aws://...`, `gcp://...`: a data key generated by AWS or GCP KMS and stored +/// KMS-encrypted in the database (`aws-kms` / `gcp-kms` features) +/// - `vault://...`: a HashiCorp Vault secret (`vault-kms` feature) +/// - `azure://...`: an Azure Key Vault secret (`azure-kv` feature) +/// +/// Static keys cannot be configured: a key written in a configuration file would be +/// printed and saved with it. Anything else is rejected when the configuration is +/// loaded, without echoing the value (it may be a key pasted by mistake). +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct KeySourceRef(String); + +impl KeySourceRef { + const EXTERNAL_SCHEMES: [&'static str; 4] = ["aws://", "gcp://", "vault://", "azure://"]; + + /// Parses a key source reference (see the type documentation for the forms). + pub fn parse(source: &str) -> crate::Result { + if let Some(var) = source.strip_prefix("env://") { + let valid = + !var.is_empty() && var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + if !valid { + return Err(crate::HammerworkError::Config( + "Invalid encryption key source: env:// needs an environment variable name \ + (letters, digits and underscores)" + .to_string(), + )); + } + return Ok(Self(source.to_string())); + } + if let Some(scheme) = Self::EXTERNAL_SCHEMES + .iter() + .find(|scheme| source.starts_with(**scheme)) + { + if source.len() == scheme.len() { + return Err(crate::HammerworkError::Config(format!( + "Invalid encryption key source: {scheme} needs a key reference" + ))); + } + return Ok(Self(source.to_string())); + } + // Do not echo the value: it may be a key + Err(crate::HammerworkError::Config( + "Invalid encryption key source: expected env://VAR, aws://, gcp://, vault:// or \ + azure://; keys cannot be written in the configuration" + .to_string(), + )) + } + + /// The reference, e.g. `env://HAMMERWORK_ENCRYPTION_KEY`. + pub fn as_str(&self) -> &str { + &self.0 + } + + /// The [`KeySource`](crate::encryption::KeySource) this reference names. + #[cfg(feature = "encryption")] + pub fn key_source(&self) -> crate::encryption::KeySource { + match self.0.strip_prefix("env://") { + Some(var) => crate::encryption::KeySource::Environment(var.to_string()), + None => crate::encryption::KeySource::External(self.0.clone()), + } + } +} + +impl Default for KeySourceRef { + fn default() -> Self { + Self("env://HAMMERWORK_ENCRYPTION_KEY".to_string()) + } +} + +impl TryFrom for KeySourceRef { + type Error = crate::HammerworkError; + + fn try_from(source: String) -> crate::Result { + Self::parse(&source) + } +} + +impl From for String { + fn from(source: KeySourceRef) -> Self { + source.0 + } +} + +impl std::fmt::Debug for KeySourceRef { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // A reference (variable name or KMS key URI), never key material + f.write_str(&self.0) + } +} + +impl std::fmt::Display for KeySourceRef { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +/// Job payload encryption (`[encryption]` in `hammerwork.toml`). +/// +/// When `enabled`, `JobQueue::from_config` builds an +/// [`EncryptionEngine`](crate::encryption::EncryptionEngine) from this section and sets +/// it on the queue (`JobQueue::with_encryption`), so jobs with an encryption config are +/// encrypted, and jobs on `encrypted_queues` are encrypted without one. +/// [`WorkerPool::from_hammerwork_config`](crate::worker::WorkerPool::from_hammerwork_config) +/// schedules the retention purge every `purge_interval_secs`. Needs the `encryption` +/// feature: `from_config` fails if the section is enabled without it. +/// +/// Keys are referenced, never written here ([`KeySourceRef`]), so the section can be +/// printed and saved safely. +/// +/// ```toml +/// [encryption] +/// enabled = true +/// algorithm = "AES256GCM" +/// key_source = "env://HAMMERWORK_ENCRYPTION_KEY" +/// key_id = "key-2026-10" +/// compression = false +/// default_retention_secs = 2592000 # 30 days +/// purge_interval_secs = 3600 +/// encrypted_queues = ["payments"] +/// +/// [encryption.decryption_keys] # decrypt-only keys of earlier key ids +/// "key-2026-04" = "env://HAMMERWORK_ENCRYPTION_KEY_2026_04" +/// ``` +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct PayloadEncryptionConfig { + /// Whether the queue encrypts payloads. + pub enabled: bool, + + /// Algorithm used to encrypt. + pub algorithm: PayloadEncryptionAlgorithm, + + /// Where the encryption key comes from. + pub key_source: KeySourceRef, + + /// Id of the encryption key, recorded with each payload (default `"default"`). + pub key_id: Option, + + /// Whether payloads are compressed before they are encrypted. + pub compression: bool, + + /// Retention of encrypted jobs whose retention policy is `UseDefault` (the default + /// for jobs without one), in seconds. `None` keeps them indefinitely. + pub default_retention_secs: Option, + + /// How often a [`WorkerPool`](crate::worker::WorkerPool) built with + /// `from_hammerwork_config` deletes encrypted jobs whose retention ended, in seconds. + /// `None` leaves the purge to `cargo hammerwork maintenance purge-encrypted`. + pub purge_interval_secs: Option, + + /// Queues whose jobs are encrypted even without an encryption config (`"*"`: all). + pub encrypted_queues: Vec, + + /// Decrypt-only keys by key id, for payloads encrypted under earlier key ids. + pub decryption_keys: std::collections::BTreeMap, +} + +impl PayloadEncryptionConfig { + /// Checks the section for settings that cannot work. Called by `JobQueue::from_config`. + /// A disabled section is only checked for settings that need it enabled. + pub fn validate(&self) -> crate::Result<()> { + let error = |message: &str| Err(crate::HammerworkError::Config(message.to_string())); + if !self.enabled { + if !self.encrypted_queues.is_empty() { + return error( + "encryption.encrypted_queues is set but encryption.enabled is false; \ + jobs on those queues would be stored in plaintext", + ); + } + return Ok(()); + } + if self.key_id.as_deref().is_some_and(str::is_empty) { + return error("encryption.key_id must not be empty"); + } + let key_id = self.key_id.as_deref().unwrap_or("default"); + if self.decryption_keys.contains_key(key_id) { + return error("encryption.decryption_keys must not contain the encryption key id"); + } + if self.decryption_keys.keys().any(String::is_empty) { + return error("encryption.decryption_keys has an empty key id"); + } + if self.purge_interval_secs == Some(0) { + return error("encryption.purge_interval_secs must be greater than zero"); + } + if self.encrypted_queues.iter().any(String::is_empty) { + return error("encryption.encrypted_queues has an empty queue name"); + } + Ok(()) + } + + /// How often the retention purge runs, if configured. + pub fn purge_interval(&self) -> Option { + self.purge_interval_secs.map(StdDuration::from_secs) + } + + /// The [`EncryptionConfig`](crate::encryption::EncryptionConfig) for the engine. + /// Validates the section first. + #[cfg(feature = "encryption")] + pub fn encryption_config(&self) -> crate::Result { + use crate::encryption::{EncryptionAlgorithm, EncryptionConfig}; + + self.validate()?; + let algorithm = match self.algorithm { + PayloadEncryptionAlgorithm::AES256GCM => EncryptionAlgorithm::AES256GCM, + PayloadEncryptionAlgorithm::ChaCha20Poly1305 => EncryptionAlgorithm::ChaCha20Poly1305, + }; + let mut config = EncryptionConfig::new(algorithm) + .with_key_source(self.key_source.key_source()) + .with_compression_enabled(self.compression); + if let Some(key_id) = &self.key_id { + config = config.with_key_id(key_id); + } + if let Some(secs) = self.default_retention_secs { + config = config.with_default_retention(StdDuration::from_secs(secs)); + } + Ok(config) + } + + /// Overrides settings from `HAMMERWORK_ENCRYPTION_*` environment variables. + /// + /// `HAMMERWORK_ENCRYPTION_ENABLED`, `_ALGORITHM`, `_KEY_SOURCE`, `_KEY_ID`, + /// `_COMPRESSION`, `_DEFAULT_RETENTION_SECS`, `_PURGE_INTERVAL_SECS`, + /// `_ENCRYPTED_QUEUES` (comma-separated) and `_DECRYPTION_KEYS` + /// (`id=source,id=source`). An invalid value is an error rather than ignored, so a + /// typo cannot silently disable encryption. (`HAMMERWORK_ENCRYPTION_KEY` is the + /// default key source, the key itself, not a setting.) + pub fn apply_env(&mut self) -> crate::Result<()> { + self.apply_vars(|name| std::env::var(name).ok()) + } + + /// [`PayloadEncryptionConfig::apply_env`] with variables looked up by `var`. + fn apply_vars(&mut self, var: impl Fn(&str) -> Option) -> crate::Result<()> { + fn invalid(name: &str) -> crate::HammerworkError { + crate::HammerworkError::Config(format!("Invalid value for {name}")) + } + fn parse_bool(name: &str, value: &str) -> crate::Result { + match value.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Ok(true), + "0" | "false" | "no" | "off" => Ok(false), + _ => Err(invalid(name)), + } + } + fn parse_secs(name: &str, value: &str) -> crate::Result { + value.trim().parse().map_err(|_| invalid(name)) + } + + const ENABLED: &str = "HAMMERWORK_ENCRYPTION_ENABLED"; + const COMPRESSION: &str = "HAMMERWORK_ENCRYPTION_COMPRESSION"; + const RETENTION: &str = "HAMMERWORK_ENCRYPTION_DEFAULT_RETENTION_SECS"; + const PURGE: &str = "HAMMERWORK_ENCRYPTION_PURGE_INTERVAL_SECS"; + const DECRYPTION_KEYS: &str = "HAMMERWORK_ENCRYPTION_DECRYPTION_KEYS"; + + if let Some(value) = var(ENABLED) { + self.enabled = parse_bool(ENABLED, &value)?; + } + if let Some(value) = var("HAMMERWORK_ENCRYPTION_ALGORITHM") { + self.algorithm = value.trim().parse()?; + } + if let Some(value) = var("HAMMERWORK_ENCRYPTION_KEY_SOURCE") { + self.key_source = KeySourceRef::parse(value.trim())?; + } + if let Some(value) = var("HAMMERWORK_ENCRYPTION_KEY_ID") { + self.key_id = Some(value.trim().to_string()); + } + if let Some(value) = var(COMPRESSION) { + self.compression = parse_bool(COMPRESSION, &value)?; + } + if let Some(value) = var(RETENTION) { + self.default_retention_secs = Some(parse_secs(RETENTION, &value)?); + } + if let Some(value) = var(PURGE) { + self.purge_interval_secs = Some(parse_secs(PURGE, &value)?); + } + if let Some(value) = var("HAMMERWORK_ENCRYPTION_ENCRYPTED_QUEUES") { + self.encrypted_queues = value + .split(',') + .map(str::trim) + .filter(|queue| !queue.is_empty()) + .map(str::to_string) + .collect(); + } + if let Some(value) = var(DECRYPTION_KEYS) { + let mut keys = std::collections::BTreeMap::new(); + for entry in value.split(',').map(str::trim).filter(|e| !e.is_empty()) { + let (key_id, source) = entry + .split_once('=') + .ok_or_else(|| invalid(DECRYPTION_KEYS))?; + keys.insert( + key_id.trim().to_string(), + KeySourceRef::parse(source.trim())?, + ); + } + self.decryption_keys = keys; + } + Ok(()) + } +} + /// Helper functions for creating configurations impl HammerworkConfig { /// Create a configuration for development use @@ -1160,4 +1498,236 @@ service_name = "hammerwork" assert_eq!(config.compression_level, 3); assert_eq!(config.archive_after, Duration::days(10)); } + + fn encryption_toml() -> &'static str { + r#" + enabled = true + algorithm = "ChaCha20Poly1305" + key_source = "env://MY_HAMMERWORK_KEY" + key_id = "key-2026-10" + compression = true + default_retention_secs = 2592000 + purge_interval_secs = 3600 + encrypted_queues = ["payments", "pii"] + + [decryption_keys] + "key-2026-04" = "env://MY_OLD_KEY" + "kms-key" = "aws://alias/hammerwork?region=us-east-1" + "# + } + + #[test] + fn test_encryption_section_parses_and_round_trips() { + let section: PayloadEncryptionConfig = toml::from_str(encryption_toml()).unwrap(); + assert!(section.enabled); + assert_eq!( + section.algorithm, + PayloadEncryptionAlgorithm::ChaCha20Poly1305 + ); + assert_eq!(section.key_source.as_str(), "env://MY_HAMMERWORK_KEY"); + assert_eq!(section.key_id.as_deref(), Some("key-2026-10")); + assert!(section.compression); + assert_eq!(section.default_retention_secs, Some(2_592_000)); + assert_eq!(section.purge_interval(), Some(StdDuration::from_secs(3600))); + assert_eq!(section.encrypted_queues, vec!["payments", "pii"]); + assert_eq!(section.decryption_keys.len(), 2); + section.validate().unwrap(); + + let config = HammerworkConfig { + encryption: section.clone(), + ..HammerworkConfig::default() + }; + let saved = toml::to_string_pretty(&config).unwrap(); + assert!(saved.contains("env://MY_HAMMERWORK_KEY"), "{saved}"); + let loaded: HammerworkConfig = toml::from_str(&saved).unwrap(); + assert_eq!(loaded.encryption, section); + + // The file operations round-trip it too + let dir = tempdir().unwrap(); + let path = dir.path().join("hammerwork.toml"); + config.save_to_file(path.to_str().unwrap()).unwrap(); + let loaded = HammerworkConfig::from_file(path.to_str().unwrap()).unwrap(); + assert_eq!(loaded.encryption, section); + } + + #[test] + fn test_encryption_section_is_optional_and_disabled_by_default() { + let config = HammerworkConfig::default(); + assert!(!config.encryption.enabled); + assert_eq!( + config.encryption.key_source.as_str(), + "env://HAMMERWORK_ENCRYPTION_KEY" + ); + config.encryption.validate().unwrap(); + + // Configuration files written before the section existed still load + let mut value = toml::Value::try_from(&config).unwrap(); + value.as_table_mut().unwrap().remove("encryption"); + let loaded: HammerworkConfig = toml::from_str(&toml::to_string(&value).unwrap()).unwrap(); + assert_eq!(loaded.encryption, PayloadEncryptionConfig::default()); + } + + #[test] + fn test_encryption_section_rejects_keys_and_typos() { + let key = "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUE="; + for source in [ + key.to_string(), + format!("static://{key}"), + "env://".to_string(), + "env://NOT-A-VAR".to_string(), + "aws://".to_string(), + "file:///etc/key".to_string(), + ] { + let err = toml::from_str::(&format!( + "enabled = true\nkey_source = \"{source}\"" + )) + .unwrap_err() + .to_string(); + assert!(err.contains("key source"), "{source}: {err}"); + // Our message never repeats the value (the TOML parser quotes the line) + let err = KeySourceRef::parse(&source).unwrap_err().to_string(); + assert!(!err.contains(key), "the error echoes the key: {err}"); + } + + // Unknown fields (e.g. a key under a guessed name) and algorithms fail closed + assert!( + toml::from_str::(&format!("enabled = true\nkey = \"{key}\"")) + .is_err() + ); + assert!(toml::from_str::("algorithm = \"AES128\"").is_err()); + assert!( + toml::from_str::("[decryption_keys]\nold = \"QUFBQQ==\"") + .is_err() + ); + } + + #[test] + fn test_encryption_section_validation() { + let enabled = PayloadEncryptionConfig { + enabled: true, + ..PayloadEncryptionConfig::default() + }; + enabled.validate().unwrap(); + + let invalid = [ + PayloadEncryptionConfig { + encrypted_queues: vec!["payments".into()], + ..PayloadEncryptionConfig::default() + }, + PayloadEncryptionConfig { + key_id: Some(String::new()), + ..enabled.clone() + }, + PayloadEncryptionConfig { + decryption_keys: [("default".to_string(), KeySourceRef::default())].into(), + ..enabled.clone() + }, + PayloadEncryptionConfig { + purge_interval_secs: Some(0), + ..enabled.clone() + }, + PayloadEncryptionConfig { + encrypted_queues: vec![String::new()], + ..enabled.clone() + }, + ]; + for config in invalid { + assert!( + matches!(config.validate(), Err(crate::HammerworkError::Config(_))), + "{config:?}" + ); + } + } + + #[test] + fn test_encryption_section_debug_shows_only_references() { + let section: PayloadEncryptionConfig = toml::from_str(encryption_toml()).unwrap(); + let debug = format!("{section:?}"); + assert!(debug.contains("env://MY_HAMMERWORK_KEY"), "{debug}"); + assert!(debug.contains("aws://alias/hammerwork"), "{debug}"); + } + + #[test] + fn test_encryption_section_from_env_vars() { + let vars: HashMap<&str, &str> = [ + ("HAMMERWORK_ENCRYPTION_ENABLED", "true"), + ("HAMMERWORK_ENCRYPTION_ALGORITHM", "ChaCha20Poly1305"), + ("HAMMERWORK_ENCRYPTION_KEY_SOURCE", "env://PROD_KEY"), + ("HAMMERWORK_ENCRYPTION_KEY_ID", "prod-1"), + ("HAMMERWORK_ENCRYPTION_COMPRESSION", "1"), + ("HAMMERWORK_ENCRYPTION_DEFAULT_RETENTION_SECS", "86400"), + ("HAMMERWORK_ENCRYPTION_PURGE_INTERVAL_SECS", "600"), + ("HAMMERWORK_ENCRYPTION_ENCRYPTED_QUEUES", "payments, pii,"), + ( + "HAMMERWORK_ENCRYPTION_DECRYPTION_KEYS", + "prod-0=env://OLD_KEY,kms=gcp://projects/p/locations/l/keyRings/r/cryptoKeys/k", + ), + ] + .into(); + let lookup = |name: &str| vars.get(name).map(|v| v.to_string()); + + let mut section = PayloadEncryptionConfig::default(); + section.apply_vars(lookup).unwrap(); + assert!(section.enabled); + assert_eq!( + section.algorithm, + PayloadEncryptionAlgorithm::ChaCha20Poly1305 + ); + assert_eq!(section.key_source.as_str(), "env://PROD_KEY"); + assert_eq!(section.key_id.as_deref(), Some("prod-1")); + assert!(section.compression); + assert_eq!(section.default_retention_secs, Some(86_400)); + assert_eq!(section.purge_interval_secs, Some(600)); + assert_eq!(section.encrypted_queues, vec!["payments", "pii"]); + assert_eq!(section.decryption_keys["prod-0"].as_str(), "env://OLD_KEY"); + section.validate().unwrap(); + + // Invalid values are errors, not silently ignored + for (name, value) in [ + ("HAMMERWORK_ENCRYPTION_ENABLED", "maybe"), + ("HAMMERWORK_ENCRYPTION_ALGORITHM", "rot13"), + ("HAMMERWORK_ENCRYPTION_KEY_SOURCE", "QUFBQQ=="), + ("HAMMERWORK_ENCRYPTION_PURGE_INTERVAL_SECS", "hourly"), + ("HAMMERWORK_ENCRYPTION_DECRYPTION_KEYS", "env://NO_ID"), + ] { + let mut section = PayloadEncryptionConfig::default(); + let result = section.apply_vars(|n| (n == name).then(|| value.to_string())); + assert!(result.is_err(), "{name}={value}"); + } + + // Nothing set: unchanged + let mut section = PayloadEncryptionConfig::default(); + section.apply_vars(|_| None).unwrap(); + assert_eq!(section, PayloadEncryptionConfig::default()); + } + + #[cfg(feature = "encryption")] + #[test] + fn test_encryption_section_engine_config() { + use crate::encryption::{EncryptionAlgorithm, KeySource}; + + let section: PayloadEncryptionConfig = toml::from_str(encryption_toml()).unwrap(); + let config = section.encryption_config().unwrap(); + assert_eq!(config.algorithm, EncryptionAlgorithm::ChaCha20Poly1305); + assert_eq!( + config.key_source, + KeySource::Environment("MY_HAMMERWORK_KEY".to_string()) + ); + assert_eq!(config.key_id.as_deref(), Some("key-2026-10")); + assert!(config.compression_enabled); + assert_eq!( + config.default_retention, + Some(StdDuration::from_secs(2_592_000)) + ); + assert_eq!( + section.decryption_keys["kms-key"].key_source(), + KeySource::External("aws://alias/hammerwork?region=us-east-1".to_string()) + ); + + let invalid = PayloadEncryptionConfig { + purge_interval_secs: Some(0), + ..section + }; + assert!(invalid.encryption_config().is_err()); + } } diff --git a/src/encryption.rs b/src/encryption.rs index df39c8e..dba0d6b 100644 --- a/src/encryption.rs +++ b/src/encryption.rs @@ -589,9 +589,37 @@ pub struct EncryptionMetadata { /// Hash of the original payload for integrity verification. pub payload_hash: String, + + /// Format of the ciphertext: which associated data it was encrypted with. + /// + /// - `0` ([`EncryptionMetadata::FORMAT_UNBOUND`]): no associated data. Payloads + /// encrypted directly with [`EncryptionEngine::encrypt_payload`], and job payloads + /// written before ciphertexts were bound to their job, have this format (it is the + /// default when the field is missing). + /// - `1` ([`EncryptionMetadata::FORMAT_JOB_BOUND`]): job payloads bound to their job + /// (id, queue name, key id, algorithm and PII fields) as associated data; see + /// [`job_payload`]. + #[serde(default)] + pub format_version: u32, } impl EncryptionMetadata { + /// [`EncryptionMetadata::format_version`] of a ciphertext without associated data. + pub const FORMAT_UNBOUND: u32 = 0; + + /// [`EncryptionMetadata::format_version`] of a job payload bound to its job. + pub const FORMAT_JOB_BOUND: u32 = 1; + + /// The [`EncryptionMetadata::format_version`] recorded in a stored metadata JSON + /// object (`0` when it is missing, as in payloads written by earlier versions). + pub fn format_version_from_json(metadata: &serde_json::Value) -> u32 { + metadata + .get("format_version") + .and_then(|v| v.as_u64()) + .map(|v| u32::try_from(v).unwrap_or(u32::MAX)) + .unwrap_or(Self::FORMAT_UNBOUND) + } + /// Creates new encryption metadata. /// /// # Arguments @@ -642,6 +670,7 @@ impl EncryptionMetadata { encrypted_at: now, delete_at, payload_hash, + format_version: Self::FORMAT_UNBOUND, } } diff --git a/src/encryption/engine.rs b/src/encryption/engine.rs index a7c831e..28f2fd6 100644 --- a/src/encryption/engine.rs +++ b/src/encryption/engine.rs @@ -20,7 +20,10 @@ use tracing::info; #[cfg(feature = "encryption")] use { - aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce, aead::Aead}, + aes_gcm::{ + Aes256Gcm, Key, KeyInit, Nonce, + aead::{Aead, Payload}, + }, base64::Engine, chacha20poly1305::{ChaCha20Poly1305, Key as ChaChaKey, Nonce as ChaChaNonce}, rand::{RngCore, rngs::OsRng}, @@ -628,7 +631,27 @@ impl EncryptionEngine { pii_fields: &[impl AsRef], retention_policy: RetentionPolicy, ) -> Result { - let result = self.encrypt_value(payload, pii_fields, retention_policy); + self.encrypt_payload_with_associated_data(payload, pii_fields, retention_policy, &[]) + .await + } + + /// Encrypts a payload and authenticates `associated_data` with it. + /// + /// The associated data is not stored: [`EncryptionEngine::decrypt_payload_with_associated_data`] + /// must be given the same bytes, or decryption fails. Use it to bind the ciphertext + /// to its context (for job payloads, [`JobQueue`](crate::JobQueue) binds it to the + /// job id, queue name, key id, algorithm and PII fields; see + /// [`job_payload`](super::job_payload)), so a ciphertext copied into another context + /// cannot be decrypted there. Empty associated data is the same as none + /// ([`EncryptionEngine::encrypt_payload_with_retention`]). + pub async fn encrypt_payload_with_associated_data( + &self, + payload: &Value, + pii_fields: &[impl AsRef], + retention_policy: RetentionPolicy, + associated_data: &[u8], + ) -> Result { + let result = self.encrypt_value(payload, pii_fields, retention_policy, associated_data); if result.is_err() && let Ok(mut stats) = self.stats.lock() { @@ -642,6 +665,7 @@ impl EncryptionEngine { payload: &Value, pii_fields: &[impl AsRef], retention_policy: RetentionPolicy, + associated_data: &[u8], ) -> Result { let start_time = Instant::now(); let key = self.active_key()?; @@ -659,7 +683,8 @@ impl EncryptionEngine { payload_bytes }; - let (ciphertext, nonce, tag) = self.encrypt_data(&key, &data_to_encrypt)?; + let (ciphertext, nonce, tag) = + self.encrypt_data(&key, &data_to_encrypt, associated_data)?; let pii_field_names: Vec = pii_fields.iter().map(|f| f.as_ref().to_string()).collect(); @@ -724,7 +749,21 @@ impl EncryptionEngine { &self, encrypted_payload: &EncryptedPayload, ) -> Result { - let result = self.decrypt_value(encrypted_payload); + self.decrypt_payload_with_associated_data(encrypted_payload, &[]) + .await + } + + /// Decrypts a payload encrypted by + /// [`EncryptionEngine::encrypt_payload_with_associated_data`]. + /// + /// Fails with [`EncryptionError::DecryptionFailed`] unless `associated_data` is + /// exactly the associated data the payload was encrypted with. + pub async fn decrypt_payload_with_associated_data( + &self, + encrypted_payload: &EncryptedPayload, + associated_data: &[u8], + ) -> Result { + let result = self.decrypt_value(encrypted_payload, associated_data); if result.is_err() && let Ok(mut stats) = self.stats.lock() { @@ -736,6 +775,7 @@ impl EncryptionEngine { fn decrypt_value( &self, encrypted_payload: &EncryptedPayload, + associated_data: &[u8], ) -> Result { let start_time = Instant::now(); let lock_error = @@ -774,7 +814,7 @@ impl EncryptionEngine { let mut first_error = None; let mut decrypted = None; for key in &candidates { - match self.decrypt_data(&ciphertext, &nonce, &tag, key, algorithm) { + match self.decrypt_data(&ciphertext, &nonce, &tag, key, algorithm, associated_data) { Ok(data) => { decrypted = Some((key, data)); break; @@ -969,7 +1009,9 @@ impl EncryptionEngine { &self, key: &[u8], data: &[u8], + aad: &[u8], ) -> Result<(Vec, Vec, Vec), EncryptionError> { + let payload = Payload { msg: data, aad }; check_key_size(key)?; match self.config.algorithm { EncryptionAlgorithm::AES256GCM => { @@ -982,7 +1024,7 @@ impl EncryptionEngine { let nonce = Nonce::from_slice(&nonce_bytes); // Encrypt the data - let ciphertext_with_tag = cipher.encrypt(nonce, data).map_err(|e| { + let ciphertext_with_tag = cipher.encrypt(nonce, payload).map_err(|e| { EncryptionError::EncryptionFailed(format!("AES encryption failed: {}", e)) })?; @@ -1003,7 +1045,7 @@ impl EncryptionEngine { let nonce = ChaChaNonce::from_slice(&nonce_bytes); // Encrypt the data - let ciphertext_with_tag = cipher.encrypt(nonce, data).map_err(|e| { + let ciphertext_with_tag = cipher.encrypt(nonce, payload).map_err(|e| { EncryptionError::EncryptionFailed(format!("ChaCha20 encryption failed: {}", e)) })?; @@ -1025,6 +1067,7 @@ impl EncryptionEngine { tag: &[u8], key: &[u8], algorithm: &EncryptionAlgorithm, + aad: &[u8], ) -> Result, EncryptionError> { // The nonce and tag come from storage: reject wrong sizes instead of panicking // in `from_slice`. @@ -1050,7 +1093,13 @@ impl EncryptionEngine { let nonce = Nonce::from_slice(nonce); cipher - .decrypt(nonce, ciphertext_with_tag.as_slice()) + .decrypt( + nonce, + Payload { + msg: ciphertext_with_tag.as_slice(), + aad, + }, + ) .map_err(|e| { EncryptionError::DecryptionFailed(format!("AES decryption failed: {}", e)) }) @@ -1061,7 +1110,13 @@ impl EncryptionEngine { let nonce = ChaChaNonce::from_slice(nonce); cipher - .decrypt(nonce, ciphertext_with_tag.as_slice()) + .decrypt( + nonce, + Payload { + msg: ciphertext_with_tag.as_slice(), + aad, + }, + ) .map_err(|e| { EncryptionError::DecryptionFailed(format!( "ChaCha20 decryption failed: {}", diff --git a/src/encryption/job_payload.rs b/src/encryption/job_payload.rs index 4f02d74..89e83c3 100644 --- a/src/encryption/job_payload.rs +++ b/src/encryption/job_payload.rs @@ -16,11 +16,72 @@ //! PII field names are paths into the JSON payload: `"ssn"` is a top-level field and //! `"customer.ssn"` the `ssn` field of the `customer` object. A key that itself contains a //! dot (`"a.b"`) is matched literally first. Fields missing from a payload are skipped. +//! +//! # Binding the ciphertext to its job +//! +//! The ciphertext is encrypted with associated data ([`job_associated_data`]) made of the +//! job's id, queue name, key id, algorithm, PII fields and encrypted fields, and the +//! metadata records [`EncryptionMetadata::FORMAT_JOB_BOUND`]. Decryption recomputes the +//! associated data from the stored row, so moving a ciphertext (or its nonce and tag) to +//! another job, moving a job to another queue, or changing its key id, algorithm or PII +//! fields makes decryption fail. All of these values are kept by archiving and restoring. +//! Setting the stored format back to [`EncryptionMetadata::FORMAT_UNBOUND`] does not help +//! an attacker either: the ciphertext then fails to authenticate without the associated +//! data it was encrypted with. +//! +//! Payloads written before this binding have format +//! [`EncryptionMetadata::FORMAT_UNBOUND`] and are still decrypted, without associated +//! data. They are not re-encrypted. -use super::{EncryptionEngine, EncryptionError, RetentionPolicy}; +use super::{ + EncryptionAlgorithm, EncryptionEngine, EncryptionError, EncryptionMetadata, RetentionPolicy, +}; use crate::job::Job; use serde_json::{Map, Value}; +/// Domain separation prefix of [`job_associated_data`]. +const JOB_AAD_CONTEXT: &[u8] = b"hammerwork/job-payload/v1"; + +/// The associated data that binds an encrypted job payload to its job +/// ([`EncryptionMetadata::FORMAT_JOB_BOUND`]). +/// +/// Each value is length-prefixed, so different values never encode to the same bytes: +/// a context string, the job id, queue name, key id, algorithm, the job's PII fields and +/// the fields that were actually encrypted (empty for whole-payload encryption). +pub fn job_associated_data( + job_id: &uuid::Uuid, + queue_name: &str, + key_id: &str, + algorithm: &EncryptionAlgorithm, + pii_fields: &[String], + encrypted_fields: &[String], +) -> Vec { + fn push(out: &mut Vec, bytes: &[u8]) { + out.extend_from_slice(&(bytes.len() as u64).to_be_bytes()); + out.extend_from_slice(bytes); + } + fn push_list(out: &mut Vec, items: &[String]) { + out.extend_from_slice(&(items.len() as u64).to_be_bytes()); + for item in items { + push(out, item.as_bytes()); + } + } + + let algorithm = match algorithm { + EncryptionAlgorithm::AES256GCM => "AES256GCM", + EncryptionAlgorithm::ChaCha20Poly1305 => "ChaCha20Poly1305", + }; + let mut out = Vec::with_capacity(128); + push(&mut out, JOB_AAD_CONTEXT); + push(&mut out, job_id.as_bytes()); + push(&mut out, queue_name.as_bytes()); + push(&mut out, key_id.as_bytes()); + push(&mut out, algorithm.as_bytes()); + push_list(&mut out, pii_fields); + push_list(&mut out, encrypted_fields); + out +} + /// The value stored in place of an encrypted PII field. pub const REDACTED_FIELD_VALUE: &str = "[ENCRYPTED]"; @@ -147,18 +208,34 @@ pub(crate) async fn seal_job( .clone() .unwrap_or(RetentionPolicy::UseDefault); - let (stored_payload, encrypted) = if job.pii_fields.is_empty() { + let aad = |encrypted_fields: &[String]| { + job_associated_data( + &job.id, + &job.queue_name, + engine.key_id(), + engine.algorithm(), + &job.pii_fields, + encrypted_fields, + ) + }; + let (stored_payload, mut encrypted) = if job.pii_fields.is_empty() { let encrypted = engine - .encrypt_payload_with_retention(&job.payload, &[] as &[&str], retention) + .encrypt_payload_with_associated_data( + &job.payload, + &[] as &[&str], + retention, + &aad(&[]), + ) .await?; (encrypted_payload_placeholder(), encrypted) } else { let (redacted, removed, found) = redact_fields(&job.payload, &job.pii_fields)?; let encrypted = engine - .encrypt_payload_with_retention(&removed, &found, retention) + .encrypt_payload_with_associated_data(&removed, &found, retention, &aad(&found)) .await?; (redacted, encrypted) }; + encrypted.metadata.format_version = EncryptionMetadata::FORMAT_JOB_BOUND; job.payload = stored_payload; job.is_encrypted = true; @@ -184,7 +261,30 @@ pub(crate) async fn open_job( )) })?; - let decrypted = engine.decrypt_payload(&encrypted).await?; + let metadata = &encrypted.metadata; + let decrypted = match metadata.format_version { + EncryptionMetadata::FORMAT_UNBOUND => engine.decrypt_payload(&encrypted).await?, + EncryptionMetadata::FORMAT_JOB_BOUND => { + let aad = job_associated_data( + &job.id, + &job.queue_name, + &metadata.key_id, + &metadata.algorithm, + &job.pii_fields, + &metadata.encrypted_fields, + ); + engine + .decrypt_payload_with_associated_data(&encrypted, &aad) + .await? + } + other => { + return Err(EncryptionError::DecryptionFailed(format!( + "Job {} has an encrypted payload in an unknown format ({}); it was written \ + by a newer version of hammerwork", + job.id, other + ))); + } + }; job.payload = if job.pii_fields.is_empty() { decrypted } else { @@ -422,6 +522,141 @@ mod tests { assert!(open_job(&engine, job).await.is_err()); } + async fn sealed(engine: &EncryptionEngine, queue: &str, payload: Value) -> Job { + let mut job = Job::new(queue.into(), payload) + .with_encryption(EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)); + seal_job(engine, &mut job).await.unwrap(); + job + } + + #[tokio::test] + async fn sealed_jobs_are_bound_to_their_job() { + let engine = engine("k1").await; + let job = sealed(&engine, "q", json!({"secret": 1})).await; + assert_eq!( + job.encrypted_payload + .as_ref() + .unwrap() + .metadata + .format_version, + EncryptionMetadata::FORMAT_JOB_BOUND + ); + assert!(open_job(&engine, job).await.is_ok()); + } + + #[tokio::test] + async fn swapped_ciphertexts_do_not_decrypt() { + let engine = engine("k1").await; + let mut a = sealed(&engine, "q", json!({"who": "a"})).await; + let mut b = sealed(&engine, "q", json!({"who": "b"})).await; + std::mem::swap(&mut a.encrypted_payload, &mut b.encrypted_payload); + for job in [a, b] { + assert!(matches!( + open_job(&engine, job).await, + Err(EncryptionError::DecryptionFailed(_)) + )); + } + } + + #[tokio::test] + async fn changed_queue_or_fields_do_not_decrypt() { + let engine = engine("k1").await; + let mut job = sealed(&engine, "q", json!({"secret": 1})).await; + job.queue_name = "other".into(); + assert!(open_job(&engine, job).await.is_err()); + + let mut job = Job::new("q".into(), json!({"ssn": "1", "name": "n"})) + .with_encryption(EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)) + .with_pii_fields(vec!["ssn"]); + seal_job(&engine, &mut job).await.unwrap(); + let mut renamed = job.clone(); + renamed.pii_fields = fields(&["name"]); + assert!(open_job(&engine, renamed).await.is_err()); + let mut whole = job.clone(); + whole.pii_fields.clear(); + assert!(open_job(&engine, whole).await.is_err()); + let mut listed = job.clone(); + listed + .encrypted_payload + .as_mut() + .unwrap() + .metadata + .encrypted_fields = fields(&["name"]); + assert!(open_job(&engine, listed).await.is_err()); + assert!(open_job(&engine, job).await.is_ok()); + } + + #[tokio::test] + async fn format_downgrade_does_not_decrypt() { + let engine = engine("k1").await; + let mut job = sealed(&engine, "q", json!({"secret": 1})).await; + job.encrypted_payload + .as_mut() + .unwrap() + .metadata + .format_version = EncryptionMetadata::FORMAT_UNBOUND; + assert!(open_job(&engine, job).await.is_err()); + + let mut job = sealed(&engine, "q", json!({"secret": 1})).await; + job.encrypted_payload + .as_mut() + .unwrap() + .metadata + .format_version = 99; + let err = open_job(&engine, job).await.unwrap_err(); + assert!(err.to_string().contains("unknown format"), "{err}"); + } + + #[tokio::test] + async fn legacy_unbound_payloads_still_decrypt() { + // What the previous release stored: no associated data, no format_version + let engine = engine("k1").await; + let payload = json!({"secret": "legacy"}); + let encrypted = engine + .encrypt_payload(&payload, &[] as &[&str]) + .await + .unwrap(); + let mut metadata = serde_json::to_value(&encrypted.metadata).unwrap(); + metadata.as_object_mut().unwrap().remove("format_version"); + assert_eq!( + EncryptionMetadata::format_version_from_json(&metadata), + EncryptionMetadata::FORMAT_UNBOUND + ); + let legacy: crate::encryption::EncryptedPayload = serde_json::from_value(json!({ + "ciphertext": encrypted.ciphertext, + "nonce": encrypted.nonce, + "tag": encrypted.tag, + "metadata": metadata, + })) + .unwrap(); + + let mut job = Job::new("q".into(), encrypted_payload_placeholder()); + job.is_encrypted = true; + job.encrypted_payload = Some(legacy); + assert_eq!(open_job(&engine, job).await.unwrap().payload, payload); + } + + #[test] + fn associated_data_is_unambiguous() { + let id = uuid::Uuid::new_v4(); + let alg = EncryptionAlgorithm::AES256GCM; + let a = job_associated_data(&id, "ab", "c", &alg, &[], &[]); + let b = job_associated_data(&id, "a", "bc", &alg, &[], &[]); + assert_ne!(a, b); + let c = job_associated_data(&id, "q", "k", &alg, &fields(&["x"]), &[]); + let d = job_associated_data(&id, "q", "k", &alg, &[], &fields(&["x"])); + assert_ne!(c, d); + let e = job_associated_data( + &id, + "q", + "k", + &EncryptionAlgorithm::ChaCha20Poly1305, + &[], + &[], + ); + assert_ne!(job_associated_data(&id, "q", "k", &alg, &[], &[]), e); + } + #[tokio::test] async fn plain_jobs_pass_through() { let engine = engine("k1").await; diff --git a/src/lib.rs b/src/lib.rs index 098a9bd..c2db6f0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -283,8 +283,8 @@ pub use archive::{ }; pub use batch::{BatchId, BatchResult, BatchStatus, JobBatch, PartialFailureMode}; pub use config::{ - ArchiveConfig, DatabaseConfig, HammerworkConfig, LoggingConfig, RateLimitingConfig, - WorkerConfig, + ArchiveConfig, DatabaseConfig, HammerworkConfig, KeySourceRef, LoggingConfig, + PayloadEncryptionAlgorithm, PayloadEncryptionConfig, RateLimitingConfig, WorkerConfig, }; #[cfg(any( diff --git a/src/queue/mod.rs b/src/queue/mod.rs index a321337..762edda 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -30,6 +30,9 @@ pub mod mysql; #[cfg(feature = "test")] pub mod test; +mod payload_encryption; +pub(crate) use payload_encryption::PayloadEncryption; + /// Information about a queue's pause state #[derive(Debug, Clone, Serialize, Deserialize)] pub struct QueuePauseInfo { @@ -1240,9 +1243,8 @@ pub struct JobQueue { pub pool: Pool, pub(crate) _phantom: PhantomData, pub(crate) throttle_configs: Arc>>, - /// Engine that encrypts the payloads of jobs with an encryption config - #[cfg(feature = "encryption")] - pub(crate) encryption: Option>, + /// Encrypts and decrypts job payloads (see [`JobQueue::with_encryption`]) + pub(crate) encryption: PayloadEncryption, } impl Clone for JobQueue { @@ -1251,7 +1253,6 @@ impl Clone for JobQueue { pool: self.pool.clone(), _phantom: PhantomData, throttle_configs: self.throttle_configs.clone(), - #[cfg(feature = "encryption")] encryption: self.encryption.clone(), } } @@ -1284,8 +1285,7 @@ impl JobQueue { pool, _phantom: PhantomData, throttle_configs: Arc::new(RwLock::new(HashMap::new())), - #[cfg(feature = "encryption")] - encryption: None, + encryption: PayloadEncryption::default(), } } @@ -1335,14 +1335,36 @@ impl JobQueue { mut self, engine: impl Into>, ) -> Self { - self.encryption = Some(engine.into()); + self.encryption.engine = Some(engine.into()); + self + } + + /// Encrypts every job enqueued to `queues` (`"*"` for all queues), even jobs without an + /// encryption config. + /// + /// Such a job is encrypted as if it had been created with + /// `Job::with_encryption(EncryptionConfig::new().with_key_id())`: + /// the whole payload, or only its [PII fields](crate::Job::with_pii_fields) if it has + /// any. Jobs with their own encryption config are unaffected. Needs an engine + /// ([`JobQueue::with_encryption`]); without one, enqueueing to these queues behaves as + /// if they were not listed. Replaces the queues set before. + /// + /// Set by [`JobQueue::from_config`](JobQueue#method.from_config) from + /// `encryption.encrypted_queues`. + #[cfg(feature = "encryption")] + pub fn with_encrypted_queues(mut self, queues: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.encryption.encrypted_queues = queues.into_iter().map(Into::into).collect(); self } /// The engine set with [`JobQueue::with_encryption`], if any. #[cfg(feature = "encryption")] pub fn encryption_engine(&self) -> Option<&Arc> { - self.encryption.as_ref() + self.encryption.engine.as_ref() } /// Encrypts the payloads of `jobs` that have an encryption config, before they are @@ -1350,26 +1372,7 @@ impl JobQueue { /// queue cannot provide. #[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) async fn seal_jobs(&self, jobs: &mut [Job]) -> Result<()> { - for job in jobs.iter_mut() { - if !job.has_encryption() || job.is_encrypted { - continue; - } - #[cfg(feature = "encryption")] - { - let engine = - self.encryption - .as_ref() - .ok_or_else(|| crate::HammerworkError::Encryption { - message: format!( - "Job {} has an encryption config but the queue has no encryption \ - engine; configure one with JobQueue::with_encryption", - job.id - ), - })?; - crate::encryption::job_payload::seal_job(engine, job).await?; - } - } - Ok(()) + self.encryption.seal(jobs).await } /// Returns `job` with its payload decrypted. @@ -1387,40 +1390,17 @@ impl JobQueue { /// [`HammerworkError::Encryption`](crate::HammerworkError::Encryption) when the job is /// encrypted and the queue has no encryption engine (or the `encryption` feature is /// disabled), the engine does not have the job's key, or decryption or the integrity - /// check fails. + /// check fails. Decryption also fails when the ciphertext does not belong to this job: + /// it was copied from another job, or the job was moved to another queue or had its + /// key id, algorithm or PII fields changed (see + /// [`encryption::job_payload`](crate::encryption::job_payload)). + /// + /// An archived job (as returned by `get_job` for a job in `hammerwork_jobs_archive`) + /// cannot be decrypted: its ciphertext stays in the archive table and is not loaded. + /// Restore it with [`DatabaseQueue::restore_archived_job`] and decrypt the restored + /// job. This fails with an error saying so. pub async fn decrypt_job(&self, job: Job) -> Result { - if !job.is_encrypted { - return Ok(job); - } - #[cfg(feature = "encryption")] - { - let engine = - self.encryption - .as_ref() - .ok_or_else(|| crate::HammerworkError::Encryption { - message: format!( - "Job {} has an encrypted payload but the queue has no encryption \ - engine; configure one with JobQueue::with_encryption", - job.id - ), - })?; - let job_id = job.id; - crate::encryption::job_payload::open_job(engine, job) - .await - .map_err(|e| crate::HammerworkError::Encryption { - message: format!("Cannot decrypt the payload of job {}: {}", job_id, e), - }) - } - #[cfg(not(feature = "encryption"))] - { - Err(crate::HammerworkError::Encryption { - message: format!( - "Job {} has an encrypted payload; decrypting it needs the `encryption` \ - feature and an encryption engine (JobQueue::with_encryption)", - job.id - ), - }) - } + self.encryption.open(job).await } /// Set throttling configuration for a specific queue. @@ -1546,13 +1526,85 @@ impl JobQueue { #[cfg(any(feature = "postgres", feature = "mysql"))] use crate::config::HammerworkConfig; +#[cfg(all(any(feature = "postgres", feature = "mysql"), feature = "encryption"))] +impl JobQueue { + /// Sets up payload encryption from an `[encryption]` configuration section. + /// + /// When `config.enabled`, builds an `EncryptionEngine` with the configured + /// algorithm, key source, key id, compression and default retention (with + /// `EncryptionEngine::new_with_pool`, so `aws://` and `gcp://` keys work), adds the + /// decrypt-only `decryption_keys`, and sets it with `JobQueue::with_encryption` and + /// `encrypted_queues` with `JobQueue::with_encrypted_queues`. Does nothing when the + /// section is disabled. Called by `from_config`. + /// + /// Fails closed: an invalid section, a key that cannot be loaded, or an enabled + /// section in a build without the `encryption` feature is an error, never a queue + /// that silently stores plaintext. + pub async fn apply_encryption_config( + self, + config: &crate::config::PayloadEncryptionConfig, + ) -> Result { + config.validate()?; + if !config.enabled { + return Ok(self); + } + let mut engine = crate::encryption::EncryptionEngine::new_with_pool( + config.encryption_config()?, + &self.pool, + ) + .await?; + for (key_id, source) in &config.decryption_keys { + engine = engine + .with_decryption_key(key_id.clone(), &source.key_source()) + .await?; + } + Ok(self + .with_encryption(engine) + .with_encrypted_queues(config.encrypted_queues.iter().cloned())) + } +} + +#[cfg(all( + any(feature = "postgres", feature = "mysql"), + not(feature = "encryption") +))] +impl JobQueue { + /// Sets up payload encryption from an `[encryption]` configuration section. + /// + /// When `config.enabled`, builds an `EncryptionEngine` with the configured + /// algorithm, key source, key id, compression and default retention (with + /// `EncryptionEngine::new_with_pool`, so `aws://` and `gcp://` keys work), adds the + /// decrypt-only `decryption_keys`, and sets it with `JobQueue::with_encryption` and + /// `encrypted_queues` with `JobQueue::with_encrypted_queues`. Does nothing when the + /// section is disabled. Called by `from_config`. + /// + /// Fails closed: an invalid section, a key that cannot be loaded, or an enabled + /// section in a build without the `encryption` feature is an error, never a queue + /// that silently stores plaintext. + pub async fn apply_encryption_config( + self, + config: &crate::config::PayloadEncryptionConfig, + ) -> Result { + config.validate()?; + if !config.enabled { + return Ok(self); + } + Err(crate::HammerworkError::Config( + "encryption.enabled is set but hammerwork was built without the `encryption` \ + feature" + .to_string(), + )) + } +} + #[cfg(feature = "postgres")] impl JobQueue { /// Connect to PostgreSQL using a [`HammerworkConfig`]. /// /// Uses `database.url`, `database.pool_size` and `database.connection_timeout_secs` - /// to build the pool, runs migrations when `database.auto_migrate` is set, and - /// registers the per-queue throttles from `rate_limiting`. + /// to build the pool, runs migrations when `database.auto_migrate` is set, + /// registers the per-queue throttles from `rate_limiting`, and sets up payload + /// encryption from `encryption` (see `JobQueue::apply_encryption_config`). /// /// # Examples /// @@ -1579,7 +1631,9 @@ impl JobQueue { .await?; } - let queue = Self::new(pool); + let queue = Self::new(pool) + .apply_encryption_config(&config.encryption) + .await?; queue .apply_rate_limiting_config(&config.rate_limiting) .await?; @@ -1592,8 +1646,9 @@ impl JobQueue { /// Connect to MySQL using a [`HammerworkConfig`]. /// /// Uses `database.url`, `database.pool_size` and `database.connection_timeout_secs` - /// to build the pool, runs migrations when `database.auto_migrate` is set, and - /// registers the per-queue throttles from `rate_limiting`. + /// to build the pool, runs migrations when `database.auto_migrate` is set, + /// registers the per-queue throttles from `rate_limiting`, and sets up payload + /// encryption from `encryption` (see `JobQueue::apply_encryption_config`). /// /// # Examples /// @@ -1620,7 +1675,9 @@ impl JobQueue { .await?; } - let queue = Self::new(pool); + let queue = Self::new(pool) + .apply_encryption_config(&config.encryption) + .await?; queue .apply_rate_limiting_config(&config.rate_limiting) .await?; diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index 60d221b..8e63309 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -512,6 +512,9 @@ impl JobRow { encrypted_at, delete_at: self.retention_delete_at, payload_hash: self.payload_hash.clone().unwrap_or_default(), + format_version: crate::encryption::EncryptionMetadata::format_version_from_json( + metadata_json, + ), } } else { // Build basic metadata from available fields @@ -538,6 +541,7 @@ impl JobRow { encrypted_at: self.encrypted_at.unwrap_or(self.created_at), delete_at: self.retention_delete_at, payload_hash: self.payload_hash.clone().unwrap_or_default(), + format_version: crate::encryption::EncryptionMetadata::FORMAT_UNBOUND, } }; diff --git a/src/queue/payload_encryption.rs b/src/queue/payload_encryption.rs new file mode 100644 index 0000000..32e2405 --- /dev/null +++ b/src/queue/payload_encryption.rs @@ -0,0 +1,139 @@ +//! Payload encryption shared by [`JobQueue`](super::JobQueue) and the in-memory +//! `TestQueue`: sealing jobs before they are stored and opening them for a handler. + +use crate::{ + HammerworkError, Result, + job::{Job, JobStatus}, +}; +#[cfg(feature = "encryption")] +use std::sync::Arc; + +/// The encryption engine of a queue and the queues whose jobs it encrypts by default. +#[derive(Clone, Default)] +pub(crate) struct PayloadEncryption { + #[cfg(feature = "encryption")] + pub(crate) engine: Option>, + /// Queues whose jobs are encrypted even without an encryption config (`"*"`: all) + #[cfg(feature = "encryption")] + pub(crate) encrypted_queues: Vec, +} + +impl std::fmt::Debug for PayloadEncryption { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut s = f.debug_struct("PayloadEncryption"); + #[cfg(feature = "encryption")] + s.field("engine", &self.engine) + .field("encrypted_queues", &self.encrypted_queues); + s.finish() + } +} + +impl PayloadEncryption { + /// Whether jobs on `queue_name` are encrypted without an encryption config. + #[cfg(feature = "encryption")] + fn encrypts_queue(&self, queue_name: &str) -> bool { + self.encrypted_queues + .iter() + .any(|queue| queue == "*" || queue == queue_name) + } + + /// Encrypts the payloads of `jobs` that need it, before they are written. Fails (and + /// nothing should be written) if a job needs encryption that cannot be provided. + /// + /// A job needs encryption when it has an encryption config, or when its queue is one + /// of `encrypted_queues` (it then gets the engine's algorithm and key id). + pub(crate) async fn seal(&self, jobs: &mut [Job]) -> Result<()> { + for job in jobs.iter_mut() { + if job.is_encrypted { + continue; + } + #[cfg(feature = "encryption")] + if job.encryption_config.is_none() + && let Some(engine) = &self.engine + && self.encrypts_queue(&job.queue_name) + { + let config = engine.config(); + let mut job_config = + crate::encryption::EncryptionConfig::new(config.algorithm.clone()) + .with_key_id(engine.key_id()); + job_config.compression_enabled = config.compression_enabled; + job.encryption_config = Some(job_config); + } + if !job.has_encryption() { + continue; + } + #[cfg(feature = "encryption")] + { + let engine = self + .engine + .as_ref() + .ok_or_else(|| HammerworkError::Encryption { + message: format!( + "Job {} has an encryption config but the queue has no encryption \ + engine; configure one with JobQueue::with_encryption", + job.id + ), + })?; + crate::encryption::job_payload::seal_job(engine, job).await?; + } + } + Ok(()) + } + + /// Returns `job` with its payload decrypted (see `JobQueue::decrypt_job`). + pub(crate) async fn open(&self, job: Job) -> Result { + if !job.is_encrypted { + return Ok(job); + } + if job.status == JobStatus::Archived && !has_ciphertext(&job) { + return Err(HammerworkError::Encryption { + message: format!( + "Job {} is archived and its ciphertext stays in the archive; restore it \ + with restore_archived_job and decrypt the restored job", + job.id + ), + }); + } + #[cfg(feature = "encryption")] + { + let engine = self + .engine + .as_ref() + .ok_or_else(|| HammerworkError::Encryption { + message: format!( + "Job {} has an encrypted payload but the queue has no encryption \ + engine; configure one with JobQueue::with_encryption", + job.id + ), + })?; + let job_id = job.id; + crate::encryption::job_payload::open_job(engine, job) + .await + .map_err(|e| HammerworkError::Encryption { + message: format!("Cannot decrypt the payload of job {}: {}", job_id, e), + }) + } + #[cfg(not(feature = "encryption"))] + { + Err(HammerworkError::Encryption { + message: format!( + "Job {} has an encrypted payload; decrypting it needs the `encryption` \ + feature and an encryption engine (JobQueue::with_encryption)", + job.id + ), + }) + } + } +} + +/// Whether `job` carries its ciphertext. +fn has_ciphertext(#[allow(unused_variables)] job: &Job) -> bool { + #[cfg(feature = "encryption")] + { + job.encrypted_payload.is_some() + } + #[cfg(not(feature = "encryption"))] + { + false + } +} diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 483dcce..10ddc74 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -497,6 +497,9 @@ impl JobRow { encrypted_at, delete_at: self.retention_delete_at, payload_hash: self.payload_hash.clone().unwrap_or_default(), + format_version: crate::encryption::EncryptionMetadata::format_version_from_json( + metadata_json, + ), } } else { // Build basic metadata from available fields @@ -523,6 +526,7 @@ impl JobRow { encrypted_at: self.encrypted_at.unwrap_or(self.created_at), delete_at: self.retention_delete_at, payload_hash: self.payload_hash.clone().unwrap_or_default(), + format_version: crate::encryption::EncryptionMetadata::FORMAT_UNBOUND, } }; diff --git a/src/queue/test.rs b/src/queue/test.rs index fd90f45..0cfeac6 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -41,7 +41,7 @@ use crate::{ batch::{BatchId, BatchResult, BatchStatus, JobBatch}, job::{Job, JobId, JobStatus}, priority::{JobPriority, PriorityWeights}, - queue::{DatabaseQueue, QueuePauseInfo}, + queue::{DatabaseQueue, PayloadEncryption, QueuePauseInfo}, rate_limit::ThrottleConfig, stats::{DeadJobSummary, QueueStats}, workflow::{JobGroup, WorkflowId, WorkflowStatus}, @@ -553,6 +553,7 @@ impl TestStorage { pub struct TestQueue { storage: Arc>, clock: MockClock, + encryption: PayloadEncryption, } impl TestQueue { @@ -574,6 +575,7 @@ impl TestQueue { Self { storage: Arc::new(RwLock::new(TestStorage::new(clock.clone()))), clock, + encryption: PayloadEncryption::default(), } } @@ -607,6 +609,7 @@ impl TestQueue { Self { storage: Arc::new(RwLock::new(TestStorage::new(clock.clone()))), clock, + encryption: PayloadEncryption::default(), } } @@ -635,6 +638,81 @@ impl TestQueue { &self.clock } + /// Encrypts job payloads with `engine`, like + /// [`JobQueue::with_encryption`](crate::JobQueue::with_encryption). + /// + /// The in-memory queue then applies the same encryption semantics as the database + /// backends, so unit tests exercise them: jobs with an encryption config are stored + /// sealed (redacted `payload`, `is_encrypted`, ciphertext in `encrypted_payload`) and + /// returned that way by `dequeue` and `get_job`; [`TestQueue::decrypt_job`] opens them + /// like a worker does; enqueueing a job with an encryption config fails without an + /// engine; and [`DatabaseQueue::purge_expired_encrypted_jobs`] enforces retention + /// against the queue's [`MockClock`]. + /// + /// # Examples + /// + /// ```rust + /// # #[cfg(feature = "encryption")] + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// use hammerwork::encryption::{EncryptionAlgorithm, EncryptionConfig, EncryptionEngine, KeySource}; + /// use hammerwork::queue::test::TestQueue; + /// use hammerwork::{Job, queue::DatabaseQueue}; + /// use serde_json::json; + /// + /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM).with_key_source( + /// KeySource::Static("QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUE=".to_string()), + /// ); + /// let queue = TestQueue::new().with_encryption(EncryptionEngine::new(config.clone()).await?); + /// + /// let job = Job::new("payments".to_string(), json!({"card": "4111", "amount": 10})) + /// .with_encryption(config) + /// .with_pii_fields(vec!["card"]); + /// let id = queue.enqueue(job).await?; + /// + /// let stored = queue.get_job(id).await?.unwrap(); + /// assert_eq!(stored.payload, json!({"card": "[ENCRYPTED]", "amount": 10})); + /// let opened = queue.decrypt_job(stored).await?; + /// assert_eq!(opened.payload, json!({"card": "4111", "amount": 10})); + /// # Ok(()) + /// # } + /// # #[cfg(not(feature = "encryption"))] + /// # fn main() {} + /// ``` + #[cfg(feature = "encryption")] + pub fn with_encryption( + mut self, + engine: impl Into>, + ) -> Self { + self.encryption.engine = Some(engine.into()); + self + } + + /// Encrypts every job enqueued to `queues` (`"*"` for all), like + /// [`JobQueue::with_encrypted_queues`](crate::JobQueue::with_encrypted_queues). + #[cfg(feature = "encryption")] + pub fn with_encrypted_queues(mut self, queues: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.encryption.encrypted_queues = queues.into_iter().map(Into::into).collect(); + self + } + + /// The engine set with [`TestQueue::with_encryption`], if any. + #[cfg(feature = "encryption")] + pub fn encryption_engine(&self) -> Option<&Arc> { + self.encryption.engine.as_ref() + } + + /// Returns `job` with its payload decrypted, like + /// [`JobQueue::decrypt_job`](crate::JobQueue::decrypt_job) (which workers call just + /// before the handler). Unencrypted jobs are returned unchanged. + pub async fn decrypt_job(&self, job: Job) -> Result { + self.encryption.open(job).await + } + /// Get the number of jobs in a specific status for a queue. /// /// This is a testing utility that helps you verify the state of your @@ -750,6 +828,7 @@ impl DatabaseQueue for TestQueue { type Database = TestDatabaseType; async fn enqueue(&self, mut job: Job) -> Result { + self.encryption.seal(std::slice::from_mut(&mut job)).await?; let mut storage = self.storage.write().await; // Set timestamps using the mock clock @@ -968,7 +1047,17 @@ impl DatabaseQueue for TestQueue { async fn get_job(&self, job_id: JobId) -> Result> { let storage = self.storage.read().await; - Ok(storage.jobs.get(&job_id).cloned()) + #[cfg_attr(not(feature = "encryption"), allow(unused_mut))] + let mut job = storage.jobs.get(&job_id).cloned(); + // Like the database backends: the ciphertext of an archived job stays in the + // archive and is not loaded, so it must be restored to be decrypted. + #[cfg(feature = "encryption")] + if let Some(job) = job.as_mut() + && job.status == JobStatus::Archived + { + job.encrypted_payload = None; + } + Ok(job) } async fn delete_job(&self, job_id: JobId) -> Result<()> { @@ -1005,6 +1094,7 @@ impl DatabaseQueue for TestQueue { // Batch operations async fn enqueue_batch(&self, mut batch: JobBatch) -> Result { + self.encryption.seal(&mut batch.jobs).await?; let mut storage = self.storage.write().await; batch.created_at = storage.clock.now(); @@ -1940,6 +2030,7 @@ impl DatabaseQueue for TestQueue { // Workflow and dependency management async fn enqueue_workflow(&self, mut workflow: JobGroup) -> Result { + self.encryption.seal(&mut workflow.jobs).await?; let mut storage = self.storage.write().await; workflow.created_at = storage.clock.now(); @@ -2549,6 +2640,48 @@ impl DatabaseQueue for TestQueue { Ok(recovery) } + + async fn purge_expired_encrypted_jobs(&self) -> Result { + #[cfg_attr(not(feature = "encryption"), allow(unused_mut))] + let mut purge = super::EncryptedJobPurge::default(); + #[cfg(feature = "encryption")] + { + let storage = self.storage.read().await; + let now = storage.clock.now(); + let expired: Vec<(JobId, bool)> = storage + .jobs + .values() + .filter(|job| job.is_encrypted) + .filter(|job| { + matches!( + job.status, + JobStatus::Completed + | JobStatus::Failed + | JobStatus::Dead + | JobStatus::TimedOut + | JobStatus::Archived + ) + }) + .filter(|job| { + job.encrypted_payload + .as_ref() + .and_then(|encrypted| encrypted.metadata.delete_at) + .is_some_and(|delete_at| delete_at <= now) + }) + .map(|job| (job.id, job.status == JobStatus::Archived)) + .collect(); + drop(storage); + for (job_id, archived) in expired { + self.delete_job(job_id).await?; + if archived { + purge.archived_jobs += 1; + } else { + purge.jobs += 1; + } + } + } + Ok(purge) + } } #[cfg(test)] @@ -2970,4 +3103,234 @@ mod tests { .unwrap() ); } + + #[cfg(feature = "encryption")] + mod encryption { + use super::*; + use crate::archive::{ArchivalConfig, ArchivalPolicy, ArchivalReason}; + use crate::encryption::{ + EncryptionAlgorithm, EncryptionConfig, EncryptionEngine, KeySource, RetentionPolicy, + }; + + const KEY: &str = "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUE="; + + fn config() -> EncryptionConfig { + EncryptionConfig::new(EncryptionAlgorithm::AES256GCM) + .with_key_id("k1") + .with_key_source(KeySource::Static(KEY.to_string())) + } + + async fn encrypted_queue() -> TestQueue { + TestQueue::new().with_encryption(EncryptionEngine::new(config()).await.unwrap()) + } + + #[tokio::test] + async fn jobs_are_stored_sealed_and_decrypt() { + let queue = encrypted_queue().await; + let payload = json!({"ssn": "123-45-6789", "amount": 5}); + let id = queue + .enqueue( + Job::new("q".into(), payload.clone()) + .with_encryption(config()) + .with_pii_fields(vec!["ssn"]), + ) + .await + .unwrap(); + + let stored = queue.get_job(id).await.unwrap().unwrap(); + assert!(stored.is_encrypted); + assert_eq!(stored.payload, json!({"ssn": "[ENCRYPTED]", "amount": 5})); + assert!(stored.encrypted_payload.is_some()); + + let dequeued = queue.dequeue("q").await.unwrap().unwrap(); + assert_eq!( + dequeued.payload, stored.payload, + "dequeue returns the stored form" + ); + let opened = queue.decrypt_job(dequeued).await.unwrap(); + assert!(!opened.is_encrypted); + assert_eq!(opened.payload, payload); + + // Unencrypted jobs pass through + let plain = queue + .enqueue(Job::new("q".into(), json!({"a": 1}))) + .await + .unwrap(); + let plain = queue.get_job(plain).await.unwrap().unwrap(); + assert_eq!( + queue.decrypt_job(plain).await.unwrap().payload, + json!({"a": 1}) + ); + } + + #[tokio::test] + async fn batch_and_workflow_are_sealed() { + let queue = encrypted_queue().await; + let job = || Job::new("q".into(), json!({"secret": 1})).with_encryption(config()); + let batch = JobBatch::new("b").with_jobs(vec![job(), job()]); + let batch_id = queue.enqueue_batch(batch).await.unwrap(); + for stored in queue.get_batch_jobs(batch_id).await.unwrap() { + assert!(stored.is_encrypted); + assert_eq!(stored.payload, json!({"encrypted": true})); + } + + let workflow = JobGroup::new("w").add_job(job()); + let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); + for stored in queue.get_workflow_jobs(workflow_id).await.unwrap() { + assert!(stored.is_encrypted); + assert_eq!( + queue.decrypt_job(stored).await.unwrap().payload, + json!({"secret": 1}) + ); + } + } + + #[tokio::test] + async fn fails_closed_without_an_engine() { + let queue = TestQueue::new(); + let err = queue + .enqueue(Job::new("q".into(), json!({"secret": 1})).with_encryption(config())) + .await + .unwrap_err(); + assert!(matches!(err, HammerworkError::Encryption { .. }), "{err}"); + assert!(queue.get_all_jobs().await.is_empty(), "nothing is stored"); + + // A sealed job cannot be opened by a queue without the engine + let sealed = encrypted_queue().await; + let id = sealed + .enqueue(Job::new("q".into(), json!({"secret": 1})).with_encryption(config())) + .await + .unwrap(); + let stored = sealed.get_job(id).await.unwrap().unwrap(); + assert!(queue.decrypt_job(stored).await.is_err()); + } + + #[tokio::test] + async fn tampering_is_detected() { + let queue = encrypted_queue().await; + let a = queue + .enqueue(Job::new("q".into(), json!({"who": "a"})).with_encryption(config())) + .await + .unwrap(); + let b = queue + .enqueue(Job::new("q".into(), json!({"who": "b"})).with_encryption(config())) + .await + .unwrap(); + let mut job_a = queue.get_job(a).await.unwrap().unwrap(); + let job_b = queue.get_job(b).await.unwrap().unwrap(); + job_a.encrypted_payload = job_b.encrypted_payload.clone(); + assert!(queue.decrypt_job(job_a).await.is_err()); + + let mut moved = job_b; + moved.queue_name = "other".into(); + assert!(queue.decrypt_job(moved).await.is_err()); + } + + #[tokio::test] + async fn encrypted_queues_encrypt_without_a_job_config() { + let queue = encrypted_queue().await.with_encrypted_queues(["secure"]); + let id = queue + .enqueue(Job::new("secure".into(), json!({"secret": 1}))) + .await + .unwrap(); + let stored = queue.get_job(id).await.unwrap().unwrap(); + assert!(stored.is_encrypted); + assert_eq!( + queue.decrypt_job(stored).await.unwrap().payload, + json!({"secret": 1}) + ); + + let other = queue + .enqueue(Job::new("open".into(), json!({"visible": 1}))) + .await + .unwrap(); + assert!(!queue.get_job(other).await.unwrap().unwrap().is_encrypted); + + let all = encrypted_queue().await.with_encrypted_queues(["*"]); + let id = all + .enqueue(Job::new("any".into(), json!({"ssn": "1"})).with_pii_fields(vec!["ssn"])) + .await + .unwrap(); + let stored = all.get_job(id).await.unwrap().unwrap(); + assert_eq!(stored.payload, json!({"ssn": "[ENCRYPTED]"})); + } + + #[tokio::test] + async fn archived_jobs_must_be_restored_to_decrypt() { + let queue = encrypted_queue().await; + let id = queue + .enqueue(Job::new("q".into(), json!({"secret": 1})).with_encryption(config())) + .await + .unwrap(); + queue.dequeue("q").await.unwrap(); + queue.complete_job(id).await.unwrap(); + queue.clock().advance(chrono::Duration::seconds(10)); + let stats = queue + .archive_jobs( + Some("q"), + &ArchivalPolicy::new() + .archive_completed_after(chrono::Duration::seconds(0)) + .enabled(true), + &ArchivalConfig::new(), + ArchivalReason::Manual, + None, + ) + .await + .unwrap(); + assert_eq!(stats.jobs_archived, 1); + + let archived = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(archived.status, JobStatus::Archived); + assert!(archived.is_encrypted); + let err = queue.decrypt_job(archived).await.unwrap_err(); + assert!(err.to_string().contains("restore_archived_job"), "{err}"); + + queue.restore_archived_job(id).await.unwrap(); + let restored = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!( + queue.decrypt_job(restored).await.unwrap().payload, + json!({"secret": 1}) + ); + } + + #[tokio::test] + async fn retention_purge_uses_the_mock_clock() { + let queue = encrypted_queue().await; + let enqueue = |policy: RetentionPolicy| { + let queue = queue.clone(); + async move { + queue + .enqueue( + Job::new("q".into(), json!({"secret": 1})) + .with_encryption(config()) + .with_retention_policy(policy), + ) + .await + .unwrap() + } + }; + let hour = RetentionPolicy::DeleteAfter(std::time::Duration::from_secs(3600)); + let done = enqueue(hour.clone()).await; + let pending = enqueue(hour).await; + let kept = enqueue(RetentionPolicy::KeepIndefinitely).await; + for id in [done, kept] { + queue.complete_job(id).await.unwrap(); + } + + assert_eq!( + queue.purge_expired_encrypted_jobs().await.unwrap().total(), + 0, + "nothing has expired yet" + ); + queue.clock().advance(chrono::Duration::hours(2)); + let purge = queue.purge_expired_encrypted_jobs().await.unwrap(); + assert_eq!(purge.jobs, 1); + assert!(queue.get_job(done).await.unwrap().is_none()); + assert!( + queue.get_job(pending).await.unwrap().is_some(), + "not finished" + ); + assert!(queue.get_job(kept).await.unwrap().is_some()); + } + } } diff --git a/src/worker.rs b/src/worker.rs index 34519ee..c8c293f 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -2681,6 +2681,13 @@ where /// [`DatabaseQueue::requeue_stale_jobs`] to reclaim jobs left `Running` by workers /// that crashed. Configure it with [`WorkerPool::with_stale_job_reaper`] or disable it /// with [`WorkerPool::without_stale_job_reaper`]. +/// +/// Optionally, the pool also enforces the retention of encrypted jobs by calling +/// [`DatabaseQueue::purge_expired_encrypted_jobs`] periodically +/// ([`WorkerPool::with_encrypted_job_purge`]). +/// +/// These maintenance tasks run each pass in its own task, so shutting the pool down +/// never cancels a pass part-way through its database transaction. pub struct WorkerPool { workers: Vec>, /// Signals shutdown to the supervisor started by `start` (dropping it also does) @@ -2692,6 +2699,8 @@ pub struct WorkerPool { /// Fallback staleness threshold for jobs without a lease (`None`: the longest /// worker lease duration) reaper_older_than: Option, + /// How often encrypted jobs whose retention ended are purged (`None`: never) + encrypted_job_purge_interval: Option, stats_collector: Option>, /// Worker template for creating new workers during autoscaling worker_template: Option>, @@ -2716,6 +2725,7 @@ where supervisor_done: None, reaper_interval: Some(DEFAULT_STALE_JOB_REAPER_INTERVAL), reaper_older_than: None, + encrypted_job_purge_interval: None, stats_collector: None, worker_template: None, autoscale_config: AutoscaleConfig::default(), @@ -2742,6 +2752,21 @@ where pool } + /// Build a pool from a [`HammerworkConfig`](crate::config::HammerworkConfig). + /// + /// Like [`WorkerPool::from_config`] with `config.worker`, and also schedules the + /// encrypted job retention purge every `encryption.purge_interval_secs`, when set + /// ([`WorkerPool::with_encrypted_job_purge`]). Validates the `encryption` section. + pub fn from_hammerwork_config( + worker: Worker, + config: &crate::config::HammerworkConfig, + ) -> Result { + config.encryption.validate()?; + let mut pool = Self::from_config(worker, &config.worker); + pool.encrypted_job_purge_interval = config.encryption.purge_interval(); + Ok(pool) + } + pub fn with_stats_collector(mut self, stats_collector: Arc) -> Self { self.stats_collector = Some(stats_collector); self @@ -2783,6 +2808,27 @@ where self } + /// Purge encrypted jobs whose retention period ended every `interval`. + /// + /// The pool calls [`DatabaseQueue::purge_expired_encrypted_jobs`], which deletes + /// finished encrypted jobs (and archived ones) past their `retention_delete_at`; it + /// needs no encryption key. Off by default: without it, run + /// `cargo hammerwork maintenance purge-encrypted` on a schedule. Running purges in + /// several pools or processes at once is safe. + /// + /// The first purge runs when the pool starts. Each purge runs in its own task, so + /// shutting the pool down never cancels one part-way through its transaction. + pub fn with_encrypted_job_purge(mut self, interval: Duration) -> Self { + self.encrypted_job_purge_interval = Some(interval); + self + } + + /// Disable the encrypted job retention purge (the default). + pub fn without_encrypted_job_purge(mut self) -> Self { + self.encrypted_job_purge_interval = None; + self + } + /// Set a worker template for autoscaling /// This worker will be cloned when creating new workers pub fn with_worker_template(mut self, worker: Worker) -> Self { @@ -2827,14 +2873,20 @@ where self.supervisor_done = Some(done_rx); let workers = std::mem::take(&mut self.workers); - let reaper = self.start_stale_job_reaper(&workers, signal_rx.clone()); + let maintenance: Vec> = [ + self.start_stale_job_reaper(&workers, signal_rx.clone()), + self.start_encrypted_job_purge(&workers, signal_rx.clone()), + ] + .into_iter() + .flatten() + .collect(); // Start autoscaling task if enabled if self.autoscale_config.enabled { self.start_autoscaling_task().await?; } - let supervisor = tokio::spawn(Self::supervise(workers, signal_rx, done_tx, reaper)); + let supervisor = tokio::spawn(Self::supervise(workers, signal_rx, done_tx, maintenance)); // Dropping a JoinHandle detaches the task, so the supervisor keeps running // even if this future is dropped. @@ -2870,7 +2922,7 @@ where workers: Vec>, mut signal_rx: watch::Receiver, done_tx: watch::Sender, - reaper: Option>, + maintenance: Vec>, ) -> Result<()> { let templates: Vec> = workers.to_vec(); let mut set = JoinSet::new(); @@ -2939,8 +2991,9 @@ where } } - if let Some(reaper) = reaper { - reaper.abort(); + // Stops the maintenance loops; a pass already running finishes in its own task + for task in maintenance { + task.abort(); } info!("All workers stopped"); done_tx.send_replace(true); @@ -2951,7 +3004,7 @@ where fn start_stale_job_reaper( &self, workers: &[Worker], - mut signal_rx: watch::Receiver, + signal_rx: watch::Receiver, ) -> Option> { let interval = self.reaper_interval?; let queue = Arc::clone(&workers.first()?.queue); @@ -2964,23 +3017,40 @@ where .unwrap_or(DEFAULT_LEASE_DURATION) }); - Some(tokio::spawn(async move { - let mut ticker = tokio::time::interval(interval.max(Duration::from_millis(1))); - ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - loop { - tokio::select! { - _ = signal_rx.changed() => break, - _ = ticker.tick() => { - match queue.requeue_stale_jobs(older_than).await { - Ok(recovery) if !recovery.is_empty() => info!( - "Stale job reaper requeued {} and marked {} dead", - recovery.requeued.len(), - recovery.dead.len() - ), - Ok(_) => {} - Err(e) => warn!("Stale job reaper failed: {}", e), - } - } + Some(spawn_periodic(interval, signal_rx, move || { + let queue = Arc::clone(&queue); + async move { + match queue.requeue_stale_jobs(older_than).await { + Ok(recovery) if !recovery.is_empty() => info!( + "Stale job reaper requeued {} and marked {} dead", + recovery.requeued.len(), + recovery.dead.len() + ), + Ok(_) => {} + Err(e) => warn!("Stale job reaper failed: {}", e), + } + } + })) + } + + /// Spawn the periodic encrypted job retention purge, if enabled. + fn start_encrypted_job_purge( + &self, + workers: &[Worker], + signal_rx: watch::Receiver, + ) -> Option> { + let interval = self.encrypted_job_purge_interval?; + let queue = Arc::clone(&workers.first()?.queue); + Some(spawn_periodic(interval, signal_rx, move || { + let queue = Arc::clone(&queue); + async move { + match queue.purge_expired_encrypted_jobs().await { + Ok(purge) if purge.total() > 0 => info!( + "Encrypted job purge deleted {} jobs and {} archived jobs", + purge.jobs, purge.archived_jobs + ), + Ok(_) => {} + Err(e) => warn!("Encrypted job purge failed: {}", e), } } })) @@ -3197,6 +3267,41 @@ where } } +/// Spawn a task that calls `run` every `interval` (first right away) until shutdown is +/// signalled on `signal_rx` (or its sender is dropped). +/// +/// Each run is spawned as its own task and awaited, so neither the shutdown signal nor +/// aborting the returned handle cancels a run part-way: database work always reaches +/// commit or rollback instead of leaving a pooled connection inside a transaction. +fn spawn_periodic( + interval: Duration, + mut signal_rx: watch::Receiver, + run: F, +) -> tokio::task::JoinHandle<()> +where + F: Fn() -> Fut + Send + 'static, + Fut: std::future::Future + Send + 'static, +{ + tokio::spawn(async move { + let mut ticker = tokio::time::interval(interval.max(Duration::from_millis(1))); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tokio::select! { + _ = signal_rx.changed() => break, + _ = ticker.tick() => {} + } + if *signal_rx.borrow() { + break; + } + if let Err(e) = tokio::spawn(run()).await + && e.is_panic() + { + error!("Periodic maintenance task panicked: {}", e); + } + } + }) +} + impl Drop for WorkerPool { fn drop(&mut self) { // Stop autoscaling task when dropping the pool @@ -4104,4 +4209,78 @@ mod tests { let payload = CatchUnwind { inner: formatted }.await.unwrap_err(); assert_eq!(panic_message(payload.as_ref()), "code 42"); } + + #[tokio::test] + async fn spawn_periodic_runs_until_shutdown() { + let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (signal_tx, signal_rx) = watch::channel(false); + let counter = Arc::clone(&runs); + let task = spawn_periodic(Duration::from_millis(10), signal_rx, move || { + let counter = Arc::clone(&counter); + async move { + counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + }); + tokio::time::sleep(Duration::from_millis(100)).await; + signal_tx.send_replace(true); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("the loop stops on shutdown") + .unwrap(); + let seen = runs.load(std::sync::atomic::Ordering::SeqCst); + assert!(seen >= 2, "ran {seen} times"); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), seen); + } + + /// Shutting down (or aborting the loop, as the pool's supervisor does) while a run is + /// in flight must not cancel the run: it would drop a database transaction mid-way. + #[tokio::test] + async fn spawn_periodic_never_cancels_a_run() { + use std::sync::atomic::{AtomicBool, Ordering}; + + let started = Arc::new(tokio::sync::Notify::new()); + let finished = Arc::new(AtomicBool::new(false)); + let (signal_tx, signal_rx) = watch::channel(false); + let (run_started, run_finished) = (Arc::clone(&started), Arc::clone(&finished)); + let task = spawn_periodic(Duration::from_secs(3600), signal_rx, move || { + let (started, finished) = (Arc::clone(&run_started), Arc::clone(&run_finished)); + async move { + started.notify_one(); + tokio::time::sleep(Duration::from_millis(200)).await; + finished.store(true, Ordering::SeqCst); + } + }); + started.notified().await; + signal_tx.send_replace(true); + task.abort(); + assert!(!finished.load(Ordering::SeqCst)); + tokio::time::sleep(Duration::from_millis(400)).await; + assert!( + finished.load(Ordering::SeqCst), + "the in-flight run completed after the loop was stopped" + ); + } + + #[cfg(any(feature = "postgres", feature = "mysql"))] + #[test] + fn encrypted_job_purge_is_opt_in_and_configurable() { + #[cfg(feature = "postgres")] + type Db = sqlx::Postgres; + #[cfg(all(feature = "mysql", not(feature = "postgres")))] + type Db = sqlx::MySql; + + let pool = WorkerPool::::new(); + assert_eq!(pool.encrypted_job_purge_interval, None); + let pool = pool.with_encrypted_job_purge(Duration::from_secs(30)); + assert_eq!( + pool.encrypted_job_purge_interval, + Some(Duration::from_secs(30)) + ); + assert_eq!( + pool.without_encrypted_job_purge() + .encrypted_job_purge_interval, + None + ); + } } diff --git a/tests/payload_encryption_tests.rs b/tests/payload_encryption_tests.rs index 815ad31..fd1c5f7 100644 --- a/tests/payload_encryption_tests.rs +++ b/tests/payload_encryption_tests.rs @@ -10,11 +10,12 @@ mod test_utils; use chrono::Utc; use hammerwork::{ - HammerworkError, Job, JobId, JobQueue, JobStatus, Worker, + HammerworkError, Job, JobId, JobQueue, JobStatus, Worker, WorkerPool, archive::{ArchivalConfig, ArchivalPolicy, ArchivalReason}, batch::JobBatch, encryption::{ - EncryptionAlgorithm, EncryptionConfig, EncryptionEngine, KeySource, RetentionPolicy, + EncryptionAlgorithm, EncryptionConfig, EncryptionEngine, EncryptionMetadata, KeySource, + RetentionPolicy, encrypted_payload_placeholder, }, queue::DatabaseQueue, worker::JobHandler, @@ -40,6 +41,25 @@ trait Inspect: sqlx::Database { table: &'static str, id: JobId, ) -> impl Future + Send; + + /// Swaps the ciphertext, nonce and tag of jobs `a` and `b`, as an attacker with write + /// access to the table could. + fn swap_ciphertexts( + pool: &sqlx::Pool, + a: JobId, + b: JobId, + ) -> impl Future + Send; + + /// Moves job `id` to queue `queue_name` directly in the table. + fn set_queue_name( + pool: &sqlx::Pool, + id: JobId, + queue_name: &str, + ) -> impl Future + Send; + + /// Removes `format_version` from the stored encryption metadata, as written by the + /// release before ciphertexts were bound to their job. + fn strip_format_version(pool: &sqlx::Pool, id: JobId) -> impl Future + Send; } #[cfg(feature = "postgres")] @@ -72,6 +92,55 @@ impl Inspect for sqlx::Postgres { .unwrap(); hex.to_lowercase() } + + async fn swap_ciphertexts(pool: &sqlx::PgPool, a: JobId, b: JobId) { + let select = "SELECT encrypted_payload, encryption_nonce, encryption_tag \ + FROM hammerwork_jobs WHERE id = $1"; + type Cipher = (Vec, Vec, Vec); + let ca: Cipher = sqlx::query_as(select) + .bind(a) + .fetch_one(pool) + .await + .unwrap(); + let cb: Cipher = sqlx::query_as(select) + .bind(b) + .fetch_one(pool) + .await + .unwrap(); + for (id, (ciphertext, nonce, tag)) in [(a, cb), (b, ca)] { + sqlx::query( + "UPDATE hammerwork_jobs SET encrypted_payload = $1, encryption_nonce = $2, \ + encryption_tag = $3 WHERE id = $4", + ) + .bind(ciphertext) + .bind(nonce) + .bind(tag) + .bind(id) + .execute(pool) + .await + .unwrap(); + } + } + + async fn set_queue_name(pool: &sqlx::PgPool, id: JobId, queue_name: &str) { + sqlx::query("UPDATE hammerwork_jobs SET queue_name = $1 WHERE id = $2") + .bind(queue_name) + .bind(id) + .execute(pool) + .await + .unwrap(); + } + + async fn strip_format_version(pool: &sqlx::PgPool, id: JobId) { + sqlx::query( + "UPDATE hammerwork_jobs SET encryption_metadata = encryption_metadata - 'format_version' \ + WHERE id = $1", + ) + .bind(id) + .execute(pool) + .await + .unwrap(); + } } #[cfg(feature = "mysql")] @@ -100,6 +169,56 @@ impl Inspect for sqlx::MySql { .unwrap(); hex.to_lowercase() } + + async fn swap_ciphertexts(pool: &sqlx::MySqlPool, a: JobId, b: JobId) { + let select = "SELECT encrypted_payload, encryption_nonce, encryption_tag \ + FROM hammerwork_jobs WHERE id = ?"; + type Cipher = (Vec, Vec, Vec); + let ca: Cipher = sqlx::query_as(select) + .bind(a.to_string()) + .fetch_one(pool) + .await + .unwrap(); + let cb: Cipher = sqlx::query_as(select) + .bind(b.to_string()) + .fetch_one(pool) + .await + .unwrap(); + for (id, (ciphertext, nonce, tag)) in [(a, cb), (b, ca)] { + sqlx::query( + "UPDATE hammerwork_jobs SET encrypted_payload = ?, encryption_nonce = ?, \ + encryption_tag = ? WHERE id = ?", + ) + .bind(ciphertext) + .bind(nonce) + .bind(tag) + .bind(id.to_string()) + .execute(pool) + .await + .unwrap(); + } + } + + async fn set_queue_name(pool: &sqlx::MySqlPool, id: JobId, queue_name: &str) { + sqlx::query("UPDATE hammerwork_jobs SET queue_name = ? WHERE id = ?") + .bind(queue_name) + .bind(id.to_string()) + .execute(pool) + .await + .unwrap(); + } + + async fn strip_format_version(pool: &sqlx::MySqlPool, id: JobId) { + sqlx::query( + "UPDATE hammerwork_jobs \ + SET encryption_metadata = JSON_REMOVE(encryption_metadata, '$.format_version') \ + WHERE id = ?", + ) + .bind(id.to_string()) + .execute(pool) + .await + .unwrap(); + } } fn hex(text: &str) -> String { @@ -503,6 +622,8 @@ where DB: Inspect + Send + Sync + 'static, JobQueue: DatabaseQueue + Send + Sync + 'static, { + // Purges run across all queues; keep them apart from the worker pool purge test + let _serial = test_utils::serial().await; let queue = encrypted_queue(&plain, engine("k1", KEY_A).await).await; let queue_name = test_utils::unique_queue("enc_retention"); let archive_queue = test_utils::unique_queue("enc_retention_archive"); @@ -644,6 +765,9 @@ where archived.payload, json!({"ssn": "[ENCRYPTED]", "visible": 1}) ); + // The ciphertext stays in the archive table: decrypting needs a restore + let err = queue.decrypt_job(archived).await.unwrap_err(); + assert!(err.to_string().contains("restore_archived_job"), "{err}"); let restored = plain.restore_archived_job(id).await.unwrap(); assert!(restored.is_encrypted); @@ -691,6 +815,275 @@ where queue.delete_job(id).await.unwrap(); } +/// Swapping the ciphertext, nonce and tag of two jobs in the table makes both fail to +/// decrypt, instead of each decrypting as the other's payload (#38). +async fn swapped_ciphertexts_do_not_decrypt(plain: Arc>) +where + DB: Inspect + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue = encrypted_queue(&plain, engine("k1", KEY_A).await).await; + let queue_name = test_utils::unique_queue("enc_swap"); + let enqueue = |payload: Value| { + queue.enqueue( + Job::new(queue_name.clone(), payload) + .with_encryption(config("k1")) + .with_retention_policy(long_retention()) + .with_max_attempts(1), + ) + }; + let a = enqueue(json!({"account": "a"})).await.unwrap(); + let b = enqueue(json!({"account": "b"})).await.unwrap(); + let stored = queue.get_job(a).await.unwrap().unwrap(); + assert_eq!( + stored.encrypted_payload.unwrap().metadata.format_version, + EncryptionMetadata::FORMAT_JOB_BOUND + ); + + DB::swap_ciphertexts(&queue.pool, a, b).await; + for id in [a, b] { + let job = queue.get_job(id).await.unwrap().unwrap(); + let err = queue.decrypt_job(job).await.unwrap_err(); + assert!(matches!(err, HammerworkError::Encryption { .. }), "{err}"); + } + + // A worker fails the run without calling the handler + let (job, seen) = run_worker_until_done(&queue, &queue_name, a).await; + assert_eq!(job.status, JobStatus::Dead); + assert!( + seen.is_empty(), + "the handler must not see another job's payload" + ); + + // Swapping back restores both + DB::swap_ciphertexts(&queue.pool, a, b).await; + let job = queue.get_job(b).await.unwrap().unwrap(); + assert_eq!( + queue.decrypt_job(job).await.unwrap().payload, + json!({"account": "b"}) + ); + + for id in [a, b] { + queue.delete_job(id).await.unwrap(); + } +} + +/// Moving an encrypted job to another queue in the table makes it fail to decrypt. +async fn moved_job_does_not_decrypt(plain: Arc>) +where + DB: Inspect + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue = encrypted_queue(&plain, engine("k1", KEY_A).await).await; + let queue_name = test_utils::unique_queue("enc_moved"); + let payload = json!({"ssn": secret("moved"), "visible": 1}); + let id = queue + .enqueue( + Job::new(queue_name.clone(), payload.clone()) + .with_encryption(config("k1")) + .with_pii_fields(vec!["ssn"]) + .with_retention_policy(long_retention()), + ) + .await + .unwrap(); + + let other = test_utils::unique_queue("enc_moved_to"); + DB::set_queue_name(&queue.pool, id, &other).await; + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.queue_name, other); + assert!(queue.decrypt_job(job).await.is_err()); + + DB::set_queue_name(&queue.pool, id, &queue_name).await; + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(queue.decrypt_job(job).await.unwrap().payload, payload); + queue.delete_job(id).await.unwrap(); +} + +/// Payloads written before ciphertexts were bound to their job (no associated data, no +/// `format_version` in the metadata) still decrypt and run. +async fn legacy_unbound_payload_decrypts(plain: Arc>) +where + DB: Inspect + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let engine = engine("k1", KEY_A).await; + let queue_name = test_utils::unique_queue("enc_legacy"); + let payload = json!({"secret": secret("legacy")}); + + // What the previous release stored: the engine's encryption without associated data + let legacy = engine + .encrypt_payload_with_retention(&payload, &[] as &[&str], long_retention()) + .await + .unwrap(); + let mut job = Job::new(queue_name.clone(), encrypted_payload_placeholder()) + .with_encryption(config("k1")) + .with_retention_policy(long_retention()); + job.is_encrypted = true; + job.encrypted_payload = Some(legacy); + let queue = encrypted_queue(&plain, engine).await; + let id = queue.enqueue(job).await.unwrap(); + DB::strip_format_version(&queue.pool, id).await; + + let stored = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!( + stored + .encrypted_payload + .as_ref() + .unwrap() + .metadata + .format_version, + EncryptionMetadata::FORMAT_UNBOUND + ); + assert_eq!(queue.decrypt_job(stored).await.unwrap().payload, payload); + + let (job, seen) = run_worker_until_done(&queue, &queue_name, id).await; + assert_eq!(job.status, JobStatus::Completed, "{:?}", job.error_message); + assert_eq!(seen, vec![payload]); + queue.delete_job(id).await.unwrap(); +} + +/// `WorkerPool::with_encrypted_job_purge` deletes expired encrypted jobs on its own. +async fn worker_pool_purges_expired_jobs(plain: Arc>) +where + DB: Inspect + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let queue = encrypted_queue(&plain, engine("k1", KEY_A).await).await; + let queue_name = test_utils::unique_queue("enc_pool_purge"); + let encrypted = |policy: RetentionPolicy| { + Job::new(queue_name.clone(), json!({"secret": secret("pool")})) + .with_encryption(config("k1")) + .with_retention_policy(policy) + }; + let past = Utc::now() - chrono::Duration::hours(1); + let expired = queue + .enqueue(encrypted(RetentionPolicy::DeleteAt(past))) + .await + .unwrap(); + let kept = queue.enqueue(encrypted(long_retention())).await.unwrap(); + for id in [expired, kept] { + queue.complete_job(id).await.unwrap(); + } + + let handler: JobHandler = Arc::new(|_job: Job| Box::pin(async { Ok(()) })); + let worker = Worker::new(Arc::clone(&plain), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(50)); + let mut pool = WorkerPool::new() + .without_autoscaling() + .without_stale_job_reaper() + .with_encrypted_job_purge(Duration::from_millis(100)); + pool.add_worker(worker); + + let deadline = Instant::now() + Duration::from_secs(15); + tokio::select! { + result = pool.start() => panic!("pool stopped early: {result:?}"), + _ = async { + while queue.get_job(expired).await.unwrap().is_some() && Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(50)).await; + } + } => {} + } + pool.shutdown().await.unwrap(); + + assert!( + queue.get_job(expired).await.unwrap().is_none(), + "the pool purged the expired job" + ); + assert!(queue.get_job(kept).await.unwrap().is_some()); + queue.delete_job(kept).await.unwrap(); +} + +/// `JobQueue::from_config` with an `[encryption]` section encrypts without code: jobs +/// on `encrypted_queues` are encrypted, and jobs under an older key id decrypt with the +/// configured decryption key. Invalid sections fail closed. +async fn configured_queue_encrypts(plain: Arc>, connect: F, url: String) +where + DB: Inspect + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + F: Fn(hammerwork::HammerworkConfig) -> Fut, + Fut: Future>>, +{ + // Read by the `env://` key sources below; every test sets the same values + unsafe { + std::env::set_var("HAMMERWORK_TEST_CONFIG_KEY", KEY_B); + std::env::set_var("HAMMERWORK_TEST_CONFIG_OLD_KEY", KEY_A); + } + let queue_name = test_utils::unique_queue("enc_config"); + let toml = format!( + r#" + enabled = true + key_source = "env://HAMMERWORK_TEST_CONFIG_KEY" + key_id = "configured" + encrypted_queues = ["{queue_name}"] + default_retention_secs = 2592000 + + [decryption_keys] + k1 = "env://HAMMERWORK_TEST_CONFIG_OLD_KEY" + "# + ); + let mut hw_config = hammerwork::HammerworkConfig::new().with_database_url(&url); + hw_config.database.pool_size = 2; + hw_config.encryption = toml::from_str(&toml).unwrap(); + let configured = Arc::new(connect(hw_config.clone()).await.unwrap()); + + // A plain job on an encrypted queue is encrypted with the configured key + let marker = secret("configured"); + let payload = json!({"secret": marker}); + let id = configured + .enqueue(Job::new(queue_name.clone(), payload.clone())) + .await + .unwrap(); + assert_row_has_no_plaintext(&configured.pool, "hammerwork_jobs", id, &marker).await; + let stored = configured.get_job(id).await.unwrap().unwrap(); + assert!(stored.is_encrypted); + let metadata = &stored.encrypted_payload.as_ref().unwrap().metadata; + assert_eq!(metadata.key_id, "configured"); + assert!(metadata.delete_at.is_some(), "default retention applies"); + let (job, seen) = run_worker_until_done(&configured, &queue_name, id).await; + assert_eq!(job.status, JobStatus::Completed, "{:?}", job.error_message); + assert_eq!(seen, vec![payload.clone()]); + configured.delete_job(id).await.unwrap(); + + // Other queues are unaffected + let other = test_utils::unique_queue("enc_config_other"); + let id = configured + .enqueue(Job::new(other, json!({"visible": 1}))) + .await + .unwrap(); + assert!(!configured.get_job(id).await.unwrap().unwrap().is_encrypted); + configured.delete_job(id).await.unwrap(); + + // A job written under the old key id decrypts with the configured decryption key + let old = encrypted_queue(&plain, engine("k1", KEY_A).await).await; + let id = old + .enqueue( + Job::new(queue_name.clone(), payload.clone()) + .with_encryption(config("k1")) + .with_retention_policy(long_retention()), + ) + .await + .unwrap(); + let stored = configured.get_job(id).await.unwrap().unwrap(); + assert_eq!( + configured.decrypt_job(stored).await.unwrap().payload, + payload + ); + configured.delete_job(id).await.unwrap(); + + // Fail closed: a missing key, and an invalid section + let mut missing = hw_config.clone(); + missing.encryption.key_source = + hammerwork::KeySourceRef::parse("env://HAMMERWORK_TEST_CONFIG_UNSET_KEY").unwrap(); + assert!(connect(missing).await.is_err()); + let mut invalid = hw_config.clone(); + invalid.encryption.enabled = false; + assert!(matches!( + connect(invalid).await, + Err(HammerworkError::Config(_)) + )); +} + #[cfg(feature = "postgres")] mod postgres { use super::*; @@ -742,6 +1135,43 @@ mod postgres { async fn test_postgres_plain_jobs_unchanged() { plain_jobs_unchanged(test_utils::setup_postgres_queue().await).await; } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_swapped_ciphertexts_do_not_decrypt() { + swapped_ciphertexts_do_not_decrypt(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_moved_job_does_not_decrypt() { + moved_job_does_not_decrypt(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_legacy_unbound_payload_decrypts() { + legacy_unbound_payload_decrypts(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_worker_pool_purges_expired_jobs() { + worker_pool_purges_expired_jobs(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_configured_queue_encrypts() { + let plain = test_utils::setup_postgres_queue().await; + let url = test_utils::postgres_url(); + configured_queue_encrypts( + plain, + |config| async move { JobQueue::::from_config(&config).await }, + url, + ) + .await; + } } #[cfg(feature = "mysql")] @@ -795,4 +1225,41 @@ mod mysql { async fn test_mysql_plain_jobs_unchanged() { plain_jobs_unchanged(test_utils::setup_mysql_queue().await).await; } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_swapped_ciphertexts_do_not_decrypt() { + swapped_ciphertexts_do_not_decrypt(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_moved_job_does_not_decrypt() { + moved_job_does_not_decrypt(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_legacy_unbound_payload_decrypts() { + legacy_unbound_payload_decrypts(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_worker_pool_purges_expired_jobs() { + worker_pool_purges_expired_jobs(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_configured_queue_encrypts() { + let plain = test_utils::setup_mysql_queue().await; + let url = test_utils::mysql_url(); + configured_queue_encrypts( + plain, + |config| async move { JobQueue::::from_config(&config).await }, + url, + ) + .await; + } }