Skip to content

fix(web): harden dashboard auth, CSRF, request limits and WebSockets (#64 H5, H6, H7, H8, M11, M12, M13, M16) - #66

Merged
CodingAnarchy merged 1 commit into
masterfrom
fix/web-security
Oct 9, 2026
Merged

CodingAnarchy merged 1 commit into
masterfrom
fix/web-security

Conversation

@CodingAnarchy

Copy link
Copy Markdown
Owner

Part of #64 (workstream W1). Fixes H5, H6, H7, H8, M11, M12, M13 and M16, all in hammerwork-web.

What changed

Finding Fix
H5 bcrypt hash used as a plaintext password auth (bcrypt) is now a default feature. The stored hash is only ever verified with bcrypt; the plaintext fallback is gone. A build without auth rejects every password, and DashboardConfig::validate (called by WebDashboard::new and the binary) refuses to start with authentication enabled.
H6 permanent lockout, unbounded failure map Failures are keyed by client IP (the connection's peer address via warp::addr::remote(), never a header; IPv6 grouped by /64) and by whether the username is the configured one. Every made-up username shares one record per address. A lockout expires after lockout_duration and the count then starts over; a successful login clears it. The table is capped at 10,000 entries: expired ones are evicted first, then the stalest.
H7 bcrypt on the async threads for every request bcrypt runs in spawn_blocking, limited by a semaphore to one verification per CPU. Successful verifications are cached as HMAC-SHA256(random per-process key, username, password) → expiry, for min(60 s, session_timeout). Only correct credentials are cached, and the cache is bounded. session_timeout = 0 turns caching off.
H8 CSRF on state-changing routes New security module. json_body() replaces warp::body::json() on every JSON route and requires Content-Type: application/json (otherwise 415). same_origin_writes() on /api refuses POST/PUT/DELETE requests that a browser sent from another origin (403). It trusts Sec-Fetch-Site when present; otherwise it compares Origin with Host, and Origin: null is refused. Requests with neither header (curl, scripts) pass, and so do origins listed in the new allowed_origins / --allowed-origin.
M11 no body limit, whole-archive reads JSON bodies are limited to 1 MiB (413). They also need a Content-Length header (411). Bulk actions take at most 1,000 IDs (400). /api/archive/jobs now goes through the new JobHistory::archived_jobs, which filters, counts (COUNT(*)) and pages (LIMIT/OFFSET) in SQL on both backends. The purge dry run counts in SQL as well.
M12 WebSocket memory max_message_size is applied to incoming messages and frames. Each connection's outbound queue is a bounded mpsc::channel(message_buffer_size); when it is full, the message is dropped. Subscribe keeps only the known event types. The /ws handshake gets the same origin check (same_origin, all methods), against cross-site WebSocket hijacking. max_connections was already enforced.
M13 pagination offset get_offset uses the clamped limit (1..=1000) with saturating arithmetic. total_pages uses integer div_ceil. The jobs paginator's page computation saturates too.
M16 timing and CORS The username is compared in constant time (subtle::ConstantTimeEq over keyed digests), and bcrypt runs whether or not the username matched. CORS no longer uses allow_any_origin(): it is granted only to allowed_origins, and enable_cors without any origin is a startup error.

Also fixed: handle_auth_rejection now checks 405 last, so a too-large body reports 413 instead of a sibling route's 405, and it maps LengthRequired to 411.

Why auth became a default feature (H5)

I chose the least surprising option:

  • Default builds (cargo install hammerwork-web): authentication just works with the bcrypt hash the README documents.
  • Builds with --no-default-features: these can no longer silently treat the hash as a password. They fail at startup with a message naming the feature and the alternatives (rebuild with auth, or --no-auth).

Making bcrypt unconditional would also work. I kept the feature so that existing features = ["auth"] users don't break, and builds without auth stay possible. The existing fail-closed behaviour (auth enabled with no password) and --no-auth are unchanged.

Behaviour changes for users

  • --cors / enable_cors = true now needs at least one --allowed-origin / allowed_origins entry. Without one, startup fails.
  • API requests with a body must send Content-Type: application/json and a Content-Length header. The dashboard's own JS already does, and so do curl -H 'Content-Type: application/json' -d …, reqwest .json() and similar clients.
  • Browser pages on other origins can no longer POST/PUT/DELETE or open /ws, unless they are listed in allowed_origins.
  • Behind a reverse proxy, the lockout is per proxy address, because the peer address is the proxy's. This is documented.
  • A WebSocket client that does not read its messages loses them; the server no longer buffers them without limit.
  • Library API:
    • server::app_routes takes AllowedOrigins as a new last argument.
    • api::archive::archive_routes requires a JobHistory queue (both JobQueue<Postgres> and JobQueue<MySql> implement it).
    • AuthState gains check(client_ip, user, pass) -> Verdict, is_locked_out_from and tracked_clients. verify_credentials and is_locked_out are kept.
    • New DashboardConfig::allowed_origins (with #[serde(default)], so old config files still load) and with_allowed_origin.

The hammerwork-web README (configuration, security, request limits, building) and CHANGELOG.md are updated.

Not addressed

M12's last bullet ("no server code ever publishes events to the socket") is a missing feature, not a memory bound. It is left for separate work.

Tests

Each finding has a regression test:

  • H5:
    • auth::the_stored_hash_is_never_a_password
    • config::builds_without_bcrypt_refuse_to_enable_authentication and main::authentication_needs_the_auth_feature (both in builds without auth)
  • H6:
    • an_expired_lockout_starts_the_count_over
    • lockout_is_per_client_address
    • the_filter_locks_out_the_failing_address_only
    • the_failure_table_is_bounded
    • ipv6_clients_are_grouped_by_network
  • H7:
    • bcrypt_runs_off_the_async_threads: on a current-thread runtime, another task keeps ticking during a cost-10 verification.
    • successful_verifications_are_remembered_briefly
  • H8:
    • security::* unit tests
    • server::cross_site_writes_are_refused
    • request_hardening in api_tests (full router, both databases)
    • the binary test: a forged cross-site POST gets 403, and a preflight from a non-allowed origin gets no CORS grant
  • M11:
    • server::oversized_bodies_are_refused
    • history::archive_filters_become_sql_conditions
    • archive paging, filtering and totals in api_tests::request_hardening (PostgreSQL and MySQL)
  • M12:
    • websocket_messages_are_size_limited
    • websocket_handshakes_from_other_origins_are_refused
    • outgoing_messages_are_bounded_per_connection
    • subscriptions_ignore_unknown_event_types
  • M13:
    • api::the_offset_uses_the_clamped_limit_and_never_overflows
    • limit=5000&page=2 and u32::MAX paging through the router
  • M16:
    • correct_credentials_pass_and_wrong_ones_do_not (username variants)
    • config::cors_is_only_granted_to_listed_origins
    • main::cors_needs_explicit_origins
    • binary startup errors

Results:

  • cargo test -p hammerwork-web --all-features -- --include-ignored --skip mysql (PostgreSQL): all pass (116 lib, 12 bin, 2 api, 4 binary, 17 integration, 43 doc).
  • cargo test -p hammerwork-web --all-features -- --include-ignored mysql (MySQL): all pass.
  • cargo test -p hammerwork-web (default features): all pass.
  • cargo test -p hammerwork-web --no-default-features --features postgres --lib --bins: all pass.
  • cargo fmt --all: clean.
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: clean. Also clean for -p hammerwork-web with default features and with --no-default-features --features postgres.
  • cargo metadata --locked: OK. The new direct dependencies (hmac 0.12, sha2 0.10, rand 0.8, subtle 2.6) were already in Cargo.lock.

🤖 Generated with Claude Code

Part of #64 (H5, H6, H7, H8, M11, M12, M13, M16).

- H5: `auth` (bcrypt) is a default feature; the stored hash is only ever
  verified with bcrypt, and a build without it refuses to start with
  authentication enabled.
- H6: failures are counted per client address and username, lockouts
  expire and the count starts over, and the failure table is bounded.
- H7: bcrypt runs on the blocking pool (one per CPU) and successful
  verifications are remembered for up to 60 s under a keyed hash.
- H8: bodies need Content-Type: application/json; cross-origin writes and
  WebSocket handshakes from browsers are refused (Sec-Fetch-Site / Origin).
- M11: 1 MiB JSON body limit, 1000-ID bulk limit, archive listing filtered,
  counted and paged in SQL.
- M12: WebSocket max_message_size and message_buffer_size are enforced and
  subscriptions accept only known event types.
- M13: the pagination offset uses the clamped limit, with saturating math.
- M16: constant-time username comparison, bcrypt always runs, and CORS is
  only granted to configured allowed_origins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CodingAnarchy
CodingAnarchy merged commit 836ae83 into master Oct 9, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant