Skip to content

feat(security): harden HTTP server auth, CORS, input validation - #254

Merged
ajianaz merged 3 commits into
developfrom
feat/security-hardening
Jun 9, 2026
Merged

ajianaz merged 3 commits into
developfrom
feat/security-hardening

Conversation

@ajianaz

@ajianaz ajianaz commented Jun 9, 2026 •

Copy link
Copy Markdown
Collaborator

Security Hardening — Priority 1

Addresses issues #204, #205, #132, #101.

Changes

#205 — Default bind address

  • Changed from 0.0.0.0 → 127.0.0.1
  • Server only accessible from localhost by default

#101/#204 — Bearer token authentication

  • Authorization: Bearer <token> required on all endpoints except GET /health
  • Config sources:
    • uteke.toml: [server].auth_token = "..."
    • CLI: --auth-token <TOKEN>
    • Env: UTEKE_AUTH_TOKEN
    • Precedence: CLI > env > config
  • Constant-time comparison prevents timing attacks

#204 — Configurable CORS origins

  • Replaces wildcard * with configurable allowlist
  • uteke.toml: cors_origins = ["http://localhost:3000"]
  • CLI: --cors-origin <URL> (repeatable)
  • Request Origin header matched against allowlist
  • Preflight: validated header allowlist (no blind reflection)
  • When auth + wildcard CORS: Authorization excluded from CORS allowed headers
  • Non-browser clients (curl, SDKs, agents) unaffected

#132 — Input validation on /remember

  • Content length, tag count, tag length validated via validate_input()
  • Returns 400 with clear error messages

Startup warnings

  • Warns when auth is disabled
  • Warns when CORS wildcard + auth enabled
  • Warns when CORS wildcard for production use

Validation

  • ✅ cargo clippy --all-targets -- -D warnings — clean
  • ✅ cargo test — 116/116 pass
  • ✅ Cora code review — 0 critical, 0 major security issues

Summary by CodeRabbit

  • New Features

    • Added bearer-token authentication for API endpoints (excluding health checks)
    • Added configurable per-request CORS origin handling
  • Chores

    • New --auth-token and repeatable --cors-origin CLI flags
    • Support for UTEKE_AUTH_TOKEN environment variable
    • Config file schema updated with authentication and CORS options
    • Added startup logging for authentication and CORS configuration

…205 #132 #101)

