Skip to content

feat: olla hardening June 2026 - #173

Merged
thushan merged 5 commits into
mainfrom
feature/olla-hardening-june-2026
Jun 11, 2026
Merged

thushan merged 5 commits into
mainfrom
feature/olla-hardening-june-2026

Conversation

@thushan

@thushan thushan commented Jun 11, 2026 •

Copy link
Copy Markdown
Owner

Some hardening of Olla based on reviews, and todo's from last couple of months + using Fable 5 - though quite a number were not actual issues.

Fixes

  • Status handlers (/internal/status, /internal/status/models) allocated per request
  • Olla config pointer is now an atomic.Pointer, snapshotted once per request/stream, so a hot-reload can't hand an in-flight request a torn config
  • Endpoint pools and circuit breakers use LoadOrCompute, so racing goroutines stop building and throwing away an http.Transport on first use
  • Capped upstream error bodies at 1 MiB and close the pipe after, so a misbehaving backend can't exhaust the heap or hang the proxy goroutine.
  • Non-proxy routes now reject oversized chunked bodies instead of waving them through (the old check only looked at Content-Length).

Security

  • AuthHeaderName no longer serialises into status JSON (was leaking the auth scheme).
  • Strip X-Olla-* headers off upstream responses so a backend can't spoof routing or session headers.
  • Sanitise inbound X-Request-ID (printable ASCII, 128 cap) before it hits the logs to close a log-injection vector.

Cleanup

  • Deleted a pile of dead code in the Olla engine: five unused methods, the unused request/error pools, a dead recordStateTransition carrying a latent panic, dead startWebServer, a forced runtime.GC(), and a request counter that was written but never
    read.

Important changes of existing behaviour and user awareness:

  • /internal/status/models endpoints now returns endpoint names for every entry. It used to return the backend URL for the first occurrence and names after, which was just inconsistent. Anyone reading endpoints[0] as a URL needs to switch to names.
  • Chunked requests to non-proxy and translator endpoints now honour max_body_size.
  • X-Olla-* response headers from upstream are dropped, so a chained Olla-in-front-of-Olla setup loses the inner instance's headers.

Summary by CodeRabbit

  • New Features

    • Request body size validation enforced for non-proxy routes; configurable middleware available.
    • Sanitised inbound request IDs to prevent log injection.
  • Bug Fixes

    • Prevented streaming deadlocks by capping upstream error-body reads.
    • Improved concurrency and configuration consistency for proxy handling.
  • Security

    • Blocked upstream injection of platform-owned response headers.
    • Endpoint auth header no longer exposed in JSON status responses.
  • Tests

    • Added regression and concurrency tests covering size limits, header handling and config races.

@thushan thushan self-assigned this Jun 11, 2026
@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 95b18fcd-e9b4-426f-8c8c-ccf8e4b464da

📥 Commits

Reviewing files that changed from the base of the PR and between 3a151f5 and fa8dc46.

📒 Files selected for processing (3)
  • internal/adapter/proxy/core/common_test.go
  • internal/adapter/security/request_size_limit.go
  • internal/adapter/security/request_size_limit_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/adapter/proxy/core/common_test.go
  • internal/adapter/security/request_size_limit.go

Walkthrough

This PR implements Phase 3 security hardening and concurrency safety: atomic proxy configuration and compute-once endpoint resources, response-header canonicalisation and X-Olla-* stripping, non-proxy request-size enforcement, upstream error-body read caps, request-ID sanitisation, and allocation cleanup in status handlers, with tests.

Changes

Security & Concurrency Hardening Phase 3

Layer / File(s) Summary
Proxy service atomic configuration & concurrency safety
internal/adapter/proxy/olla/service.go, internal/adapter/proxy/olla/service_concurrency_test.go, internal/adapter/proxy/olla/service_leak_test.go, internal/adapter/proxy/olla/service_retry.go, internal/adapter/proxy/core/base.go, internal/adapter/proxy/olla/benchmark_url_building_test.go
Service.configuration becomes atomic.Pointer[Configuration]; streaming and retry paths snapshot config once per operation; endpoint pools and circuit-breakers use LoadOrCompute for one-time concurrent creation; per-request request/error pools removed; benchmarks/tests updated to use common.BuildTargetURL.
Response header spoofing prevention & auth field hiding
internal/adapter/proxy/core/common.go, internal/adapter/proxy/core/common_test.go, internal/core/domain/endpoint.go, internal/core/domain/json_safety_test.go
CopyResponseHeaders canonicalises keys once, checks deny-set against canonical name, and strips backend-injected X-Olla-* headers via HeaderXOllaPrefix; Endpoint.AuthHeaderName marked json:"-"; tests added.
Request body size validation for non-proxy routes
internal/adapter/security/request_size_limit.go, internal/adapter/security/factory.go, internal/adapter/security/request_size_limit_test.go, internal/app/handlers/application.go, internal/app/services/http.go, internal/router/registry.go, internal/router/registry_security_test.go
New CreateNonProxyMiddleware drains chunked bodies up to configured limit, returns 413 on overflow, restores drained bytes for downstream handlers; wired into handlers/router when adapters supply it; metrics/log recording centralised; tests added for chunked/known-length cases.
Upstream error body size limiting & deadlock prevention
internal/app/handlers/handler_translation.go, internal/app/handlers/handler_translation_security_test.go, internal/core/constants/security.go
Upstream error-body reads are capped at MaxUpstreamErrorBodyBytes via io.LimitReader and the pipe is closed (io.ErrClosedPipe) after the capped read to unblock writers; regression test verifies no deadlock.
Status response handler allocation cleanup & endpoint name consistency
internal/app/handlers/handler_status.go, internal/app/handlers/handler_status_models.go, internal/app/handlers/handler_status_models_test.go, internal/app/handlers/handler_status_race_test.go
Pooled global slices/maps removed; model summaries and grouping use per-request locals; ModelSummary.Endpoints consistently use endpoint names (fallback to URL when name missing); concurrency tests added.
Request ID sanitisation, constants & cleanup
internal/app/middleware/logging.go, internal/app/middleware/logging_test.go, internal/core/constants/security.go, internal/adapter/unifier/lifecycle_unifier.go, internal/app/handlers/server.go
Add sanitiseRequestID and maxRequestIDLength to prevent control-character/log-injection IDs; EnhancedLoggingMiddleware uses sanitized IDs; new security constants added; private lifecycle state-transition helper removed; startWebServer method removed.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • thushan/olla#113: Modifies proxy retry/path code; related to proxy config/timeout handling changes in this PR.
  • thushan/olla#81: Introduced common.BuildTargetURL and preserve-path logic; this PR updates tests/benchmarks to use that helper.
  • thushan/olla#146: Works in the proxy response-header/denylist area; related to CopyResponseHeaders hardening here.

Suggested labels

security, enhancement, bug

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The pull request title 'feat: olla hardening June 2026' is vague and generic. While it references the project (olla) and time period, it does not convey the specific, meaningful changes made in the changeset, such as concurrency fixes, security hardening, or the removal of dead code. Consider using a more descriptive title that captures the primary changes, such as 'feat: improve olla concurrency safety and security hardening' or break into more specific titles highlighting key improvements like atomic config pointers, request body size validation, and header sanitisation.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 93.62% 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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/olla-hardening-june-2026

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.

@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: 2

🧹 Nitpick comments (1)
internal/adapter/proxy/olla/service.go (1)

69-69: ⚡ Quick win

Add comment explaining why atomic configuration is needed.

The atomic.Pointer[Configuration] field lacks a comment explaining the concurrency rationale. Per coding guidelines, comments should explain "why" rather than "what". Consider adding a comment above line 69 explaining that atomicity prevents torn reads during hot config reloads.

📝 Suggested comment
 	// Buffer pool for streaming
 	bufferPool *pool.Pool[*[]byte]
 
 	transport     *http.Transport
+	// Configuration uses atomic.Pointer to ensure in-flight requests always read
+	// a complete, consistent snapshot during hot config reloads.
 	configuration atomic.Pointer[Configuration]
🤖 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 `@internal/adapter/proxy/olla/service.go` at line 69, Add a brief "why" comment
above the configuration atomic.Pointer[Configuration] field explaining the
concurrency rationale: note that the pointer is atomically loaded/stored to
allow lock-free, race-free hot configuration reloads and to prevent
torn/inconsistent reads across goroutines (rather than describing what
atomic.Pointer does); reference the use of atomic.Load/Store semantics and that
this choice avoids a mutex for frequent reads while supporting safe swaps during
updates.

Source: Coding guidelines

🤖 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 `@internal/adapter/proxy/core/common_test.go`:
- Around line 1025-1030: The test currently checks len(vals) with t.Errorf but
then immediately indexes vals[0], which can panic; change the length assertion
to a fatal assertion (use t.Fatalf) or return/stop the test when len(vals) != 1
so you never access vals[0] on an empty slice—update the block around the
len(vals) check in the test (the code that inspects vals and the
"X-Olla-Endpoint" expectation) so the test fails fast before the subsequent
vals[0] comparison.

In `@internal/adapter/security/request_size_limit.go`:
- Around line 185-193: The chunked-body overflow branch in request_size_limit.go
logs and returns without recording the violation, so update the overflow
handling blocks (the one inside the readErr != nil branch around the
sv.logger.Warn call and the similar branch between lines 205-238) to also call
the metrics recording function used elsewhere (recordViolation /
SecurityMetricsService.recordViolation) with the same contextual info (request r
and a "body_too_large" or equivalent reason) before writing the HTTP 413
response; ensure you call the same helper used by other size-limit rejects so
these chunked overflows are captured in SecurityMetricsService.

---

Nitpick comments:
In `@internal/adapter/proxy/olla/service.go`:
- Line 69: Add a brief "why" comment above the configuration
atomic.Pointer[Configuration] field explaining the concurrency rationale: note
that the pointer is atomically loaded/stored to allow lock-free, race-free hot
configuration reloads and to prevent torn/inconsistent reads across goroutines
(rather than describing what atomic.Pointer does); reference the use of
atomic.Load/Store semantics and that this choice avoids a mutex for frequent
reads while supporting safe swaps during updates.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a176c35b-9d45-436c-b6dd-f7083f7d8be7

📥 Commits

Reviewing files that changed from the base of the PR and between f0d87a4 and 3a151f5.

📒 Files selected for processing (32)
  • internal/adapter/proxy/core/base.go
  • internal/adapter/proxy/core/common.go
  • internal/adapter/proxy/core/common_test.go
  • internal/adapter/proxy/olla/benchmark_url_building_test.go
  • internal/adapter/proxy/olla/service.go
  • internal/adapter/proxy/olla/service_concurrency_test.go
  • internal/adapter/proxy/olla/service_leak_test.go
  • internal/adapter/proxy/olla/service_preserve_path_test.go
  • internal/adapter/proxy/olla/service_retry.go
  • internal/adapter/proxy/olla/service_transport_test.go
  • internal/adapter/proxy/olla/service_url_test.go
  • internal/adapter/proxy/olla/streaming_helpers.go
  • internal/adapter/security/factory.go
  • internal/adapter/security/request_size_limit.go
  • internal/adapter/security/request_size_limit_test.go
  • internal/adapter/unifier/lifecycle_unifier.go
  • internal/app/handlers/application.go
  • internal/app/handlers/handler_status.go
  • internal/app/handlers/handler_status_models.go
  • internal/app/handlers/handler_status_models_test.go
  • internal/app/handlers/handler_status_race_test.go
  • internal/app/handlers/handler_translation.go
  • internal/app/handlers/handler_translation_security_test.go
  • internal/app/handlers/server.go
  • internal/app/middleware/logging.go
  • internal/app/middleware/logging_test.go
  • internal/app/services/http.go
  • internal/core/constants/security.go
  • internal/core/domain/endpoint.go
  • internal/core/domain/json_safety_test.go
  • internal/router/registry.go
  • internal/router/registry_security_test.go
💤 Files with no reviewable changes (3)
  • internal/adapter/unifier/lifecycle_unifier.go
  • internal/adapter/proxy/core/base.go
  • internal/app/handlers/server.go

…r test

CodeRabbit pickup: the chunked-body 413 path was the only size-limit
rejection that didn't feed SecurityMetricsService, so those rejects were
invisible. Route it through recordViolation like every other path. Also
swap a t.Errorf for t.Fatalf so the header test fails fast instead of
panicking on an empty slice.
@thushan
thushan merged commit 455e501 into main Jun 11, 2026
5 checks passed
@thushan
thushan deleted the feature/olla-hardening-june-2026 branch June 11, 2026 06:08
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