Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 <path>` / `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:<hex>`) 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.
Expand Down
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ hex = "0.4"
aes-gcm = "0.10"
chacha20poly1305 = "0.10"
argon2 = "0.5"
zeroize = "1.8"

[package]
name = "hammerwork"
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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"]
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
11 changes: 10 additions & 1 deletion cargo-hammerwork/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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"
Expand Down
50 changes: 43 additions & 7 deletions cargo-hammerwork/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <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

Expand All @@ -141,6 +163,7 @@ cargo hammerwork job show <job-id> # 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 <job-id> # Retry one job (--job-id also works)
cargo hammerwork job retry --queue emails # Retry every failed job in a queue
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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`)

Expand All @@ -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
Expand Down
Loading
Loading