Security fixes:
- Default bind address changed from 0.0.0.0 to 127.0.0.1 (#205)
- Bearer token authentication for all endpoints except GET /health (#101 #204)
  - Config: uteke.toml [server].auth_token
  - CLI: --auth-token <TOKEN>
  - Env: UTEKE_AUTH_TOKEN
  - Precedence: CLI > env > config
  - Constant-time token comparison to resist timing attacks
- Configurable CORS origins replacing wildcard (#204)
  - Config: uteke.toml [server].cors_origins = [...]
  - CLI: --cors-origin <URL> (repeatable)
  - Origin matching: request Origin header matched against allowlist
  - Preflight: validated header allowlist (no blind reflection)
  - When auth + wildcard CORS: Authorization header excluded from CORS
- Input validation wired to /remember endpoint (#132)
  - Content length, tag count, tag length validated via validate_input()
- Startup warnings for insecure configurations
  - Warns when auth disabled
  - Warns when CORS wildcard with auth enabled
  - Non-browser clients (curl, SDKs) unaffected by CORS restrictions

Closes #204, Closes #205, Closes #132, Closes #101
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ajianaz, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 20 minutes and 47 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 48f276d2-87d1-4c72-8a4d-740c714b4a4f

📥 Commits

Reviewing files that changed from the base of the PR and between c7ba673 and e54e9ce.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • crates/uteke-server/Cargo.toml
  • crates/uteke-server/src/main.rs
📝 Walkthrough

Walkthrough

This PR adds bearer-token authentication and configurable per-request CORS handling to the server. A new ReqCtx type carries auth tokens and allowed origins, enforcing auth for all endpoints except GET /health and OPTIONS preflight. CLI flags --auth-token and repeatable --cors-origin configure behavior, with precedence from CLI, environment variable, and config file. All endpoint responses now use CORS-aware helpers.

Changes

Bearer-Token Auth & CORS Support

Layer / File(s) Summary
Auth & CORS Infrastructure
crates/uteke-server/src/main.rs
Introduces constant_time_eq for safe token comparison, check_auth function for bearer token validation, and ReqCtx type that resolves allowed CORS origins per request, generates preflight headers, and provides JSON response helpers that apply CORS headers.
Router Rewrite & Auth Integration
crates/uteke-server/src/main.rs
Router signature updated to accept ReqCtx and mutable Request. Adds explicit OPTIONS preflight handling, exempts GET /health from auth, and enforces check_auth before dispatching other routes. Request loop wired to new router signature.
Endpoint Response Updates
crates/uteke-server/src/main.rs
All endpoint handlers (/remember, /recall, /search, /list, /forget with UUID validation, /stats, /namespaces, /memory, 404 handler) updated to use ctx.ok_response_for and ctx.error_response_for for consistent JSON responses and CORS headers.
CLI Arguments & Config Schema
crates/uteke-server/src/main.rs
New CLI variables and argument parsing for --auth-token and repeatable --cors-origin. Help text and UTEKE_AUTH_TOKEN environment variable documented. ServerFileSection struct extended with auth_token and cors_origins fields for config file support.
Configuration Resolution & Startup Validation
crates/uteke-server/src/main.rs
Config file loaded and CORS origins merged with CLI overriding file settings. Auth token precedence: CLI > environment > config file. ReqCtx built from resolved values. Startup warning emitted when auth enabled without CORS origins, and security/CORS configuration logged.

Sequence Diagram

sequenceDiagram
  participant Request as HTTP Request
  participant Router as Router
  participant Auth as check_auth()
  participant ReqCtx as ReqCtx
  participant Handler as Endpoint Handler
  participant Response as CORS Response
  
  Request->>Router: incoming request (origin, auth header)
  alt OPTIONS Preflight
    Router->>Response: skip auth, return CORS headers
  else GET /health
    Router->>Handler: skip auth, process endpoint
  else Other Routes
    Router->>Auth: validate bearer token
    alt Auth Success
      Auth->>ReqCtx: token valid
      ReqCtx->>Handler: pass context to handler
      Handler->>ReqCtx: handler returns data
      ReqCtx->>Response: apply CORS headers + JSON body
    else Auth Failure
      Auth->>Response: return 401 error with CORS headers
    end
  end
  Response-->>Request: HTTP response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • ajianaz/uteke#234: Modifies the same crates/uteke-server/src/main.rs HTTP routing and control flow paths, particularly around DELETE /forget handling and request parsing/response logic.

Suggested labels

security, rust

Poem

🐰 A token guards each request now,
CORS headers bowing low,
Origins blessed, auth in place,
The server stands with stronger grace! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(security): harden HTTP server auth, CORS, input validation' directly and accurately summarizes the main changes—it highlights the three primary security improvements (auth, CORS, input validation) that are central to the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/security-hardening

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.

@github-actions

github-actions Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

🔍 Cora AI Code Review

❌ Blocked — critical issues found.

🔴 Error (1)

  • crates/uteke-server/src/main.rs:170 — In resolve_origin_for, when cors_origins is non-empty but no Origin header is present (e.g., non-browser clients like curl), the function returns an empty string, which omits CORS headers. This is correct for browser enforcement. However, when cors_origins is empty (the default), it returns "*" (wildcard), meaning any origin is allowed. This is the default behavior and is warned about at startup, but the combination of auth enabled + CORS wildcard means any website can make authenticated requests via browser if they know the token. The code partially mitigates this by omitting Authorization from Access-Control-Allow-Headers when auth is on and CORS is wildcard, which is good.

Review powered by cora-cli · BYOK · MIT

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
crates/uteke-server/src/main.rs (1)

269-273: 💤 Low value

Fallback behavior could be clarified.

When the browser requests headers that aren't in the allowlist (resulting in empty intersection), this falls back to returning the full allowlist. While not a security issue (browser will still enforce CORS on the actual request), it's inconsistent with the comment at line 259 stating "only echo back headers that are in our allowlist."

Consider returning an empty string or explicitly returning the full allowlist as the default rather than using it as a fallback for no-match scenarios.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/uteke-server/src/main.rs` around lines 269 - 273, The current logic
sets allow_headers to allowed_headers_set.join(", ") when the computed
intersection (allow_headers) is empty, which contradicts the earlier comment
about echoing only headers in our allowlist; update the behavior in the code
handling allow_headers so that when the intersection is empty it returns an
empty string (or explicitly returns the full allowlist only if you intend that
as the explicit default), and keep the change localized to the same block that
assigns allow_headers and references allowed_headers_set so the result matches
the comment "only echo back headers that are in our allowlist."
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/uteke-server/src/main.rs`:
- Around line 178-188: The current constant_time_eq returns immediately on
a.len() != b.len(), leaking token length to timing attacks; instead, change auth
checks in check_auth to compare fixed-size digests: hash both the incoming token
and the configured token with a fixed-size digest (e.g., SHA-256) and then
perform a constant-time comparison on the resulting fixed-size byte arrays (use
subtle::ConstantTimeEq or a purpose-built constant_time_eq that accepts
fixed-size [u8; N] and does not early-return). Update check_auth to compute the
digest for both values before calling the comparator and remove/replace the
length-based early-return in constant_time_eq so only fixed-size digests are
compared.

---

Nitpick comments:
In `@crates/uteke-server/src/main.rs`:
- Around line 269-273: The current logic sets allow_headers to
allowed_headers_set.join(", ") when the computed intersection (allow_headers) is
empty, which contradicts the earlier comment about echoing only headers in our
allowlist; update the behavior in the code handling allow_headers so that when
the intersection is empty it returns an empty string (or explicitly returns the
full allowlist only if you intend that as the explicit default), and keep the
change localized to the same block that assigns allow_headers and references
allowed_headers_set so the result matches the comment "only echo back headers
that are in our allowlist."
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1d28d42b-33cc-4be3-8da9-d919eb171fd6

📥 Commits

Reviewing files that changed from the base of the PR and between 97c4bca and c7ba673.

📒 Files selected for processing (1)
  • crates/uteke-server/src/main.rs

Comment thread crates/uteke-server/src/main.rs Resolved
ajianaz added 2 commits June 9, 2026 22:38
…ve bearer, DRY 401

- Replace constant_time_eq with SHA-256 digest comparison to prevent
  token length leakage via timing attacks. Configured token hash is
  precomputed at startup; only incoming token is hashed per-request.
- Parse Authorization header case-insensitively per RFC 7235.
  Split on whitespace, require exactly 2 parts (scheme + token).
- Extract unauthorized_response() helper to eliminate 3x duplicated
  401 response building code in check_auth.
- Fix preflight header fallback: return empty string instead of full
  allowlist when no requested headers match (consistent with comments).
@ajianaz
ajianaz merged commit e6e7b19 into develop Jun 9, 2026
9 checks passed
@ajianaz
ajianaz deleted the feat/security-hardening branch June 9, 2026 22:53
ajianaz added a commit that referenced this pull request Aug 13, 2026
* feat(security): harden HTTP server auth, CORS, input validation (#204 #205 #132 #101)

Security fixes:
- Default bind address changed from 0.0.0.0 to 127.0.0.1 (#205)
- Bearer token authentication for all endpoints except GET /health (#101 #204)
  - Config: uteke.toml [server].auth_token
  - CLI: --auth-token <TOKEN>
  - Env: UTEKE_AUTH_TOKEN
  - Precedence: CLI > env > config
  - Constant-time token comparison to resist timing attacks
- Configurable CORS origins replacing wildcard (#204)
  - Config: uteke.toml [server].cors_origins = [...]
  - CLI: --cors-origin <URL> (repeatable)
  - Origin matching: request Origin header matched against allowlist
  - Preflight: validated header allowlist (no blind reflection)
  - When auth + wildcard CORS: Authorization header excluded from CORS
- Input validation wired to /remember endpoint (#132)
  - Content length, tag count, tag length validated via validate_input()
- Startup warnings for insecure configurations
  - Warns when auth disabled
  - Warns when CORS wildcard with auth enabled
  - Non-browser clients (curl, SDKs) unaffected by CORS restrictions

Closes #204, Closes #205, Closes #132, Closes #101

* style: cargo fmt

* fix(security): address review comments — SHA-256 auth, case-insensitive bearer, DRY 401

- Replace constant_time_eq with SHA-256 digest comparison to prevent
  token length leakage via timing attacks. Configured token hash is
  precomputed at startup; only incoming token is hashed per-request.
- Parse Authorization header case-insensitively per RFC 7235.
  Split on whitespace, require exactly 2 parts (scheme + token).
- Extract unauthorized_response() helper to eliminate 3x duplicated
  401 response building code in check_auth.
- Fix preflight header fallback: return empty string instead of full
  allowlist when no requested headers match (consistent with comments).
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