Skip to content

feat: add /health Bearer auth (#73) and readiness probe hysteresis (#72)#141

Merged
nao1215 merged 3 commits intomainfrom
feat/health-auth-and-hysteresis
Mar 13, 2026
Merged

feat: add /health Bearer auth (#73) and readiness probe hysteresis (#72)#141
nao1215 merged 3 commits intomainfrom
feat/health-auth-and-hysteresis

Conversation

@nao1215
Copy link
Owner

@nao1215 nao1215 commented Mar 13, 2026

Summary

  • Issue Consider authentication for /health diagnostic endpoint #73: Add optional TRUSS_HEALTH_TOKEN env var for Bearer authentication on /health. Sub-paths /health/live and /health/ready remain unauthenticated for load balancer probes.
  • Issue Add hysteresis to readiness probe resource checks to prevent flapping #72: Add hysteresis to readiness probe resource checks (disk free bytes, RSS memory) to prevent flapping when values oscillate around the threshold. Configurable via TRUSS_HEALTH_HYSTERESIS_MARGIN (default 5%, range 0.01–0.50).
  • Review fixes: Extract shared extract_bearer_token helper (DRY), expose "recovering" state in health JSON, reject whitespace-only tokens, add startup log, replace bool with ThresholdDirection enum.

Closes #73, #72

Changes

File Description
src/adapters/server/auth.rs Add shared extract_bearer_token helper
src/adapters/server/config.rs Add health_token and hysteresis_margin fields, parse_env_f64_ranged
src/adapters/server/handler.rs ThresholdDirection enum, check_with_hysteresis returns (ok, recovering), configurable margin
src/adapters/server/routing.rs Early-reject /health auth (before body read)
src/adapters/server/mod.rs Pass margin to HealthCache::new()
doc/openapi.yaml Add 401 response and Authorization param for /health
docs/configuration.md Document TRUSS_HEALTH_TOKEN and TRUSS_HEALTH_HYSTERESIS_MARGIN
tests/server_transform_basic.rs 5 integration tests for health token auth

Test plan

  • cargo fmt --all -- --check passes
  • cargo clippy --all-targets --all-features -- -D warnings passes
  • cargo test — all 941+ tests pass
  • Integration tests cover: reject unauthenticated, reject wrong token, accept valid token, /health/live and /health/ready unaffected
  • Unit tests cover hysteresis state machine for both HigherIsWorse (memory) and LowerIsWorse (disk) directions

Summary by CodeRabbit

  • New Features

    • Added optional Bearer token authentication to the /health endpoint via TRUSS_HEALTH_TOKEN configuration
    • Introduced configurable hysteresis margin for health check recovery via TRUSS_HEALTH_HYSTERESIS_MARGIN configuration
    • Live and ready health endpoints remain unauthenticated and publicly accessible
  • Documentation

    • Added configuration reference for new health token and hysteresis margin settings

nao1215 added 3 commits March 13, 2026 22:23
)

When TRUSS_HEALTH_TOKEN is set, GET/HEAD /health requires
Authorization: Bearer <token>. The /health/live and /health/ready
probe endpoints remain unauthenticated for Kubernetes compatibility.
Disk and memory threshold checks now use a 5% hysteresis margin to
prevent flapping when values hover near the boundary. Once a check
fails, it must recover past threshold ± 5% before returning to ok.
- Extract shared extract_bearer_token helper (DRY)
- Add "recovering" field to health response JSON
- Reject whitespace-only bearer tokens
- Add startup log when TRUSS_HEALTH_TOKEN is set
- Make hysteresis margin configurable via TRUSS_HEALTH_HYSTERESIS_MARGIN
- Replace bool with ThresholdDirection enum
@coderabbitai
Copy link

coderabbitai bot commented Mar 13, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR adds optional Bearer token authentication to the /health endpoint and introduces hysteresis-based recovery for resource health checks. New configuration options (TRUSS_HEALTH_TOKEN and TRUSS_HEALTH_HYSTERESIS_MARGIN) enable authentication and reduce check flapping. Changes span auth extraction, config parsing, health cache logic, routing, and comprehensive test coverage.

Changes

Cohort / File(s) Summary
Documentation
doc/openapi.yaml, docs/configuration.md
Added OpenAPI Authorization header parameter and 401 response for /health endpoint. Added documentation for TRUSS_HEALTH_TOKEN and TRUSS_HEALTH_HYSTERESIS_MARGIN environment variables.
Authentication & Token Extraction
src/adapters/server/auth.rs
Extracted Bearer token parsing logic into reusable extract_bearer_token() helper function; refactored authorize_request_headers to use the new helper.
Server Configuration
src/adapters/server/config.rs
Added health_token: Option<String> field to ServerConfig; implemented environment parsing for TRUSS_HEALTH_TOKEN and TRUSS_HEALTH_HYSTERESIS_MARGIN with validation; updated Clone, Debug, PartialEq implementations; added parse_env_f64_ranged() helper for margin validation.
Health Check Logic & Hysteresis
src/adapters/server/handler.rs, src/adapters/server/mod.rs
Introduced hysteresis-based recovery with ThresholdDirection enum and check_with_hysteresis() method. Extended HealthCache with hysteresis_margin and per-check state tracking (disk_state, rss_state). Updated constructor signature to accept margin parameter. Updated all HealthCache instantiations to include DEFAULT_HYSTERESIS_MARGIN.
Request Routing & Early Auth
src/adapters/server/routing.rs
Added early health token authentication check for GET/HEAD /health requests when health_token is configured; returns 401 for unauthenticated requests; refactored Bearer token extraction to use centralized helper.
Health Authentication Tests
tests/server_transform_basic.rs
Added five new test cases covering unauthenticated /health access (401), wrong token rejection (401), valid token acceptance (200), and /health/live and /health/ready remaining unaffected by token requirement.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router as Routing Layer
    participant AuthCheck as Auth Check
    participant Handler as Health Handler
    participant Cache as Health Cache
    participant Response

    Client->>Router: GET /health
    Router->>AuthCheck: Check health_token configured?
    alt health_token is set
        AuthCheck->>AuthCheck: Extract Bearer token from header
        alt Token missing or invalid
            AuthCheck->>Response: 401 Unauthorized + WWW-Authenticate
            Response->>Client: 401 with problem+json
        else Token valid
            AuthCheck->>Handler: Proceed to health check
            Handler->>Cache: Check disk/memory with hysteresis
            Cache->>Cache: Apply threshold + margin logic
            Cache->>Handler: Return (status, recovering)
            Handler->>Response: 200 OK with health JSON
            Response->>Client: 200 with status
        end
    else health_token not set
        Router->>Handler: Proceed to health check
        Handler->>Cache: Check disk/memory with hysteresis
        Cache->>Handler: Return (status, recovering)
        Handler->>Response: 200 OK with health JSON
        Response->>Client: 200 with status
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 With tokens and health checks held tight,
Our endpoints now dance day and night,
Hysteresis margins prevent the fright,
Of flapping checks—no more, we're right! ✨
Bearer tokens guard what matters, ah,
A rabbit's secure health spa-ha!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the two main features: Bearer authentication for /health endpoint and hysteresis for readiness probes, matching the changeset scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/health-auth-and-hysteresis
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nao1215 nao1215 merged commit 7ec4351 into main Mar 13, 2026
16 of 17 checks passed
@nao1215 nao1215 deleted the feat/health-auth-and-hysteresis branch March 13, 2026 13:57
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.

Consider authentication for /health diagnostic endpoint

1 participant