Repository navigation
Description
Final adversarial production-readiness review of origin/master @ ab31df8, for #7. Open PRs #59 (TestQueue fail_job / workflow failure policies) and #63 (CLI flags / connect timeout) were out of scope.
Line numbers refer to ab31df8. "Verified" means one of:
- I traced the code path end to end;
- I reproduced it against local PostgreSQL 16 / MySQL 8 scratch databases;
- I grepped to confirm that nothing reads a value.
There are findings above MEDIUM: 3 CRITICAL and 16 HIGH.
CRITICAL
C1. The stale-job reaper reclaims jobs that are still running, so they execute twice
- Where:
- The claim never writes a lease:
src/queue/postgres.rs:2413-2427(claim_sql) andsrc/queue/mysql.rs:747-756. - The first heartbeat only comes after
lease/3:src/worker.rs:2480-2499. - Until then the reaper falls back to
started_at < now - older_than:src/queue/postgres.rs:2215-2228andsrc/queue/mysql.rs:2344-2354. requeue_stale_jobscovers all queues, but each pool derivesolder_thanfrom its own workers' leases:src/worker.rs:3173-3180.
- The claim never writes a lease:
- Scenario A (two pools): service A's workers use
with_lease_duration(1h), so their first heartbeat comes at 20 min. Service B runs a defaultWorkerPool, whose reaper usesolder_than= 5 min. Five minutes into one of A's jobs, B's reaper moves it back toPending, and another A worker runs it concurrently. - Scenario B (CLI):
job requeue-stale --older-than-secs N, with N below the workers'lease/3, does the same thing. - Scenario C (lease 0): a worker with
with_lease_duration(Duration::ZERO)never heartbeats (worker.rs:2481), so any job of it that runs longer than the pool's fallback (5 min by default) is re-run. - Docs contradicted:
worker.rs:2898says "Running reapers in several pools or processes at once is safe". The CLI help says the same. - Related (MEDIUM):
heartbeat_jobmatches only onid AND status = 'Running'(postgres.rs:2122-2135), not on the run. After a reclaim and re-claim, the stale worker's heartbeat still returnstrueand keeps extending the new run's lease. That contradicts the trait doc (queue/mod.rs:765), which says it returnsfalseonce the lease is lost. - Verified: on PostgreSQL
hw_reviewI inserted a job, claimed it with the exactclaim_sqlstatement (lease_expires_atstayed NULL), waited 3 s and rancargo hammerwork job requeue-stale --older-than-secs 2. The job, still held by its "worker", went back toPendingwith "Job lease expired while Running; the worker is presumed dead". - Fix:
- Write
lease_expires_at = now() + lease(andlast_heartbeat_at) in the claim statement, passing the lease into dequeue. The reaper can then rely only on leases, witholder_thankept just for rows claimed by pre-015 code. - Treat lease 0 as "never reap", or reject it.
- Scope
heartbeat_jobto the run (attemptsandstarted_at).
- Write
C2. Spawned child jobs are lost when spawning fails after the parent completes
-
Where:
src/worker.rs:2138commits the parent asCompleted.- Only afterwards does
:2164callSpawnManager::execute_spawn. - That enqueues the children one at a time, outside any transaction (
src/spawn.rs:420-471).
-
Scenario: any of the following leaves the parent
Completed, never retried, with zero or only some of its children:- a transient DB error on the third child enqueue;
- a
spawn_jobshandler error; SpawnLimitExceeded;- a crash or SIGTERM between the commit and the loop;
- the shutdown grace period expiring mid-loop.
The only trace is a
warn!("Failed to spawn child jobs"). -
Verified: I read the code path end to end.
-
Fix: do both.
- Enqueue the children in the same transaction that completes the parent, or before completing it with deterministic child IDs so a retry is idempotent.
- Make a spawn failure a run failure, so the parent retries.
C3. CLI backup create / backup restore destroys encrypted payloads and most job attributes
- Where:
cargo-hammerwork/src/commands/backup.rs:69.JOB_DATA_COLUMNShas only 13 columns, and the restore INSERT is at:545-606. - Scenario: an encrypted job is backed up as its placeholder
{"encrypted": true}or as its redacted PII form. The ciphertext, nonce, tag, key id andpii_fieldsare not exported. On restore it comes back withis_encrypted = false, so the handler runs on the placeholder and the original payload is unrecoverable. - Other columns dropped:
cron_schedule,recurring,timeout_seconds,retry_strategy,depends_on,workflow_id,batch_idand the trace IDs. A recurring job comes back as a one-shot job. - Verified: on a scratch PostgreSQL DB I inserted an encrypted, recurring row and ran the backup SELECT and the restore INSERT. The result was
payload={"encrypted": true},is_encrypted=f,encrypted_payload NULL,cron_schedule NULL,recurring=f,timeout NULL. - Fix: back up and restore the full
JOB_SELECT_FIELDS, including the encryption columns. If that is not done, refuse to back up encrypted or recurring rows.
HIGH
H1. CLI and web dashboard enqueue jobs in plaintext on queues configured for encryption
- Where:
- CLI:
cargo-hammerwork/src/utils/database.rs:179-180(JobQueue::new(pool)), used bycommands/job.rs:589-631. - Web:
hammerwork-web/src/server.rs:174,186andhammerwork-web/src/api/mod.rs:313, used byPOST /api/jobs(api/jobs.rs:504).
- CLI:
- Scenario: the app sets
encrypted_queues = ["payments"]inhammerwork.toml. Then an operator runscargo hammerwork job enqueue -n payments -p '{"card":"4111…"}', or creates the job from the dashboard. That queue object has no engine and no encrypted-queue list, soPayloadEncryption::seal(src/queue/payload_encryption.rs:46-80) does nothing, and the row is stored as plaintext withis_encrypted=false. - Docs contradicted:
docs/encryption.md:357says that is "how a queue configured from hammerwork.toml encrypts without code changes". - Verified: I read the code, and grep shows that neither crate reads the
[encryption]config. - Fix: do one of the following.
- Build the CLI and web queues from
HammerworkConfigwithapply_encryption_config. - Persist the per-queue encryption policy in the DB and have
enqueuereject plaintext on those queues.
- Build the CLI and web queues from
H2. get_dead_jobs / get_dead_jobs_by_queue return encrypted jobs labelled as plaintext
- Where:
- PostgreSQL:
src/queue/postgres.rs:948-983usesDeadJobRow, which hard-codesis_encrypted: falseandpii_fields: [](:615-629). - MySQL:
src/queue/mysql.rs:1097,1120and:641.
- PostgreSQL:
- Scenario: a DLQ tool calls
queue.decrypt_job(dead_job). That returns the placeholder or redacted payload with no error, becauseopen()short-circuits for non-encrypted jobs. If the tool then re-enqueuesJob::new(queue, job.payload), the original data is lost. - Verified: I read the SQL and the row mapping.
get_joband TestQueue are correct, so the tests miss this. - Fix: select
JOB_SELECT_FIELDSintoJobRow.
H3. Concurrent migrations (auto_migrate on several replicas, or CLI plus app) crash all but one process
-
Where:
src/migrations/mod.rs:132-195;src/migrations/postgres.rs:23-145andsrc/migrations/mysql.rs:23-125;- called from
src/queue/mod.rs:1656,1700.
Nothing takes an advisory lock, and
record_migrationruns outside the migration transaction. -
Scenario: a fresh deploy starts 4 replicas. The losers fail with
duplicate key … pg_type_typname_nsp_index(concurrentCREATE TABLE IF NOT EXISTS) orduplicate key … hammerwork_migrations_pkey, andfrom_configreturns an error. -
Verified: I ran 4 concurrent copies of migration
001plus the record INSERT on a scratch PostgreSQL DB, 3 times over. The losers failed every time. -
Fix:
- Hold
pg_advisory_lock/ MySQLGET_LOCKfor the whole run and re-read the executed list after acquiring it. - Record the migration inside its transaction on PostgreSQL, and use
ON CONFLICT DO NOTHING/INSERT IGNORE.
- Hold
H4. KMS data-key rotation in a multi-process fleet sends jobs to Dead
- Where:
src/encryption/engine.rs:193-235(rotate_kms_key) and:777-830(decrypt_valueonly tries in-memory keys). - Scenario: process A rotates
key_idto v2 and encrypts new jobs with it. The metadata does not record the version. Worker B only holds v1, so AEAD fails. The worker treats that as a run failure (worker.rs:2071-2074), and the job burns its attempts and goes to Dead until B restarts. - Docs gap:
docs/encryption.md:203mentions the stale key, but not that jobs fail. - Verified: I read the code path.
- Fix: do both.
- On a decrypt failure for a KMS-backed key, reload newer versions from
hammerwork_kms_data_keysand retry, or record the key version in the metadata. - Document a two-phase rollout.
- On a decrypt failure for a KMS-backed key, reload newer versions from
H5. Web dashboard: the default build compares passwords as plaintext, so the documented bcrypt hash becomes the password
- Where:
hammerwork-web/src/auth.rs:97-105: without theauthfeature this ispassword == password_hash.hammerwork-web/Cargo.toml:default = ["postgres"], andauth = ["bcrypt"]is opt-in.main.rs:153-158,206-218:--passwordrefuses to hash without the feature, which leaves--password-file("File containing password hash").
- Scenario: following the README (lines 82, 343, 357-361), the operator stores
$2b$12$…. The real password is rejected, and the hash string itself logs in. Anyone who can read the config or a backup gets in. - Verified: I read the code and the feature flags.
- Fix: make bcrypt unconditional, or put it in the default features. Without it, refuse to start.
H6. Web dashboard: anyone can lock the admin out permanently, and the failed-attempt map grows without bound
- Where:
hammerwork-web/src/auth.rs:109-130and:139-145. - Lockout:
record_failed_attemptnever resets the count after the lockout expires.- Five bad requests for the default
adminlock it for 15 minutes, and correct credentials then get 429. - After that, one bad request every 15 minutes re-locks it indefinitely: the count stays ≥ 5 and only a successful login clears it.
- Five bad requests for the default
- Memory: the map is keyed by an attacker-chosen username with no cap. Entries live 30 minutes. Unauthenticated
Authorization: Basic base64(<random 8KB>:x)requests to/api/*grow memory without limit. - Verified: I read the code.
- Fix:
- Reset the count once
last_attemptis older thanlockout_duration. - Only track the configured username, or key per IP.
- Cap the map's size.
- Reset the count once
H7. Web dashboard: with the auth feature, bcrypt (cost 12) runs synchronously on the Tokio runtime for every request
- Where:
hammerwork-web/src/auth.rs:99,212. There are no sessions, so every/apicall and every/wsupgrade costs about 250 ms of blocking CPU. - Scenario: the dashboard polls several endpoints at once and stalls every worker thread, including WebSocket pings.
- Verified: I read the code.
- Fix:
- Run the verification in
spawn_blocking. - Cache successful verifications with a short-lived token. That would also give the ignored
session_timeouta purpose.
- Run the verification in
H8. Web dashboard: no CSRF protection on state-changing POSTs
- Where: every route that uses
warp::body::json():api/jobs.rs:176,192,200,208api/queues.rs:198api/system.rs:277api/archive.rs:287,300
- The gap: warp accepts a request body with no
Content-Type, and nothing checksOriginorSec-Fetch-Site. - Scenario: a web page the operator visits sends a no-cors
fetchwith a type-less Blob body tohttp://127.0.0.1:8080/api/jobs/bulk({"action":"delete",…}). That is a simple request, so there is no preflight. It works outright with--no-auth, and wherever the browser attaches cached Basic credentials. - Exposed actions: enqueue, bulk delete or retry, queue pause or clear, maintenance and archive.
- Verified: I read the code and warp 0.4's
body.rs. - Fix: do both.
- Require
Content-Type: application/json. - Reject a cross-site
Origin/Sec-Fetch-Siteon non-GET requests, or require a custom header.
- Require
H9. WorkerPool::new() autoscales by default and retires workers of other queues
- Where:
AutoscaleConfig::default()hasenabled: true(src/worker.rs:330), used at:2833.- The first added worker becomes the template, and the autoscaler measures only the template's queue.
- Scale-down retires the highest-index workers, whatever their queue (
:3100).
- Scenario:
examples/postgres_example.rs:84-87adds email, notifications and api_calls workers. With a quiet email queue, the autoscaler retiresapi_calls, then a minute laternotifications, and those queues stop being processed.- An email backlog instead clones up to 10 email workers.
- A retired worker is shut down with the 30 s grace period. A job running longer than that is cancelled and left
Runningfor the reaper, and that run counts as an attempt.
- Inconsistency:
WorkerConfig::default()hasautoscaling_enabled: false. - Verified: I read the code.
- Fix:
- Make the default disabled.
- Only scale workers cloned from the template.
- Retire only idle workers.
H10. Alert delivery runs inline in the worker's dequeue loop, with no HTTP timeout and no backoff
- Where:
acquire_jobcallscheck_alert_thresholds()on every poll (src/worker.rs:1822), andcheck_worker_starvationon every empty poll.- Delivery uses
reqwest::Client::new()(src/alerting.rs:447), which has no timeout. - The cooldown only starts after a successful delivery (
alerting.rs:648).
- Scenario: a hanging Slack or webhook alert endpoint stalls every worker's poll loop, so no jobs are processed. A failing endpoint is retried on every poll by every worker.
- Verified: I read the code.
- Fix:
- Give the client a timeout.
- Move alert checks to the existing 30 s monitoring task.
- Apply the cooldown after failures too.
H11. WebhookManager::update_webhook duplicates delivery
- Where:
src/webhooks.rs:706-718isremove_webhook+add_webhookwith the same ID. - What goes wrong: the old listener (
:765-800) is blocked inrecv(). When it wakes, its exit checks (webhooks.get(id),subscriptions.contains_key(id)) both pass because of the new entry, so it keeps delivering. - Scenario: every update adds another listener, so after N updates each event is POSTed N+1 times.
test_enable_disable_update_webhookonly checks the first request. - Verified: I read the code.
- Fix: give each listener a generation number or cancellation token.
H12. Webhook and stream delivery backlog has no bound
- Where:
src/webhooks.rs:811andsrc/streaming.rs:1455spawn one task per event or batch before acquiring the concurrency semaphore. Retries sleep while still holding the permit. - Scenario: with the endpoint or broker down and steady job traffic, the waiting tasks (each holding a cloned event) grow until the process is OOM-killed.
BufferConfig.max_eventsdoes not bound this. - Verified: I read the code.
- Fix: acquire the permit (or a slot in a bounded queue) before spawning, and count overflow as a drop.
H13. The webhook timeout does not cover the response body
- Where:
src/webhooks.rs:980-988.timeout(.., request.send())covers only the headers;response.text()is unbounded both in time and in size, and the client has no global timeout (:524). - Scenario: an endpoint that sends headers and then trickles the body holds a delivery permit forever. Enough of those block delivery to every webhook.
- Verified: I read the code.
- Fix: wrap the whole attempt in the timeout and read a bounded number of bytes.
MEDIUM
Lifecycle and API
M1. disable_recurring_job doesn't stop the next run, and enable_recurring_job can't revive one.
- Where:
src/queue/postgres.rs:1419-1435, MySQL equivalent. - The disable gap: disabling only sets
recurring = FALSE. The already-Pendingnext occurrence still runs, which contradicts the doc "stop future executions" (queue/mod.rs:213). - The enable gap: after that run the job is
Completed, and enabling only flips the flag back, so it never runs again. - Fix: do both.
- Disable: also stop the pending occurrence, for example by moving it to a paused state.
- Enable: reschedule from
next_cron_runwhen the job is notPending.
M2. with_max_retries doc example contradicts its behaviour.
- Where:
src/worker.rs:1059-1061. - The example says "Critical jobs get more retry attempts" with
.with_max_retries(10), but the setting can only lower the limit (effective_attempt_limit,worker.rs:124). Worker::newdocs also mention "3 maximum retry attempts", although there is no cap by default.
M3. PriorityWeights::with_fairness_factor is accepted and ignored.
- Where:
src/priority.rs:388. Nothing readsfairness_factoroutside its getter. - The config example sets it (
src/config.rs:1273), and the docstring promises "1.0 = round-robin".
M4. Other config values are accepted and ignored. I confirmed by grep that nothing reads them:
AutoscaleConfig.idle_timeout(worker.rs:324)StatsConfig.cleanup_interval_secs,max_event_age_secsandcollect_timing(stats.rs:153-157)MetricsConfig.update_interval(metrics.rs:84; the interval is hard-coded to 30 s atworker.rs:2687)AlertingConfig.custom_thresholds(alerting.rs:25)WebhookManagerConfig.default_timeout_secs(webhooks.rs:455)StreamManagerConfig.global_flush_interval_secs(streaming.rs:825)- the whole
LoggingConfig(config.rs:665) JobBatch::with_batch_size(batch.rs:279; the doc says it chunks, but the insert uses a fixedINSERT_CHUNK_ROWS)- web
request_timeoutandauth.session_timeout(hammerwork-web/src/config.rs:120,341) - web WebSocket
max_message_sizeandmessage_buffer_size(config.rs:372-376; tungstenite's 64 MiB default applies)
M5. Zero durations in config are footguns.
polling_interval = 0makes idle workers hot-loop onsleep(0)(worker.rs:1924).job_timeout = 0times every job out at 0 s (worker.rs:1232).with_hammerwork_configalways applies the 300 s defaultjob_timeoutto every job.
M6. The rate limiter spends tokens on empty and paused polls (worker.rs:1827), so idle polling keeps the bucket empty and bursts never happen. rate_limit.rs:184 also loses sub-millisecond refill time.
Resources
M7. The InMemoryStatsCollector hot path is O(n).
- At its cap,
drain(0..1)(stats.rs:379) shifts 100k events on every event, under astd::sync::RwLock. - With alerting enabled, every poll clones up to 100k events (
stats.rs:214). - Fix: use a
VecDeque.
M8. An extra COUNT(*) runs on every poll of every worker when metrics are enabled (worker.rs:1866). The monitoring task already updates the queue depth.
M9. Webhook and stream listeners miss events published just after add_webhook/add_stream returns. They resubscribe() inside the spawned task (webhooks.rs:770, streaming.rs:1415). The tests sleep 100 ms to hide this.
M10. The monitoring task leaks when a worker's run panics or is dropped. It is only aborted on normal return (worker.rs:1751), so each supervisor restart adds another 30 s loop.
M11. Web dashboard: no request body limit, and archive listing reads the whole archive.
- No JSON route has a
content_length_limit, and/api/jobs/bulk'sjob_idsarray is unbounded. /api/archive/jobscallsall_archived_jobs(api/archive.rs:385-404,449-477) on any filtered request or full first page, so each view reads the entire archive table.
M12. Web dashboard: WebSocket memory has no bound.
- Each connection uses an
unbounded_channel(websocket.rs:104,135). A client that sends Pings and never reads piles up Pongs. Subscribeaccepts unlimited arbitrary strings./wshas noOrigincheck (server.rs:295-315).- No server code ever publishes events to the socket, so the advertised "real-time updates" carry only pings.
M13. Web dashboard: pagination offset uses the unclamped limit and can overflow.
- Where:
api/mod.rs:167-179. limit=5000&page=2serves 1000 rows from offset 5000, which skips 4000 rows.(page-1)*limitis uncheckedu32arithmetic.
Data safety
M14. Secrets in Debug output and logs.
- The derived
Debugprints:DatabaseConfig.url(src/config.rs:204,354);- webhook
secret,headersandWebhookAuthtokens and passwords (src/webhooks.rs:171,243); - Azure
ClientSecret(src/encryption/azure.rs:57); - web
AuthConfig.password_hashandDashboardConfig.database_url(hammerwork-web/src/config.rs:93,329).
src/webhooks.rs:635logs the full webhook URL at info level. Slack, Discord and Teams URLs are bearer secrets.cargo hammerwork config showprintsdatabase_urlwith its password (cargo-hammerwork/src/commands/config.rs:69-76), while the migration commands already useredact_url.
M15. Weak Vault/Azure key material is padded instead of rejected.
fit_vault_key(engine.rs:1300-1325) pads a 1-byte value with its own SHA-256, which gives a 32-byte key with 8 bits of entropy. A non-base64 passphrase is hashed once with plain SHA-256.fit_azure_key(engine.rs:1366-1396) pads short material the same way.- Static and env key sources correctly reject the wrong size.
- Fix: require exactly
expected_sizebytes.
M16. Web dashboard: username and password checks are not constant-time.
auth.rs:80runs bcrypt only when the username matches, which is a timing oracle for the username.- The plaintext
==in the default build exits early. - With CORS enabled,
allow_any_origin()(server.rs:245-250) plus--no-authlets any site read and mutate the dashboard.
M17. Key material is never zeroized. There is no zeroize dependency, and keys are cloned as Vec<u8> on every use (key_manager.rs:1664-1675, engine.rs:777-795). This is a hardening gap, not an exploit.
Checked and clean
- Dequeue: atomic
FOR UPDATE SKIP LOCKEDclaim on both backends. - Outcome recording: guarded by the run's attempt and
started_at, so late or stale workers cannot overwrite a newer state. - Recurring jobs: rescheduled on success, Dead and TimedOut (including jobs the reaper marks Dead).
- Cron catch-up: coalesces missed occurrences.
- Weighted selection: seeded per call and considers every runnable level.
- Pause: enforced inside the dequeue SQL.
- Shutdown: outcome recording is spawned, so it is never cancelled mid-transaction.
- SQL injection: none found in the library, CLI or web. Every
format!interpolates only constants, placeholders or integers. - Encryption: sealing covers enqueue, batch, workflow and cron on both backends. Archive and restore copy the ciphertext as-is. Nonces are fresh per encryption, and the AAD binds id, queue, key id, algorithm and PII fields.
- Migrations: all 18 apply twice cleanly on both backends, and the schemas are at parity. One exception:
hammerwork_encryption_keys.rotation_interval(PostgreSQL) isrotation_interval_secondson MySQL. I did not check whether the key manager handles that difference. - Web dashboard:
- Every
/api/*route and/wssit behind auth. - The server binds to 127.0.0.1 by default, and auth fails closed when no password is set.
- The DB URL is masked in the API and in the logs.
- Every
🤖 Generated with Claude Code
Activity
CodingAnarchy commentedon Oct 9, 2026
Fix plan. One PR per workstream, each referencing the finding IDs:
hammerwork-web)🤖 Generated with Claude Code
fix(web): harden dashboard auth, CSRF, request limits and WebSockets (#…
fix(encryption): close the encryption and data-safety gaps of #64 (W3)
fix(encryption): close the encryption and data-safety gaps of #64 (W3) (
fix(worker,queue): job lifecycle hardening from #64 (W2) (#68)
fix(delivery): bound webhook/stream backlogs, fix duplicate listeners…
fix(delivery): bound webhook/stream backlogs, fix duplicate listeners…
CodingAnarchy commentedon Oct 10, 2026
All findings are fixed:
Remaining follow-ups that were outside these findings are tracked in #71.
🤖 Generated with Claude Code