Skip to content

Final hardening review findings #64

Closed

Description

@CodingAnarchy

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) and src/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-2228 and src/queue/mysql.rs:2344-2354.
    • requeue_stale_jobs covers all queues, but each pool derives older_than from its own workers' leases: src/worker.rs:3173-3180.
  • 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 default WorkerPool, whose reaper uses older_than = 5 min. Five minutes into one of A's jobs, B's reaper moves it back to Pending, 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:2898 says "Running reapers in several pools or processes at once is safe". The CLI help says the same.
  • Related (MEDIUM): heartbeat_job matches only on id AND status = 'Running' (postgres.rs:2122-2135), not on the run. After a reclaim and re-claim, the stale worker's heartbeat still returns true and keeps extending the new run's lease. That contradicts the trait doc (queue/mod.rs:765), which says it returns false once the lease is lost.
  • Verified: on PostgreSQL hw_review I inserted a job, claimed it with the exact claim_sql statement (lease_expires_at stayed NULL), waited 3 s and ran cargo hammerwork job requeue-stale --older-than-secs 2. The job, still held by its "worker", went back to Pending with "Job lease expired while Running; the worker is presumed dead".
  • Fix:
    • Write lease_expires_at = now() + lease (and last_heartbeat_at) in the claim statement, passing the lease into dequeue. The reaper can then rely only on leases, with older_than kept just for rows claimed by pre-015 code.
    • Treat lease 0 as "never reap", or reject it.
    • Scope heartbeat_job to the run (attempts and started_at).

C2. Spawned child jobs are lost when spawning fails after the parent completes

  • Where:

    • src/worker.rs:2138 commits the parent as Completed.
    • Only afterwards does :2164 call SpawnManager::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_jobs handler 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_COLUMNS has 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 and pii_fields are not exported. On restore it comes back with is_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_id and 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 by commands/job.rs:589-631.
    • Web: hammerwork-web/src/server.rs:174,186 and hammerwork-web/src/api/mod.rs:313, used by POST /api/jobs (api/jobs.rs:504).
  • Scenario: the app sets encrypted_queues = ["payments"] in hammerwork.toml. Then an operator runs cargo 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, so PayloadEncryption::seal (src/queue/payload_encryption.rs:46-80) does nothing, and the row is stored as plaintext with is_encrypted=false.
  • Docs contradicted: docs/encryption.md:357 says 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 HammerworkConfig with apply_encryption_config.
    • Persist the per-queue encryption policy in the DB and have enqueue reject plaintext on those queues.

H2. get_dead_jobs / get_dead_jobs_by_queue return encrypted jobs labelled as plaintext

  • Where:
    • PostgreSQL: src/queue/postgres.rs:948-983 uses DeadJobRow, which hard-codes is_encrypted: false and pii_fields: [] (:615-629).
    • MySQL: src/queue/mysql.rs:1097,1120 and :641.
  • Scenario: a DLQ tool calls queue.decrypt_job(dead_job). That returns the placeholder or redacted payload with no error, because open() short-circuits for non-encrypted jobs. If the tool then re-enqueues Job::new(queue, job.payload), the original data is lost.
  • Verified: I read the SQL and the row mapping. get_job and TestQueue are correct, so the tests miss this.
  • Fix: select JOB_SELECT_FIELDS into JobRow.

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-145 and src/migrations/mysql.rs:23-125;
    • called from src/queue/mod.rs:1656,1700.

    Nothing takes an advisory lock, and record_migration runs outside the migration transaction.

  • Scenario: a fresh deploy starts 4 replicas. The losers fail with duplicate key … pg_type_typname_nsp_index (concurrent CREATE TABLE IF NOT EXISTS) or duplicate key … hammerwork_migrations_pkey, and from_config returns an error.

  • Verified: I ran 4 concurrent copies of migration 001 plus the record INSERT on a scratch PostgreSQL DB, 3 times over. The losers failed every time.

  • Fix:

    • Hold pg_advisory_lock / MySQL GET_LOCK for 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.

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_value only tries in-memory keys).
  • Scenario: process A rotates key_id to 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:203 mentions 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_keys and retry, or record the key version in the metadata.
    • Document a two-phase rollout.

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 the auth feature this is password == password_hash.
    • hammerwork-web/Cargo.toml: default = ["postgres"], and auth = ["bcrypt"] is opt-in.
    • main.rs:153-158,206-218: --password refuses 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-130 and :139-145.
  • Lockout: record_failed_attempt never resets the count after the lockout expires.
    • Five bad requests for the default admin lock 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.
  • 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_attempt is older than lockout_duration.
    • Only track the configured username, or key per IP.
    • Cap the map's size.

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 /api call and every /ws upgrade 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_timeout a purpose.

H8. Web dashboard: no CSRF protection on state-changing POSTs

  • Where: every route that uses warp::body::json():
    • api/jobs.rs:176,192,200,208
    • api/queues.rs:198
    • api/system.rs:277
    • api/archive.rs:287,300
  • The gap: warp accepts a request body with no Content-Type, and nothing checks Origin or Sec-Fetch-Site.
  • Scenario: a web page the operator visits sends a no-cors fetch with a type-less Blob body to http://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-Site on non-GET requests, or require a custom header.

H9. WorkerPool::new() autoscales by default and retires workers of other queues

  • Where:
    • AutoscaleConfig::default() has enabled: 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-87 adds email, notifications and api_calls workers. With a quiet email queue, the autoscaler retires api_calls, then a minute later notifications, 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 Running for the reaper, and that run counts as an attempt.
  • Inconsistency: WorkerConfig::default() has autoscaling_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_job calls check_alert_thresholds() on every poll (src/worker.rs:1822), and check_worker_starvation on 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-718 is remove_webhook + add_webhook with the same ID.
  • What goes wrong: the old listener (:765-800) is blocked in recv(). 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_webhook only 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:811 and src/streaming.rs:1455 spawn 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_events does 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-Pending next 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_run when the job is not Pending.

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::new docs 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 reads fairness_factor outside 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_secs and collect_timing (stats.rs:153-157)
  • MetricsConfig.update_interval (metrics.rs:84; the interval is hard-coded to 30 s at worker.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 fixed INSERT_CHUNK_ROWS)
  • web request_timeout and auth.session_timeout (hammerwork-web/src/config.rs:120,341)
  • web WebSocket max_message_size and message_buffer_size (config.rs:372-376; tungstenite's 64 MiB default applies)

M5. Zero durations in config are footguns.

  • polling_interval = 0 makes idle workers hot-loop on sleep(0) (worker.rs:1924).
  • job_timeout = 0 times every job out at 0 s (worker.rs:1232).
  • with_hammerwork_config always applies the 300 s default job_timeout to 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 a std::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's job_ids array is unbounded.
  • /api/archive/jobs calls all_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.
  • Subscribe accepts unlimited arbitrary strings.
  • /ws has no Origin check (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=2 serves 1000 rows from offset 5000, which skips 4000 rows.
  • (page-1)*limit is unchecked u32 arithmetic.

Data safety

M14. Secrets in Debug output and logs.

  • The derived Debug prints:
    • DatabaseConfig.url (src/config.rs:204,354);
    • webhook secret, headers and WebhookAuth tokens and passwords (src/webhooks.rs:171,243);
    • Azure ClientSecret (src/encryption/azure.rs:57);
    • web AuthConfig.password_hash and DashboardConfig.database_url (hammerwork-web/src/config.rs:93,329).
  • src/webhooks.rs:635 logs the full webhook URL at info level. Slack, Discord and Teams URLs are bearer secrets.
  • cargo hammerwork config show prints database_url with its password (cargo-hammerwork/src/commands/config.rs:69-76), while the migration commands already use redact_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_size bytes.

M16. Web dashboard: username and password checks are not constant-time.

  • auth.rs:80 runs 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-auth lets 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 LOCKED claim 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) is rotation_interval_seconds on MySQL. I did not check whether the key manager handles that difference.
  • Web dashboard:
    • Every /api/* route and /ws sit 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.

🤖 Generated with Claude Code

Activity

  1. CodingAnarchy commented on Oct 9, 2026

    @CodingAnarchy
    OwnerAuthor

    Fix plan. One PR per workstream, each referencing the finding IDs:

    🤖 Generated with Claude Code

  2. CodingAnarchy commented on Oct 10, 2026

    @CodingAnarchy
    OwnerAuthor

    All findings are fixed:

    Remaining follow-ups that were outside these findings are tracked in #71.

    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions