diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cb7de6..cc03b82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Migration `018_add_job_retry_strategy` adds `hammerwork_jobs.retry_strategy` (JSON) and an index on `(batch_id, status)`. **Required**: every job query reads the new column, so run `cargo hammerwork migration run` before upgrading. ### Changed +- **Upgrade notes for [#64](https://github.com/CodingAnarchy/hammerwork/issues/64)** (see Security): + - `vault://` and `azure://` keys must be exactly 32 bytes (base64 in the Vault `key` field). A source that relied on padding or passphrase hashing now fails to load; store a real 32-byte key. Jobs encrypted under the old derived key cannot be decrypted with the new one, so drain or re-enqueue them before switching. + - `cargo hammerwork backup create` writes format `2.0`: every column, with `priority` as its numeric level. `backup restore` still reads `1.0` files. + - `cargo hammerwork job enqueue`, `batch enqueue`, `cron create` and `workflow create` fail with an error when they would store a plaintext job on a queue that holds encrypted jobs, or when the configured encryption key cannot be loaded; `hammerwork-web` does not start in the latter case. + - `ExternalKmsConfig`, `WebhookConfig`, `WebhookAuth`, `AlertTarget`, `StreamBackend`, `DatabaseConfig`, `cargo_hammerwork::config::Config`, `hammerwork_web::DashboardConfig` and `AuthConfig` implement `Debug` by hand (secrets redacted) instead of deriving it. `cargo_hammerwork::config::Config` has a new `encryption_config` field. - **CLI flag consistency** ([#61](https://github.com/CodingAnarchy/hammerwork/issues/61)); old spellings keep working as aliases: - `queue` commands take `-u/--database-url` like every other group (`-d` remains as a hidden alias). - The queue filter is `-n/--queue` everywhere (`job purge`, `spawn list/stats/pending/monitor`, `archive run/list/stats`); `-Q` and `archive --queue-name` still work. @@ -92,6 +97,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Unused `ArchiveConfig` fields `archive_directory`, `max_file_size_bytes` and `include_payloads`. Existing TOML files containing them still load. ### Security +- **Encryption and data-safety hardening** (part of [#64](https://github.com/CodingAnarchy/hammerwork/issues/64): C3, H1, H2, H4, M14, M15, M17): + - **C3 — `cargo hammerwork backup` destroyed encrypted payloads.** `backup create` exported 13 columns, so an encrypted job was backed up as its redacted placeholder and restored with `is_encrypted = false` and no ciphertext (the payload was unrecoverable); cron schedules, recurrence, timeouts, retry strategies, dependencies, workflows, batches, results and tracing ids were dropped too. JSON backups (format `2.0`) now hold every column of `hammerwork_jobs`, read from `information_schema` so columns added by future migrations are included (a column type the backup cannot copy is an error), with one encoding for both backends (bytes as base64, timestamps as RFC 3339 with microseconds, arrays as JSON arrays). `backup restore` writes every column back, checks the whole file first and inserts in one transaction; existing ids are skipped, never overwritten or duplicated (MySQL no longer uses `INSERT IGNORE`, which turned conversion errors into warnings); a non-null value for a column the database lacks is an error. Format `1.0` backups still restore. CSV stays an export and cannot be restored. New `cargo_hammerwork::utils::job_rows`. + - **H1 — the CLI and the web dashboard wrote plaintext to encrypted queues.** They built their queue without the application's `[encryption]` settings. Commands that write jobs (`job enqueue`, `batch enqueue`, `cron create`, `workflow create`) and `POST /api/jobs` now load the application's settings (new `PayloadEncryptionConfig::load`: the `[encryption]` section of a `hammerwork.toml` plus `HAMMERWORK_ENCRYPTION_*`; CLI `config set encryption_config ` / `HAMMERWORK_ENCRYPTION_CONFIG`, dashboard `HAMMERWORK_ENCRYPTION_CONFIG`) and encrypt like the application. If the key cannot be loaded the CLI refuses to write and the dashboard refuses to start. Without settings, both refuse to store a plaintext job on a queue that already holds encrypted jobs (new `JobQueue::with_plaintext_guard`, applied to `enqueue`, `enqueue_batch`, `enqueue_workflow` and `enqueue_cron_job`). New `job enqueue --encrypt` / `--pii-field`. `cargo-hammerwork` and `hammerwork-web` now enable hammerwork's `encryption` feature; `cargo-hammerwork` gains `aws-kms`, `gcp-kms`, `vault-kms` and `azure-kv` features for KMS key sources. + - **H2 — `get_dead_jobs` / `get_dead_jobs_by_queue` returned encrypted jobs as plaintext.** They selected 15 columns and hard-coded `is_encrypted = false`, so `decrypt_job` returned the redacted payload without error. They now return the full job (ciphertext, key id, PII fields, cron, batch, workflow, tracing and result columns) on both backends; a test covers every read path that builds a `Job`. + - **H4 — after a KMS data-key rotation, other processes sent new jobs to Dead.** An engine only knew the key versions it loaded at start. `EncryptionEngine::new_with_pool` engines now keep the pool and, when a payload does not decrypt with the keys they hold, load the stored versions they lack (and other key ids stored in the table) and retry; they then encrypt with the newest active version. New `EncryptionEngine::reload_kms_keys()`. A failed reload leaves the run failed and retried as before. + - **M14 — secrets in `Debug` output, logs and `config show`.** `Debug` no longer prints the database URL password (`DatabaseConfig`, CLI `Config`, web `DashboardConfig`), webhook signing secrets, header values, auth tokens and passwords and URL paths (`WebhookConfig`, `WebhookAuth`, `AlertTarget`), streaming credentials and config values (`StreamBackend`), KMS credentials (`ExternalKmsConfig`, the Azure client secret) or the dashboard password hash (`AuthConfig`). Adding a webhook logs only the scheme and host of its URL. `cargo hammerwork config show` masks the database password. New `hammerwork::config::redact_url` and `redact_url_path`. + - **M15 — weak Vault and Azure keys were padded.** A Vault `key` that was not base64 of exactly 32 bytes was hashed or padded into a key (a 1-byte value gave a 32-byte key with 8 bits of entropy), and short Azure key material was padded. Both are now rejected with `EncryptionError::InvalidConfiguration`, for engine data keys and `KeyManager` master keys. + - **M17 — key material is zeroized.** Engine keys (now shared, not copied per operation), KMS data keys, `KeyManager` master, root and cached keys, and keys read from the environment, files, Vault and Azure are held in `zeroize::Zeroizing` and wiped when dropped (new dependency `zeroize`, part of the `encryption` feature). - **SQL injection in `cargo-hammerwork`** (part of [#7](https://github.com/CodingAnarchy/hammerwork/issues/7)): `cron list`/`cron next`, `monitor dashboard`/`metrics`, `backup create`, `queue stats`/`health`, `spawn list`/`stats`/`pending` spliced the `--queue` name into the SQL text inside quotes, so a queue name such as `x' OR '1'='1` changed the statement. Every value in these statements (queue names, hour/day windows, `LIMIT`, cutoff timestamps, status names) is now a bound parameter with the placeholder style of the backend (`$n` PostgreSQL, `?` MySQL), built by the new `cargo_hammerwork::utils::sql::SqlParams`; `job list`'s `--last-hours`/`--limit`, `job purge --older-than-days`, `maintenance vacuum` cutoffs and the bulk selectors behind `batch retry/cancel` and `maintenance cleanup/check` (`JobSelector`, whose free-form `extra` SQL fragments were replaced by typed, bound filters) no longer format numbers or timestamps into the SQL either. `hammerwork-web` was audited and already binds everything. Each fixed command has database-backed tests with a queue name full of quotes and SQL metacharacters on both backends, and `tests/sql_query_tests.rs` now exercises the real query builders instead of copies of their SQL. - **Job payload encryption was never applied ([#11](https://github.com/CodingAnarchy/hammerwork/issues/11))**: with the `encryption` feature, jobs created with `with_encryption` / `with_pii_fields` were stored and processed in plaintext and the encryption columns stayed empty. They are now encrypted at rest (see Added). Jobs enqueued by earlier versions remain in plaintext. - The payload integrity hash stored next to an encrypted payload is now an HMAC-SHA256 keyed by the data key (`hmac-sha256:`) instead of a plain SHA-256 of the plaintext, which could be reversed by brute force for low-entropy values such as SSNs or card numbers. Payloads with the old hash still decrypt. diff --git a/Cargo.lock b/Cargo.lock index c48db4e..e57e25c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -905,6 +905,7 @@ name = "cargo-hammerwork" version = "1.15.5" dependencies = [ "anyhow", + "base64 0.22.1", "chrono", "clap", "comfy-table", @@ -2007,6 +2008,7 @@ dependencies = [ "uuid", "vaultrs", "warp", + "zeroize", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a7ad192..7e28510 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,7 @@ hex = "0.4" aes-gcm = "0.10" chacha20poly1305 = "0.10" argon2 = "0.5" +zeroize = "1.8" [package] name = "hammerwork" @@ -100,6 +101,7 @@ hex = { workspace = true, optional = true } aes-gcm = { workspace = true, optional = true } chacha20poly1305 = { workspace = true, optional = true } argon2 = { workspace = true, optional = true } +zeroize = { workspace = true, optional = true } base64 = { workspace = true } toml = { workspace = true } aws-sdk-kms = { version = "1.80", default-features = false, features = ["default-https-client", "rt-tokio"], optional = true } @@ -131,7 +133,7 @@ mysql = ["sqlx/mysql"] metrics = ["prometheus", "warp"] alerting = ["reqwest", "lettre"] webhooks = ["reqwest", "hmac", "sha2", "hex"] -encryption = ["aes-gcm", "chacha20poly1305", "argon2", "hmac", "sha2", "hex"] +encryption = ["aes-gcm", "chacha20poly1305", "argon2", "hmac", "sha2", "hex", "zeroize"] aws-kms = ["aws-sdk-kms", "aws-config"] gcp-kms = ["google-cloud-kms", "google-cloud-auth", "rustls"] vault-kms = ["vaultrs", "url"] diff --git a/README.md b/README.md index f0071da..e4402aa 100644 --- a/README.md +++ b/README.md @@ -431,7 +431,8 @@ What you get: - **Fail closed**: enqueueing a job with an encryption config on a queue without an engine is an error; a worker that cannot decrypt a job (no engine, unknown key, tampered data) fails it without running the handler. - **Decryption only for the handler**: `dequeue`, `get_job`, the web dashboard and the CLI show the stored, redacted payload. Call `JobQueue::decrypt_job` to read the plaintext. - **Retention**: `DatabaseQueue::purge_expired_encrypted_jobs` deletes finished encrypted jobs past their retention time. Archiving and restoring move the ciphertext without decrypting it. -- **Key management**: decrypt-only keys for rotated key ids (`EncryptionEngine::with_decryption_key`), KMS-wrapped data keys (AWS, GCP), Vault and Azure Key Vault sources, and the `KeyManager` for stored keys and audit trails. +- **Key management**: decrypt-only keys for rotated key ids (`EncryptionEngine::with_decryption_key`), KMS-wrapped data keys (AWS, GCP) that every process picks up after a rotation, Vault and Azure Key Vault sources (keys of exactly 32 bytes), and the `KeyManager` for stored keys and audit trails. Key material is wiped from memory when dropped. +- **CLI and dashboard**: `cargo hammerwork` and `hammerwork-web` read the application's `[encryption]` settings, encrypt the jobs they create like the application, and never write a plaintext job to a queue that holds encrypted jobs. `cargo hammerwork backup create` / `restore` keep encrypted payloads (and every other column) intact. See [Job Encryption & PII Protection](docs/encryption.md) for details. diff --git a/cargo-hammerwork/Cargo.toml b/cargo-hammerwork/Cargo.toml index 0ce1782..d0e9be2 100644 --- a/cargo-hammerwork/Cargo.toml +++ b/cargo-hammerwork/Cargo.toml @@ -17,7 +17,7 @@ name = "cargo-hammerwork" path = "src/main.rs" [dependencies] -hammerwork = { workspace = true, features = ["postgres", "mysql"] } +hammerwork = { workspace = true, features = ["postgres", "mysql", "encryption"] } clap = { workspace = true, features = ["env"] } tokio = { workspace = true } anyhow = { workspace = true } @@ -34,6 +34,15 @@ toml = { workspace = true } dirs = { workspace = true } cron = { workspace = true } reqwest = { workspace = true } +base64 = { workspace = true } + +# Key sources for the application's `[encryption]` settings (see `encryption_config` in +# the CLI configuration). `env://` keys work without any of these. +[features] +aws-kms = ["hammerwork/aws-kms"] +gcp-kms = ["hammerwork/gcp-kms"] +vault-kms = ["hammerwork/vault-kms"] +azure-kv = ["hammerwork/azure-kv"] [dev-dependencies] tempfile = "3.8" diff --git a/cargo-hammerwork/README.md b/cargo-hammerwork/README.md index 1af8296..9847ade 100644 --- a/cargo-hammerwork/README.md +++ b/cargo-hammerwork/README.md @@ -124,9 +124,31 @@ cargo hammerwork config reset --confirm # Back to defaults ``` Valid keys for `set` and `get` are `database_url`, `default_queue`, `default_limit`, -`log_level`, `connection_pool_size` and `connect_timeout_secs`. `set` validates the value (the database URL must +`log_level`, `connection_pool_size`, `connect_timeout_secs` and `encryption_config`. `set` validates the value (the database URL must start with `postgres://`, `postgresql://` or `mysql://`, `log_level` must be one of -`trace`, `debug`, `info`, `warn`, `error`, and `connection_pool_size` must be 1-100, `connect_timeout_secs` 1-600). +`trace`, `debug`, `info`, `warn`, `error`, and `connection_pool_size` must be 1-100, `connect_timeout_secs` 1-600, +and `encryption_config` must be a readable `hammerwork.toml`). `config show` masks the +password of the database URL, and summarises the payload encryption settings. + +#### Encrypted queues + +Commands that write jobs (`job enqueue`, `batch enqueue`, `cron create`, `workflow create`) +encrypt them like your application. Point the CLI at the application's `hammerwork.toml` +and make its key available: + +```bash +cargo hammerwork config set encryption_config /etc/myapp/hammerwork.toml +export HAMMERWORK_ENCRYPTION_KEY=... # the key its [encryption] key_source names +``` + +Only the `[encryption]` section is read; `HAMMERWORK_ENCRYPTION_CONFIG` overrides the path, +and the `HAMMERWORK_ENCRYPTION_*` variables override the settings, as for the application. +Jobs on its `encrypted_queues` are then encrypted; `job enqueue --encrypt` (whole payload) +or `--pii-field ` (repeatable) encrypt a job on any queue. The CLI never writes +plaintext by mistake: with encryption enabled but the key unavailable, these commands fail, +and without any settings they still refuse to write a plaintext job to a queue that already +holds encrypted jobs. KMS key sources need the matching cargo feature of `cargo-hammerwork` +(`aws-kms`, `gcp-kms`, `vault-kms`, `azure-kv`). ### Job Management Commands @@ -141,6 +163,7 @@ cargo hammerwork job show # Detailed job information cargo hammerwork job enqueue --queue emails --payload '{"to": "a@example.com"}' cargo hammerwork job enqueue --queue emails --payload '{"n": 1}' --priority high --delay 60 --max-attempts 5 --timeout 30 +cargo hammerwork job enqueue --queue payments --payload '{"card": "4111..."}' --pii-field card # encrypted cargo hammerwork job retry # Retry one job (--job-id also works) cargo hammerwork job retry --queue emails # Retry every failed job in a queue @@ -422,10 +445,21 @@ cargo hammerwork backup restore --input backup.json --confirm cargo hammerwork backup restore --input backup.json --skip-existing --confirm ``` -`backup create` requires `--output` and `--format` is `json` or `csv`. `backup restore` -requires `--input` and refuses to run without `--confirm`. `backup list` only reads the -`.json` and `.csv` files in a local directory (default `./backups`). There is no -`backup verify`. +`backup create` requires `--output` and `--format` is `json` or `csv`. A JSON backup +(format version 2.0) holds every column of every selected job: encrypted payloads stay +encrypted, with their nonce, tag, key id and metadata, and cron schedules, timeouts, retry +strategies, dependencies, workflows, batches, results, tracing ids and retention are all +kept. A CSV backup is an export of the main columns and cannot be restored. + +`backup restore` requires `--input` and refuses to run without `--confirm`. It recreates +the jobs exactly as they were backed up (into PostgreSQL or MySQL, whichever the backup +came from), and restored encrypted jobs decrypt with the same key. Jobs whose id already +exists are never overwritten or duplicated: they are skipped and counted, with or without +`--skip-existing`. The whole backup is checked before anything is written and the jobs are +inserted in one transaction, so a bad backup restores nothing; a backup from a newer schema +must be restored into a database migrated at least as far. Backups from earlier versions +(format 1.0) still restore. `backup list` only reads the `.json` and `.csv` files in a local +directory (default `./backups`). There is no `backup verify`. ## Architecture & Design @@ -453,7 +487,8 @@ Settings come from these sources, highest priority first: 1. **Command-line flags**: for the database URL, `--database-url` / `-u` (`-d` on `queue` commands) 2. **Environment variables**: `DATABASE_URL`, `HAMMERWORK_DEFAULT_QUEUE`, - `HAMMERWORK_DEFAULT_LIMIT`, `HAMMERWORK_LOG_LEVEL`, `HAMMERWORK_POOL_SIZE` + `HAMMERWORK_DEFAULT_LIMIT`, `HAMMERWORK_LOG_LEVEL`, `HAMMERWORK_POOL_SIZE`, + `HAMMERWORK_ENCRYPTION_CONFIG` (and the `HAMMERWORK_ENCRYPTION_*` payload encryption settings) 3. **Configuration file** 4. **Default values** (`default_limit = 50`, `log_level = "info"`, `connection_pool_size = 5`) @@ -472,6 +507,7 @@ default_queue = "emails" default_limit = 50 log_level = "info" connection_pool_size = 5 +encryption_config = "/etc/myapp/hammerwork.toml" # optional: the application's encryption settings ``` ### Database Support diff --git a/cargo-hammerwork/src/commands/backup.rs b/cargo-hammerwork/src/commands/backup.rs index 28cb030..4e12aca 100644 --- a/cargo-hammerwork/src/commands/backup.rs +++ b/cargo-hammerwork/src/commands/backup.rs @@ -9,12 +9,28 @@ use tracing::info; use crate::commands::job::priority_display; use crate::config::Config; use crate::utils::database::DatabasePool; +use crate::utils::job_rows::{self, Column, Param, RowInsert}; use crate::utils::sql::{Backend, Bind, SqlParams, bind_mysql, bind_pg}; use crate::utils::validation::validate_priority; +/// Version of the JSON backup format written by `backup create`. +/// +/// - `2.0`: every column of `hammerwork_jobs` (see [`job_rows`]), including encrypted +/// payloads and their encryption metadata. +/// - `1.0`: the 13 columns of [`JobData`]. Still restored. +pub const BACKUP_VERSION: &str = "2.0"; + #[derive(Subcommand)] pub enum BackupCommand { - #[command(about = "Create a backup of job data")] + #[command( + about = "Create a backup of job data", + long_about = "Create a backup of job data.\n\n\ + The JSON format (the default) holds every column of every selected job, \ + including encrypted payloads (still encrypted) and their encryption metadata, \ + cron schedules, timeouts, retry strategies, dependencies, workflows, results, \ + tracing and retention, so `backup restore` recreates the jobs exactly. The CSV \ + format is an export of the main columns only and cannot be restored." + )] Create { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, @@ -31,10 +47,21 @@ pub enum BackupCommand { include_completed: bool, #[arg(long, help = "Include failed jobs")] include_failed: bool, - #[arg(long, help = "Backup format (json, csv)")] + #[arg( + long, + help = "Backup format: json (complete, restorable; default) or csv (export only)" + )] format: Option, }, - #[command(about = "Restore job data from backup")] + #[command( + about = "Restore job data from backup", + long_about = "Restore jobs from a JSON backup made by `backup create`.\n\n\ + Every column in the backup is restored as it was. Jobs whose id already exists \ + in the database are never overwritten or duplicated: they are skipped and \ + counted. The backup is checked before anything is written, and the jobs are \ + inserted in one transaction, so a bad backup restores nothing. A backup taken \ + from a newer schema must be restored into a database migrated at least as far." + )] Restore { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, @@ -42,7 +69,10 @@ pub enum BackupCommand { input: String, #[arg(long, help = "Confirm the restore operation")] confirm: bool, - #[arg(long, help = "Skip existing jobs")] + #[arg( + long, + help = "Skip existing jobs (always the case: existing jobs are never overwritten)" + )] skip_existing: bool, }, #[command(about = "List available backups")] @@ -130,15 +160,33 @@ impl BackupCommand { } } -/// The `SELECT` that gathers the jobs to back up. The queue name is bound, never interpolated. +/// The `SELECT` of [`JOB_DATA_COLUMNS`] that gathers the jobs to back up (as CSV). The +/// queue name is bound, never interpolated. pub fn build_backup_query( backend: Backend, queue: Option<&str>, include_completed: bool, include_failed: bool, +) -> (String, Vec) { + build_backup_select( + backend, + JOB_DATA_COLUMNS, + queue, + include_completed, + include_failed, + ) +} + +/// The `SELECT` of `select_list` that gathers the jobs to back up. +pub fn build_backup_select( + backend: Backend, + select_list: &str, + queue: Option<&str>, + include_completed: bool, + include_failed: bool, ) -> (String, Vec) { let mut params = SqlParams::new(backend); - let mut query = format!("SELECT {JOB_DATA_COLUMNS} FROM hammerwork_jobs WHERE 1=1"); + let mut query = format!("SELECT {select_list} FROM hammerwork_jobs WHERE 1=1"); let mut conditions = Vec::new(); if let Some(queue_name) = queue { @@ -157,6 +205,38 @@ pub fn build_backup_query( (query, params.into_binds()) } +/// Every column of the jobs to back up, as backup objects (see [`job_rows`]). +async fn fetch_backup_rows( + pool: &DatabasePool, + columns: &[Column], + queue: Option<&str>, + include_completed: bool, + include_failed: bool, +) -> Result>> { + let select = job_rows::select_list(pool.backend(), columns); + let (query, binds) = build_backup_select( + pool.backend(), + &select, + queue, + include_completed, + include_failed, + ); + match pool { + DatabasePool::Postgres(pg_pool) => bind_pg(sqlx::query(&query), &binds) + .fetch_all(pg_pool) + .await? + .iter() + .map(|row| job_rows::pg_row_to_json(row, columns)) + .collect(), + DatabasePool::MySQL(mysql_pool) => bind_mysql(sqlx::query(&query), &binds) + .fetch_all(mysql_pool) + .await? + .iter() + .map(|row| job_rows::mysql_row_to_json(row, columns)) + .collect(), + } +} + async fn fetch_backup_jobs( pool: &DatabasePool, queue: Option<&str>, @@ -236,46 +316,58 @@ async fn create_backup( format: &str, pool_size: u32, ) -> Result<()> { + if !matches!(format, "json" | "csv") { + anyhow::bail!("Unknown backup format '{}': use json or csv", format); + } let pool = DatabasePool::connect(database_url, pool_size).await?; - let job_data = - fetch_backup_jobs(&pool, queue.as_deref(), include_completed, include_failed).await?; - - info!("Found {} jobs to backup", job_data.len()); + // Read everything before creating the file, so a failure leaves no partial backup. + let (content, total) = if format == "csv" { + let job_data = + fetch_backup_jobs(&pool, queue.as_deref(), include_completed, include_failed).await?; + let mut csv = format!("{}\n", CSV_HEADER); + for job in &job_data { + csv.push_str(&csv_row(job)); + csv.push('\n'); + } + (csv, job_data.len()) + } else { + let columns = job_rows::job_columns(&pool).await?; + let rows = fetch_backup_rows( + &pool, + &columns, + queue.as_deref(), + include_completed, + include_failed, + ) + .await?; + let backup_data = serde_json::json!({ + "version": BACKUP_VERSION, + "created_at": chrono::Utc::now(), + "backend": match pool.backend() { + Backend::Postgres => "postgres", + Backend::MySql => "mysql", + }, + "total_jobs": rows.len(), + "filters": { + "queue": queue, + "include_completed": include_completed, + "include_failed": include_failed + }, + "columns": columns.iter().map(|c| c.name.as_str()).collect::>(), + "jobs": rows + }); + (serde_json::to_string_pretty(&backup_data)?, rows.len()) + }; + info!("Found {} jobs to backup", total); - // Create output file let file = File::create(output)?; let mut writer = BufWriter::new(file); - - match format { - "csv" => { - writeln!(writer, "{}", CSV_HEADER)?; - for job in &job_data { - writeln!(writer, "{}", csv_row(job))?; - } - } - _ => { - // JSON format (default) - let backup_data = serde_json::json!({ - "version": "1.0", - "created_at": chrono::Utc::now(), - "total_jobs": job_data.len(), - "filters": { - "queue": queue, - "include_completed": include_completed, - "include_failed": include_failed - }, - "jobs": job_data - }); - - serde_json::to_writer_pretty(&mut writer, &backup_data)?; - } - } - + writer.write_all(content.as_bytes())?; writer.flush()?; info!("✅ Backup created successfully: {}", output); println!("💾 Backup saved to: {}", output); - println!("📊 Total jobs backed up: {}", job_data.len()); + println!("📊 Total jobs backed up: {}", total); Ok(()) } @@ -341,37 +433,38 @@ async fn restore_backup( ) })?; + match backup_data.get("version").and_then(Value::as_str) { + None | Some("1.0") | Some("2.0") => {} + Some(other) => anyhow::bail!( + "{} is a version {} backup, which this cargo-hammerwork cannot restore; \ + upgrade cargo-hammerwork", + input, + other + ), + } let jobs = backup_data["jobs"] .as_array() .ok_or_else(|| anyhow::anyhow!("Invalid backup format: missing jobs array"))?; info!("Restoring {} jobs from backup", jobs.len()); - let mut restored = 0; + // Check every job before writing anything. + let target = job_rows::job_columns(&pool).await?; + let mut rows = Vec::with_capacity(jobs.len()); let mut skipped = 0; - for job in jobs { - let id = job["id"] - .as_str() - .ok_or_else(|| anyhow::anyhow!("Invalid job: missing id"))?; - - // Check if job already exists - if skip_existing { - let exists = check_job_exists(&pool, id).await?; - if exists { - skipped += 1; - continue; - } - } - - // Insert job; a row that appeared since the check is left alone - if insert_job_from_backup(&pool, job).await? { - restored += 1; - } else { + let row = restore_row(job, &target)?; + if skip_existing && check_job_exists(&pool, &row.id).await? { skipped += 1; + continue; } + rows.push(row); } + // Jobs whose id exists (now, or by the time they are inserted) are left alone. + let restored = job_rows::insert_rows(&pool, &rows).await?; + skipped += rows.len() - restored; + info!( "✅ Restore completed: {} jobs restored, {} skipped", restored, skipped @@ -545,70 +638,83 @@ fn parse_backup_job(job: &Value) -> Result> { }) } -/// Insert one backed-up job. Returns `false` when a job with that id already exists (the -/// existing row is left untouched). -async fn insert_job_from_backup(pool: &DatabasePool, job: &Value) -> Result { +/// A backed-up job with its core fields validated and normalized ([`parse_backup_job`]: +/// priority names become levels, missing timestamps become now, a missing payload +/// becomes `{}`), and every other column as it was backed up. +fn normalized_backup_job(job: &Value) -> Result> { + let mut object = job + .as_object() + .cloned() + .ok_or_else(|| anyhow::anyhow!("backup job must be a JSON object, got {}", job))?; let fields = parse_backup_job(job)?; - let empty = Value::Object(Default::default()); + let time = |t: chrono::DateTime| { + Value::String(t.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)) + }; + let optional_time = |t: Option>| t.map_or(Value::Null, time); let payload = if fields.payload.is_null() { - &empty + Value::Object(Default::default()) } else { - fields.payload - }; - - let affected = match pool { - DatabasePool::Postgres(pg_pool) => sqlx::query( - r#" - INSERT INTO hammerwork_jobs ( - id, queue_name, payload, status, priority, attempts, max_attempts, - created_at, scheduled_at, started_at, completed_at, failed_at, error_message - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) - ON CONFLICT (id) DO NOTHING - "#, - ) - .bind(fields.id) - .bind(fields.queue_name) - .bind(payload) - .bind(fields.status) - .bind(fields.priority) - .bind(fields.attempts) - .bind(fields.max_attempts) - .bind(fields.created_at) - .bind(fields.scheduled_at) - .bind(fields.started_at) - .bind(fields.completed_at) - .bind(fields.failed_at) - .bind(fields.error_message) - .execute(pg_pool) - .await? - .rows_affected(), - DatabasePool::MySQL(mysql_pool) => sqlx::query( - r#" - INSERT IGNORE INTO hammerwork_jobs ( - id, queue_name, payload, status, priority, attempts, max_attempts, - created_at, scheduled_at, started_at, completed_at, failed_at, error_message - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - "#, - ) - .bind(fields.id.to_string()) - .bind(fields.queue_name) - .bind(payload) - .bind(fields.status) - .bind(fields.priority) - .bind(fields.attempts) - .bind(fields.max_attempts) - .bind(fields.created_at) - .bind(fields.scheduled_at) - .bind(fields.started_at) - .bind(fields.completed_at) - .bind(fields.failed_at) - .bind(fields.error_message) - .execute(mysql_pool) - .await? - .rows_affected(), + fields.payload.clone() }; + for (column, value) in [ + ("id", Value::String(fields.id.to_string())), + ("queue_name", Value::String(fields.queue_name.to_string())), + ("payload", payload), + ("status", Value::String(fields.status.to_string())), + ("priority", Value::from(fields.priority)), + ("attempts", Value::from(fields.attempts)), + ("max_attempts", Value::from(fields.max_attempts)), + ("created_at", time(fields.created_at)), + ("scheduled_at", time(fields.scheduled_at)), + ("started_at", optional_time(fields.started_at)), + ("completed_at", optional_time(fields.completed_at)), + ("failed_at", optional_time(fields.failed_at)), + ( + "error_message", + fields + .error_message + .map_or(Value::Null, |m| Value::String(m.to_string())), + ), + ] { + object.insert(column.to_string(), value); + } + Ok(object) +} - Ok(affected > 0) +/// The insert of one backed-up job into a `hammerwork_jobs` table with `target` columns. +/// +/// Every column in the backup is restored. A non-null value for a column the table does +/// not have is an error (the backup comes from a newer schema), so nothing is lost +/// silently; columns missing from the backup get their defaults. +fn restore_row(job: &Value, target: &[Column]) -> Result { + let object = normalized_backup_job(job)?; + let id = object["id"].as_str().unwrap_or_default().to_string(); + let mut columns = Vec::new(); + let mut params = Vec::new(); + for (name, value) in &object { + match target.iter().find(|column| column.name == *name) { + Some(column) => { + params.push( + Param::from_backup(column, value) + .map_err(|e| anyhow::anyhow!("backup job {}: {}", id, e))?, + ); + columns.push(column.clone()); + } + None if value.is_null() => {} + None => anyhow::bail!( + "backup job {} has a value for column '{}', which this database's \ + hammerwork_jobs table does not have; run `cargo hammerwork migration run` \ + on it first", + id, + name + ), + } + } + Ok(RowInsert { + id, + columns, + params, + }) } async fn list_backups(path: Option) -> Result<()> { @@ -960,11 +1066,11 @@ mod tests { .unwrap(); let doc: Value = serde_json::from_str(&std::fs::read_to_string(&default_out).unwrap()).unwrap(); - assert_eq!(doc["version"], "1.0"); + assert_eq!(doc["version"], BACKUP_VERSION); assert_eq!(doc["total_jobs"], 1); assert_eq!(doc["filters"]["queue"], hostile.as_str()); assert_eq!(doc["jobs"][0]["id"], pending.as_str()); - assert_eq!(doc["jobs"][0]["priority"], "critical"); + assert_eq!(doc["jobs"][0]["priority"], 4); assert_eq!(doc["jobs"][0]["payload"]["to"], "a@example.com"); let full_out = file("full.json"); @@ -1122,4 +1228,333 @@ mod tests { test_backup_roundtrip_postgres, test_backup_roundtrip_mysql ); + + use hammerwork::queue::DatabaseQueue; + use hammerwork::{Job, JobPriority}; + + const TEST_KEY: &str = "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUE="; + + fn test_engine_config() -> hammerwork::encryption::EncryptionConfig { + hammerwork::encryption::EncryptionConfig::new( + hammerwork::encryption::EncryptionAlgorithm::AES256GCM, + ) + .with_key_id("backup-key") + .with_key_source(hammerwork::encryption::KeySource::Static( + TEST_KEY.to_string(), + )) + } + + /// Jobs on `queue_name` that set every kind of attribute: encrypted (whole payload + /// and PII fields, with retention), recurring with a timezone, timeouts, retry + /// strategies, dependencies in a workflow, a batch, a stored result, tracing, and a + /// dead job. Returns their ids. + async fn seed_every_kind( + queue: &hammerwork::JobQueue, + queue_name: &str, + secret: &str, + ) -> Vec + where + DB: sqlx::Database, + hammerwork::JobQueue: hammerwork::queue::DatabaseQueue, + { + use hammerwork::encryption::RetentionPolicy; + use std::time::Duration; + + let q = queue_name.to_string(); + let thirty_days = RetentionPolicy::DeleteAfter(Duration::from_secs(30 * 24 * 3600)); + let mut ids = Vec::new(); + + let whole = Job::new(q.clone(), serde_json::json!({"card": secret})) + .with_encryption(test_engine_config()) + .with_retention_policy(thirty_days.clone()) + .with_priority(JobPriority::High) + .with_max_attempts(7) + .with_timeout(Duration::from_secs(90)); + ids.push(queue.enqueue(whole).await.unwrap()); + + let pii = Job::new(q.clone(), serde_json::json!({"card": secret, "amount": 3})) + .with_encryption(test_engine_config()) + .with_pii_fields(vec!["card"]) + .with_retention_policy(thirty_days) + .with_trace_id("trace-1") + .with_correlation_id("corr-1") + .with_parent_span_id("span-1") + .with_span_context("ctx"); + ids.push(queue.enqueue(pii).await.unwrap()); + + let cron = Job::new(q.clone(), serde_json::json!({"report": "daily"})) + .with_cron( + hammerwork::cron::CronSchedule::with_timezone("0 0 9 * * *", "America/New_York") + .unwrap(), + ) + .unwrap() + .with_retry_strategy(hammerwork::retry::RetryStrategy::exponential( + Duration::from_secs(2), + 2.0, + Some(Duration::from_secs(600)), + )); + ids.push(queue.enqueue_cron_job(cron).await.unwrap()); + + let first = Job::new(q.clone(), serde_json::json!({"step": 1})); + let second = Job::new(q.clone(), serde_json::json!({"step": 2})).depends_on(&first.id); + ids.extend([first.id, second.id]); + queue + .enqueue_workflow( + hammerwork::workflow::JobGroup::new("backup workflow") + .add_job(first) + .add_job(second), + ) + .await + .unwrap(); + + let batched = Job::new(q.clone(), serde_json::json!({"in": "batch"})); + ids.push(batched.id); + queue + .enqueue_batch( + hammerwork::batch::JobBatch::new("backup batch").with_jobs(vec![batched]), + ) + .await + .unwrap(); + + let done = queue + .enqueue( + Job::new(q.clone(), serde_json::json!({"done": true})) + .with_result_ttl(Duration::from_secs(3600)), + ) + .await + .unwrap(); + queue.complete_job(done).await.unwrap(); + queue + .store_job_result( + done, + serde_json::json!({"rows": 42}), + Some(chrono::Utc::now() + chrono::Duration::hours(1)), + ) + .await + .unwrap(); + ids.push(done); + + let dead = queue + .enqueue(Job::new(q, serde_json::json!({"doomed": true}))) + .await + .unwrap(); + queue.mark_job_dead(dead, "gave up").await.unwrap(); + ids.push(dead); + ids + } + + /// Every column of `id`, as text computed by the database (independent of the + /// backup code). + async fn row_fingerprint(pool: &DatabasePool, id: &str) -> String { + match pool { + DatabasePool::Postgres(p) => { + sqlx::query_scalar("SELECT j::text FROM hammerwork_jobs j WHERE id = $1::uuid") + .bind(id) + .fetch_one(p) + .await + .unwrap() + } + DatabasePool::MySQL(p) => { + let columns: Vec<(String, String)> = sqlx::query_as( + "SELECT CAST(COLUMN_NAME AS CHAR), CAST(DATA_TYPE AS CHAR) \ + FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE() \ + AND TABLE_NAME = 'hammerwork_jobs' ORDER BY ORDINAL_POSITION", + ) + .fetch_all(p) + .await + .unwrap(); + let parts = columns + .iter() + .map(|(name, data_type)| { + if data_type.contains("blob") || data_type.contains("binary") { + format!("COALESCE(HEX(`{name}`), 'NULL')") + } else { + format!("COALESCE(CAST(`{name}` AS CHAR), 'NULL')") + } + }) + .collect::>() + .join(", "); + sqlx::query_scalar(&format!( + "SELECT CONCAT_WS('|', {parts}) FROM hammerwork_jobs WHERE id = ?" + )) + .bind(id) + .fetch_one(p) + .await + .unwrap() + } + } + } + + /// The names of every column of hammerwork_jobs, straight from the database. + async fn table_column_names(pool: &DatabasePool) -> Vec { + let sql = match pool.backend() { + Backend::Postgres => { + "SELECT column_name::text AS name FROM information_schema.columns \ + WHERE table_schema = current_schema() AND table_name = 'hammerwork_jobs' \ + ORDER BY ordinal_position" + } + Backend::MySql => { + "SELECT CAST(COLUMN_NAME AS CHAR) AS name FROM information_schema.columns \ + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'hammerwork_jobs' \ + ORDER BY ORDINAL_POSITION" + } + }; + column_strings(pool, sql, &[], "name").await + } + + /// `backup create` + `backup restore` recreate every column of every job exactly, + /// including encrypted payloads, which still decrypt afterwards (#64 C3). + async fn backup_restores_every_column(url: String) { + let config = config_for(&url); + let pool = DatabasePool::connect(&url, 2).await.unwrap(); + let queue_name = unique_queue("backup_full"); + let secret = format!("4111-{}", uuid::Uuid::new_v4().simple()); + let engine = || async { + hammerwork::encryption::EncryptionEngine::new(test_engine_config()) + .await + .unwrap() + }; + let ids: Vec = match pool.clone() { + DatabasePool::Postgres(p) => { + let queue = hammerwork::JobQueue::new(p).with_encryption(engine().await); + seed_every_kind(&queue, &queue_name, &secret).await + } + DatabasePool::MySQL(p) => { + let queue = hammerwork::JobQueue::new(p).with_encryption(engine().await); + seed_every_kind(&queue, &queue_name, &secret).await + } + } + .iter() + .map(uuid::Uuid::to_string) + .collect(); + // Columns no builder sets + exec_sql( + &pool, + &format!( + "UPDATE hammerwork_jobs SET last_heartbeat_at = created_at, \ + lease_expires_at = scheduled_at WHERE queue_name = '{queue_name}'" + ), + ) + .await; + + let mut before = Vec::new(); + for id in &ids { + before.push(row_fingerprint(&pool, id).await); + } + let columns = job_rows::job_columns(&pool).await.unwrap(); + + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("full.json").to_string_lossy().into_owned(); + let run = |args: &[&str]| { + let cmd = parse(args); + let config = config.clone(); + async move { cmd.execute(&config).await } + }; + run(&[ + "create", + "-o", + &file, + "-n", + &queue_name, + "--include-completed", + "--include-failed", + ]) + .await + .unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + assert!(!text.contains(&secret), "the backup holds only ciphertext"); + let doc: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(doc["version"], BACKUP_VERSION); + assert_eq!(doc["total_jobs"], ids.len()); + // Every column of the table is in the backup: a column added by a migration + // that backups could not copy fails here. + let backed_up: Vec = doc["columns"] + .as_array() + .unwrap() + .iter() + .map(|c| c.as_str().unwrap().to_string()) + .collect(); + assert_eq!(backed_up, table_column_names(&pool).await); + for job in doc["jobs"].as_array().unwrap() { + assert_eq!(job.as_object().unwrap().len(), backed_up.len()); + } + + // Wipe and restore + cleanup(&pool, &[&queue_name]).await; + run(&["restore", "-i", &file, "--confirm"]).await.unwrap(); + for (id, fingerprint) in ids.iter().zip(&before) { + assert_eq!( + &row_fingerprint(&pool, id).await, + fingerprint, + "job {id} differs after restore" + ); + } + // The reader agrees column by column (clearer failures than the fingerprint) + let restored = fetch_backup_rows(&pool, &columns, Some(&queue_name), true, true) + .await + .unwrap(); + assert_eq!( + Value::from(restored.into_iter().map(Value::Object).collect::>()), + doc["jobs"] + ); + + // Encrypted jobs decrypt after the restore + let opened = match pool.clone() { + DatabasePool::Postgres(p) => { + let queue = hammerwork::JobQueue::new(p).with_encryption(engine().await); + let mut payloads = Vec::new(); + for id in &ids[..2] { + let job = queue + .get_job(uuid::Uuid::parse_str(id).unwrap()) + .await + .unwrap() + .unwrap(); + assert!(job.is_encrypted); + payloads.push(queue.decrypt_job(job).await.unwrap().payload); + } + payloads + } + DatabasePool::MySQL(p) => { + let queue = hammerwork::JobQueue::new(p).with_encryption(engine().await); + let mut payloads = Vec::new(); + for id in &ids[..2] { + let job = queue + .get_job(uuid::Uuid::parse_str(id).unwrap()) + .await + .unwrap() + .unwrap(); + assert!(job.is_encrypted); + payloads.push(queue.decrypt_job(job).await.unwrap().payload); + } + payloads + } + }; + assert_eq!(opened[0], serde_json::json!({"card": secret})); + assert_eq!(opened[1], serde_json::json!({"card": secret, "amount": 3})); + + // Restoring again changes nothing: existing ids are skipped, never duplicated + run(&["restore", "-i", &file, "--confirm"]).await.unwrap(); + assert_eq!(count_jobs(&pool, &queue_name, None).await, ids.len() as i64); + for (id, fingerprint) in ids.iter().zip(&before) { + assert_eq!(&row_fingerprint(&pool, id).await, fingerprint); + } + + // A backup with a column this database lacks restores nothing + cleanup(&pool, &[&queue_name]).await; + let mut newer = doc.clone(); + newer["jobs"][ids.len() - 1]["column_from_the_future"] = Value::from("x"); + let newer_file = dir.path().join("newer.json").to_string_lossy().into_owned(); + std::fs::write(&newer_file, newer.to_string()).unwrap(); + let err = run(&["restore", "-i", &newer_file, "--confirm"]) + .await + .unwrap_err(); + assert!(err.to_string().contains("column_from_the_future"), "{err}"); + assert_eq!(count_jobs(&pool, &queue_name, None).await, 0); + } + + db_tests!( + backup_restores_every_column, + test_backup_restores_every_column_postgres, + test_backup_restores_every_column_mysql + ); } diff --git a/cargo-hammerwork/src/commands/batch.rs b/cargo-hammerwork/src/commands/batch.rs index 93d08eb..0a0913d 100644 --- a/cargo-hammerwork/src/commands/batch.rs +++ b/cargo-hammerwork/src/commands/batch.rs @@ -108,6 +108,7 @@ impl BatchCommand { } => { batch_enqueue( pool, + &config.encryption_settings()?, file.clone(), queue, priority.clone(), @@ -237,14 +238,13 @@ pub fn parse_job_line( /// Enqueue every record of `reader` (see [`parse_job_line`]). A bad record stops the run unless /// `continue_on_error`, and is reported on stderr either way. pub async fn enqueue_lines( - pool: DatabasePool, + queue: JobQueueWrapper, reader: impl BufRead, default_queue: &str, default_priority: Option<&str>, progress_every: u32, continue_on_error: bool, ) -> Result { - let queue = pool.create_job_queue(); let mut summary = EnqueueSummary::default(); for (line_num, line) in reader.lines().enumerate() { @@ -283,6 +283,7 @@ pub async fn enqueue_lines( async fn batch_enqueue( pool: DatabasePool, + encryption: &hammerwork::config::PayloadEncryptionConfig, file: Option, default_queue: &str, default_priority: Option, @@ -303,8 +304,10 @@ async fn batch_enqueue( Box::new(BufReader::new(std::io::stdin())) }; + // Encrypts like the application, and never writes plaintext to encrypted queues + let queue = pool.create_enqueue_queue(encryption).await?; let summary = enqueue_lines( - pool, + queue, reader, default_queue, default_priority.as_deref(), diff --git a/cargo-hammerwork/src/commands/config.rs b/cargo-hammerwork/src/commands/config.rs index 8ac76ae..a7d9a93 100644 --- a/cargo-hammerwork/src/commands/config.rs +++ b/cargo-hammerwork/src/commands/config.rs @@ -58,52 +58,79 @@ impl ConfigCommand { } } +/// The rows of `config show`: setting, value, source. Secrets are never shown: the +/// database URL's password is replaced by `***`, and encryption keys are only ever +/// referenced (`env://VAR`, a KMS URI), never stored in a configuration. +fn config_rows( + config: &Config, + env: impl Fn(&str) -> Option, +) -> Vec<(&'static str, String, &'static str)> { + let from = |value: &Option, var: &str| match (value, env(var)) { + (Some(value), _) => (value.clone(), "Config File"), + (None, Some(value)) => (value, "Environment"), + (None, None) => ("Not set".to_string(), "Default"), + }; + let (db_url, db_source) = from(&config.database_url, "DATABASE_URL"); + let db_url = crate::utils::validation::redact_url(&db_url); + let (queue, queue_source) = from(&config.default_queue, "HAMMERWORK_DEFAULT_QUEUE"); + let (encryption_config, encryption_source) = + from(&config.encryption_config, "HAMMERWORK_ENCRYPTION_CONFIG"); + let encryption = match config.encryption_settings() { + Ok(settings) if settings.enabled => format!( + "enabled ({:?}, key {} from {}, encrypted queues: {})", + settings.algorithm, + settings.key_id.as_deref().unwrap_or("default"), + settings.key_source, + if settings.encrypted_queues.is_empty() { + "none".to_string() + } else { + settings.encrypted_queues.join(", ") + } + ), + Ok(_) => "disabled".to_string(), + Err(e) => format!("invalid: {}", e), + }; + vec![ + ("database_url", db_url, db_source), + ("default_queue", queue, queue_source), + ( + "default_limit", + config.get_default_limit().to_string(), + "Config File", + ), + ( + "log_level", + config.get_log_level().to_string(), + "Config File", + ), + ( + "connection_pool_size", + config.get_connection_pool_size().to_string(), + "Config File", + ), + ( + "connect_timeout_secs", + config.get_connect_timeout_secs().to_string(), + "Config File", + ), + ("encryption_config", encryption_config, encryption_source), + ( + "encryption", + encryption, + "encryption_config + HAMMERWORK_ENCRYPTION_*", + ), + ] +} + async fn show_config(config: &Config) -> Result<()> { println!("⚙️ Hammerwork Configuration"); println!("═══════════════════════════"); let mut table = comfy_table::Table::new(); table.set_header(vec!["Setting", "Value", "Source"]); - - // Database URL - let (db_url, db_source) = if let Some(url) = &config.database_url { - (url.clone(), "Config File") - } else if let Ok(env_url) = std::env::var("DATABASE_URL") { - (env_url, "Environment") - } else { - ("Not set".to_string(), "Default") - }; - table.add_row(vec!["database_url", &db_url, db_source]); - - // Default queue - let (queue, queue_source) = if let Some(q) = &config.default_queue { - (q.clone(), "Config File") - } else if let Ok(env_queue) = std::env::var("HAMMERWORK_DEFAULT_QUEUE") { - (env_queue, "Environment") - } else { - ("Not set".to_string(), "Default") - }; - table.add_row(vec!["default_queue", &queue, queue_source]); - - // Default limit - let limit = config.get_default_limit().to_string(); - table.add_row(vec!["default_limit", &limit, "Config File"]); - - // Log level - let log_level = config.get_log_level(); - table.add_row(vec!["log_level", log_level, "Config File"]); - - // Connection pool size - let pool_size = config.get_connection_pool_size().to_string(); - table.add_row(vec!["connection_pool_size", &pool_size, "Config File"]); - - // Connect timeout - let connect_timeout = config.get_connect_timeout_secs().to_string(); - table.add_row(vec![ - "connect_timeout_secs", - &connect_timeout, - "Config File", - ]); + for (setting, value, source) in config_rows(config, |var| std::env::var(var).ok()) { + table.add_row(vec![setting, value.as_str(), source]); + } println!("{}", table); @@ -165,10 +192,20 @@ async fn set_config_value(config: &mut Config, key: &str, value: &str, path: &Pa config.connect_timeout_secs = Some(secs); info!("✅ Set connect_timeout_secs to: {}", secs); } + "encryption_config" => { + let candidate = Config { + encryption_config: Some(value.to_string()), + ..config.clone() + }; + candidate.encryption_settings()?; + config.encryption_config = Some(value.to_string()); + info!("✅ Set encryption_config to: {}", value); + } _ => { return Err(anyhow::anyhow!( - "Unknown configuration key: {}. Valid keys: database_url, default_queue, default_limit, log_level, connection_pool_size, connect_timeout_secs", - key + "Unknown configuration key: {}. Valid keys: {}", + key, + VALID_KEYS )); } } @@ -188,10 +225,16 @@ async fn get_config_value(config: &Config, key: &str) -> Result<()> { "log_level" => config.get_log_level().to_string(), "connection_pool_size" => config.get_connection_pool_size().to_string(), "connect_timeout_secs" => config.get_connect_timeout_secs().to_string(), + "encryption_config" => config + .encryption_config + .as_deref() + .unwrap_or("Not set") + .to_string(), _ => { return Err(anyhow::anyhow!( - "Unknown configuration key: {}. Valid keys: database_url, default_queue, default_limit, log_level, connection_pool_size, connect_timeout_secs", - key + "Unknown configuration key: {}. Valid keys: {}", + key, + VALID_KEYS )); } }; @@ -200,6 +243,9 @@ async fn get_config_value(config: &Config, key: &str) -> Result<()> { Ok(()) } +const VALID_KEYS: &str = "database_url, default_queue, default_limit, log_level, \ + connection_pool_size, connect_timeout_secs, encryption_config"; + async fn reset_config(config: &mut Config, confirm: bool, path: &Path) -> Result<()> { if !confirm { println!("⚠️ This will reset all configuration to defaults. Use --confirm to proceed."); @@ -404,6 +450,99 @@ mod tests { ); } + #[test] + fn show_never_prints_the_database_password() { + let config = Config { + database_url: Some("postgres://app:hunter2-db@db.internal/jobs".into()), + ..Config::default() + }; + let rows = config_rows(&config, |_| None); + let shown = format!("{rows:?}"); + assert!(!shown.contains("hunter2-db"), "{shown}"); + assert!( + shown.contains("postgres://app:***@db.internal/jobs"), + "{shown}" + ); + assert!(!format!("{config:?}").contains("hunter2-db")); + + // Also when the URL comes from the environment + let rows = config_rows(&Config::default(), |var| { + (var == "DATABASE_URL").then(|| "mysql://root:hunter2-env@db/jobs".to_string()) + }); + let (_, url, source) = &rows[0]; + assert_eq!( + (url.as_str(), *source), + ("mysql://root:***@db/jobs", "Environment") + ); + } + + #[test] + fn show_summarises_the_encryption_settings() { + let _guard = crate::utils::test_support::serial_blocking(); + let dir = tempfile::tempdir().unwrap(); + let app = dir.path().join("hammerwork.toml"); + std::fs::write( + &app, + "[encryption]\nenabled = true\nkey_source = \"env://APP_KEY\"\n\ + encrypted_queues = [\"payments\"]\n", + ) + .unwrap(); + let config = Config { + encryption_config: Some(app.to_string_lossy().into_owned()), + ..Config::default() + }; + let rows = config_rows(&config, |_| None); + let encryption = &rows.iter().find(|r| r.0 == "encryption").unwrap().1; + assert!(encryption.starts_with("enabled"), "{encryption}"); + assert!(encryption.contains("env://APP_KEY"), "{encryption}"); + assert!(encryption.contains("payments"), "{encryption}"); + let rows = config_rows(&Config::default(), |_| None); + assert_eq!( + rows.iter().find(|r| r.0 == "encryption").unwrap().1, + "disabled" + ); + } + + #[tokio::test] + async fn encryption_config_can_be_set_and_read() { + let _guard = crate::utils::test_support::serial().await; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + let app = dir.path().join("hammerwork.toml"); + std::fs::write(&app, "[encryption]\nenabled = false\n").unwrap(); + let mut config = Config::default(); + run( + &["set", "encryption_config", app.to_str().unwrap()], + &mut config, + &path, + ) + .await + .unwrap(); + assert_eq!( + Config::load_from_path(&path) + .unwrap() + .encryption_config + .as_deref(), + app.to_str() + ); + run(&["get", "encryption_config"], &mut config, &path) + .await + .unwrap(); + // A file that cannot be read is rejected and not saved + let err = run( + &["set", "encryption_config", "/no/such/hammerwork.toml"], + &mut config, + &path, + ) + .await + .unwrap_err(); + assert!( + err.to_string().contains("Invalid encryption settings"), + "{err}" + ); + assert_eq!(config.encryption_config.as_deref(), app.to_str()); + } + #[tokio::test] async fn show_and_path_work_with_and_without_a_file() { let dir = tempfile::tempdir().unwrap(); diff --git a/cargo-hammerwork/src/commands/cron.rs b/cargo-hammerwork/src/commands/cron.rs index c2febf7..a5466f7 100644 --- a/cargo-hammerwork/src/commands/cron.rs +++ b/cargo-hammerwork/src/commands/cron.rs @@ -121,8 +121,11 @@ impl CronCommand { priority, .. } => { + let job_queue = pool + .create_enqueue_queue(&config.encryption_settings()?) + .await?; create_cron_job( - pool, + job_queue, queue, payload, schedule, @@ -355,7 +358,7 @@ pub fn build_cron_job( } async fn create_cron_job( - pool: DatabasePool, + job_queue: JobQueueWrapper, queue: &str, payload: &str, schedule: &str, @@ -368,7 +371,7 @@ async fn create_cron_job( let timezone = job.timezone.clone().unwrap_or_else(|| "UTC".to_string()); info!("Creating cron job with schedule: {}", schedule); - let job_id = match pool.create_job_queue() { + let job_id = match job_queue { JobQueueWrapper::Postgres(q) => q.enqueue_cron_job(job).await?, JobQueueWrapper::MySQL(q) => q.enqueue_cron_job(job).await?, }; diff --git a/cargo-hammerwork/src/commands/job.rs b/cargo-hammerwork/src/commands/job.rs index b3f0840..084dd41 100644 --- a/cargo-hammerwork/src/commands/job.rs +++ b/cargo-hammerwork/src/commands/job.rs @@ -64,6 +64,19 @@ pub enum JobCommand { max_attempts: Option, #[arg(long, help = "Timeout in seconds")] timeout: Option, + #[arg( + long, + help = "Encrypt the payload with the application's encryption key (see the \ + encryption_config setting), even if the queue is not one of its \ + encrypted_queues" + )] + encrypt: bool, + #[arg( + long = "pii-field", + value_name = "FIELD", + help = "Encrypt only this payload field (repeatable; implies --encrypt)" + )] + pii_fields: Vec, }, #[command( about = "Retry failed, dead and timed-out jobs", @@ -197,16 +210,25 @@ impl JobCommand { delay, max_attempts, timeout, + encrypt, + pii_fields, .. } => { + let job_queue = pool + .create_enqueue_queue(&config.encryption_settings()?) + .await?; enqueue_job( - pool, + job_queue, queue, payload, priority, *delay, *max_attempts, *timeout, + EncryptionRequest { + encrypt: *encrypt, + pii_fields: pii_fields.clone(), + }, ) .await?; } @@ -626,14 +648,52 @@ fn encryption_detail_lines(details: &EncryptionDetails) -> Vec { lines } +/// `job enqueue --encrypt` / `--pii-field`. +#[derive(Debug, Clone, Default)] +struct EncryptionRequest { + encrypt: bool, + pii_fields: Vec, +} + +/// Ask for `job` to be encrypted with `job_queue`'s engine (the application's key), as +/// requested by `--encrypt` / `--pii-field`. Fails if the queue has no engine. +fn request_encryption( + job: Job, + job_queue: &JobQueueWrapper, + request: &EncryptionRequest, +) -> Result { + if !request.encrypt && request.pii_fields.is_empty() { + return Ok(job); + } + let engine = job_queue.encryption_engine().ok_or_else(|| { + anyhow::anyhow!( + "--encrypt and --pii-field need the application's encryption settings with \ + encryption enabled: set encryption_config (`cargo hammerwork config set \ + encryption_config `) or the HAMMERWORK_ENCRYPTION_* \ + environment variables, and make its key available" + ) + })?; + let mut config = hammerwork::encryption::EncryptionConfig::new(engine.algorithm().clone()) + .with_key_id(engine.key_id()); + config.compression_enabled = engine.config().compression_enabled; + let job = job.with_encryption(config); + Ok(if request.pii_fields.is_empty() { + job + } else { + job.with_pii_fields(request.pii_fields.clone()) + }) +} + +#[allow(clippy::too_many_arguments)] async fn enqueue_job( - pool: DatabasePool, + job_queue: JobQueueWrapper, queue: &str, payload: &str, priority: &Option, delay: Option, max_attempts: Option, timeout: Option, + encryption: EncryptionRequest, ) -> Result<()> { let payload_value = validate_json_payload(payload)?; let job_priority = if let Some(p) = priority { @@ -642,8 +702,11 @@ async fn enqueue_job( JobPriority::Normal }; - let job_queue = pool.create_job_queue(); - let mut job = Job::new(queue.to_string(), payload_value); + let mut job = request_encryption( + Job::new(queue.to_string(), payload_value), + &job_queue, + &encryption, + )?; job.priority = job_priority; if let Some(max_att) = max_attempts { @@ -1603,4 +1666,172 @@ mod tests { test_job_commands_postgres, test_job_commands_mysql ); + + /// `job enqueue` encrypts like the application (its `[encryption]` settings), and + /// without them refuses to write plaintext to a queue that holds encrypted jobs + /// (#64 H1). + async fn enqueue_follows_the_application_encryption(url: String) { + use base64::Engine as _; + + let _guard = serial().await; + let pool = DatabasePool::connect(&url, 2).await.unwrap(); + let encrypted_q = unique_queue("cli_enc"); + let plain_q = unique_queue("cli_plain"); + let key_var = format!("HW_CLI_TEST_KEY_{}", uuid::Uuid::new_v4().simple()); + let key = base64::engine::general_purpose::STANDARD.encode([7u8; 32]); + // SAFETY: tests touching the environment hold the `serial` lock. + unsafe { std::env::set_var(&key_var, &key) }; + + let dir = tempfile::tempdir().unwrap(); + let app_config = dir.path().join("hammerwork.toml"); + std::fs::write( + &app_config, + format!( + "[database]\nurl = \"ignored\"\n\n[encryption]\nenabled = true\n\ + key_source = \"env://{key_var}\"\nkey_id = \"cli-key\"\n\ + encrypted_queues = [\"{encrypted_q}\"]\n" + ), + ) + .unwrap(); + let with_app = Config { + encryption_config: Some(app_config.to_string_lossy().into_owned()), + ..config_for(&url) + }; + let without_app = config_for(&url); + let run = |config: &Config, args: &[&str]| { + let cmd = parse(args); + let config = config.clone(); + async move { cmd.execute(&config).await } + }; + let ids = |queue: String| { + let pool = pool.clone(); + async move { fetch_job_ids(&pool, &queue).await } + }; + let secret = format!("4111-{}", uuid::Uuid::new_v4().simple()); + let payload = format!(r#"{{"card": "{secret}", "amount": 5}}"#); + + // An encrypted queue of the application: encrypted without asking + run(&with_app, &["enqueue", "-n", &encrypted_q, "-j", &payload]) + .await + .unwrap(); + let id = ids(encrypted_q.clone()).await.pop().unwrap(); + let is_encrypted = job_column(&pool, &id, "is_encrypted").await.unwrap(); + assert!( + is_encrypted == "true" || is_encrypted == "1", + "{is_encrypted}" + ); + assert_eq!( + job_column(&pool, &id, "encryption_key_id").await.as_deref(), + Some("cli-key") + ); + let stored = job_column(&pool, &id, "payload").await.unwrap(); + assert!(!stored.contains(&secret), "{stored}"); + + // --encrypt / --pii-field encrypt jobs for any queue + run( + &with_app, + &[ + "enqueue", + "-n", + &plain_q, + "-j", + &payload, + "--pii-field", + "card", + ], + ) + .await + .unwrap(); + let id = ids(plain_q.clone()).await.pop().unwrap(); + let stored = job_column(&pool, &id, "payload").await.unwrap(); + assert!( + !stored.contains(&secret) && stored.contains("amount"), + "{stored}" + ); + assert!( + job_column(&pool, &id, "pii_fields") + .await + .unwrap() + .contains("card") + ); + + // The application's engine decrypts what the CLI wrote + let app_queue = match pool.clone() { + DatabasePool::Postgres(p) => JobQueueWrapper::Postgres(hammerwork::JobQueue::new(p)), + DatabasePool::MySQL(p) => JobQueueWrapper::MySQL(hammerwork::JobQueue::new(p)), + }; + let engine = hammerwork::encryption::EncryptionEngine::new( + hammerwork::encryption::EncryptionConfig::new( + hammerwork::encryption::EncryptionAlgorithm::AES256GCM, + ) + .with_key_id("cli-key") + .with_key_source(hammerwork::encryption::KeySource::Static(key.clone())), + ) + .await + .unwrap(); + let job_id = uuid::Uuid::parse_str(&id).unwrap(); + let opened = match app_queue { + JobQueueWrapper::Postgres(q) => { + let q = q.with_encryption(engine); + q.decrypt_job(q.get_job(job_id).await.unwrap().unwrap()) + .await + } + JobQueueWrapper::MySQL(q) => { + let q = q.with_encryption(engine); + q.decrypt_job(q.get_job(job_id).await.unwrap().unwrap()) + .await + } + } + .unwrap(); + assert_eq!(opened.payload["card"], secret.as_str()); + + // Without the application's settings: refused on the queue holding encrypted + // jobs, for jobs, cron jobs and batches; other queues are unaffected. + let before = count_jobs(&pool, &encrypted_q, None).await; + let err = run( + &without_app, + &["enqueue", "-n", &encrypted_q, "-j", &payload], + ) + .await + .unwrap_err(); + assert!(err.to_string().contains("holds encrypted jobs"), "{err}"); + let cron = crate::commands::cron::CronCommand::Create { + database_url: None, + queue: encrypted_q.clone(), + payload: payload.clone(), + schedule: "0 0 0 1 1 *".to_string(), + timezone: None, + priority: None, + }; + assert!(cron.execute(&without_app).await.is_err()); + assert_eq!(count_jobs(&pool, &encrypted_q, None).await, before); + let err = run( + &without_app, + &["enqueue", "-n", &plain_q, "-j", "{}", "--encrypt"], + ) + .await + .unwrap_err(); + assert!(err.to_string().contains("--encrypt"), "{err}"); + let fresh_q = unique_queue("cli_fresh"); + run(&without_app, &["enqueue", "-n", &fresh_q, "-j", "{}"]) + .await + .unwrap(); + + // Settings whose key is unavailable: nothing is written + // SAFETY: as above. + unsafe { std::env::remove_var(&key_var) }; + let err = run(&with_app, &["enqueue", "-n", &fresh_q, "-j", "{}"]) + .await + .unwrap_err(); + assert!(err.to_string().contains("refusing to write jobs"), "{err}"); + assert_eq!(count_jobs(&pool, &fresh_q, None).await, 1); + + cleanup(&pool, &[&encrypted_q, &plain_q, &fresh_q]).await; + } + + db_tests!( + enqueue_follows_the_application_encryption, + test_enqueue_follows_the_application_encryption_postgres, + test_enqueue_follows_the_application_encryption_mysql + ); } diff --git a/cargo-hammerwork/src/commands/workflow.rs b/cargo-hammerwork/src/commands/workflow.rs index d52f0f4..13cd37d 100644 --- a/cargo-hammerwork/src/commands/workflow.rs +++ b/cargo-hammerwork/src/commands/workflow.rs @@ -318,6 +318,7 @@ impl WorkflowCommand { } => { self.create_workflow( pool, + &config.encryption_settings()?, name, jobs_file, failure_policy.as_deref(), @@ -412,6 +413,7 @@ impl WorkflowCommand { async fn create_workflow( &self, pool: DatabasePool, + encryption: &hammerwork::config::PayloadEncryptionConfig, name: &str, jobs_file: &str, failure_policy: Option<&str>, @@ -448,7 +450,8 @@ impl WorkflowCommand { format!("{:?}", workflow.failure_policy), ); - match pool.create_job_queue() { + // Encrypts like the application, and never writes plaintext to encrypted queues + match pool.create_enqueue_queue(encryption).await? { JobQueueWrapper::Postgres(q) => q.enqueue_workflow(workflow).await?, JobQueueWrapper::MySQL(q) => q.enqueue_workflow(workflow).await?, }; diff --git a/cargo-hammerwork/src/config/mod.rs b/cargo-hammerwork/src/config/mod.rs index f48b4c6..1a59ad7 100644 --- a/cargo-hammerwork/src/config/mod.rs +++ b/cargo-hammerwork/src/config/mod.rs @@ -116,7 +116,9 @@ use std::path::{Path, PathBuf}; /// assert_eq!(config.get_log_level(), "info"); /// assert_eq!(config.get_connection_pool_size(), 5); /// ``` -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` shows `database_url` with its password replaced by `***`. +#[derive(Clone, Serialize, Deserialize)] pub struct Config { /// Database connection URL (e.g., "postgresql://localhost/hammerwork") pub database_url: Option, @@ -136,6 +138,33 @@ pub struct Config { /// Seconds to wait for a database connection before failing (default 10) #[serde(default)] pub connect_timeout_secs: Option, + + /// Path of the application's `hammerwork.toml`, whose `[encryption]` section commands + /// that write jobs (`job enqueue`, `batch enqueue`, `cron create`, + /// `workflow create`) use, so they encrypt exactly like the application. See + /// [`Config::encryption_settings`]. + #[serde(default)] + pub encryption_config: Option, +} + +impl std::fmt::Debug for Config { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Config") + .field( + "database_url", + &self + .database_url + .as_deref() + .map(crate::utils::validation::redact_url), + ) + .field("default_queue", &self.default_queue) + .field("default_limit", &self.default_limit) + .field("log_level", &self.log_level) + .field("connection_pool_size", &self.connection_pool_size) + .field("connect_timeout_secs", &self.connect_timeout_secs) + .field("encryption_config", &self.encryption_config) + .finish() + } } impl Default for Config { @@ -147,6 +176,7 @@ impl Default for Config { log_level: Some("info".to_string()), connection_pool_size: Some(5), connect_timeout_secs: None, + encryption_config: None, } } } @@ -217,6 +247,24 @@ impl Config { if let Some(secs) = get("HAMMERWORK_CONNECT_TIMEOUT").and_then(|v| v.parse().ok()) { self.connect_timeout_secs = Some(secs); } + if let Some(path) = get("HAMMERWORK_ENCRYPTION_CONFIG").filter(|p| !p.is_empty()) { + self.encryption_config = Some(path); + } + } + + /// The application's payload encryption settings, for commands that write jobs. + /// + /// The `[encryption]` section of [`Config::encryption_config`] (the application's + /// `hammerwork.toml`; `HAMMERWORK_ENCRYPTION_CONFIG` overrides it), with the + /// `HAMMERWORK_ENCRYPTION_*` environment variables applied on top, exactly as + /// `HammerworkConfig::from_env` does for the application. Without either, encryption + /// is disabled: the CLI then still refuses to write plaintext jobs to queues that hold + /// encrypted jobs (see `DatabasePool::create_enqueue_queue`). + pub fn encryption_settings(&self) -> Result { + hammerwork::config::PayloadEncryptionConfig::load( + self.encryption_config.as_deref().map(Path::new), + ) + .map_err(|e| anyhow::anyhow!("Invalid encryption settings: {}", e)) } /// Save configuration to file. @@ -354,6 +402,7 @@ mod tests { log_level: None, connection_pool_size: None, connect_timeout_secs: None, + encryption_config: None, }; assert_eq!(bare.get_default_limit(), 50); assert_eq!(bare.get_log_level(), "info"); @@ -443,6 +492,7 @@ mod tests { log_level: Some("warn".into()), connection_pool_size: Some(3), connect_timeout_secs: Some(7), + encryption_config: None, }; config.save_to(&path).unwrap(); let loaded = Config::load_from_path(&path).unwrap(); diff --git a/cargo-hammerwork/src/utils/database.rs b/cargo-hammerwork/src/utils/database.rs index 295cdb4..463485b 100644 --- a/cargo-hammerwork/src/utils/database.rs +++ b/cargo-hammerwork/src/utils/database.rs @@ -255,6 +255,47 @@ impl DatabasePool { } } + /// Create a job queue for commands that write new jobs (`job enqueue`, + /// `batch enqueue`, `cron create`, `workflow create`). + /// + /// The queue encrypts like the application: when `encryption` (the application's + /// `[encryption]` settings, see [`Config::encryption_settings`]) is enabled, its key + /// is loaded and jobs on its `encrypted_queues` are encrypted. A key that cannot be + /// loaded is an error: the CLI never falls back to writing plaintext. The queue also + /// has the plaintext guard (`JobQueue::with_plaintext_guard`), so even without + /// encryption settings it refuses to write a plaintext job to a queue that already + /// holds encrypted jobs. + /// + /// [`Config::encryption_settings`]: crate::config::Config::encryption_settings + pub async fn create_enqueue_queue( + self, + encryption: &hammerwork::config::PayloadEncryptionConfig, + ) -> Result { + let key_error = |e: hammerwork::HammerworkError| { + anyhow::anyhow!( + "Cannot set up payload encryption from the application's [encryption] \ + settings ({}); refusing to write jobs rather than store them in plaintext", + e + ) + }; + Ok(match self { + DatabasePool::Postgres(pool) => JobQueueWrapper::Postgres( + JobQueue::new(pool) + .apply_encryption_config(encryption) + .await + .map_err(key_error)? + .with_plaintext_guard(true), + ), + DatabasePool::MySQL(pool) => JobQueueWrapper::MySQL( + JobQueue::new(pool) + .apply_encryption_config(encryption) + .await + .map_err(key_error)? + .with_plaintext_guard(true), + ), + }) + } + /// Run database migrations. /// /// This method runs all pending migrations on the connected database. @@ -360,6 +401,19 @@ pub enum JobQueueWrapper { MySQL(JobQueue), } +impl JobQueueWrapper { + /// The queue's encryption engine, if it has one + /// ([`DatabasePool::create_enqueue_queue`] with encryption enabled). + pub fn encryption_engine( + &self, + ) -> Option<&std::sync::Arc> { + match self { + JobQueueWrapper::Postgres(queue) => queue.encryption_engine(), + JobQueueWrapper::MySQL(queue) => queue.encryption_engine(), + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/cargo-hammerwork/src/utils/job_rows.rs b/cargo-hammerwork/src/utils/job_rows.rs new file mode 100644 index 0000000..305cc46 --- /dev/null +++ b/cargo-hammerwork/src/utils/job_rows.rs @@ -0,0 +1,636 @@ +//! Whole rows of `hammerwork_jobs`, for `backup create` and `backup restore`. +//! +//! The columns are read from `information_schema`, so every column a migration adds is +//! backed up and restored without a list to keep in sync: encrypted payloads and their +//! encryption metadata, cron schedules, timeouts, retry strategies, dependencies, +//! workflows, results, tracing and retention all round-trip. A column whose type this +//! module does not know is an error, never silently dropped. +//! +//! Values are written in one encoding for both backends, so a backup taken from +//! PostgreSQL can be restored into MySQL and the other way round: +//! +//! | Column type | Backup value | +//! |-----------------------------------------------|-------------------------------------| +//! | `uuid`, `char`/`varchar`/`text` | string | +//! | integers | number | +//! | `boolean`, MySQL `tinyint(1)` | `true` / `false` | +//! | `timestamptz`, `timestamp`, `datetime` | RFC 3339 string, microseconds, UTC | +//! | `jsonb`, `json` | the JSON value | +//! | `bytea`, `blob` (encrypted payloads) | base64 string | +//! | PostgreSQL `uuid[]`, `text[]` | array of strings | +//! +//! SQL `NULL` is `null`. + +use anyhow::{Result, anyhow, bail}; +use base64::Engine; +use chrono::{DateTime, SecondsFormat, Utc}; +use serde_json::{Map, Value}; +use sqlx::Row; +use uuid::Uuid; + +use crate::utils::database::DatabasePool; +use crate::utils::sql::Backend; + +/// How the values of a column are read, written to a backup, and bound back. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ColumnKind { + Uuid, + Text, + Int, + Bool, + Timestamp, + Json, + Bytes, + UuidArray, + TextArray, +} + +impl ColumnKind { + /// The kind of a PostgreSQL column, from its `information_schema` `udt_name`. + pub fn postgres(udt_name: &str) -> Option { + Some(match udt_name { + "uuid" => Self::Uuid, + "varchar" | "text" | "bpchar" => Self::Text, + "int2" | "int4" | "int8" => Self::Int, + "bool" => Self::Bool, + "timestamptz" | "timestamp" => Self::Timestamp, + "jsonb" | "json" => Self::Json, + "bytea" => Self::Bytes, + "_uuid" => Self::UuidArray, + "_text" | "_varchar" => Self::TextArray, + _ => return None, + }) + } + + /// The kind of a MySQL column, from its `information_schema` `DATA_TYPE` and + /// `COLUMN_TYPE`. + pub fn mysql(data_type: &str, column_type: &str) -> Option { + Some(match data_type { + "tinyint" if column_type.starts_with("tinyint(1)") => Self::Bool, + "tinyint" | "smallint" | "mediumint" | "int" | "bigint" => Self::Int, + "char" | "varchar" | "tinytext" | "text" | "mediumtext" | "longtext" => Self::Text, + "timestamp" | "datetime" => Self::Timestamp, + "json" => Self::Json, + "tinyblob" | "blob" | "mediumblob" | "longblob" | "binary" | "varbinary" => Self::Bytes, + _ => return None, + }) + } +} + +/// A column of `hammerwork_jobs`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Column { + pub name: String, + pub kind: ColumnKind, +} + +/// The columns of `hammerwork_jobs`, in table order. +/// +/// Fails on a column whose type backups cannot copy, so a column added by a future +/// migration is reported instead of being left out of backups. +pub async fn job_columns(pool: &DatabasePool) -> Result> { + let described: Vec<(String, Option, String)> = match pool { + DatabasePool::Postgres(p) => { + let rows: Vec<(String, String)> = sqlx::query_as( + "SELECT column_name::text, udt_name::text FROM information_schema.columns \ + WHERE table_schema = current_schema() AND table_name = 'hammerwork_jobs' \ + ORDER BY ordinal_position", + ) + .fetch_all(p) + .await?; + rows.into_iter() + .map(|(name, udt)| (name, ColumnKind::postgres(&udt), udt)) + .collect() + } + DatabasePool::MySQL(p) => { + let rows: Vec<(String, String, String)> = sqlx::query_as( + "SELECT CAST(COLUMN_NAME AS CHAR), CAST(DATA_TYPE AS CHAR), \ + CAST(COLUMN_TYPE AS CHAR) FROM information_schema.columns \ + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'hammerwork_jobs' \ + ORDER BY ORDINAL_POSITION", + ) + .fetch_all(p) + .await?; + rows.into_iter() + .map(|(name, data_type, column_type)| { + let kind = ColumnKind::mysql(&data_type, &column_type); + (name, kind, column_type) + }) + .collect() + } + }; + if described.is_empty() { + bail!("Table hammerwork_jobs not found; run `cargo hammerwork migration run` first"); + } + described + .into_iter() + .map(|(name, kind, sql_type)| { + let kind = kind.ok_or_else(|| { + anyhow!( + "Column hammerwork_jobs.{} has type {}, which backups cannot copy yet", + name, + sql_type + ) + })?; + Ok(Column { name, kind }) + }) + .collect() +} + +/// A column name quoted as an identifier. +fn quoted(backend: Backend, name: &str) -> String { + match backend { + Backend::Postgres => format!("\"{}\"", name.replace('"', "\"\"")), + Backend::MySql => format!("`{}`", name.replace('`', "``")), + } +} + +/// The `SELECT` list reading `columns` in the form [`row_to_json`] decodes. +pub fn select_list(backend: Backend, columns: &[Column]) -> String { + columns + .iter() + .map(|column| { + let name = quoted(backend, &column.name); + match (backend, column.kind) { + (Backend::Postgres, ColumnKind::Int) => format!("{name}::bigint AS {name}"), + (Backend::Postgres, ColumnKind::Timestamp) => { + format!("{name}::timestamptz AS {name}") + } + (Backend::MySql, ColumnKind::Int) => format!("CAST({name} AS SIGNED) AS {name}"), + _ => name, + } + }) + .collect::>() + .join(", ") +} + +fn timestamp_value(t: Option>) -> Value { + t.map_or(Value::Null, |t| { + Value::String(t.to_rfc3339_opts(SecondsFormat::Micros, true)) + }) +} + +fn strings_value(items: Option>) -> Value { + items.map_or(Value::Null, |items| { + Value::Array( + items + .iter() + .map(|item| Value::String(item.to_string())) + .collect(), + ) + }) +} + +fn bytes_value(bytes: Option>) -> Value { + bytes.map_or(Value::Null, |bytes| { + Value::String(base64::engine::general_purpose::STANDARD.encode(bytes)) + }) +} + +/// A PostgreSQL row selected with [`select_list`], as a backup object. +pub fn pg_row_to_json( + row: &sqlx::postgres::PgRow, + columns: &[Column], +) -> Result> { + let mut object = Map::new(); + for column in columns { + let name = column.name.as_str(); + let value = match column.kind { + ColumnKind::Uuid => row + .try_get::, _>(name)? + .map_or(Value::Null, |id| Value::String(id.to_string())), + ColumnKind::Text => row + .try_get::, _>(name)? + .map_or(Value::Null, Value::String), + ColumnKind::Int => row + .try_get::, _>(name)? + .map_or(Value::Null, Value::from), + ColumnKind::Bool => row + .try_get::, _>(name)? + .map_or(Value::Null, Value::Bool), + ColumnKind::Timestamp => timestamp_value(row.try_get(name)?), + ColumnKind::Json => row + .try_get::, _>(name)? + .unwrap_or(Value::Null), + ColumnKind::Bytes => bytes_value(row.try_get(name)?), + ColumnKind::UuidArray => strings_value(row.try_get::>, _>(name)?), + ColumnKind::TextArray => strings_value(row.try_get::>, _>(name)?), + }; + object.insert(column.name.clone(), value); + } + Ok(object) +} + +/// A MySQL row selected with [`select_list`], as a backup object. +pub fn mysql_row_to_json( + row: &sqlx::mysql::MySqlRow, + columns: &[Column], +) -> Result> { + let mut object = Map::new(); + for column in columns { + let name = column.name.as_str(); + let value = match column.kind { + ColumnKind::Uuid | ColumnKind::Text => row + .try_get::, _>(name)? + .map_or(Value::Null, Value::String), + ColumnKind::Int => row + .try_get::, _>(name)? + .map_or(Value::Null, Value::from), + ColumnKind::Bool => row + .try_get::, _>(name)? + .map_or(Value::Null, Value::Bool), + ColumnKind::Timestamp => timestamp_value(row.try_get(name)?), + ColumnKind::Json | ColumnKind::UuidArray | ColumnKind::TextArray => row + .try_get::, _>(name)? + .unwrap_or(Value::Null), + ColumnKind::Bytes => bytes_value(row.try_get(name)?), + }; + object.insert(column.name.clone(), value); + } + Ok(object) +} + +/// A backup value converted for binding to a column. +#[derive(Debug, Clone, PartialEq)] +pub enum Param { + /// SQL `NULL`, typed for the column (PostgreSQL rejects untyped parameters). + Null(ColumnKind), + Uuid(Uuid), + Text(String), + Int(i64), + Bool(bool), + Time(DateTime), + Json(Value), + Bytes(Vec), + UuidArray(Vec), + TextArray(Vec), +} + +impl Param { + /// Convert the backup value of column `column` for binding (see the module docs for + /// the encoding). + pub fn from_backup(column: &Column, value: &Value) -> Result { + let invalid = |expected: &str| { + anyhow!( + "backup column '{}' must be {}, got {}", + column.name, + expected, + value + ) + }; + let strings = |value: &Value| -> Result> { + value + .as_array() + .ok_or_else(|| invalid("an array of strings"))? + .iter() + .map(|item| { + item.as_str() + .map(str::to_string) + .ok_or_else(|| invalid("an array of strings")) + }) + .collect() + }; + if value.is_null() { + return Ok(Self::Null(column.kind)); + } + Ok(match column.kind { + ColumnKind::Uuid => { + let text = value.as_str().ok_or_else(|| invalid("a UUID string"))?; + Self::Uuid(Uuid::parse_str(text).map_err(|_| invalid("a UUID string"))?) + } + ColumnKind::Text => Self::Text( + value + .as_str() + .ok_or_else(|| invalid("a string"))? + .to_string(), + ), + ColumnKind::Int => Self::Int(value.as_i64().ok_or_else(|| invalid("an integer"))?), + ColumnKind::Bool => Self::Bool(match value { + Value::Bool(b) => *b, + Value::Number(n) if n.as_i64() == Some(0) => false, + Value::Number(n) if n.as_i64() == Some(1) => true, + _ => return Err(invalid("a boolean")), + }), + ColumnKind::Timestamp => { + let text = value + .as_str() + .ok_or_else(|| invalid("an RFC 3339 timestamp"))?; + Self::Time( + DateTime::parse_from_rfc3339(text) + .map_err(|_| invalid("an RFC 3339 timestamp"))? + .with_timezone(&Utc), + ) + } + ColumnKind::Json => Self::Json(value.clone()), + ColumnKind::Bytes => { + let text = value.as_str().ok_or_else(|| invalid("a base64 string"))?; + Self::Bytes( + base64::engine::general_purpose::STANDARD + .decode(text) + .map_err(|_| invalid("a base64 string"))?, + ) + } + ColumnKind::UuidArray => Self::UuidArray( + strings(value)? + .iter() + .map(|id| Uuid::parse_str(id).map_err(|_| invalid("an array of UUIDs"))) + .collect::>()?, + ), + ColumnKind::TextArray => Self::TextArray(strings(value)?), + }) + } +} + +/// An `INSERT` of one backed-up job: the columns it sets and their values. +#[derive(Debug, Clone, PartialEq)] +pub struct RowInsert { + pub id: String, + pub columns: Vec, + pub params: Vec, +} + +impl RowInsert { + /// The statement inserting this row; an existing row with the same id is left + /// alone (PostgreSQL `ON CONFLICT (id) DO NOTHING`; on MySQL the duplicate key error + /// is caught by [`insert_rows`]). + pub fn sql(&self, backend: Backend) -> String { + let names = self + .columns + .iter() + .map(|column| quoted(backend, &column.name)) + .collect::>() + .join(", "); + match backend { + Backend::Postgres => { + let placeholders = (1..=self.params.len()) + .map(|i| format!("${i}")) + .collect::>() + .join(", "); + format!( + "INSERT INTO hammerwork_jobs ({names}) VALUES ({placeholders}) \ + ON CONFLICT (id) DO NOTHING" + ) + } + Backend::MySql => { + let placeholders = vec!["?"; self.params.len()].join(", "); + format!("INSERT INTO hammerwork_jobs ({names}) VALUES ({placeholders})") + } + } + } +} + +fn bind_pg<'q>( + mut query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>, + params: &'q [Param], +) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> { + for param in params { + query = match param { + Param::Null(kind) => match kind { + ColumnKind::Uuid => query.bind(None::), + ColumnKind::Text => query.bind(None::), + ColumnKind::Int => query.bind(None::), + ColumnKind::Bool => query.bind(None::), + ColumnKind::Timestamp => query.bind(None::>), + ColumnKind::Json => query.bind(None::), + ColumnKind::Bytes => query.bind(None::>), + ColumnKind::UuidArray => query.bind(None::>), + ColumnKind::TextArray => query.bind(None::>), + }, + Param::Uuid(v) => query.bind(*v), + Param::Text(v) => query.bind(v.as_str()), + Param::Int(v) => query.bind(*v), + Param::Bool(v) => query.bind(*v), + Param::Time(v) => query.bind(*v), + Param::Json(v) => query.bind(v), + Param::Bytes(v) => query.bind(v.as_slice()), + Param::UuidArray(v) => query.bind(v.as_slice()), + Param::TextArray(v) => query.bind(v.as_slice()), + }; + } + query +} + +fn bind_mysql<'q>( + mut query: sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments>, + params: &'q [Param], +) -> sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments> { + for param in params { + query = match param { + Param::Null(_) => query.bind(None::), + Param::Uuid(v) => query.bind(v.to_string()), + Param::Text(v) => query.bind(v.as_str()), + Param::Int(v) => query.bind(*v), + Param::Bool(v) => query.bind(*v), + Param::Time(v) => query.bind(*v), + Param::Json(v) => query.bind(v), + Param::Bytes(v) => query.bind(v.as_slice()), + // MySQL stores these as JSON + Param::UuidArray(v) => query.bind(Value::from( + v.iter().map(|id| id.to_string()).collect::>(), + )), + Param::TextArray(v) => query.bind(Value::from(v.clone())), + }; + } + query +} + +/// Insert `rows` in one transaction. Returns how many were inserted; rows whose id +/// already exists are left untouched and not counted. On any other error nothing is +/// inserted. +pub async fn insert_rows(pool: &DatabasePool, rows: &[RowInsert]) -> Result { + let mut inserted = 0; + match pool { + DatabasePool::Postgres(p) => { + let mut tx = p.begin().await?; + for row in rows { + let sql = row.sql(Backend::Postgres); + let affected = bind_pg(sqlx::query(&sql), &row.params) + .execute(&mut *tx) + .await + .map_err(|e| anyhow!("Cannot restore job {}: {}", row.id, e))? + .rows_affected(); + inserted += affected as usize; + } + tx.commit().await?; + } + DatabasePool::MySQL(p) => { + let mut tx = p.begin().await?; + for row in rows { + let sql = row.sql(Backend::MySql); + match bind_mysql(sqlx::query(&sql), &row.params) + .execute(&mut *tx) + .await + { + Ok(result) => inserted += result.rows_affected() as usize, + // A failed statement does not end a MySQL transaction. + Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {} + Err(e) => return Err(anyhow!("Cannot restore job {}: {}", row.id, e)), + } + } + tx.commit().await?; + } + } + Ok(inserted) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn column(name: &str, kind: ColumnKind) -> Column { + Column { + name: name.to_string(), + kind, + } + } + + #[test] + fn column_types_are_classified() { + assert_eq!(ColumnKind::postgres("uuid"), Some(ColumnKind::Uuid)); + assert_eq!(ColumnKind::postgres("_uuid"), Some(ColumnKind::UuidArray)); + assert_eq!(ColumnKind::postgres("_text"), Some(ColumnKind::TextArray)); + assert_eq!(ColumnKind::postgres("bytea"), Some(ColumnKind::Bytes)); + assert_eq!(ColumnKind::postgres("int4"), Some(ColumnKind::Int)); + assert_eq!(ColumnKind::postgres("interval"), None); + assert_eq!( + ColumnKind::mysql("tinyint", "tinyint(1)"), + Some(ColumnKind::Bool) + ); + assert_eq!( + ColumnKind::mysql("tinyint", "tinyint(4)"), + Some(ColumnKind::Int) + ); + assert_eq!( + ColumnKind::mysql("longblob", "longblob"), + Some(ColumnKind::Bytes) + ); + assert_eq!( + ColumnKind::mysql("char", "char(36)"), + Some(ColumnKind::Text) + ); + assert_eq!(ColumnKind::mysql("geometry", "geometry"), None); + } + + #[test] + fn select_list_casts_integers_and_quotes_names() { + let columns = [ + column("id", ColumnKind::Uuid), + column("attempts", ColumnKind::Int), + column("created_at", ColumnKind::Timestamp), + ]; + assert_eq!( + select_list(Backend::Postgres, &columns), + r#""id", "attempts"::bigint AS "attempts", "created_at"::timestamptz AS "created_at""# + ); + assert_eq!( + select_list(Backend::MySql, &columns), + "`id`, CAST(`attempts` AS SIGNED) AS `attempts`, `created_at`" + ); + } + + #[test] + fn backup_values_convert_by_column_kind() { + let id = "11111111-1111-1111-1111-111111111111"; + let cases = [ + ( + ColumnKind::Uuid, + json!(id), + Param::Uuid(Uuid::parse_str(id).unwrap()), + ), + (ColumnKind::Text, json!("q"), Param::Text("q".into())), + (ColumnKind::Int, json!(7), Param::Int(7)), + (ColumnKind::Bool, json!(true), Param::Bool(true)), + (ColumnKind::Bool, json!(0), Param::Bool(false)), + ( + ColumnKind::Timestamp, + json!("2024-01-02T03:04:05.123456Z"), + Param::Time( + DateTime::parse_from_rfc3339("2024-01-02T03:04:05.123456Z") + .unwrap() + .with_timezone(&Utc), + ), + ), + ( + ColumnKind::Json, + json!({"a": [1]}), + Param::Json(json!({"a": [1]})), + ), + ( + ColumnKind::Bytes, + json!("AAEC"), + Param::Bytes(vec![0, 1, 2]), + ), + ( + ColumnKind::UuidArray, + json!([id]), + Param::UuidArray(vec![Uuid::parse_str(id).unwrap()]), + ), + ( + ColumnKind::TextArray, + json!(["ssn"]), + Param::TextArray(vec!["ssn".into()]), + ), + ( + ColumnKind::Bytes, + Value::Null, + Param::Null(ColumnKind::Bytes), + ), + ]; + for (kind, value, expected) in cases { + assert_eq!( + Param::from_backup(&column("c", kind), &value).unwrap(), + expected, + "{kind:?} {value}" + ); + } + + for (kind, value) in [ + (ColumnKind::Uuid, json!("nope")), + (ColumnKind::Text, json!(1)), + (ColumnKind::Int, json!("1")), + (ColumnKind::Bool, json!(2)), + (ColumnKind::Timestamp, json!("yesterday")), + (ColumnKind::Bytes, json!("not base64!")), + (ColumnKind::UuidArray, json!(["x"])), + (ColumnKind::TextArray, json!("ssn")), + ] { + let err = Param::from_backup(&column("c", kind), &value).unwrap_err(); + assert!(err.to_string().contains("backup column 'c'"), "{err}"); + } + } + + #[test] + fn timestamps_and_bytes_are_encoded_losslessly() { + let t = DateTime::parse_from_rfc3339("2024-01-02T03:04:05.000007Z") + .unwrap() + .with_timezone(&Utc); + assert_eq!( + timestamp_value(Some(t)), + json!("2024-01-02T03:04:05.000007Z") + ); + assert_eq!(timestamp_value(None), Value::Null); + assert_eq!(bytes_value(Some(vec![0, 1, 2])), json!("AAEC")); + assert_eq!(strings_value(Some(vec!["a", "b"])), json!(["a", "b"])); + } + + #[test] + fn insert_sql_names_every_column() { + let row = RowInsert { + id: "x".into(), + columns: vec![ + column("id", ColumnKind::Uuid), + column("payload", ColumnKind::Json), + ], + params: vec![Param::Null(ColumnKind::Uuid), Param::Json(json!({}))], + }; + assert_eq!( + row.sql(Backend::Postgres), + r#"INSERT INTO hammerwork_jobs ("id", "payload") VALUES ($1, $2) ON CONFLICT (id) DO NOTHING"# + ); + assert_eq!( + row.sql(Backend::MySql), + "INSERT INTO hammerwork_jobs (`id`, `payload`) VALUES (?, ?)" + ); + } +} diff --git a/cargo-hammerwork/src/utils/mod.rs b/cargo-hammerwork/src/utils/mod.rs index 6925927..225a2f3 100644 --- a/cargo-hammerwork/src/utils/mod.rs +++ b/cargo-hammerwork/src/utils/mod.rs @@ -1,6 +1,7 @@ pub mod database; pub mod display; pub mod job_ops; +pub mod job_rows; pub mod sql; #[cfg(test)] pub mod test_support; diff --git a/cargo-hammerwork/src/utils/validation.rs b/cargo-hammerwork/src/utils/validation.rs index 26971ea..b2cdd24 100644 --- a/cargo-hammerwork/src/utils/validation.rs +++ b/cargo-hammerwork/src/utils/validation.rs @@ -46,21 +46,9 @@ pub fn validate_database_url(url: &str) -> Result<()> { } /// `url` with the password replaced by `***`, safe to log. A URL without credentials is -/// returned unchanged. +/// returned unchanged (see [`hammerwork::config::redact_url`]). pub fn redact_url(url: &str) -> String { - let Some((scheme, rest)) = url.split_once("://") else { - return url.to_string(); - }; - // Credentials end at the last '@' before the first '/' of the path. - let authority_end = rest.find('/').unwrap_or(rest.len()); - let Some(at) = rest[..authority_end].rfind('@') else { - return url.to_string(); - }; - let (userinfo, tail) = rest.split_at(at); - match userinfo.split_once(':') { - Some((user, _password)) => format!("{scheme}://{user}:***{tail}"), - None => url.to_string(), - } + hammerwork::config::redact_url(url) } pub fn validate_cron_expression(cron: &str) -> Result<()> { diff --git a/cargo-hammerwork/tests/workflow_visualization_tests.rs b/cargo-hammerwork/tests/workflow_visualization_tests.rs index d783fef..f7d47e5 100644 --- a/cargo-hammerwork/tests/workflow_visualization_tests.rs +++ b/cargo-hammerwork/tests/workflow_visualization_tests.rs @@ -205,6 +205,7 @@ fn test_workflow_command_database_url_priority() { log_level: None, connection_pool_size: None, connect_timeout_secs: None, + encryption_config: None, }; let config_without_url = Config { @@ -214,6 +215,7 @@ fn test_workflow_command_database_url_priority() { log_level: None, connection_pool_size: None, connect_timeout_secs: None, + encryption_config: None, }; // Test command with URL overrides config diff --git a/docs/encryption.md b/docs/encryption.md index bbcaf71..1160da8 100644 --- a/docs/encryption.md +++ b/docs/encryption.md @@ -200,7 +200,9 @@ Stored keys are scoped by name (`key-manager/master` for the `KeyManager` master - `KeyManager::new` handles `aws://` / `gcp://` master key sources this way automatically. - `EncryptionEngine` needs the database: create it with `EncryptionEngine::new_with_pool(config, &pool)`. `EncryptionEngine::new` returns `EncryptionError::InvalidConfiguration` for these sources instead of generating a key that would be lost on restart. -**Rotation.** `KeyManager::rotate_kms_master_key()` and `EncryptionEngine::rotate_kms_key(&pool)` generate a new data key with the KMS, store it as the new active version and retire the previous one. Retired versions are kept and stay decryptable: the key manager decrypts keys wrapped by an older master key version (including key-encryption keys from `generate_master_key`), and the engine falls back to older versions when decrypting payloads. Other running instances keep the version they loaded until they are recreated. Rotating the KMS key itself inside AWS or GCP (automatic key rotation) needs no action: the KMS still decrypts blobs encrypted under earlier key versions. +**Rotation.** `KeyManager::rotate_kms_master_key()` and `EncryptionEngine::rotate_kms_key(&pool)` generate a new data key with the KMS, store it as the new active version and retire the previous one. Retired versions are kept and stay decryptable: the key manager decrypts keys wrapped by an older master key version (including key-encryption keys from `generate_master_key`), and the engine falls back to older versions when decrypting payloads. Rotating the KMS key itself inside AWS or GCP (automatic key rotation) needs no action: the KMS still decrypts blobs encrypted under earlier key versions. + +**Rotating in a fleet.** An engine created with `new_with_pool` keeps a handle on the pool. When it meets a payload it cannot decrypt with the keys it holds (another process rotated the data key and encrypted jobs with the new version, or the payload names another key id stored in the same table), it loads the stored versions it does not have yet, decrypts them with the KMS and tries again; from then on it also encrypts with the newest active version. So a worker that started before a rotation still runs the jobs encrypted after it, instead of failing them until they go Dead. Reloading costs one database query (and a KMS call per new version); a payload that still cannot be decrypted (tampered, or a key the table does not hold) fails as before, and if the reload itself fails (database or KMS unavailable) the run fails and is retried like any other failed run. `EncryptionEngine::reload_kms_keys()` loads new versions without waiting for such a payload; call it periodically, or after a rotation, to move every process to the new version promptly. A two-phase rollout (deploy, then rotate) needs no restart. **Upgrading.** Before this change, each process asked the KMS for a fresh key on every start, so anything encrypted by an earlier process was already unrecoverable. After running migration 017, the first start generates and stores a key; from then on it is stable. Data encrypted by the old per-process keys cannot be recovered. @@ -238,7 +240,7 @@ let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM) **Vault Requirements:** - KV v2 secrets engine enabled -- Secret stored with `key` field containing base64-encoded key material +- Secret stored with a `key` field holding a base64-encoded key of exactly the algorithm's key size (32 bytes). A passphrase, or key material of any other length, is rejected with `EncryptionError::InvalidConfiguration`: it is never hashed, padded or truncated into a key (a 1-byte value padded to 32 bytes would still have only 8 bits of entropy). The same applies to `vault://` master key sources of the `KeyManager`. - Proper authentication and access policies configured - The `vault-kms` feature @@ -256,7 +258,7 @@ let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM) # } ``` -Credentials come from the environment (`AZURE_TENANT_ID` / `AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET`, workload identity, managed identity, or the Azure CLI). Requires the `azure-kv` feature. +Credentials come from the environment (`AZURE_TENANT_ID` / `AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET`, workload identity, managed identity, or the Azure CLI). Requires the `azure-kv` feature. The key material must be exactly the algorithm's key size (32 bytes, e.g. a 256-bit `oct` key); shorter or longer material is rejected with `EncryptionError::InvalidConfiguration` instead of being padded or truncated, for engine keys and `KeyManager` master keys alike. #### Key loading fails closed @@ -306,7 +308,7 @@ How it works: - **What `payload` holds.** Never the plaintext of encrypted data. With no PII fields the whole payload is encrypted and `payload` is the placeholder `{"encrypted": true}`. With PII fields (see below) `payload` is the original payload with each listed field's value replaced by `"[ENCRYPTED]"`. - **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. +- **Dequeue and reads.** `dequeue`, `get_job`, `get_batch_jobs`, `get_dead_jobs`, `get_dead_jobs_by_queue` and the other reads return jobs as stored: `is_encrypted` is `true`, `payload` is redacted and `encrypted_payload` holds the ciphertext, so `decrypt_job` works on any of them (a dead-letter tool can decrypt a dead job and re-enqueue its plaintext). 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 to read. - **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. @@ -356,6 +358,16 @@ There is no decrypt-on-read for the archive: archived jobs are cold data, and ke `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. +### The CLI and the web dashboard + +`cargo hammerwork` and `hammerwork-web` write jobs on the application's behalf (`job enqueue`, `batch enqueue`, `cron create`, `workflow create`, and `POST /api/jobs`), so they use the application's encryption settings: + +- **The same settings.** They read the `[encryption]` section of the application's `hammerwork.toml` (the rest of the file is ignored) and apply the `HAMMERWORK_ENCRYPTION_*` environment variables on top (`PayloadEncryptionConfig::load`). Point the CLI at the file with `cargo hammerwork config set encryption_config /etc/app/hammerwork.toml` or `HAMMERWORK_ENCRYPTION_CONFIG`; the dashboard reads `HAMMERWORK_ENCRYPTION_CONFIG`. The key must be available to them too (for `env://` keys, the variable). Jobs on `encrypted_queues` are then encrypted exactly as the application would. +- **Never plaintext by mistake.** When the settings are enabled but the key cannot be loaded, the CLI refuses to write jobs and the dashboard refuses to start. Without any settings, both still refuse to store a plaintext job on a queue that already holds encrypted jobs (`JobQueue::with_plaintext_guard`): the error names the queue and says to configure the settings. A queue that has never held an encrypted job cannot be recognised that way, so configure the settings wherever the CLI or dashboard writes jobs. +- **Explicit encryption.** `cargo hammerwork job enqueue --encrypt` encrypts the whole payload with the application's key on any queue; `--pii-field card` (repeatable) encrypts only those fields. +- **Reading** needs no key: both show the redacted payload, and never decrypt. +- **Backups** (`cargo hammerwork backup create`, JSON format) hold every column of every job, with encrypted payloads still encrypted, and `backup restore` puts them back unchanged, so restored jobs decrypt with the same key. CSV backups are an export of the main columns and cannot be restored. + ### Configuration file `JobQueue::from_config` reads an optional `[encryption]` section of `HammerworkConfig` (`PayloadEncryptionConfig`) and sets up the engine itself: @@ -855,7 +867,7 @@ async fn main() -> Result<(), Box> { 1. **Environment Variables**: Store keys in environment variables, not code 2. **Secure Transmission**: Use TLS for all database connections -3. **Memory Protection**: Keys are held in process memory while the engine exists; they are not printed by `Debug` +3. **Memory Protection**: Keys are held in process memory while the engine exists, without copies per operation, and are wiped (`zeroize`) when the engine, key manager or KMS client drops them; they are not printed by `Debug`. Neither are database URL passwords, webhook and alert secrets and URLs (whose paths can be credentials), streaming credentials, KMS credentials or the dashboard's password hash; `cargo hammerwork config show` masks the database password. 4. **Error Handling**: Encryption errors never include payload data ## Performance diff --git a/hammerwork-web/Cargo.toml b/hammerwork-web/Cargo.toml index 7b97f95..c95bfa1 100644 --- a/hammerwork-web/Cargo.toml +++ b/hammerwork-web/Cargo.toml @@ -19,7 +19,7 @@ path = "src/main.rs" [dependencies] # Core Hammerwork functionality -hammerwork = { workspace = true, features = ["postgres", "mysql", "metrics"] } +hammerwork = { workspace = true, features = ["postgres", "mysql", "metrics", "encryption"] } # Web framework and HTTP warp = { workspace = true } diff --git a/hammerwork-web/README.md b/hammerwork-web/README.md index ffebfaf..63cacd3 100644 --- a/hammerwork-web/README.md +++ b/hammerwork-web/README.md @@ -104,6 +104,17 @@ Then start with: hammerwork-web --config dashboard.toml ``` +### Encrypted Queues + +Jobs created from the dashboard (`POST /api/jobs`) are encrypted like your application's. +Set `HAMMERWORK_ENCRYPTION_CONFIG` to the application's `hammerwork.toml` (only its +`[encryption]` section is read; the `HAMMERWORK_ENCRYPTION_*` variables apply on top) and +make its key available, e.g. `HAMMERWORK_ENCRYPTION_KEY`. Jobs on its `encrypted_queues` are +then encrypted with its key. If encryption is enabled but the key cannot be loaded, the +dashboard does not start. Without these settings it still refuses to create a plaintext job +on a queue that already holds encrypted jobs. Viewing jobs never needs the key: encrypted +payloads are shown redacted. + ## Library Usage Add to your `Cargo.toml`: diff --git a/hammerwork-web/src/config.rs b/hammerwork-web/src/config.rs index 4f39be8..6c6975f 100644 --- a/hammerwork-web/src/config.rs +++ b/hammerwork-web/src/config.rs @@ -90,7 +90,9 @@ use std::time::Duration; /// assert_eq!(config.bind_addr(), "0.0.0.0:9090"); /// assert!(config.enable_cors); /// ``` -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` shows `database_url` with its password replaced by `***`. +#[derive(Clone, Serialize, Deserialize)] pub struct DashboardConfig { /// Server bind address pub bind_address: String, @@ -369,7 +371,9 @@ impl DashboardConfig { /// assert_eq!(auth_config.username, "dashboard_admin"); /// assert_eq!(auth_config.max_failed_attempts, 3); /// ``` -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` never shows `password_hash`. +#[derive(Clone, Serialize, Deserialize)] pub struct AuthConfig { /// Whether authentication is enabled pub enabled: bool, @@ -433,6 +437,60 @@ impl Default for WebSocketConfig { } } +impl std::fmt::Debug for DashboardConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DashboardConfig") + .field("bind_address", &self.bind_address) + .field("port", &self.port) + .field( + "database_url", + &hammerwork::config::redact_url(&self.database_url), + ) + .field("pool_size", &self.pool_size) + .field("static_dir", &self.static_dir) + .field("auth", &self.auth) + .field("websocket", &self.websocket) + .field("enable_cors", &self.enable_cors) + .field("request_timeout", &self.request_timeout) + .finish() + } +} + +impl std::fmt::Debug for AuthConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Fields added later are left out rather than risk printing a secret. + f.debug_struct("AuthConfig") + .field("enabled", &self.enabled) + .field("username", &self.username) + .field("password_hash", &"[REDACTED]") + .field("session_timeout", &self.session_timeout) + .field("max_failed_attempts", &self.max_failed_attempts) + .field("lockout_duration", &self.lockout_duration) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod debug_redaction_tests { + use super::*; + + #[test] + fn debug_does_not_print_secrets() { + let mut config = DashboardConfig { + database_url: "postgres://app:hunter2-db@db.internal/jobs".to_string(), + ..Default::default() + }; + config.auth.password_hash = "$2b$12$hunter2hashhunter2hashhu".to_string(); + let debug = format!("{config:?}"); + assert!(!debug.contains("hunter2"), "{debug}"); + assert!( + debug.contains("postgres://app:***@db.internal/jobs"), + "{debug}" + ); + assert!(debug.contains("[REDACTED]"), "{debug}"); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/hammerwork-web/src/server.rs b/hammerwork-web/src/server.rs index de46e05..bd73f6e 100644 --- a/hammerwork-web/src/server.rs +++ b/hammerwork-web/src/server.rs @@ -185,7 +185,8 @@ impl WebDashboard { "Connected to PostgreSQL with {} connections", self.config.pool_size ); - self.serve(JobQueue::new(pool), "PostgreSQL").await + let queue = job_queue(pool, &encryption_settings()?).await?; + self.serve(queue, "PostgreSQL").await } #[cfg(feature = "mysql")] DatabaseBackend::MySql => { @@ -197,7 +198,8 @@ impl WebDashboard { "Connected to MySQL with {} connections", self.config.pool_size ); - self.serve(JobQueue::new(pool), "MySQL").await + let queue = job_queue(pool, &encryption_settings()?).await?; + self.serve(queue, "MySQL").await } } } @@ -410,12 +412,96 @@ impl DatabaseBackend { } } +/// The application's payload encryption settings: the `[encryption]` section of the +/// `hammerwork.toml` named by `HAMMERWORK_ENCRYPTION_CONFIG`, with the +/// `HAMMERWORK_ENCRYPTION_*` environment variables applied on top (see +/// `PayloadEncryptionConfig::load`). Disabled when neither is set. +#[cfg(any(feature = "postgres", feature = "mysql"))] +fn encryption_settings() -> Result { + let path = std::env::var("HAMMERWORK_ENCRYPTION_CONFIG") + .ok() + .filter(|path| !path.is_empty()); + Ok(hammerwork::config::PayloadEncryptionConfig::load( + path.as_deref().map(std::path::Path::new), + )?) +} + +/// The dashboard's job queue. +/// +/// It encrypts like the application (jobs created from the dashboard on the +/// application's `encrypted_queues` are encrypted with its key), and it has the plaintext +/// guard, so it refuses to write a plaintext job to a queue that holds encrypted jobs +/// even without encryption settings. A key that cannot be loaded is an error: the +/// dashboard does not start rather than write plaintext. +#[cfg(any(feature = "postgres", feature = "mysql"))] +async fn job_queue( + pool: sqlx::Pool, + encryption: &hammerwork::config::PayloadEncryptionConfig, +) -> Result> { + let queue = JobQueue::new(pool) + .apply_encryption_config(encryption) + .await + .map_err(|e| { + anyhow::anyhow!( + "Cannot set up payload encryption from the application's [encryption] \ + settings ({}); refusing to start rather than store jobs in plaintext", + e + ) + })?; + if encryption.enabled { + info!( + "Payload encryption enabled for queues: {:?}", + encryption.encrypted_queues + ); + } + Ok(queue.with_plaintext_guard(true)) +} + #[cfg(test)] mod tests { use super::*; use crate::config::DashboardConfig; use tempfile::tempdir; + #[cfg(feature = "postgres")] + #[tokio::test] + async fn test_job_queue_encrypts_like_the_application() { + use base64::Engine as _; + let pool = || { + sqlx::postgres::PgPoolOptions::new() + .connect_lazy("postgres://nobody:nothing@127.0.0.1:1/none") + .unwrap() + }; + + // No settings: no engine (the plaintext guard still applies) + let queue = job_queue(pool(), &Default::default()).await.unwrap(); + assert!(queue.encryption_engine().is_none()); + + // The application's settings: its engine, with its key + let var = format!("HW_WEB_TEST_KEY_{}", uuid::Uuid::new_v4().simple()); + let settings = hammerwork::config::PayloadEncryptionConfig { + enabled: true, + key_source: hammerwork::config::KeySourceRef::parse(&format!("env://{var}")).unwrap(), + key_id: Some("web-key".to_string()), + encrypted_queues: vec!["payments".to_string()], + ..Default::default() + }; + let err = job_queue(pool(), &settings) + .await + .err() + .expect("the key is missing"); + assert!(err.to_string().contains("refusing to start"), "{err}"); + // SAFETY: the variable name is unique to this test. + unsafe { + std::env::set_var( + &var, + base64::engine::general_purpose::STANDARD.encode([3u8; 32]), + ) + }; + let queue = job_queue(pool(), &settings).await.unwrap(); + assert_eq!(queue.encryption_engine().unwrap().key_id(), "web-key"); + } + #[tokio::test] async fn test_dashboard_creation() { let temp_dir = tempdir().unwrap(); diff --git a/src/alerting.rs b/src/alerting.rs index 17ac229..f2cc9de 100644 --- a/src/alerting.rs +++ b/src/alerting.rs @@ -335,7 +335,10 @@ fn single_line(value: &str) -> String { } /// Alert target configuration -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` never shows header values or the path of a webhook or Slack URL (a Slack +/// webhook URL is itself a credential). +#[derive(Clone, Serialize, Deserialize)] pub enum AlertTarget { /// Webhook alert target Webhook { @@ -358,6 +361,34 @@ pub enum AlertTarget { }, } +impl std::fmt::Debug for AlertTarget { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AlertTarget::Webhook { url, headers } => { + let mut names: Vec<&String> = headers.keys().collect(); + names.sort(); + f.debug_struct("Webhook") + .field("url", &crate::config::redact_url_path(url)) + .field("headers", &names) + .finish() + } + AlertTarget::Email { recipient, smtp } => f + .debug_struct("Email") + .field("recipient", recipient) + .field("smtp", smtp) + .finish(), + AlertTarget::Slack { + webhook_url, + channel, + } => f + .debug_struct("Slack") + .field("webhook_url", &crate::config::redact_url_path(webhook_url)) + .field("channel", channel) + .finish(), + } + } +} + /// Alert severity levels #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum AlertSeverity { @@ -1411,6 +1442,36 @@ mod tests { assert!(bad_recipient.validate().is_err()); } + #[test] + fn test_alert_target_debug_hides_urls_and_header_values() { + let targets = [ + AlertTarget::Webhook { + url: "https://alerts.example.com/hook/hunter2-path".to_string(), + headers: HashMap::from([( + "Authorization".to_string(), + "Bearer hunter2-token".to_string(), + )]), + }, + AlertTarget::Slack { + webhook_url: "https://hooks.slack.com/services/T0/B0/hunter2-path".to_string(), + channel: "#ops".to_string(), + }, + ]; + for target in targets { + let debug = format!("{target:?}"); + assert!(!debug.contains("hunter2"), "{debug}"); + assert!(debug.contains("/***"), "{debug}"); + } + let debug = format!( + "{:?}", + AlertTarget::Email { + recipient: "ops@example.com".to_string(), + smtp: None, + } + ); + assert!(debug.contains("ops@example.com"), "{debug}"); + } + #[test] fn test_smtp_defaults_and_secret_redaction() { let smtp = SmtpConfig::new("smtp.example.com", "alerts@example.com"); diff --git a/src/config.rs b/src/config.rs index 841b9ab..e16b98f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -351,7 +351,9 @@ impl HammerworkConfig { } /// Database configuration -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` shows `url` with its password replaced by `***` ([`redact_url`]). +#[derive(Clone, Serialize, Deserialize)] pub struct DatabaseConfig { /// Database connection URL pub url: String, @@ -374,6 +376,78 @@ pub struct DatabaseConfig { pub create_tables: bool, } +impl std::fmt::Debug for DatabaseConfig { + #[allow(deprecated)] + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DatabaseConfig") + .field("url", &redact_url(&self.url)) + .field("pool_size", &self.pool_size) + .field("connection_timeout_secs", &self.connection_timeout_secs) + .field("auto_migrate", &self.auto_migrate) + .field("create_tables", &self.create_tables) + .finish() + } +} + +/// `url` with the password in its user info replaced by `***`, safe to print or log: +/// `postgres://app:s3cret@db/jobs` becomes `postgres://app:***@db/jobs`. A URL without +/// a password is returned unchanged. +/// +/// ``` +/// use hammerwork::config::redact_url; +/// +/// assert_eq!( +/// redact_url("postgres://app:s3cret@db:5432/jobs"), +/// "postgres://app:***@db:5432/jobs" +/// ); +/// assert_eq!(redact_url("mysql://db/jobs"), "mysql://db/jobs"); +/// ``` +pub fn redact_url(url: &str) -> String { + let Some((scheme, rest)) = url.split_once("://") else { + return url.to_string(); + }; + // Credentials end at the last '@' before the first '/' of the path. + let authority_end = rest.find('/').unwrap_or(rest.len()); + let Some(at) = rest[..authority_end].rfind('@') else { + return url.to_string(); + }; + let (userinfo, tail) = rest.split_at(at); + match userinfo.split_once(':') { + Some((user, _password)) => format!("{scheme}://{user}:***{tail}"), + None => url.to_string(), + } +} + +/// Only the scheme and host of `url`, safe to print or log for URLs whose path or query +/// is itself a credential (Slack, Discord and Teams webhook URLs, signed URLs): +/// `https://hooks.slack.com/services/T0/B0/xyz` becomes `https://hooks.slack.com/***`. +/// User info is dropped. Something that is not a URL is replaced by `***`. +/// +/// ``` +/// use hammerwork::config::redact_url_path; +/// +/// assert_eq!( +/// redact_url_path("https://hooks.slack.com/services/T0/B0/xyz"), +/// "https://hooks.slack.com/***" +/// ); +/// assert_eq!(redact_url_path("https://example.com"), "https://example.com"); +/// ``` +pub fn redact_url_path(url: &str) -> String { + let Some((scheme, rest)) = url.split_once("://") else { + return "***".to_string(); + }; + let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let authority = &rest[..authority_end]; + let host = authority + .rsplit_once('@') + .map_or(authority, |(_, host)| host); + if authority_end == rest.len() || rest[authority_end..] == *"/" { + format!("{scheme}://{host}") + } else { + format!("{scheme}://{host}/***") + } +} + impl DatabaseConfig { /// Connection acquire timeout as a [`std::time::Duration`] pub fn connection_timeout(&self) -> StdDuration { @@ -920,6 +994,63 @@ impl PayloadEncryptionConfig { Ok(()) } + /// The encryption settings of an application, for tools that write jobs on its behalf + /// (`cargo hammerwork`, the web dashboard). + /// + /// Reads the `[encryption]` section of the application's `hammerwork.toml` at `path` + /// (other sections are ignored, so the file does not need to be complete; a file + /// without the section means encryption is disabled), then applies the + /// `HAMMERWORK_ENCRYPTION_*` environment variables ([`Self::apply_env`]). Without a + /// path, only the environment is used. The result is validated. + /// + /// ```no_run + /// use hammerwork::config::PayloadEncryptionConfig; + /// + /// let encryption = PayloadEncryptionConfig::load(Some("hammerwork.toml".as_ref()))?; + /// if encryption.enabled { + /// println!("encrypting queues {:?}", encryption.encrypted_queues); + /// } + /// # Ok::<(), hammerwork::HammerworkError>(()) + /// ``` + pub fn load(path: Option<&std::path::Path>) -> crate::Result { + let mut config = match path { + Some(path) => { + let content = std::fs::read_to_string(path).map_err(|e| { + crate::HammerworkError::Config(format!("Cannot read {}: {}", path.display(), e)) + })?; + Self::from_toml_document(&content).map_err(|e| { + crate::HammerworkError::Config(format!("{}: {}", path.display(), e)) + })? + } + None => Self::default(), + }; + config.apply_env()?; + config.validate()?; + Ok(config) + } + + /// The `[encryption]` section of a `hammerwork.toml` document (the default if there + /// is none). + fn from_toml_document(content: &str) -> crate::Result { + #[derive(Deserialize)] + struct Document { + #[serde(default)] + encryption: PayloadEncryptionConfig, + } + let document: Document = toml::from_str(content)?; + Ok(document.encryption) + } + + /// Whether jobs on `queue_name` are encrypted without an encryption config of their + /// own (`enabled` and listed in `encrypted_queues`, or `"*"` is listed). + pub fn encrypts_queue(&self, queue_name: &str) -> bool { + self.enabled + && self + .encrypted_queues + .iter() + .any(|queue| queue == "*" || queue == queue_name) + } + /// How often the retention purge runs, if configured. pub fn purge_interval(&self) -> Option { self.purge_interval_secs.map(StdDuration::from_secs) @@ -1787,4 +1918,107 @@ service_name = "hammerwork" }; assert!(invalid.encryption_config().is_err()); } + + #[test] + fn test_redact_url_hides_only_the_password() { + assert_eq!( + redact_url("postgres://admin:s3cret@db.internal:5432/app?sslmode=require"), + "postgres://admin:***@db.internal:5432/app?sslmode=require" + ); + // The password itself may contain ':' and '@'. + assert_eq!( + redact_url("mysql://root:p@ss:word@127.0.0.1:3306/db"), + "mysql://root:***@127.0.0.1:3306/db" + ); + assert_eq!( + redact_url("postgres://user@host/db"), + "postgres://user@host/db" + ); + assert_eq!(redact_url("postgres://host/db"), "postgres://host/db"); + assert_eq!(redact_url("not a url"), "not a url"); + // An '@' after the path is not user info. + assert_eq!( + redact_url("postgres://host/db?options=a:b@c"), + "postgres://host/db?options=a:b@c" + ); + } + + #[test] + fn test_redact_url_path_keeps_only_scheme_and_host() { + for (url, expected) in [ + ( + "https://hooks.slack.com/services/T0/B0/secret", + "https://hooks.slack.com/***", + ), + ( + "https://discord.com/api/webhooks/1/token", + "https://discord.com/***", + ), + ("https://example.com?sig=secret", "https://example.com/***"), + ( + "https://user:pw@example.com/hook", + "https://example.com/***", + ), + ("https://example.com/", "https://example.com"), + ("https://example.com", "https://example.com"), + ("garbage-secret", "***"), + ] { + assert_eq!(redact_url_path(url), expected, "{url}"); + } + } + + #[test] + fn test_debug_does_not_print_the_database_password() { + let config = HammerworkConfig::new() + .with_database_url("postgres://app:hunter2-db-password@db.internal/jobs"); + for debug in [format!("{:?}", config.database), format!("{:?}", config)] { + assert!(!debug.contains("hunter2-db-password"), "{debug}"); + assert!( + debug.contains("postgres://app:***@db.internal/jobs"), + "{debug}" + ); + } + } + + #[test] + fn test_encryption_section_is_loaded_from_an_application_config_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("hammerwork.toml"); + // Only the [encryption] section is read; the rest of the file may be partial. + std::fs::write( + &path, + "[database]\nurl = \"postgres://db/jobs\"\n\n[encryption]\nenabled = true\n\ + encrypted_queues = [\"payments\"]\n", + ) + .unwrap(); + let section = + PayloadEncryptionConfig::from_toml_document(&std::fs::read_to_string(&path).unwrap()) + .unwrap(); + assert!(section.enabled); + assert!(section.encrypts_queue("payments")); + assert!(!section.encrypts_queue("emails")); + + // No section: disabled. + let none = PayloadEncryptionConfig::from_toml_document("[database]\n").unwrap(); + assert!(!none.enabled); + assert!(!none.encrypts_queue("payments")); + + // A wildcard covers every queue, but only when enabled. + let mut all = PayloadEncryptionConfig { + enabled: true, + encrypted_queues: vec!["*".to_string()], + ..Default::default() + }; + assert!(all.encrypts_queue("anything")); + all.enabled = false; + assert!(!all.encrypts_queue("anything")); + + // Errors name the file. + let missing = dir.path().join("missing.toml"); + let err = PayloadEncryptionConfig::load(Some(&missing)).unwrap_err(); + assert!(err.to_string().contains("missing.toml"), "{err}"); + std::fs::write(&path, "[encryption]\nenabled = \"yes\"\n").unwrap(); + let err = PayloadEncryptionConfig::load(Some(&path)).unwrap_err(); + assert!(err.to_string().contains("hammerwork.toml"), "{err}"); + } } diff --git a/src/encryption.rs b/src/encryption.rs index b43b498..599e3ff 100644 --- a/src/encryption.rs +++ b/src/encryption.rs @@ -78,6 +78,9 @@ use thiserror::Error; use base64::Engine; +/// Key material that is wiped from memory when dropped. +pub(crate) type SecretBytes = zeroize::Zeroizing>; + /// Errors that can occur during encryption operations. #[derive(Error, Debug)] pub enum EncryptionError { diff --git a/src/encryption/azure.rs b/src/encryption/azure.rs index 0a34853..5b1cfad 100644 --- a/src/encryption/azure.rs +++ b/src/encryption/azure.rs @@ -54,7 +54,7 @@ fn env_var(name: &str) -> Option { } /// Which credential [`credential`] builds (see the module docs for the order). -#[derive(Debug, PartialEq, Eq)] +#[derive(PartialEq, Eq)] enum CredentialChoice { ClientSecret { tenant: String, @@ -65,6 +65,26 @@ enum CredentialChoice { ManagedIdentityThenDeveloperTools, } +impl std::fmt::Debug for CredentialChoice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + // Never print the client secret + Self::ClientSecret { + tenant, client_id, .. + } => f + .debug_struct("ClientSecret") + .field("tenant", tenant) + .field("client_id", client_id) + .field("secret", &"[REDACTED]") + .finish(), + Self::WorkloadIdentity => f.write_str("WorkloadIdentity"), + Self::ManagedIdentityThenDeveloperTools => { + f.write_str("ManagedIdentityThenDeveloperTools") + } + } + } +} + /// Pick a credential from the variables returned by `var`. Empty values count as /// unset. fn choose_credential(var: impl Fn(&str) -> Option) -> CredentialChoice { @@ -119,7 +139,10 @@ pub(crate) fn credential() -> azure_core::Result> { /// /// The 1.x SDK already base64url-decodes the JSON Web Key `k` field, so the returned /// bytes are the raw key material. -pub(crate) async fn fetch_key_material(vault_url: &str, key_name: &str) -> Result, String> { +pub(crate) async fn fetch_key_material( + vault_url: &str, + key_name: &str, +) -> Result { let credential = credential().map_err(|e| format!("Failed to create Azure credentials: {}", e))?; @@ -136,6 +159,7 @@ pub(crate) async fn fetch_key_material(vault_url: &str, key_name: &str) -> Resul key.key .and_then(|jwk| jwk.k) .filter(|k| !k.is_empty()) + .map(super::SecretBytes::new) .ok_or_else(|| "Azure Key Vault key response missing key material".to_string()) } @@ -170,6 +194,29 @@ mod tests { ); } + #[test] + fn debug_does_not_print_the_client_secret() { + let choice = CredentialChoice::ClientSecret { + tenant: "tenant".to_string(), + client_id: "client".to_string(), + secret: "hunter2-client-secret".to_string(), + }; + let debug = format!("{:?}", choice); + assert!(!debug.contains("hunter2-client-secret"), "{debug}"); + assert!( + debug.contains("client") && debug.contains("[REDACTED]"), + "{debug}" + ); + assert_eq!( + format!("{:?}", CredentialChoice::WorkloadIdentity), + "WorkloadIdentity" + ); + assert_eq!( + format!("{:?}", CredentialChoice::ManagedIdentityThenDeveloperTools), + "ManagedIdentityThenDeveloperTools" + ); + } + #[test] fn workload_identity_needs_a_federated_token_file() { // An incomplete (or empty) client secret configuration is not used. diff --git a/src/encryption/engine.rs b/src/encryption/engine.rs index 15225cb..40872cd 100644 --- a/src/encryption/engine.rs +++ b/src/encryption/engine.rs @@ -3,20 +3,20 @@ //! This module provides the actual cryptographic operations for encrypting and //! decrypting job payloads using various algorithms and key management strategies. -use super::envelope::{self, DbStore, KmsKeyWrapper}; +use super::envelope::{self, DbStore, EnvelopeKey, KmsKeyWrapper, PoolStore, WrappedKeyStore}; #[cfg(feature = "encryption")] use super::key_manager::KeyManager; use super::key_manager::KeyManagerBackend; use super::{ EncryptedPayload, EncryptionAlgorithm, EncryptionConfig, EncryptionError, EncryptionMetadata, - EncryptionStats, KeySource, RetentionPolicy, kms, + EncryptionStats, KeySource, RetentionPolicy, SecretBytes, kms, }; use serde_json::Value; use sqlx::{Database, Pool}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Instant; -use tracing::info; +use tracing::{info, warn}; #[cfg(feature = "encryption")] use { @@ -85,15 +85,100 @@ use { /// ``` pub struct EncryptionEngine { config: EncryptionConfig, - keys: Arc>>>, - /// Earlier (rotated) versions of KMS-wrapped keys, newest first, used to decrypt - /// payloads written before a rotation - previous_keys: Arc>>>>, - /// KMS that wraps the data key, for `aws://` and `gcp://` key sources - kms: Option>, + /// Keys by key id. Key material is shared (never copied for an operation) and wiped + /// from memory when the engine drops it. + keys: Arc>>, + /// KMS that wraps the data keys and the database that stores them, for `aws://` and + /// `gcp://` key sources + kms: Option, stats: Arc>, } +/// Key material shared without copying, wiped from memory when the last reference goes. +type SharedKey = Arc; + +/// The keys an engine holds for one key id. +struct KeyVersions { + /// The key used to encrypt under this key id (and tried first to decrypt) + active: SharedKey, + /// Stored version of `active`, for KMS-wrapped keys (0 for other keys) + active_version: u32, + /// Earlier versions of a KMS-wrapped key, newest first, used to decrypt payloads + /// written before a rotation + previous: Vec<(u32, SharedKey)>, +} + +impl KeyVersions { + /// A key that is not KMS-wrapped (it has no versions). + fn single(key: SecretBytes) -> Self { + Self { + active: Arc::new(key), + active_version: 0, + previous: Vec::new(), + } + } + + /// KMS-wrapped key versions loaded from the store; `None` if there are none. + fn from_envelope_keys(keys: Vec) -> Option { + let mut keys = keys.into_iter(); + let first = keys.next()?; + let mut versions = Self { + active: Arc::new(first.key), + active_version: first.version, + previous: Vec::new(), + }; + versions.add(keys); + Some(versions) + } + + /// Versions of a KMS-wrapped key held. + fn versions(&self) -> Vec { + std::iter::once(self.active_version) + .chain(self.previous.iter().map(|(version, _)| *version)) + .collect() + } + + /// Add versions loaded from the store. A newer active version becomes the key used + /// for encryption, and the one it replaces is kept for decryption. + fn add(&mut self, keys: impl IntoIterator) { + for key in keys { + if self.versions().contains(&key.version) { + continue; + } + let version = key.version; + let shared = Arc::new(key.key); + if key.active && version > self.active_version { + let old = std::mem::replace(&mut self.active, shared); + self.previous.push((self.active_version, old)); + self.active_version = version; + } else { + self.previous.push((version, shared)); + } + } + self.previous + .sort_by_key(|(version, _)| std::cmp::Reverse(*version)); + } + + /// Every key to try for decryption: the active one first, then earlier versions. + fn candidates(&self) -> Vec { + std::iter::once(self.active.clone()) + .chain(self.previous.iter().map(|(_, key)| key.clone())) + .collect() + } +} + +/// Where an engine with an `aws://` or `gcp://` key source gets its data keys. +struct KmsBacking { + kms: Arc, + /// The database that stores the KMS-wrapped keys, to reload versions rotated by + /// other processes + store: Arc, +} + +fn key_lock_error() -> EncryptionError { + EncryptionError::KeyManagement("Failed to acquire key lock".to_string()) +} + impl std::fmt::Debug for EncryptionEngine { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Never print key material @@ -115,6 +200,13 @@ impl EncryptionEngine { /// [`EncryptionEngine::rotate_kms_key`]) are loaded too, so payloads encrypted before /// a rotation can still be decrypted. /// + /// The engine keeps a handle on `pool`: when it meets a payload encrypted with a key + /// version it does not hold (another process rotated the key with + /// [`EncryptionEngine::rotate_kms_key`]), or with another key id stored in the same + /// table, it reloads the stored versions and retries before failing. From then on it + /// also encrypts with the newest active version. See also + /// [`EncryptionEngine::reload_kms_keys`]. + /// /// Other key sources behave exactly as with [`EncryptionEngine::new`]. /// /// # Examples @@ -149,6 +241,15 @@ impl EncryptionEngine { config: EncryptionConfig, pool: &Pool, kms: Arc, + ) -> Result { + Self::with_kms_store(config, Arc::new(PoolStore(pool.clone())), kms).await + } + + /// Create an engine whose data key is wrapped by `kms` and stored in `store`. + async fn with_kms_store( + config: EncryptionConfig, + store: Arc, + kms: Arc, ) -> Result { let key_id = config .key_id @@ -156,25 +257,28 @@ impl EncryptionEngine { .unwrap_or_else(|| "default".to_string()); let key_name = kms_key_name(&key_id); let size = config.key_size_bytes(); - let store = DbStore(pool); - - let active = envelope::load_or_create(&store, kms.as_ref(), &key_name, size).await?; - let previous: Vec> = if active.version > 1 { - envelope::load_all(&store, kms.as_ref(), &key_name, size) - .await? - .into_iter() - .filter(|key| key.version != active.version) - .map(|key| key.key) - .collect() - } else { - Vec::new() + + let active = + envelope::load_or_create(store.as_ref(), kms.as_ref(), &key_name, size).await?; + let active_version = active.version; + let mut versions = KeyVersions { + active: Arc::new(active.key), + active_version, + previous: Vec::new(), }; + if active_version > 1 { + versions.add( + envelope::load_new(store.as_ref(), kms.as_ref(), &key_name, size, |v| { + v == active_version + }) + .await?, + ); + } Ok(Self { config, - keys: Arc::new(Mutex::new(HashMap::from([(key_id.clone(), active.key)]))), - previous_keys: Arc::new(Mutex::new(HashMap::from([(key_id, previous)]))), - kms: Some(kms), + keys: Arc::new(Mutex::new(HashMap::from([(key_id, versions)]))), + kms: Some(KmsBacking { kms, store }), stats: Arc::new(Mutex::new(EncryptionStats::new())), }) } @@ -184,8 +288,11 @@ impl EncryptionEngine { /// The KMS generates a new data key; its KMS-encrypted form becomes the active version /// in `hammerwork_kms_data_keys` and the previous version is retired but kept. This /// engine encrypts with the new key from now on and can still decrypt payloads - /// encrypted with earlier versions. Other engines pick up the new version when they - /// are recreated. + /// encrypted with earlier versions. + /// + /// Other engines (other workers and processes) load the new version from the database + /// the first time they meet a payload encrypted with it, and from then on encrypt + /// with it too; [`EncryptionEngine::reload_kms_keys`] loads it right away. /// /// Returns the new version number. Fails with /// [`EncryptionError::InvalidConfiguration`] for engines not created by @@ -194,7 +301,12 @@ impl EncryptionEngine { &self, pool: &Pool, ) -> Result { - let kms = self.kms.clone().ok_or_else(|| { + self.rotate_kms_key_in(&DbStore(pool)).await + } + + /// [`EncryptionEngine::rotate_kms_key`] with the keys stored in `store`. + async fn rotate_kms_key_in(&self, store: &dyn WrappedKeyStore) -> Result { + let kms = self.kms.as_ref().ok_or_else(|| { EncryptionError::InvalidConfiguration( "rotate_kms_key needs an engine created by new_with_pool with an aws:// or \ gcp:// key source" @@ -207,29 +319,82 @@ impl EncryptionEngine { .clone() .unwrap_or_else(|| "default".to_string()); let rotated = envelope::rotate( - &DbStore(pool), - kms.as_ref(), + store, + kms.kms.as_ref(), &kms_key_name(&key_id), self.config.key_size_bytes(), ) .await?; + let version = rotated.version; - let lock_error = - || EncryptionError::KeyManagement("Failed to acquire key lock".to_string()); - let old_key = self + let mut keys = self.keys.lock().map_err(|_| key_lock_error())?; + match keys.get_mut(&key_id) { + Some(versions) => versions.add([rotated]), + None => { + if let Some(versions) = KeyVersions::from_envelope_keys(vec![rotated]) { + keys.insert(key_id, versions); + } + } + } + Ok(version) + } + + /// Loads the versions of this engine's KMS-wrapped data key that other processes + /// stored since it started (see [`EncryptionEngine::rotate_kms_key`]). + /// + /// A newer active version becomes the key this engine encrypts with; earlier ones + /// stay available for decryption. Returns whether a version was added. Engines reload + /// on their own when a payload cannot be decrypted, so this is only needed to switch + /// encryption to a rotated key without waiting for such a payload. + /// + /// Only engines created by [`EncryptionEngine::new_with_pool`] with an `aws://` or + /// `gcp://` key source have stored versions; for other engines this does nothing and + /// returns `false`. + pub async fn reload_kms_keys(&self) -> Result { + self.reload_kms_key(self.key_id()).await + } + + /// Load the stored versions of `key_id` that this engine does not hold yet. Returns + /// whether a version was added. + async fn reload_kms_key(&self, key_id: &str) -> Result { + let Some(backing) = &self.kms else { + return Ok(false); + }; + // The lock is not held across the queries below. + let known: Vec = self .keys .lock() - .map_err(|_| lock_error())? - .insert(key_id.clone(), rotated.key); - if let Some(old_key) = old_key { - self.previous_keys - .lock() - .map_err(|_| lock_error())? - .entry(key_id) - .or_default() - .insert(0, old_key); + .map_err(|_| key_lock_error())? + .get(key_id) + .map(KeyVersions::versions) + .unwrap_or_default(); + let loaded = envelope::load_new( + backing.store.as_ref(), + backing.kms.as_ref(), + &kms_key_name(key_id), + self.config.key_size_bytes(), + |version| known.contains(&version), + ) + .await?; + if loaded.is_empty() { + return Ok(false); + } + info!( + "Loaded {} new version(s) of KMS-wrapped data key {}", + loaded.len(), + key_id + ); + + let mut keys = self.keys.lock().map_err(|_| key_lock_error())?; + match keys.get_mut(key_id) { + Some(versions) => versions.add(loaded), + None => { + if let Some(versions) = KeyVersions::from_envelope_keys(loaded) { + keys.insert(key_id.to_string(), versions); + } + } } - Ok(rotated.version) + Ok(true) } } @@ -262,12 +427,11 @@ impl EncryptionEngine { // Load the encryption key let key = Self::load_key(&config.key_source, config.key_size_bytes()).await?; - keys.insert(key_id, key); + keys.insert(key_id, KeyVersions::single(key)); Ok(Self { config, keys: Arc::new(Mutex::new(keys)), - previous_keys: Arc::new(Mutex::new(HashMap::new())), kms: None, stats: Arc::new(Mutex::new(EncryptionStats::new())), }) @@ -286,19 +450,21 @@ impl EncryptionEngine { fn load_or_generate_key( location: &str, expected_size: usize, - ) -> Result, EncryptionError> { + ) -> Result { use base64::Engine; use std::io::Write; - let decode = |stored: &str, place: &str| -> Result, EncryptionError> { - let key = base64::engine::general_purpose::STANDARD - .decode(stored.trim()) - .map_err(|e| { - EncryptionError::KeyManagement(format!( - "Invalid base64 key stored in {}: {}", - place, e - )) - })?; + let decode = |stored: &str, place: &str| -> Result { + let key = SecretBytes::new( + base64::engine::general_purpose::STANDARD + .decode(stored.trim()) + .map_err(|e| { + EncryptionError::KeyManagement(format!( + "Invalid base64 key stored in {}: {}", + place, e + )) + })?, + ); if key.len() != expected_size { return Err(EncryptionError::KeyManagement(format!( "Key size mismatch in {}: expected {} bytes, got {}", @@ -316,24 +482,25 @@ impl EncryptionEngine { )) }; - let mut key = vec![0u8; expected_size]; + let mut key = SecretBytes::new(vec![0u8; expected_size]); OsRng.fill_bytes(&mut key); - let encoded = base64::engine::general_purpose::STANDARD.encode(&key); + let encoded = + zeroize::Zeroizing::new(base64::engine::general_purpose::STANDARD.encode(&key)); if let Some(var_name) = location.strip_prefix("env://") { if let Ok(stored) = std::env::var(var_name) { - return decode(&stored, var_name); + return decode(&zeroize::Zeroizing::new(stored), var_name); } // SAFETY: as for any `set_var`, the caller must not read or write the // environment from other threads meanwhile. unsafe { - std::env::set_var(var_name, encoded); + std::env::set_var(var_name, encoded.as_str()); } info!("Stored generated key in environment variable: {}", var_name); return Ok(key); } if location.starts_with("stdout://") { - println!("Generated encryption key: {}", encoded); + println!("Generated encryption key: {}", encoded.as_str()); println!("Store this key securely and set it as an environment variable."); return Ok(key); } @@ -361,12 +528,13 @@ impl EncryptionEngine { Ok(key) } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { - let stored = std::fs::read_to_string(file_path).map_err(|e| { - EncryptionError::KeyManagement(format!( - "Failed to read stored key {}: {}", - file_path, e - )) - })?; + let stored = + zeroize::Zeroizing::new(std::fs::read_to_string(file_path).map_err(|e| { + EncryptionError::KeyManagement(format!( + "Failed to read stored key {}: {}", + file_path, e + )) + })?); info!("Loaded previously generated key from file: {}", file_path); decode(&stored, file_path) } @@ -378,14 +546,16 @@ impl EncryptionEngine { async fn load_key( key_source: &KeySource, expected_size: usize, - ) -> Result, EncryptionError> { + ) -> Result { match key_source { KeySource::Static(key_str) => { - let key_bytes = base64::engine::general_purpose::STANDARD - .decode(key_str) - .map_err(|e| { - EncryptionError::KeyManagement(format!("Invalid base64 key: {}", e)) - })?; + let key_bytes = SecretBytes::new( + base64::engine::general_purpose::STANDARD + .decode(key_str) + .map_err(|e| { + EncryptionError::KeyManagement(format!("Invalid base64 key: {}", e)) + })?, + ); if key_bytes.len() != expected_size { return Err(EncryptionError::KeyManagement(format!( @@ -398,21 +568,23 @@ impl EncryptionEngine { Ok(key_bytes) } KeySource::Environment(var_name) => { - let key_str = std::env::var(var_name).map_err(|_| { + let key_str = zeroize::Zeroizing::new(std::env::var(var_name).map_err(|_| { EncryptionError::KeyManagement(format!( "Environment variable {} not found", var_name )) - })?; - - let key_bytes = base64::engine::general_purpose::STANDARD - .decode(&key_str) - .map_err(|e| { - EncryptionError::KeyManagement(format!( - "Invalid base64 key in {}: {}", - var_name, e - )) - })?; + })?); + + let key_bytes = SecretBytes::new( + base64::engine::general_purpose::STANDARD + .decode(key_str.as_str()) + .map_err(|e| { + EncryptionError::KeyManagement(format!( + "Invalid base64 key in {}: {}", + var_name, e + )) + })?, + ); if key_bytes.len() != expected_size { return Err(EncryptionError::KeyManagement(format!( @@ -525,8 +697,8 @@ impl EncryptionEngine { let key = Self::load_key(key_source, self.config.key_size_bytes()).await?; self.keys .lock() - .map_err(|_| EncryptionError::KeyManagement("Failed to acquire key lock".to_string()))? - .insert(key_id, key); + .map_err(|_| key_lock_error())? + .insert(key_id, KeyVersions::single(key)); Ok(self) } @@ -545,14 +717,12 @@ impl EncryptionEngine { &self.config.algorithm } - /// The key used for encryption. - fn active_key(&self) -> Result, EncryptionError> { + /// The key used for encryption (shared, not copied). + fn active_key(&self) -> Result { let key_id = self.key_id(); - let keys = self.keys.lock().map_err(|_| { - EncryptionError::KeyManagement("Failed to acquire key lock".to_string()) - })?; + let keys = self.keys.lock().map_err(|_| key_lock_error())?; keys.get(key_id) - .cloned() + .map(|versions| versions.active.clone()) .ok_or_else(|| EncryptionError::KeyManagement(format!("Key not found: {}", key_id))) } @@ -749,7 +919,22 @@ impl EncryptionEngine { encrypted_payload: &EncryptedPayload, associated_data: &[u8], ) -> Result { - let result = self.decrypt_value(encrypted_payload, associated_data); + let mut result = self.decrypt_value(encrypted_payload, associated_data); + // The payload may use a key version (or key id) that another process stored after + // this engine loaded its keys, e.g. after a rotation: reload and try again. + if result.is_err() && self.kms.is_some() { + match self + .reload_kms_key(&encrypted_payload.metadata.key_id) + .await + { + Ok(true) => result = self.decrypt_value(encrypted_payload, associated_data), + Ok(false) => {} + Err(e) => warn!( + "Could not reload KMS-wrapped data key {} after a decryption failure: {}", + encrypted_payload.metadata.key_id, e + ), + } + } if result.is_err() && let Ok(mut stats) = self.stats.lock() { @@ -764,33 +949,22 @@ impl EncryptionEngine { associated_data: &[u8], ) -> Result { let start_time = Instant::now(); - let lock_error = - || EncryptionError::KeyManagement("Failed to acquire key lock".to_string()); // The key named by the payload, then earlier versions of a rotated KMS-wrapped key let key_id = &encrypted_payload.metadata.key_id; - let mut candidates = vec![ - self.keys - .lock() - .map_err(|_| lock_error())? - .get(key_id) - .cloned() - .ok_or_else(|| { - EncryptionError::KeyManagement(format!( - "Key not found: {} (the payload was encrypted with a key this engine \ - does not have; see EncryptionEngine::with_decryption_key)", - key_id - )) - })?, - ]; - candidates.extend( - self.previous_keys - .lock() - .map_err(|_| lock_error())? - .get(key_id) - .cloned() - .unwrap_or_default(), - ); + let candidates = self + .keys + .lock() + .map_err(|_| key_lock_error())? + .get(key_id) + .map(KeyVersions::candidates) + .ok_or_else(|| { + EncryptionError::KeyManagement(format!( + "Key not found: {} (the payload was encrypted with a key this engine \ + does not have; see EncryptionEngine::with_decryption_key)", + key_id + )) + })?; let ciphertext = encrypted_payload.decode_ciphertext()?; let nonce = encrypted_payload.decode_nonce()?; @@ -1242,7 +1416,7 @@ fn keyed_payload_hash(key: &[u8], data: &[u8]) -> Result Result, EncryptionError> { +) -> Result { if service_config.starts_with("aws://") || service_config.starts_with("gcp://") { // Validates the configuration and the cargo feature first envelope::parse_kms_source(&KeySource::External(service_config.to_string()))?; @@ -1265,12 +1439,12 @@ async fn load_external_key( /// Load a key from a HashiCorp Vault KV v2 secret (`vault:///?addr=`). /// -/// The secret's string `key` field is used: a base64 key is truncated or padded to -/// `expected_size`, any other string is hashed with SHA-256. +/// The secret's string `key` field must be a base64-encoded key of exactly +/// `expected_size` bytes; anything else is an [`EncryptionError::InvalidConfiguration`]. async fn load_from_vault( service_config: &str, expected_size: usize, -) -> Result, EncryptionError> { +) -> Result { let (secret_path, params) = kms::parse_service_config(service_config, "vault://"); let vault_addr = kms::vault_address(¶ms)?; let (mount, secret) = kms::vault_mount_and_path(secret_path)?; @@ -1289,48 +1463,19 @@ async fn load_from_vault( #[cfg(feature = "vault-kms")] { let key_str = kms::vault_read_key_field(&vault_addr, mount, secret).await?; - Ok(fit_vault_key(&key_str, expected_size)) + let key = kms::exact_vault_key(&key_str, expected_size)?; + info!("Successfully loaded encryption key from HashiCorp Vault"); + Ok(key) } } -/// Turn the `key` field of a Vault secret into a key of `expected_size` bytes: base64 -/// key material is used as is (truncated, or padded with its SHA-256 hash when short); -/// anything else is hashed. -#[cfg(feature = "vault-kms")] -fn fit_vault_key(key_str: &str, expected_size: usize) -> Vec { - if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(key_str) { - if decoded.len() == expected_size { - info!("Successfully loaded encryption key from HashiCorp Vault"); - return decoded; - } - // Wrong size: truncate, or pad with a hash of the decoded key - let mut key = vec![0u8; expected_size]; - let copy_len = std::cmp::min(decoded.len(), expected_size); - key[..copy_len].copy_from_slice(&decoded[..copy_len]); - if decoded.len() < expected_size { - let hash = Sha256::digest(&decoded); - for (i, byte) in key.iter_mut().enumerate().skip(decoded.len()) { - *byte = hash[i % hash.len()]; - } - } - info!("Successfully loaded and resized encryption key from HashiCorp Vault"); - return key; - } - - // Not base64: hash the string to the expected size - let hash = Sha256::digest(key_str.as_bytes()); - let key = (0..expected_size).map(|i| hash[i % hash.len()]).collect(); - info!("Successfully loaded and hashed encryption key from HashiCorp Vault"); - key -} - /// Load a key from Azure Key Vault (`azure:///keys/`, key name -/// defaults to `encryption-key`). Material shorter than `expected_size` is padded with -/// HMAC-SHA256 output keyed by the material. +/// defaults to `encryption-key`). The key material must be exactly `expected_size` +/// bytes; anything else is an [`EncryptionError::InvalidConfiguration`]. async fn load_from_azure_kv( service_config: &str, expected_size: usize, -) -> Result, EncryptionError> { +) -> Result { let (vault_url, key_name) = kms::azure_vault_and_key(service_config, "encryption-key")?; info!( @@ -1355,45 +1500,14 @@ async fn load_from_azure_kv( )) })?; - fit_azure_key(&decoded_key, &vault_url, &key_name, expected_size) - } -} - -/// Turn Azure Key Vault key material into a key of `expected_size` bytes: longer -/// material is truncated; shorter material is padded with HMAC-SHA256 output keyed by -/// the material and bound to the vault URL and key name. -#[cfg(feature = "azure-kv")] -fn fit_azure_key( - decoded_key: &[u8], - vault_url: &str, - key_name: &str, - expected_size: usize, -) -> Result, EncryptionError> { - if decoded_key.len() >= expected_size { + let key = kms::exact_size( + decoded_key, + expected_size, + &format!("Azure Key Vault key {} in {}", key_name, vault_url), + )?; info!("Successfully loaded encryption key from Azure Key Vault"); - return Ok(decoded_key[..expected_size].to_vec()); + Ok(key) } - - // Key is shorter than expected: pad it using key derivation - use hmac::{Hmac, Mac}; - type HmacSha256 = Hmac; - - let mut final_key = vec![0u8; expected_size]; - final_key[..decoded_key.len()].copy_from_slice(decoded_key); - - let mut mac = ::new_from_slice(decoded_key) - .map_err(|e| EncryptionError::KeyManagement(format!("HMAC creation failed: {}", e)))?; - mac.update(b"azure-kv-key-derivation"); - mac.update(vault_url.as_bytes()); - mac.update(key_name.as_bytes()); - let derived = mac.finalize().into_bytes(); - - for (i, byte) in final_key.iter_mut().enumerate().skip(decoded_key.len()) { - *byte = derived[i % derived.len()]; - } - - info!("Successfully loaded and padded encryption key from Azure Key Vault"); - Ok(final_key) } #[cfg(test)] @@ -1772,19 +1886,95 @@ mod tests { } fn active_key(engine: &EncryptionEngine, key_id: &str) -> Vec { - engine.keys.lock().unwrap()[key_id].clone() + engine.keys.lock().unwrap()[key_id].active.to_vec() } fn previous_keys(engine: &EncryptionEngine, key_id: &str) -> Vec> { engine - .previous_keys + .keys .lock() .unwrap() .get(key_id) - .cloned() + .map(|versions| versions.previous.iter().map(|(_, k)| k.to_vec()).collect()) .unwrap_or_default() } + /// Two engines (two workers, or two processes) share one key store. After one of them + /// rotates the data key, the other decrypts payloads encrypted with the new version + /// by reloading the stored versions, and then encrypts with it too (#64 H4). + #[tokio::test] + async fn test_engines_sharing_a_store_survive_a_rotation() { + use crate::encryption::envelope::test_support::MemoryStore; + + let kms = MockKms::unique(); + let store: Arc = Arc::new(MemoryStore::default()); + let config = || EncryptionConfig::new(EncryptionAlgorithm::AES256GCM); + let payload = json!({"ssn": "123-45-6789"}); + + let rotating = EncryptionEngine::with_kms_store(config(), store.clone(), same_kms(&kms)) + .await + .unwrap(); + let other = EncryptionEngine::with_kms_store(config(), store.clone(), same_kms(&kms)) + .await + .unwrap(); + let v1 = active_key(&other, "default"); + // Nothing new to load yet. + assert!(!other.reload_kms_keys().await.unwrap()); + + assert_eq!(rotating.rotate_kms_key_in(store.as_ref()).await.unwrap(), 2); + let after_rotation = rotating.encrypt_payload(&payload, &["ssn"]).await.unwrap(); + + // The other engine only held v1: it reloads v2 and decrypts. + assert_eq!( + other.decrypt_payload(&after_rotation).await.unwrap(), + payload + ); + let v2 = active_key(&rotating, "default"); + assert_ne!(v1, v2); + assert_eq!(active_key(&other, "default"), v2, "now encrypts with v2"); + assert_eq!(previous_keys(&other, "default"), vec![v1.clone()]); + assert_eq!(other.get_stats().decryption_errors, 0); + + // What it encrypts now is readable by an engine that only knows v2 and v1. + let from_other = other.encrypt_payload(&payload, &["ssn"]).await.unwrap(); + assert_eq!( + rotating.decrypt_payload(&from_other).await.unwrap(), + payload + ); + + // A third rotation is picked up by an explicit reload. + rotating.rotate_kms_key_in(store.as_ref()).await.unwrap(); + assert!(other.reload_kms_keys().await.unwrap()); + assert_eq!( + active_key(&other, "default"), + active_key(&rotating, "default") + ); + assert_eq!(previous_keys(&other, "default").len(), 2); + + // A payload under another key id stored in the same table is looked up by the + // key id it records. + let other_id = EncryptionEngine::with_kms_store( + config().with_key_id("tenant-b"), + store.clone(), + same_kms(&kms), + ) + .await + .unwrap(); + let tenant_b = other_id.encrypt_payload(&payload, &["ssn"]).await.unwrap(); + assert_eq!(other.decrypt_payload(&tenant_b).await.unwrap(), payload); + + // A tampered payload still fails, after one reload attempt that finds nothing. + let mut tampered = rotating.encrypt_payload(&payload, &["ssn"]).await.unwrap(); + tampered.metadata.payload_hash = "hmac-sha256:00".to_string(); + assert!(other.decrypt_payload(&tampered).await.is_err()); + + // Engines without a KMS have nothing to reload. + let static_engine = EncryptionEngine::new(static_engine("k", KEY_A)) + .await + .unwrap(); + assert!(!static_engine.reload_kms_keys().await.unwrap()); + } + /// Engines in different processes (or after a restart) load the same stored data key, /// and keep earlier versions after a rotation. async fn engine_kms_roundtrip(pool: Pool) { @@ -1870,6 +2060,85 @@ mod tests { assert_eq!(stored.len(), 1); } + /// Two processes share the KMS-wrapped key in the database. One rotates the data key + /// and enqueues; a worker of the other, started before the rotation, still runs the + /// job with its plaintext instead of failing it until it goes Dead (#64 H4). + async fn worker_survives_a_rotation_by_another_process(pool: Pool) + where + DB: KeyManagerBackend + Send + Sync + 'static, + crate::JobQueue: crate::queue::DatabaseQueue + Send + Sync + 'static, + { + use crate::queue::DatabaseQueue; + use crate::{Job, JobQueue, JobStatus, Worker}; + + let kms = MockKms::unique(); + let config = || EncryptionConfig::new(EncryptionAlgorithm::AES256GCM); + let producer_engine = EncryptionEngine::with_kms(config(), &pool, same_kms(&kms)) + .await + .unwrap(); + let worker_engine = EncryptionEngine::with_kms(config(), &pool, same_kms(&kms)) + .await + .unwrap(); + let queue_name = format!("kms_rotation_{}", uuid::Uuid::new_v4().simple()); + + // The producer rotates after the worker loaded version 1 + producer_engine.rotate_kms_key(&pool).await.unwrap(); + let producer = JobQueue::new(pool.clone()) + .with_encryption(producer_engine) + .with_encrypted_queues([queue_name.clone()]); + let payload = json!({"ssn": "123-45-6789"}); + let id = producer + .enqueue(Job::new(queue_name.clone(), payload.clone()).with_max_attempts(1)) + .await + .unwrap(); + + let consumer = Arc::new(JobQueue::new(pool.clone()).with_encryption(worker_engine)); + let seen = Arc::new(Mutex::new(Vec::new())); + let handler_seen = Arc::clone(&seen); + let handler: crate::worker::JobHandler = Arc::new(move |job: Job| { + let seen = Arc::clone(&handler_seen); + Box::pin(async move { + seen.lock().unwrap().push(job.payload.clone()); + Ok(()) + }) + }); + let worker = Worker::new(Arc::clone(&consumer), queue_name, handler) + .with_poll_interval(Duration::from_millis(50)); + let (shutdown_tx, shutdown_rx) = tokio::sync::mpsc::channel(1); + let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + let deadline = std::time::Instant::now() + Duration::from_secs(15); + let job = loop { + let job = consumer.get_job(id).await.unwrap().unwrap(); + if !matches!(job.status, JobStatus::Pending | JobStatus::Running) + || std::time::Instant::now() > deadline + { + break job; + } + tokio::time::sleep(Duration::from_millis(50)).await; + }; + shutdown_tx.send(()).await.unwrap(); + task.await.unwrap().unwrap(); + + assert_eq!(job.status, JobStatus::Completed, "{:?}", job.error_message); + assert_eq!(*seen.lock().unwrap(), vec![payload]); + consumer.delete_job(id).await.unwrap(); + } + + #[cfg(feature = "postgres")] + #[tokio::test] + #[ignore = "requires PostgreSQL: DATABASE_URL"] + async fn test_worker_survives_a_rotation_by_another_process_postgres() { + worker_survives_a_rotation_by_another_process(postgres_pool().await).await; + } + + #[cfg(feature = "mysql")] + #[tokio::test] + #[ignore = "requires MySQL: MYSQL_DATABASE_URL"] + async fn test_worker_survives_a_rotation_by_another_process_mysql() { + worker_survives_a_rotation_by_another_process(mysql_pool().await).await; + } + /// Payloads encrypted before a restart and before a rotation can be decrypted. async fn engine_kms_payload_roundtrip(pool: Pool) { let kms = MockKms::unique(); @@ -1906,8 +2175,15 @@ mod tests { third.decrypt_payload(&after_rotation).await.unwrap(), payload ); - // The engine that did not rotate cannot read the new version until it reloads - assert!(first.decrypt_payload(&after_rotation).await.is_err()); + // The engine that did not rotate loads the new version from the database (#64 H4) + assert_eq!( + first.decrypt_payload(&after_rotation).await.unwrap(), + payload + ); + assert_eq!( + active_key(&first, "default"), + active_key(&second, "default") + ); } #[cfg(feature = "postgres")] @@ -2293,55 +2569,59 @@ mod tests { assert_eq!(engine.get_stats().retention_cleanups, 1); } - #[cfg(feature = "vault-kms")] #[test] - fn test_fit_vault_key() { + fn test_vault_key_must_be_exactly_the_key_size() { use base64::Engine as _; let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); // The right size is used as is. let exact: Vec = (0..32).collect(); - assert_eq!(fit_vault_key(&b64(&exact), 32), exact); - // Longer material is truncated. - let long: Vec = (0..40).collect(); - assert_eq!(fit_vault_key(&b64(&long), 32), long[..32].to_vec()); - // Shorter material keeps its bytes and is padded deterministically. - let short = fit_vault_key(&b64(b"short"), 32); - assert_eq!(&short[..5], b"short"); - assert_eq!(short.len(), 32); - assert_eq!(short, fit_vault_key(&b64(b"short"), 32)); - assert_ne!(short[5..], [0u8; 27]); - // Not base64: hashed to the right size. - let hashed = fit_vault_key("a passphrase!", 16); - assert_eq!(hashed.len(), 16); - assert_eq!(hashed, fit_vault_key("a passphrase!", 16)); - assert_ne!(hashed, fit_vault_key("another one!", 16)); - } - - #[cfg(feature = "azure-kv")] - #[test] - fn test_fit_azure_key() { - let long: Vec = (0..40).collect(); assert_eq!( - fit_azure_key(&long, "https://v", "k", 32).unwrap(), - long[..32].to_vec() - ); - let padded = fit_azure_key(b"0123456789", "https://v", "k", 32).unwrap(); - assert_eq!(&padded[..10], b"0123456789"); - assert_eq!(padded.len(), 32); - // The padding is bound to the vault and key name. - assert_ne!( - padded, - fit_azure_key(b"0123456789", "https://other", "k", 32).unwrap() + kms::exact_vault_key(&b64(&exact), 32).unwrap().as_slice(), + exact.as_slice() ); - assert_ne!( - padded, - fit_azure_key(b"0123456789", "https://v", "other", 32).unwrap() + // Longer or shorter material is rejected, not truncated or padded. + for wrong in [(0..40).collect::>(), b"short".to_vec(), vec![7]] { + let err = kms::exact_vault_key(&b64(&wrong), 32).unwrap_err(); + assert!( + matches!(err, EncryptionError::InvalidConfiguration(_)), + "{err}" + ); + assert!( + err.to_string().contains("expected exactly 32 bytes"), + "{err}" + ); + } + // A passphrase (not base64) is rejected, not hashed into a key. + let err = kms::exact_vault_key("a passphrase!", 32).unwrap_err(); + assert!( + matches!(err, EncryptionError::InvalidConfiguration(_)), + "{err}" ); + assert!(err.to_string().contains("not base64"), "{err}"); + } + + #[test] + fn test_azure_key_material_must_be_exactly_the_key_size() { + let exact: Vec = (0..32).collect(); assert_eq!( - padded, - fit_azure_key(b"0123456789", "https://v", "k", 32).unwrap() + kms::exact_size(SecretBytes::new(exact.clone()), 32, "Azure key") + .unwrap() + .as_slice(), + exact.as_slice() ); + for wrong in [(0..40).collect::>(), b"0123456789".to_vec()] { + let err = kms::exact_size(SecretBytes::new(wrong), 32, "Azure key").unwrap_err(); + assert!( + matches!(err, EncryptionError::InvalidConfiguration(_)), + "{err}" + ); + assert!( + err.to_string() + .starts_with("Invalid configuration: Azure key"), + "{err}" + ); + } } #[cfg(feature = "azure-kv")] diff --git a/src/encryption/envelope.rs b/src/encryption/envelope.rs index 137827e..88296e7 100644 --- a/src/encryption/envelope.rs +++ b/src/encryption/envelope.rs @@ -16,7 +16,7 @@ //! authenticated data), so a blob stored for one purpose cannot be decrypted as another. use super::key_manager::{KeyManagerBackend, KmsWrappedKey}; -use super::{EncryptionError, KeySource, kms}; +use super::{EncryptionError, KeySource, SecretBytes, kms}; use chrono::Utc; use sqlx::Pool; use std::sync::Arc; @@ -24,7 +24,7 @@ use uuid::Uuid; /// A data key generated by a KMS: the plaintext and its KMS-encrypted form. pub(crate) struct DataKey { - pub plaintext: Vec, + pub plaintext: SecretBytes, pub ciphertext: Vec, } @@ -48,7 +48,11 @@ pub(crate) trait KmsKeyWrapper: Send + Sync { /// Decrypt a data key produced by [`KmsKeyWrapper::generate_data_key`] with the same /// `context`. - async fn decrypt(&self, ciphertext: &[u8], context: &str) -> Result, EncryptionError>; + async fn decrypt( + &self, + ciphertext: &[u8], + context: &str, + ) -> Result; } /// A parsed `aws://` or `gcp://` key source. @@ -177,10 +181,38 @@ impl WrappedKeyStore for DbStore<'_, DB> { } } +/// [`WrappedKeyStore`] backed by `hammerwork_kms_data_keys`, owning its pool, for an +/// engine that reloads keys later (after another process rotated them). +pub(crate) struct PoolStore(pub Pool); + +#[async_trait::async_trait] +impl WrappedKeyStore for PoolStore { + async fn insert_if_absent(&self, key: &KmsWrappedKey) -> Result<(), EncryptionError> { + DbStore(&self.0).insert_if_absent(key).await + } + + async fn insert_rotated(&self, key: &KmsWrappedKey) -> Result<(), EncryptionError> { + DbStore(&self.0).insert_rotated(key).await + } + + async fn load_versions( + &self, + key_name: &str, + kms_provider: &str, + kms_key_id: &str, + ) -> Result, EncryptionError> { + DbStore(&self.0) + .load_versions(key_name, kms_provider, kms_key_id) + .await + } +} + /// A plaintext key recovered from the KMS, with its stored version. pub(crate) struct EnvelopeKey { pub version: u32, - pub key: Vec, + pub key: SecretBytes, + /// Whether this is the active version (the one new data is encrypted with) + pub active: bool, } fn new_record( @@ -239,6 +271,7 @@ async fn unwrap( Ok(EnvelopeKey { version: record.version, key, + active: record.active, }) } @@ -308,6 +341,7 @@ pub(crate) async fn load_or_create( Ok(EnvelopeKey { version: record.version, key: data_key.plaintext, + active: true, }) } else { // Another process stored its key first: use that one. @@ -344,6 +378,7 @@ pub(crate) async fn rotate( Ok(EnvelopeKey { version: next_version, key: data_key.plaintext, + active: true, }) } @@ -353,17 +388,33 @@ pub(crate) async fn load_all( kms: &dyn KmsKeyWrapper, key_name: &str, size: usize, +) -> Result, EncryptionError> { + load_new(store, kms, key_name, size, |_| false).await +} + +/// Decrypt the stored versions of `key_name` for which `known` is false, newest first. +/// +/// Reading the stored versions is one database query; the KMS is only called for +/// versions that are not known yet. +pub(crate) async fn load_new( + store: &dyn WrappedKeyStore, + kms: &dyn KmsKeyWrapper, + key_name: &str, + size: usize, + known: impl Fn(u32) -> bool, ) -> Result, EncryptionError> { let mut keys = Vec::new(); for record in versions(store, kms, key_name).await? { - keys.push(unwrap(kms, &record, size).await?); + if !known(record.version) { + keys.push(unwrap(kms, &record, size).await?); + } } Ok(keys) } #[cfg(feature = "aws-kms")] mod aws { - use super::{DataKey, KmsKeyWrapper}; + use super::{DataKey, KmsKeyWrapper, SecretBytes}; use crate::encryption::EncryptionError; use aws_sdk_kms::{ Client, @@ -463,7 +514,7 @@ mod aws { ) })?; Ok(DataKey { - plaintext: plaintext.into_inner(), + plaintext: SecretBytes::new(plaintext.into_inner()), ciphertext: ciphertext.into_inner(), }) } @@ -472,7 +523,7 @@ mod aws { &self, ciphertext: &[u8], context: &str, - ) -> Result, EncryptionError> { + ) -> Result { let response = self .client .decrypt() @@ -491,7 +542,7 @@ mod aws { })?; response .plaintext - .map(|plaintext| plaintext.into_inner()) + .map(|plaintext| SecretBytes::new(plaintext.into_inner())) .ok_or_else(|| { EncryptionError::KeyManagement( "AWS KMS Decrypt response has no plaintext".to_string(), @@ -503,7 +554,7 @@ mod aws { #[cfg(feature = "gcp-kms")] mod gcp { - use super::{DataKey, KmsKeyWrapper}; + use super::{DataKey, KmsKeyWrapper, SecretBytes}; use crate::encryption::EncryptionError; use google_cloud_kms::client::{Client, ClientConfig}; use google_cloud_kms::grpc::kms::v1::{ @@ -595,30 +646,31 @@ mod gcp { size )) })?; - let plaintext = self - .client - .generate_random_bytes( - GenerateRandomBytesRequest { - location: self.location.clone(), - length_bytes, - protection_level: 1, // SOFTWARE - }, - None, - ) - .await - .map_err(|e| { - EncryptionError::KeyManagement(format!( - "GCP KMS GenerateRandomBytes failed: {}", - e - )) - })? - .data; + let plaintext = SecretBytes::new( + self.client + .generate_random_bytes( + GenerateRandomBytesRequest { + location: self.location.clone(), + length_bytes, + protection_level: 1, // SOFTWARE + }, + None, + ) + .await + .map_err(|e| { + EncryptionError::KeyManagement(format!( + "GCP KMS GenerateRandomBytes failed: {}", + e + )) + })? + .data, + ); let ciphertext = self .client .encrypt( EncryptRequest { name: self.resource.clone(), - plaintext: plaintext.clone(), + plaintext: plaintext.to_vec(), additional_authenticated_data: context.as_bytes().to_vec(), ..Default::default() }, @@ -642,26 +694,27 @@ mod gcp { &self, ciphertext: &[u8], context: &str, - ) -> Result, EncryptionError> { - Ok(self - .client - .decrypt( - DecryptRequest { - name: self.resource.clone(), - ciphertext: ciphertext.to_vec(), - additional_authenticated_data: context.as_bytes().to_vec(), - ..Default::default() - }, - None, - ) - .await - .map_err(|e| { - EncryptionError::KeyManagement(format!( - "GCP KMS Decrypt with key {} failed: {}", - self.resource, e - )) - })? - .plaintext) + ) -> Result { + Ok(SecretBytes::new( + self.client + .decrypt( + DecryptRequest { + name: self.resource.clone(), + ciphertext: ciphertext.to_vec(), + additional_authenticated_data: context.as_bytes().to_vec(), + ..Default::default() + }, + None, + ) + .await + .map_err(|e| { + EncryptionError::KeyManagement(format!( + "GCP KMS Decrypt with key {} failed: {}", + self.resource, e + )) + })? + .plaintext, + )) } } } @@ -720,7 +773,7 @@ pub(crate) mod test_support { context: &str, ) -> Result { self.generated.fetch_add(1, Ordering::SeqCst); - let mut plaintext = vec![0u8; size]; + let mut plaintext = SecretBytes::new(vec![0u8; size]); OsRng.fill_bytes(&mut plaintext); let cipher = Aes256Gcm::new_from_slice(&self.secret).unwrap(); let mut nonce = [0u8; 12]; @@ -747,7 +800,7 @@ pub(crate) mod test_support { &self, ciphertext: &[u8], context: &str, - ) -> Result, EncryptionError> { + ) -> Result { self.decrypted.fetch_add(1, Ordering::SeqCst); if ciphertext.len() < 12 { return Err(EncryptionError::DecryptionFailed("short".to_string())); @@ -762,6 +815,7 @@ pub(crate) mod test_support { aad: context.as_bytes(), }, ) + .map(SecretBytes::new) .map_err(|_| EncryptionError::DecryptionFailed("mock KMS decrypt".to_string())) } } @@ -857,7 +911,12 @@ mod tests { let keys = store.keys.lock().unwrap(); assert_eq!(keys.len(), 1); - assert!(!keys[0].wrapped_key.windows(32).any(|w| w == first.key)); + assert!( + !keys[0] + .wrapped_key + .windows(32) + .any(|w| w == first.key.as_slice()) + ); assert_eq!(keys[0].kms_key_id, kms.kms_key_id()); assert_eq!(keys[0].kms_provider, "aws"); } @@ -1185,8 +1244,8 @@ mod tests { assert_eq!(kms.kms_key_id(), "alias/test"); let data_key = kms.generate_data_key(32, "engine/k1").await.unwrap(); - assert_eq!(data_key.plaintext, vec![7u8; 32]); - assert_ne!(data_key.ciphertext, data_key.plaintext); + assert_eq!(data_key.plaintext.as_slice(), [7u8; 32].as_slice()); + assert_ne!(data_key.ciphertext, data_key.plaintext.to_vec()); assert_eq!( kms.decrypt(&data_key.ciphertext, "engine/k1") .await diff --git a/src/encryption/key_manager.rs b/src/encryption/key_manager.rs index 8193c72..78d5a84 100644 --- a/src/encryption/key_manager.rs +++ b/src/encryption/key_manager.rs @@ -138,7 +138,7 @@ //! ``` use super::envelope::{self, DbStore, KmsKeyWrapper}; -use super::{EncryptionAlgorithm, EncryptionError, KeySource, kms}; +use super::{EncryptionAlgorithm, EncryptionError, KeySource, SecretBytes, kms}; use aes_gcm::{Aes256Gcm, KeyInit, Nonce, aead::Aead}; use base64::Engine; use chrono::{DateTime, Duration, Utc}; @@ -176,7 +176,9 @@ pub struct KeyManagerConfig { } /// Configuration for external Key Management Service integration -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` shows the names of the `auth_config` entries but never their values. +#[derive(Clone, Serialize, Deserialize)] pub struct ExternalKmsConfig { /// KMS service type (AWS, GCP, Azure, HashiCorp Vault, etc.) pub service_type: String, @@ -194,6 +196,26 @@ pub struct ExternalKmsConfig { pub namespace: Option, } +impl std::fmt::Debug for ExternalKmsConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut auth_keys: Vec<&String> = self.auth_config.keys().collect(); + auth_keys.sort(); + f.debug_struct("ExternalKmsConfig") + .field("service_type", &self.service_type) + .field("endpoint", &crate::config::redact_url(&self.endpoint)) + .field( + "auth_config", + &auth_keys + .into_iter() + .map(|key| (key, "[REDACTED]")) + .collect::>(), + ) + .field("region", &self.region) + .field("namespace", &self.namespace) + .finish() + } +} + /// Configuration for key derivation from passwords or passphrases #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KeyDerivationConfig { @@ -378,9 +400,10 @@ pub struct KeyManagerStats { } /// Main key management system -type KeyCacheEntry = (Vec, DateTime); // (decrypted_material, cached_at) +// Key material held in memory is `SecretBytes`, wiped when dropped. +type KeyCacheEntry = (SecretBytes, DateTime); // (decrypted_material, cached_at) type KeyCache = Arc>>; -type RootKey = (Uuid, Vec); // (derived ID, key material) +type RootKey = (Uuid, SecretBytes); // (derived ID, key material) /// Name under which [`KeyManager`] stores its KMS-wrapped master key in /// `hammerwork_kms_data_keys` (for `aws://` and `gcp://` master key sources). @@ -430,12 +453,12 @@ pub struct KeyManager { /// Key loaded from `master_key_source`, with its derived ID root_key: Arc>>, /// Key that wraps newly generated keys (the active KEK, or the root key) - master_key: Arc>>>, + master_key: Arc>>, master_key_id: Arc>>, /// KMS that wraps the master key, for `aws://` and `gcp://` master key sources kms: Option>, /// Earlier versions of a KMS-wrapped master key, by derived ID - retired_root_keys: Arc>>>, + retired_root_keys: Arc>>, key_cache: KeyCache, stats: Arc>, } @@ -1143,7 +1166,9 @@ impl KeyManager { check_key_usable(&key_record)?; let key_material = self.unwrap_key_material(&key_record).await?; - self.cache_key(key_id, key_material.clone()); + // The caller gets its own copy; the cached one is wiped when evicted or dropped. + let copy = key_material.to_vec(); + self.cache_key(key_id, key_material); self.record_key_usage(key_id).await?; if self.config.audit_enabled { @@ -1151,7 +1176,7 @@ impl KeyManager { .await?; } - Ok(key_material) + Ok(copy) } /// Retrieve the key material of a specific version of a key @@ -1181,7 +1206,7 @@ impl KeyManager { } self.update_stats(|stats| stats.total_access_operations += 1); - Ok(key_material) + Ok(key_material.to_vec()) } /// Rotate a key to a new version @@ -1523,7 +1548,7 @@ impl KeyManager { .map_err(|_| lock_error("retired root keys"))? .insert(old_id, old_key); *self.root_key.lock().map_err(|_| lock_error("root key"))? = - Some((new_id, rotated.key.clone())); + Some((new_id, SecretBytes::new(rotated.key.to_vec()))); if self.get_master_key_id().await == Some(old_id) { // No key-encryption key: the root key wraps new keys directly *self @@ -1661,7 +1686,7 @@ impl KeyManager { } /// The master key that new keys are encrypted with, and its ID. - fn current_master_key(&self) -> Result<(Uuid, Vec), EncryptionError> { + fn current_master_key(&self) -> Result<(Uuid, SecretBytes), EncryptionError> { let id = (*self .master_key_id .lock() @@ -1677,7 +1702,7 @@ impl KeyManager { } /// The configured master key (from `master_key_source`) and its ID. - fn root_key(&self) -> Result<(Uuid, Vec), EncryptionError> { + fn root_key(&self) -> Result<(Uuid, SecretBytes), EncryptionError> { self.root_key .lock() .map_err(|_| lock_error("root key"))? @@ -1686,7 +1711,10 @@ impl KeyManager { } /// Decrypt a stored key with the master key that encrypted it. - async fn unwrap_key_material(&self, key: &EncryptionKey) -> Result, EncryptionError> { + async fn unwrap_key_material( + &self, + key: &EncryptionKey, + ) -> Result { let (current_id, current_key) = self.current_master_key()?; let wrapping_key = match key.master_key_id { None => current_key, @@ -1711,7 +1739,7 @@ impl KeyManager { } /// Decrypt a key-encryption key with the root key that encrypted it. - async fn unwrap_kek(&self, kek: &EncryptionKey) -> Result, EncryptionError> { + async fn unwrap_kek(&self, kek: &EncryptionKey) -> Result { let (root_id, root_key) = self.root_key()?; let wrapping_key = match kek.master_key_id { Some(id) if id != root_id => self.root_key_by_id(id).await?.unwrap_or(root_key), @@ -1722,7 +1750,7 @@ impl KeyManager { /// The configured master key (root key) with derived ID `id`: the current one or, for /// a KMS-wrapped master key, an earlier (rotated) version. - async fn root_key_by_id(&self, id: Uuid) -> Result>, EncryptionError> { + async fn root_key_by_id(&self, id: Uuid) -> Result, EncryptionError> { let (root_id, root_key) = self.root_key()?; if id == root_id { return Ok(Some(root_key)); @@ -1756,7 +1784,7 @@ impl KeyManager { Ok(retired.get(&id).cloned()) } - fn cache_key(&self, key_id: &str, key_material: Vec) { + fn cache_key(&self, key_id: &str, key_material: SecretBytes) { if let Ok(mut cache) = self.key_cache.lock() { cache.insert(key_id.to_string(), (key_material, Utc::now())); } @@ -1768,7 +1796,7 @@ impl KeyManager { cache .get(key_id) .filter(|(_, cached_at)| Utc::now() - *cached_at < Duration::hours(1)) - .map(|(key_material, _)| key_material.clone()) + .map(|(key_material, _)| key_material.to_vec()) } fn update_stats(&self, update: impl FnOnce(&mut KeyManagerStats)) { @@ -1858,12 +1886,12 @@ fn check_key_usable(key: &EncryptionKey) -> Result<(), EncryptionError> { Ok(()) } -fn random_key_material(algorithm: &EncryptionAlgorithm) -> Vec { +fn random_key_material(algorithm: &EncryptionAlgorithm) -> SecretBytes { let key_length = match algorithm { EncryptionAlgorithm::AES256GCM => 32, EncryptionAlgorithm::ChaCha20Poly1305 => 32, }; - let mut key_material = vec![0u8; key_length]; + let mut key_material = SecretBytes::new(vec![0u8; key_length]); OsRng.fill_bytes(&mut key_material); key_material } @@ -1897,7 +1925,10 @@ fn wrap_key_material(wrapping_key: &[u8], key_material: &[u8]) -> Result } /// Decrypt key material produced by [`wrap_key_material`]. -fn unwrap_key_material(wrapping_key: &[u8], encrypted: &[u8]) -> Result, EncryptionError> { +fn unwrap_key_material( + wrapping_key: &[u8], + encrypted: &[u8], +) -> Result { if encrypted.len() < 12 { return Err(EncryptionError::DecryptionFailed( "Encrypted key data too short".to_string(), @@ -1908,6 +1939,7 @@ fn unwrap_key_material(wrapping_key: &[u8], encrypted: &[u8]) -> Result, let (nonce, ciphertext) = encrypted.split_at(12); cipher .decrypt(Nonce::from_slice(nonce), ciphertext) + .map(SecretBytes::new) .map_err(|e| EncryptionError::DecryptionFailed(format!("Key decryption failed: {}", e))) } @@ -1950,23 +1982,25 @@ fn to_u32(value: i32, what: &str) -> Result { /// Load the master key material named by a [`KeySource`]. /// /// Fails closed: there is no fallback key when the source is unavailable. -async fn load_master_key_material(source: &KeySource) -> Result, EncryptionError> { +async fn load_master_key_material(source: &KeySource) -> Result { match source { KeySource::Environment(env_var) => { - let key_str = std::env::var(env_var).map_err(|_| { + let key_str = zeroize::Zeroizing::new(std::env::var(env_var).map_err(|_| { EncryptionError::KeyManagement(format!( "Master key environment variable {} not found", env_var )) - })?; + })?); base64::engine::general_purpose::STANDARD .decode(key_str.trim()) + .map(SecretBytes::new) .map_err(|e| { EncryptionError::KeyManagement(format!("Invalid base64 master key: {}", e)) }) } KeySource::Static(key_str) => base64::engine::general_purpose::STANDARD .decode(key_str) + .map(SecretBytes::new) .map_err(|e| { EncryptionError::KeyManagement(format!("Invalid base64 master key: {}", e)) }), @@ -2005,8 +2039,9 @@ async fn load_master_key_material(source: &KeySource) -> Result, Encrypt /// /// Format: `vault:///?addr=`. The address falls back to /// `VAULT_ADDR`; the token is read from `VAULT_TOKEN`. The secret must have a string `key` -/// field: a base64-encoded 32-byte key, or a passphrase that is hashed with SHA-256. -async fn load_master_key_from_vault(service_config: &str) -> Result, EncryptionError> { +/// field holding a base64-encoded 32-byte key; anything else (a passphrase, or key +/// material of another length) is an [`EncryptionError::InvalidConfiguration`]. +async fn load_master_key_from_vault(service_config: &str) -> Result { let (secret_path, params) = kms::parse_service_config(service_config, "vault://"); let vault_addr = kms::vault_address(¶ms)?; let (mount, secret) = kms::vault_mount_and_path(secret_path)?; @@ -2025,19 +2060,9 @@ async fn load_master_key_from_vault(service_config: &str) -> Result, Enc #[cfg(feature = "vault-kms")] { let key_str = kms::vault_read_key_field(&vault_addr, mount, secret).await?; - - if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(&key_str) - && decoded.len() == 32 - { - info!("Successfully loaded master key from HashiCorp Vault"); - return Ok(decoded); - } - - // Not a base64 32-byte key: treat it as a passphrase - use sha2::{Digest, Sha256}; - let hash = Sha256::digest(key_str.as_bytes()); - info!("Successfully loaded and hashed master key from HashiCorp Vault"); - Ok(hash.to_vec()) + let key = kms::exact_vault_key(&key_str, 32)?; + info!("Successfully loaded master key from HashiCorp Vault"); + Ok(key) } } @@ -2045,9 +2070,9 @@ async fn load_master_key_from_vault(service_config: &str) -> Result, Enc /// /// Format: `azure:///keys/` (key name defaults to `master-key`). /// Credentials are resolved from the environment (client secret, workload identity, -/// managed identity, Azure CLI). Key material shorter than 32 bytes is expanded with -/// HMAC-SHA256; longer material is truncated. -async fn load_master_key_from_azure(service_config: &str) -> Result, EncryptionError> { +/// managed identity, Azure CLI). The key material must be exactly 32 bytes; anything else +/// is an [`EncryptionError::InvalidConfiguration`]. +async fn load_master_key_from_azure(service_config: &str) -> Result { let (vault_url, key_name) = kms::azure_vault_and_key(service_config, "master-key")?; info!( @@ -2063,7 +2088,7 @@ async fn load_master_key_from_azure(service_config: &str) -> Result, Enc #[cfg(feature = "azure-kv")] { - let key_material = load_from_azure_key_vault(&vault_url, &key_name) + let key_material = super::azure::fetch_key_material(&vault_url, &key_name) .await .map_err(|e| { EncryptionError::KeyManagement(format!( @@ -2071,32 +2096,13 @@ async fn load_master_key_from_azure(service_config: &str) -> Result, Enc e )) })?; + let key = kms::exact_size( + key_material, + 32, + &format!("Azure Key Vault master key {} in {}", key_name, vault_url), + )?; info!("Successfully loaded master key from Azure Key Vault"); - Ok(key_material) - } -} - -/// Load key material from Azure Key Vault and normalize it to 32 bytes. -/// -/// Material of 32 bytes or more is truncated to 32 bytes; shorter material is used as the -/// HMAC-SHA256 key to derive 32 bytes. -#[cfg(feature = "azure-kv")] -async fn load_from_azure_key_vault(vault_url: &str, key_name: &str) -> Result, String> { - let decoded_key = super::azure::fetch_key_material(vault_url, key_name).await?; - - if decoded_key.len() >= 32 { - Ok(decoded_key[0..32].to_vec()) - } else { - use hmac::{Hmac, Mac}; - use sha2::Sha256; - - let mut hmac = as Mac>::new_from_slice(&decoded_key) - .map_err(|e| format!("Failed to create HMAC: {}", e))?; - hmac.update(b"azure-kv-master-key-derivation"); - hmac.update(vault_url.as_bytes()); - hmac.update(key_name.as_bytes()); - let result = hmac.finalize(); - Ok(result.into_bytes()[0..32].to_vec()) + Ok(key) } } @@ -4103,8 +4109,10 @@ mod tests { assert_eq!(wrapped.len(), 12 + 32 + 16); assert!(!wrapped.windows(32).any(|w| w == material)); assert_eq!( - unwrap_key_material(&wrapping_key, &wrapped).unwrap(), - material + unwrap_key_material(&wrapping_key, &wrapped) + .unwrap() + .as_slice(), + material.as_slice() ); assert!(unwrap_key_material(&[8u8; 32], &wrapped).is_err()); } diff --git a/src/encryption/kms.rs b/src/encryption/kms.rs index a99f540..0dc7911 100644 --- a/src/encryption/kms.rs +++ b/src/encryption/kms.rs @@ -87,13 +87,61 @@ pub(crate) fn vault_mount_and_path(secret_path: &str) -> Result<(&str, &str), En } } +/// The key in the `key` field of a Vault secret: base64 of exactly `expected_size` bytes. +/// +/// Anything else (a passphrase, or base64 of another length) is a configuration error. +/// Short material is never padded or hashed into a key: that would give a full-size key +/// with only the entropy of the input. +#[cfg_attr(not(feature = "vault-kms"), allow(dead_code))] +pub(crate) fn exact_vault_key( + key_str: &str, + expected_size: usize, +) -> Result { + use base64::Engine; + let decoded = super::SecretBytes::new( + base64::engine::general_purpose::STANDARD + .decode(key_str.trim()) + .map_err(|_| { + EncryptionError::InvalidConfiguration(format!( + "The Vault secret's `key` field is not base64; it must be a base64-encoded \ + {}-byte key (passphrases are not accepted)", + expected_size + )) + })?, + ); + exact_size(decoded, expected_size, "The Vault secret's `key` field") +} + +/// Key material of exactly `expected_size` bytes, or a configuration error naming `what`. +#[cfg_attr( + not(any(feature = "vault-kms", feature = "azure-kv")), + allow(dead_code) +)] +pub(crate) fn exact_size( + material: super::SecretBytes, + expected_size: usize, + what: &str, +) -> Result { + if material.len() == expected_size { + Ok(material) + } else { + Err(EncryptionError::InvalidConfiguration(format!( + "{} holds a {}-byte key, expected exactly {} bytes; key material of the wrong \ + size is rejected rather than padded or truncated", + what, + material.len(), + expected_size + ))) + } +} + /// Read the string `key` field of a KV v2 secret, authenticating with `VAULT_TOKEN`. #[cfg(feature = "vault-kms")] pub(crate) async fn vault_read_key_field( vault_addr: &str, mount: &str, path: &str, -) -> Result { +) -> Result, EncryptionError> { let token = std::env::var("VAULT_TOKEN") .ok() .filter(|token| !token.is_empty()) @@ -112,7 +160,7 @@ pub(crate) async fn vault_read_key_field_with_token( token: &str, mount: &str, path: &str, -) -> Result { +) -> Result, EncryptionError> { use vaultrs::{ client::{VaultClient, VaultClientSettingsBuilder}, kv2, @@ -146,7 +194,7 @@ pub(crate) async fn vault_read_key_field_with_token( secret .get("key") .and_then(|key| key.as_str()) - .map(str::to_string) + .map(|key| zeroize::Zeroizing::new(key.to_string())) .ok_or_else(|| { EncryptionError::KeyManagement(format!( "Vault secret {}/{} has no string `key` field", @@ -352,7 +400,7 @@ mod tests { let key = vault_read_key_field_with_token(&addr, "s.token", "secret", "hammerwork") .await .unwrap(); - assert_eq!(key, "c2VjcmV0"); + assert_eq!(key.as_str(), "c2VjcmV0"); assert_eq!(tokens.lock().unwrap().as_slice(), ["s.token"]); for (path, expected) in [ diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 062568e..8cf7193 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -1417,6 +1417,26 @@ impl JobQueue { self.encryption.engine.as_ref() } + /// Refuses to store a job unencrypted on a queue that already holds encrypted jobs. + /// + /// For tools that write jobs on behalf of an application and may not have its + /// encryption settings, such as `cargo hammerwork` and the web dashboard. Without + /// the guard, a handle without the application's engine or `encrypted_queues` + /// stores a job for such a queue in plaintext; with it, `enqueue`, + /// `enqueue_batch`, `enqueue_workflow` and `enqueue_cron_job` fail with + /// [`HammerworkError::Encryption`](crate::HammerworkError::Encryption) instead, and + /// nothing is written. Jobs this handle encrypts are not affected. + /// + /// The check looks for encrypted rows of the job's queue in `hammerwork_jobs`, so it + /// cannot protect a queue that has never held an encrypted job: configure the + /// encryption settings too (see + /// [`PayloadEncryptionConfig::load`](crate::config::PayloadEncryptionConfig::load)). + /// It costs one query per queue on each enqueue. Off by default. + pub fn with_plaintext_guard(mut self, enabled: bool) -> Self { + self.encryption.plaintext_guard = enabled; + self + } + /// Encrypts the payloads of `jobs` that have an encryption config, before they are /// written. Fails (and nothing should be written) if a job needs encryption the /// queue cannot provide. diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index a366dc7..58c76fc 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -560,91 +560,6 @@ impl JobRow { } } -#[derive(FromRow)] -pub(crate) struct DeadJobRow { - pub id: String, - pub queue_name: String, - pub payload: serde_json::Value, - pub status: String, - pub priority: i32, - pub attempts: i32, - pub max_attempts: i32, - pub timeout_seconds: Option, - pub created_at: DateTime, - pub scheduled_at: DateTime, - pub started_at: Option>, - pub completed_at: Option>, - pub failed_at: Option>, - pub timed_out_at: Option>, - pub error_message: Option, -} - -impl DeadJobRow { - pub fn into_job(self) -> Result { - Ok(Job { - id: uuid::Uuid::parse_str(&self.id)?, - queue_name: self.queue_name, - payload: self.payload, - status: { - // Handle both quoted (old format) and unquoted (new format) status values - let cleaned_str = self.status.trim_matches('"'); - match cleaned_str { - "Pending" => JobStatus::Pending, - "Running" => JobStatus::Running, - "Completed" => JobStatus::Completed, - "Failed" => JobStatus::Failed, - "Dead" => JobStatus::Dead, - "TimedOut" => JobStatus::TimedOut, - "Retrying" => JobStatus::Retrying, - "Archived" => JobStatus::Archived, - _ => JobStatus::Dead, // Default fallback for unknown status - } - }, - priority: JobPriority::from_i32(self.priority).unwrap_or(JobPriority::Normal), - attempts: self.attempts, - max_attempts: self.max_attempts, - created_at: self.created_at, - scheduled_at: self.scheduled_at, - started_at: self.started_at, - completed_at: self.completed_at, - failed_at: self.failed_at, - timed_out_at: self.timed_out_at, - timeout: self - .timeout_seconds - .map(|s| super::db_seconds(s, "timeout_seconds")) - .transpose()?, - error_message: self.error_message, - cron_schedule: None, - next_run_at: None, - recurring: false, - timezone: None, - batch_id: None, - result_config: crate::job::ResultConfig::default(), - result_data: None, - result_stored_at: None, - result_expires_at: None, - retry_strategy: None, - depends_on: Vec::new(), - dependents: Vec::new(), - dependency_status: crate::workflow::DependencyStatus::None, - workflow_id: None, - workflow_name: None, - trace_id: None, - correlation_id: None, - parent_span_id: None, - span_context: None, - #[cfg(feature = "encryption")] - encryption_config: None, - pii_fields: Vec::new(), - #[cfg(feature = "encryption")] - retention_policy: None, - is_encrypted: false, - #[cfg(feature = "encryption")] - encrypted_payload: None, - }) - } -} - /// Number of attempts for a job claim that keeps hitting InnoDB deadlocks. const CLAIM_DEADLOCK_ATTEMPTS: u32 = 5; @@ -803,12 +718,36 @@ impl crate::queue::JobQueue { } } +impl crate::queue::JobQueue { + /// Seals `jobs` for storage ([`JobQueue::seal_jobs`](super::JobQueue)), then applies + /// the plaintext guard ([`JobQueue::with_plaintext_guard`](super::JobQueue)). + async fn seal_for_insert(&self, jobs: &mut [Job]) -> Result<()> { + self.seal_jobs(jobs).await?; + for queue_name in self.encryption.guarded_queues(jobs) { + let holds_encrypted_jobs = sqlx::query( + "SELECT 1 FROM hammerwork_jobs WHERE queue_name = ? AND is_encrypted = TRUE \ + LIMIT 1", + ) + .bind(&queue_name) + .fetch_optional(&self.pool) + .await? + .is_some(); + if holds_encrypted_jobs { + return Err( + super::payload_encryption::PayloadEncryption::plaintext_refused(&queue_name), + ); + } + } + Ok(()) + } +} + #[async_trait] impl DatabaseQueue for crate::queue::JobQueue { type Database = MySql; async fn enqueue(&self, mut job: Job) -> Result { - self.seal_jobs(std::slice::from_mut(&mut job)).await?; + self.seal_for_insert(std::slice::from_mut(&mut job)).await?; if job.depends_on.is_empty() { let mut conn = self.pool.acquire().await?; insert_jobs(&mut conn, std::slice::from_ref(&job)).await?; @@ -933,7 +872,7 @@ impl DatabaseQueue for crate::queue::JobQueue { job }) .collect(); - self.seal_jobs(&mut jobs).await?; + self.seal_for_insert(&mut jobs).await?; let mut tx = self.pool.begin().await?; @@ -1094,9 +1033,9 @@ impl DatabaseQueue for crate::queue::JobQueue { let limit = limit.unwrap_or(100) as i64; let offset = offset.unwrap_or(0) as i64; - let rows = sqlx::query_as::<_, DeadJobRow>( - "SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message FROM hammerwork_jobs WHERE status = ? ORDER BY failed_at DESC LIMIT ? OFFSET ?" - ) + let rows = sqlx::query_as::<_, JobRow>(&format!( + "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE status = ? ORDER BY failed_at DESC LIMIT ? OFFSET ?" + )) .bind(JobStatus::Dead) .bind(limit) .bind(offset) @@ -1117,9 +1056,9 @@ impl DatabaseQueue for crate::queue::JobQueue { let limit = limit.unwrap_or(100) as i64; let offset = offset.unwrap_or(0) as i64; - let rows = sqlx::query_as::<_, DeadJobRow>( - "SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message FROM hammerwork_jobs WHERE status = ? AND queue_name = ? ORDER BY failed_at DESC LIMIT ? OFFSET ?" - ) + let rows = sqlx::query_as::<_, JobRow>(&format!( + "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE status = ? AND queue_name = ? ORDER BY failed_at DESC LIMIT ? OFFSET ?" + )) .bind(JobStatus::Dead) .bind(queue_name) .bind(limit) @@ -1668,7 +1607,7 @@ impl DatabaseQueue for crate::queue::JobQueue { workflow.validate()?; let mut jobs = workflow.jobs.clone(); - self.seal_jobs(&mut jobs).await?; + self.seal_for_insert(&mut jobs).await?; let mut tx = self.pool.begin().await?; diff --git a/src/queue/payload_encryption.rs b/src/queue/payload_encryption.rs index 32e2405..60dbfe1 100644 --- a/src/queue/payload_encryption.rs +++ b/src/queue/payload_encryption.rs @@ -16,6 +16,9 @@ pub(crate) struct PayloadEncryption { /// Queues whose jobs are encrypted even without an encryption config (`"*"`: all) #[cfg(feature = "encryption")] pub(crate) encrypted_queues: Vec, + /// Refuse to store plaintext jobs on queues that hold encrypted jobs (see + /// `JobQueue::with_plaintext_guard`) + pub(crate) plaintext_guard: bool, } impl std::fmt::Debug for PayloadEncryption { @@ -24,11 +27,43 @@ impl std::fmt::Debug for PayloadEncryption { #[cfg(feature = "encryption")] s.field("engine", &self.engine) .field("encrypted_queues", &self.encrypted_queues); + s.field("plaintext_guard", &self.plaintext_guard); s.finish() } } impl PayloadEncryption { + /// The queues the plaintext guard must check before `jobs` (already sealed) are + /// stored: the distinct queues of the jobs that stay unencrypted. Empty when the + /// guard is off. + #[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] + pub(crate) fn guarded_queues(&self, jobs: &[Job]) -> Vec { + if !self.plaintext_guard { + return Vec::new(); + } + let mut queues: Vec = jobs + .iter() + .filter(|job| !job.is_encrypted) + .map(|job| job.queue_name.clone()) + .collect(); + queues.sort(); + queues.dedup(); + queues + } + + /// The error for a plaintext job refused by the plaintext guard. + #[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] + pub(crate) fn plaintext_refused(queue_name: &str) -> HammerworkError { + HammerworkError::Encryption { + message: format!( + "Queue '{}' holds encrypted jobs, but this queue handle would store the new \ + job in plaintext; refusing. Give it the application's encryption settings \ + (the [encryption] section and its key), or encrypt the job explicitly", + queue_name + ), + } + } + /// Whether jobs on `queue_name` are encrypted without an encryption config. #[cfg(feature = "encryption")] fn encrypts_queue(&self, queue_name: &str) -> bool { @@ -137,3 +172,39 @@ fn has_ciphertext(#[allow(unused_variables)] job: &Job) -> bool { false } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn plaintext_guard_checks_each_unencrypted_queue_once() { + let mut sealed = Job::new("payments".into(), json!({})); + sealed.is_encrypted = true; + let jobs = vec![ + Job::new("emails".into(), json!({})), + Job::new("emails".into(), json!({})), + Job::new("audit".into(), json!({})), + sealed, + ]; + assert!( + PayloadEncryption::default() + .guarded_queues(&jobs) + .is_empty() + ); + // Without the `encryption` feature `plaintext_guard` is the only field. + #[allow(clippy::needless_update)] + let guard = PayloadEncryption { + plaintext_guard: true, + ..Default::default() + }; + assert_eq!(guard.guarded_queues(&jobs), vec!["audit", "emails"]); + let message = PayloadEncryption::plaintext_refused("payments").to_string(); + assert!( + message.contains("'payments' holds encrypted jobs"), + "{message}" + ); + assert!(format!("{guard:?}").contains("plaintext_guard: true")); + } +} diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 1fe7fe5..4f1300f 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -545,88 +545,27 @@ impl JobRow { } } -#[derive(FromRow)] -pub(crate) struct DeadJobRow { - pub id: uuid::Uuid, - pub queue_name: String, - pub payload: serde_json::Value, - pub status: String, - pub priority: i32, - pub attempts: i32, - pub max_attempts: i32, - pub timeout_seconds: Option, - pub created_at: DateTime, - pub scheduled_at: DateTime, - pub started_at: Option>, - pub completed_at: Option>, - pub failed_at: Option>, - pub timed_out_at: Option>, - pub error_message: Option, -} - -impl DeadJobRow { - pub fn into_job(self) -> Result { - Ok(Job { - id: self.id, - queue_name: self.queue_name, - payload: self.payload, - status: { - // Handle both quoted (old format) and unquoted (new format) status values - let cleaned_str = self.status.trim_matches('"'); - match cleaned_str { - "Pending" => JobStatus::Pending, - "Running" => JobStatus::Running, - "Completed" => JobStatus::Completed, - "Failed" => JobStatus::Failed, - "Dead" => JobStatus::Dead, - "TimedOut" => JobStatus::TimedOut, - "Retrying" => JobStatus::Retrying, - "Archived" => JobStatus::Archived, - _ => JobStatus::Dead, // Default fallback for unknown status - } - }, - priority: JobPriority::from_i32(self.priority).unwrap_or(JobPriority::Normal), - attempts: self.attempts, - max_attempts: self.max_attempts, - created_at: self.created_at, - scheduled_at: self.scheduled_at, - started_at: self.started_at, - completed_at: self.completed_at, - failed_at: self.failed_at, - timed_out_at: self.timed_out_at, - timeout: self - .timeout_seconds - .map(|s| super::db_seconds(s, "timeout_seconds")) - .transpose()?, - error_message: self.error_message, - cron_schedule: None, - next_run_at: None, - recurring: false, - timezone: None, - batch_id: None, // DeadJobRow doesn't track batch_id - result_config: crate::job::ResultConfig::default(), - result_data: None, - result_stored_at: None, - result_expires_at: None, - retry_strategy: None, - depends_on: Vec::new(), - dependents: Vec::new(), - dependency_status: crate::workflow::DependencyStatus::None, - workflow_id: None, - workflow_name: None, - trace_id: None, - correlation_id: None, - parent_span_id: None, - span_context: None, - #[cfg(feature = "encryption")] - encryption_config: None, - pii_fields: Vec::new(), - #[cfg(feature = "encryption")] - retention_policy: None, - is_encrypted: false, - #[cfg(feature = "encryption")] - encrypted_payload: None, - }) +impl crate::queue::JobQueue { + /// Seals `jobs` for storage ([`JobQueue::seal_jobs`](super::JobQueue)), then applies + /// the plaintext guard ([`JobQueue::with_plaintext_guard`](super::JobQueue)). + async fn seal_for_insert(&self, jobs: &mut [Job]) -> Result<()> { + self.seal_jobs(jobs).await?; + for queue_name in self.encryption.guarded_queues(jobs) { + let holds_encrypted_jobs = sqlx::query( + "SELECT 1 FROM hammerwork_jobs WHERE queue_name = $1 AND is_encrypted = TRUE \ + LIMIT 1", + ) + .bind(&queue_name) + .fetch_optional(&self.pool) + .await? + .is_some(); + if holds_encrypted_jobs { + return Err( + super::payload_encryption::PayloadEncryption::plaintext_refused(&queue_name), + ); + } + } + Ok(()) } } @@ -635,7 +574,7 @@ impl DatabaseQueue for crate::queue::JobQueue { type Database = Postgres; async fn enqueue(&self, mut job: Job) -> Result { - self.seal_jobs(std::slice::from_mut(&mut job)).await?; + self.seal_for_insert(std::slice::from_mut(&mut job)).await?; if job.depends_on.is_empty() { let mut conn = self.pool.acquire().await?; insert_jobs(&mut conn, std::slice::from_ref(&job)).await?; @@ -794,7 +733,7 @@ impl DatabaseQueue for crate::queue::JobQueue { job }) .collect(); - self.seal_jobs(&mut jobs).await?; + self.seal_for_insert(&mut jobs).await?; let mut tx = self.pool.begin().await?; @@ -949,9 +888,9 @@ impl DatabaseQueue for crate::queue::JobQueue { let limit = limit.unwrap_or(100) as i64; let offset = offset.unwrap_or(0) as i64; - let rows = sqlx::query_as::<_, DeadJobRow>( - "SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message FROM hammerwork_jobs WHERE status = $1 ORDER BY failed_at DESC LIMIT $2 OFFSET $3" - ) + let rows = sqlx::query_as::<_, JobRow>(&format!( + "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE status = $1 ORDER BY failed_at DESC LIMIT $2 OFFSET $3" + )) .bind(JobStatus::Dead) .bind(limit) .bind(offset) @@ -970,9 +909,9 @@ impl DatabaseQueue for crate::queue::JobQueue { let limit = limit.unwrap_or(100) as i64; let offset = offset.unwrap_or(0) as i64; - let rows = sqlx::query_as::<_, DeadJobRow>( - "SELECT id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message FROM hammerwork_jobs WHERE status = $1 AND queue_name = $2 ORDER BY failed_at DESC LIMIT $3 OFFSET $4" - ) + let rows = sqlx::query_as::<_, JobRow>(&format!( + "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE status = $1 AND queue_name = $2 ORDER BY failed_at DESC LIMIT $3 OFFSET $4" + )) .bind(JobStatus::Dead) .bind(queue_name) .bind(limit) @@ -1528,7 +1467,7 @@ impl DatabaseQueue for crate::queue::JobQueue { workflow.validate()?; let mut jobs = workflow.jobs.clone(); - self.seal_jobs(&mut jobs).await?; + self.seal_for_insert(&mut jobs).await?; let mut tx = self.pool.begin().await?; diff --git a/src/queue/test.rs b/src/queue/test.rs index f9997fe..00cafc2 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -3367,6 +3367,36 @@ mod tests { ); } + /// Every read path returns an encrypted job with its ciphertext and PII fields, so + /// `decrypt_job` works on it (#64 H2). + #[tokio::test] + async fn dead_and_listed_jobs_keep_their_ciphertext() { + let queue = encrypted_queue().await; + let payload = json!({"ssn": "123-45-6789", "amount": 5}); + let id = queue + .enqueue( + Job::new("dlq".into(), payload.clone()) + .with_encryption(config()) + .with_pii_fields(vec!["ssn"]), + ) + .await + .unwrap(); + queue.mark_job_dead(id, "boom").await.unwrap(); + + let dead = queue.get_dead_jobs(None, None).await.unwrap(); + let by_queue = queue + .get_dead_jobs_by_queue("dlq", None, None) + .await + .unwrap(); + for job in dead.into_iter().chain(by_queue) { + assert_eq!(job.id, id); + assert!(job.is_encrypted); + assert!(job.encrypted_payload.is_some()); + assert_eq!(job.pii_fields, vec!["ssn"]); + assert_eq!(queue.decrypt_job(job).await.unwrap().payload, payload); + } + } + #[tokio::test] async fn retention_purge_uses_the_mock_clock() { let queue = encrypted_queue().await; diff --git a/src/streaming.rs b/src/streaming.rs index c6b74bf..e5747fd 100644 --- a/src/streaming.rs +++ b/src/streaming.rs @@ -320,7 +320,10 @@ pub struct StreamConfig { /// config: HashMap::new(), /// }; /// ``` -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` never shows credentials (`secret_access_key`, `service_account_key`) or the +/// values of the `config` maps (they may hold SASL passwords), only their keys. +#[derive(Clone, Serialize, Deserialize)] #[serde(tag = "type")] pub enum StreamBackend { /// Apache Kafka backend @@ -358,6 +361,55 @@ pub enum StreamBackend { }, } +impl std::fmt::Debug for StreamBackend { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn keys(map: &HashMap) -> Vec<&String> { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + keys + } + let redacted = |secret: &Option| secret.as_ref().map(|_| "[REDACTED]"); + match self { + StreamBackend::Kafka { + brokers, + topic, + config, + } => f + .debug_struct("Kafka") + .field("brokers", brokers) + .field("topic", topic) + .field("config", &keys(config)) + .finish(), + StreamBackend::Kinesis { + region, + stream_name, + access_key_id, + secret_access_key, + config, + } => f + .debug_struct("Kinesis") + .field("region", region) + .field("stream_name", stream_name) + .field("access_key_id", access_key_id) + .field("secret_access_key", &redacted(secret_access_key)) + .field("config", &keys(config)) + .finish(), + StreamBackend::PubSub { + project_id, + topic_name, + service_account_key, + config, + } => f + .debug_struct("PubSub") + .field("project_id", project_id) + .field("topic_name", topic_name) + .field("service_account_key", &redacted(service_account_key)) + .field("config", &keys(config)) + .finish(), + } + } +} + /// Partitioning strategies for distributing events across stream partitions. /// /// Partitioning strategies determine how events are distributed across partitions @@ -3010,6 +3062,35 @@ mod tests { use super::*; use crate::{events::JobLifecycleEventType, priority::JobPriority}; + #[test] + fn test_stream_backend_debug_hides_credentials() { + let config = HashMap::from([("sasl.password".to_string(), "hunter2-sasl".to_string())]); + for backend in [ + StreamBackend::Kafka { + brokers: vec!["kafka:9092".to_string()], + topic: "events".to_string(), + config: config.clone(), + }, + StreamBackend::Kinesis { + region: "us-east-1".to_string(), + stream_name: "events".to_string(), + access_key_id: Some("AKIDEXAMPLE".to_string()), + secret_access_key: Some("hunter2-aws".to_string()), + config: config.clone(), + }, + StreamBackend::PubSub { + project_id: "project".to_string(), + topic_name: "events".to_string(), + service_account_key: Some("hunter2-gcp".to_string()), + config: config.clone(), + }, + ] { + let debug = format!("{backend:?}"); + assert!(!debug.contains("hunter2"), "{debug}"); + assert!(debug.contains("sasl.password"), "{debug}"); + } + } + #[test] fn test_clamp_processor_permits() { assert_eq!(clamp_processor_permits(0), 1); diff --git a/src/webhooks.rs b/src/webhooks.rs index 76f495d..a29002e 100644 --- a/src/webhooks.rs +++ b/src/webhooks.rs @@ -168,7 +168,10 @@ mod uuid_string { /// .with_secret("hmac-signing-secret".to_string()) /// .with_timeout_secs(15); /// ``` -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` never shows the signing secret, header values, credentials, or the path of +/// the URL (webhook URLs of chat services are themselves credentials). +#[derive(Clone, Serialize, Deserialize)] pub struct WebhookConfig { /// Unique identifier for this webhook #[serde(with = "uuid_string")] @@ -220,6 +223,27 @@ impl Default for WebhookConfig { } } +impl std::fmt::Debug for WebhookConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut header_names: Vec<&String> = self.headers.keys().collect(); + header_names.sort(); + f.debug_struct("WebhookConfig") + .field("id", &self.id) + .field("name", &self.name) + .field("url", &crate::config::redact_url_path(&self.url)) + .field("method", &self.method) + .field("headers", &header_names) + .field("filter", &self.filter) + .field("retry_policy", &self.retry_policy) + .field("auth", &self.auth) + .field("timeout_secs", &self.timeout_secs) + .field("enabled", &self.enabled) + .field("secret", &self.secret.as_ref().map(|_| "[REDACTED]")) + .field("payload_template", &self.payload_template) + .finish() + } +} + /// HTTP methods supported for webhooks #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] @@ -240,7 +264,10 @@ impl std::fmt::Display for HttpMethod { } /// Authentication methods for webhooks -#[derive(Debug, Clone, Serialize, Deserialize)] +/// +/// `Debug` shows the kind of authentication and header names, never tokens, passwords, +/// API keys or header values. +#[derive(Clone, Serialize, Deserialize)] #[serde(tag = "type")] pub enum WebhookAuth { /// Bearer token authentication @@ -256,6 +283,32 @@ pub enum WebhookAuth { Custom { headers: HashMap }, } +impl std::fmt::Debug for WebhookAuth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + const REDACTED: &str = "[REDACTED]"; + match self { + WebhookAuth::Bearer { .. } => { + f.debug_struct("Bearer").field("token", &REDACTED).finish() + } + WebhookAuth::Basic { username, .. } => f + .debug_struct("Basic") + .field("username", username) + .field("password", &REDACTED) + .finish(), + WebhookAuth::ApiKey { header_name, .. } => f + .debug_struct("ApiKey") + .field("header_name", header_name) + .field("api_key", &REDACTED) + .finish(), + WebhookAuth::Custom { headers } => { + let mut names: Vec<&String> = headers.keys().collect(); + names.sort(); + f.debug_struct("Custom").field("headers", &names).finish() + } + } + } +} + /// Retry policy configuration #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RetryPolicy { @@ -632,7 +685,12 @@ impl WebhookManager { self.start_webhook_delivery_task(webhook_id).await; if self.config.log_deliveries { - tracing::info!("Added webhook: {} -> {}", webhook.name, webhook.url); + // The URL path of chat webhooks (Slack, Discord, Teams) is a credential. + tracing::info!( + "Added webhook: {} -> {}", + webhook.name, + crate::config::redact_url_path(&webhook.url) + ); } Ok(()) @@ -1550,6 +1608,40 @@ fn truncate_response_body(body: String, max_bytes: usize) -> String { mod tests { use super::*; + #[test] + fn test_debug_does_not_print_webhook_secrets() { + let mut config = WebhookConfig::new( + "chat".to_string(), + "https://hooks.slack.com/services/T0/B0/url-hunter2".to_string(), + ) + .with_secret("sign-hunter2".to_string()); + config + .headers + .insert("X-Api-Token".to_string(), "header-hunter2".to_string()); + for auth in [ + WebhookAuth::Bearer { + token: "bearer-hunter2".to_string(), + }, + WebhookAuth::Basic { + username: "svc".to_string(), + password: "basic-hunter2".to_string(), + }, + WebhookAuth::ApiKey { + header_name: "X-Key".to_string(), + api_key: "api-hunter2".to_string(), + }, + WebhookAuth::Custom { + headers: HashMap::from([("X-Custom".to_string(), "custom-hunter2".to_string())]), + }, + ] { + config.auth = Some(auth); + let debug = format!("{:?}", config); + assert!(!debug.contains("hunter2"), "{debug}"); + assert!(debug.contains("https://hooks.slack.com/***"), "{debug}"); + assert!(debug.contains("X-Api-Token"), "{debug}"); + } + } + #[tokio::test] async fn test_webhook_manager_from_config() { let mut config = crate::config::WebhookConfigs::default(); diff --git a/tests/payload_encryption_tests.rs b/tests/payload_encryption_tests.rs index ad17d5a..9e12d90 100644 --- a/tests/payload_encryption_tests.rs +++ b/tests/payload_encryption_tests.rs @@ -497,6 +497,195 @@ where queue.delete_job(job_id).await.unwrap(); } +/// `job` decrypts back to `payload` with `queue`'s engine. `path` names the read path. +async fn assert_decrypts(queue: &JobQueue, job: Job, payload: &Value, path: &str) +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + assert!(job.is_encrypted, "{path}: is_encrypted"); + assert!(job.encrypted_payload.is_some(), "{path}: ciphertext"); + assert_eq!(job.pii_fields, vec!["ssn"], "{path}: PII fields"); + assert_eq!(job.payload["ssn"], "[ENCRYPTED]", "{path}: stored form"); + let opened = queue + .decrypt_job(job) + .await + .unwrap_or_else(|e| panic!("{path}: {e}")); + assert_eq!(&opened.payload, payload, "{path}"); +} + +/// The job `id` in `jobs`, which a read path named `path` returned. +fn find_job(jobs: Vec, id: JobId, path: &str) -> Job { + jobs.into_iter() + .find(|job| job.id == id) + .unwrap_or_else(|| panic!("{path} does not list job {id}")) +} + +/// Every read path returns an encrypted job with its ciphertext, key id and PII fields, +/// so `decrypt_job` works on it. The dead-letter listings used to drop them and return +/// the redacted payload labelled as plaintext (#64 H2). +async fn every_read_path_keeps_the_ciphertext(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_reads"); + let payload = json!({"ssn": secret("ssn"), "amount": 7}); + let job = || { + Job::new(queue_name.clone(), payload.clone()) + .with_encryption(config("k1")) + .with_pii_fields(vec!["ssn"]) + .with_retention_policy(long_retention()) + }; + + // Dead letter queue + let dead = queue.enqueue(job()).await.unwrap(); + queue.mark_job_dead(dead, "boom").await.unwrap(); + let path = "get_dead_jobs"; + let listed = queue.get_dead_jobs(Some(100_000), None).await.unwrap(); + assert_decrypts(&queue, find_job(listed, dead, path), &payload, path).await; + let path = "get_dead_jobs_by_queue"; + let listed = queue + .get_dead_jobs_by_queue(&queue_name, None, None) + .await + .unwrap(); + assert_decrypts(&queue, find_job(listed, dead, path), &payload, path).await; + queue.delete_job(dead).await.unwrap(); + + // Pending and completed jobs + let pending = queue.enqueue(job()).await.unwrap(); + let got = queue.get_job(pending).await.unwrap().unwrap(); + assert_decrypts(&queue, got, &payload, "get_job").await; + let path = "get_ready_jobs"; + let ready = queue.get_ready_jobs(&queue_name, 100).await.unwrap(); + assert_decrypts(&queue, find_job(ready, pending, path), &payload, path).await; + queue.complete_job(pending).await.unwrap(); + let now = Utc::now(); + let path = "get_jobs_completed_in_range"; + let completed = queue + .get_jobs_completed_in_range( + Some(&queue_name), + now - chrono::Duration::hours(1), + now + chrono::Duration::hours(1), + None, + ) + .await + .unwrap(); + assert_decrypts(&queue, find_job(completed, pending, path), &payload, path).await; + queue.delete_job(pending).await.unwrap(); + + // Batches, workflows and recurring jobs + let batch_id = queue + .enqueue_batch(JobBatch::new("reads").with_jobs(vec![job()])) + .await + .unwrap(); + let batch = queue.get_batch_jobs(batch_id).await.unwrap(); + assert_eq!(batch.len(), 1); + for listed in batch { + assert_decrypts(&queue, listed, &payload, "get_batch_jobs").await; + } + queue.delete_batch(batch_id).await.unwrap(); + + let workflow_job = job(); + let workflow_job_id = workflow_job.id; + let workflow_id = queue + .enqueue_workflow(JobGroup::new("reads").add_job(workflow_job)) + .await + .unwrap(); + let path = "get_workflow_jobs"; + let listed = queue.get_workflow_jobs(workflow_id).await.unwrap(); + assert_decrypts( + &queue, + find_job(listed, workflow_job_id, path), + &payload, + path, + ) + .await; + queue.delete_job(workflow_job_id).await.unwrap(); + + let cron = job() + .with_cron(hammerwork::cron::CronSchedule::new("0 0 0 1 1 *").unwrap()) + .unwrap(); + let cron_id = queue.enqueue_cron_job(cron).await.unwrap(); + let path = "get_recurring_jobs"; + let listed = queue.get_recurring_jobs(&queue_name).await.unwrap(); + assert_decrypts(&queue, find_job(listed, cron_id, path), &payload, path).await; + queue.delete_job(cron_id).await.unwrap(); +} + +/// A queue handle with the plaintext guard (the CLI's and dashboard's) refuses to store +/// a plaintext job on a queue that holds encrypted jobs, and still stores jobs it +/// encrypts (#64 H1). +async fn plaintext_guard_refuses_plaintext_on_encrypted_queues(plain: Arc>) +where + DB: Inspect + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let app = encrypted_queue(&plain, engine("k1", KEY_A).await).await; + let encrypted_queue_name = test_utils::unique_queue("enc_guard"); + let other_queue_name = test_utils::unique_queue("plain_guard"); + let card = secret("card"); + let encrypted = app + .enqueue( + Job::new(encrypted_queue_name.clone(), json!({"card": card})) + .with_encryption(config("k1")) + .with_retention_policy(long_retention()), + ) + .await + .unwrap(); + + // A tool without the application's encryption settings + let tool = JobQueue::new(plain.pool.clone()).with_plaintext_guard(true); + let refused = Job::new(encrypted_queue_name.clone(), json!({"card": card})); + let refused_id = refused.id; + let err = tool.enqueue(refused).await.unwrap_err(); + assert!(matches!(err, HammerworkError::Encryption { .. }), "{err:?}"); + assert!(err.to_string().contains(&encrypted_queue_name), "{err}"); + assert!( + tool.get_job(refused_id).await.unwrap().is_none(), + "nothing written" + ); + let batch = JobBatch::new("guarded").with_jobs(vec![Job::new( + encrypted_queue_name.clone(), + json!({"n": 1}), + )]); + assert!(tool.enqueue_batch(batch).await.is_err()); + let workflow = + JobGroup::new("guarded").add_job(Job::new(encrypted_queue_name.clone(), json!({"n": 2}))); + assert!(tool.enqueue_workflow(workflow).await.is_err()); + let cron = Job::new(encrypted_queue_name.clone(), json!({"n": 3})) + .with_cron(hammerwork::cron::CronSchedule::new("0 0 0 1 1 *").unwrap()) + .unwrap(); + assert!(tool.enqueue_cron_job(cron).await.is_err()); + + // Queues without encrypted jobs are unaffected + let fine = tool + .enqueue(Job::new(other_queue_name.clone(), json!({"n": 4}))) + .await + .unwrap(); + tool.delete_job(fine).await.unwrap(); + + // With the application's engine and encrypted queues, its jobs pass the guard + let tool = JobQueue::new(plain.pool.clone()) + .with_encryption(engine("k1", KEY_A).await) + .with_encrypted_queues([encrypted_queue_name.clone()]) + .with_plaintext_guard(true); + let sealed = tool + .enqueue( + Job::new(encrypted_queue_name.clone(), json!({"card": card})) + .with_retention_policy(long_retention()), + ) + .await + .unwrap(); + assert_row_has_no_plaintext(&tool.pool, "hammerwork_jobs", sealed, &card).await; + assert!(tool.get_job(sealed).await.unwrap().unwrap().is_encrypted); + + for id in [encrypted, sealed] { + app.delete_job(id).await.unwrap(); + } +} + /// A queue without an encryption engine refuses jobs that ask for encryption, and /// writes nothing. async fn missing_engine_fails_closed(plain: Arc>) @@ -1168,6 +1357,21 @@ mod postgres { pii_fields_round_trip(test_utils::setup_postgres_queue().await).await; } + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_every_read_path_keeps_the_ciphertext() { + every_read_path_keeps_the_ciphertext(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_plaintext_guard_refuses_plaintext_on_encrypted_queues() { + plaintext_guard_refuses_plaintext_on_encrypted_queues( + test_utils::setup_postgres_queue().await, + ) + .await; + } + #[tokio::test] #[ignore] // Requires database connection async fn test_postgres_batch_and_workflow_are_encrypted() { @@ -1264,6 +1468,21 @@ mod mysql { pii_fields_round_trip(test_utils::setup_mysql_queue().await).await; } + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_every_read_path_keeps_the_ciphertext() { + every_read_path_keeps_the_ciphertext(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_plaintext_guard_refuses_plaintext_on_encrypted_queues() { + plaintext_guard_refuses_plaintext_on_encrypted_queues( + test_utils::setup_mysql_queue().await, + ) + .await; + } + #[tokio::test] #[ignore] // Requires database connection async fn test_mysql_batch_and_workflow_are_encrypted() {