Skip to content

feat: Authentication for local backends - #146

Merged
thushan merged 63 commits into
mainfrom
feature/local-auth
Jun 4, 2026
Merged

thushan merged 63 commits into
mainfrom
feature/local-auth

Conversation

@thushan

@thushan thushan commented May 15, 2026 •

Copy link
Copy Markdown
Owner

An attempt to address #132.

Adds per-endpoint auth for local backends. Three types: bearer, api_key, basic. Credentials come from inline strings, env vars (${VAR}), or _file siblings for Docker / k8s. Configurred per endpoint, not per profile. Also we're focused on local backends only.

auth:
type: bearer
token: "${VLLM_API_KEY}"

Works against vLLM / llama.cpp / LiteLLM with --api-key, or anything behind a bearer-auth reverse proxy. There's also a headers: map for custom outbound headers as an escape hatch.

The plumbing works for them but cloud-specific things (rate limits, model namespacing, path-prefix bases) aren't first-class concerns.

A few related things tagged along:

  • 401 / 403 from a health probe now show as config_error instead of dead
  • 429 honours Retry-After, doesn't trip the circuit breaker
  • POST retries skipped once response bytes have flushed (no double billing on RST mid-stream)
  • Upstream response headers get a strip list mirroring the request side, plus dynamic deny for any header named in the endpoint's auth or headers: config
  • HTTPS_PROXY removed from outbound proxy transports (kept on health)
  • Auth applied to model discovery too, not just proxy and health

Unresolved ${VAR} is fatal at startup with a suitable error message at startup rather than later, we figured.

Letting this simmer for a bit.

Summary by CodeRabbit

  • New Features

    • Per-endpoint outbound authentication (bearer, api_key, basic), env-var expansion and file-backed secrets, and endpoint-specific custom headers.
    • Health probes and model discovery send endpoint auth/headers; 429 Retry-After parsing enforces rate-limited scheduling.
    • Proxy injects auth into upstream requests and strips sensitive upstream headers; sensitive endpoint/auth data omitted from JSON outputs.
  • Documentation

    • New Endpoint Auth and Remote Backends (Experimental) guides plus integration and security updates.

thushan added 30 commits May 15, 2026 15:40
Health probes now carry the same per-endpoint auth and custom headers
that proxy requests do. Without this every authenticated backend gets
marked unhealthy on its first probe because it returns 401.

injectEndpointAuth applies endpoint.Headers then AuthHeaderName/Value
with the same precedence as CopyHeaders, but skips the client-request
strip logic that is inappropriate for synthesised probe requests.
401 and 403 from a health probe now map to StatusConfigError rather than
StatusUnhealthy. This tells the operator the backend is alive but the
credentials are wrong, and avoids tripping the circuit breaker on a
problem that retrying can never fix.

429 maps to StatusRateLimited using the same non-routable, no-CB logic.

Both statuses appear in /internal/status/endpoints so the operator can
distinguish a misconfigured endpoint from a genuinely dead one.
When a health probe receives 429, the Retry-After header is parsed
(delay-seconds and HTTP-date formats per RFC 9110) and stored as
RateLimitedUntil on the endpoint. The scheduler skips any endpoint
whose window hasn't elapsed, preventing quota exhaustion on throttled
backends.

Missing or malformed Retry-After falls back to 30s with an Info log
so the operator can investigate without the system going silent.
429 never trips the circuit breaker — it's a policy response, not a failure.
ExecuteWithRetry now suppresses failover for non-idempotent methods
(POST, PATCH, DELETE) when the response has already been committed to
the client. Retrying after bytes are flushed would double-charge metered
APIs or send the client a corrupted response from two different backends.

GET, HEAD and OPTIONS are unconditionally retried — they are defined as
idempotent by RFC 9110. The responseStartedWriter wrapper tracks whether
WriteHeader or Write has been called without allocating on the hot path.
Five end-to-end bash scripts covering bearer, api_key, basic, headers-only,
and the missing-env-var fatal case. Each script spins up the Go mock backend,
starts Olla with a generated config, and asserts both the happy path (correct
credential → 200) and the failure path (wrong credential → non-200). The
env-fatal script has no backend at all — it proves Olla exits non-zero with
the endpoint name and missing variable in the error message.
@thushan thushan self-assigned this May 15, 2026
@thushan thushan added documentation Improvements or additions to documentation enhancement New feature or request configuration Configuration bug or issue work in progress We're working on it labels May 15, 2026
@coderabbitai

coderabbitai Bot commented May 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Adds per-endpoint outbound authentication (bearer, api_key, basic) with env/_file secret resolution and header precomputation; health probes inject credentials and handle 429 Retry-After to mark rate-limited endpoints; proxy applies endpoint-aware headers and strips sensitive upstream response headers; extensive docs, tests, and integration scripts added.

Changes

Per-Endpoint Authentication System

Layer / File(s) Summary
Configuration types and profile hints
internal/config/types.go, internal/config/types_test.go, internal/core/domain/profile_config.go, config/profiles/*
Adds AuthConfig and EndpointConfig.Headers/Auth plus profile AuthHint and updates profiles to declare supported auth types.
Environment resolver
pkg/envresolver/resolver.go, pkg/envresolver/resolver_test.go, pkg/envresolver/platform_test.go
Implements ${VAR} and ${VAR:-default} expansion, strict expansion errors, and ExpandWithFile enforcing inline/_file precedence with trimming; tests cover edge cases.
Auth validation & header precomputation
internal/adapter/discovery/auth.go, internal/adapter/discovery/auth_test.go
Validates auth shapes per type, resolves credentials via env/file helpers, precomputes outbound header name/value (Authorization or custom header), and includes security tests to prevent leaking secrets in JSON.
Discovery repository & client
internal/adapter/discovery/repository.go, internal/adapter/discovery/http_client.go, tests
LoadFromConfig validates/resolves auth and headers into endpoint state; UpdateEndpoint persists RateLimitedUntil; discovery client includes endpoint headers/auth on requests; tests for authenticated discovery added.
Health checking, classification & scheduling
internal/adapter/health/*, internal/adapter/health/types.go
Health probes inject endpoint auth/headers, parse 429 Retry-After into RateLimitedUntil, classify 401/403 as StatusConfigError (no circuit-breaker trip), skip rate-limited endpoints, set ResponseHeaderTimeout; tests added.
Proxy header handling & retry safety
internal/adapter/proxy/core/common.go, internal/adapter/proxy/*, internal/adapter/proxy/core/retry.go
CopyHeaders gains endpoint context to apply Headers then auth (auth wins); CopyResponseHeaders strips sensitive and endpoint-configured response headers; services call endpoint-aware helpers; retry logic tracks response-start to avoid unsafe retries; transport header-timeouts added; tests updated/added.
Domain JSON safety & status fields
internal/core/domain/*
Endpoint and model fields updated to omit sensitive data from JSON (auth/header values, internal URLs); new status values for config_error and rate_limited; HealthCheckResult gains RateLimitedUntil; tests added.
Logging middleware
internal/app/middleware/logging.go, tests
Redacts sensitive query parameter values (token/password/etc.) in access logs via redactQuery; tests added.
Docs and navigation
docs/content/configuration/endpoint-auth.md, docs/content/configuration/endpoint-auth-remote.md, reference/FAQ/integrations, docs/mkdocs.yml
Comprehensive endpoint-auth docs, remote-backend recipes, examples (Docker/K8s), fail-fast validation rules, and nav entries; integration docs updated.
Integration tests, mock backend & scripts
test/cmd/mockbackend/*, test/scripts/auth/*, test/manual/config.auth.yaml, makefile, handler tests
Mock backend binary and bash scripts validate bearer/api_key/basic/header-only and missing-env fatal cases; shared test lib, handler-layer tests ensure auth flows through routes; makefile targets added.

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

  • thushan/olla#71: Both PRs modify internal/adapter/proxy/core/common.go’s CopyHeaders logic (header-copy behavior).
  • thushan/olla#113: Overlaps on changes to proxyToSingleEndpoint flow and proxy header handling.
✨ 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/local-auth

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

🤖 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/discovery/repository_test.go`:
- Around line 871-873: The test currently ignores the error returned by
repo.GetAll() (eps, _ := repo.GetAll(context.Background())) and then indexes
into eps which can mask repository failures; update the calls to check the
returned error from GetAll (e.g., eps, err := repo.GetAll(context.Background());
if err != nil { t.Fatalf("GetAll failed: %v", err) } or use require.NoError(t,
err)) before accessing eps and similarly fix the other occurrence around the
eps/ep usage (lines referencing eps, ep) so the test fails with a clear message
on repo errors instead of panicking.

In `@internal/adapter/health/client_auth_test.go`:
- Around line 65-83: The comment in TestHealthProbe_MissingAuth is outdated
about future refinement; update or remove the "Phase 6 will refine this to
StatusConfigError" phrasing because determineStatus in client.go already maps
HTTP 401 to domain.StatusConfigError. Edit the comment in
TestHealthProbe_MissingAuth to state the current behavior (401 is mapped to
StatusConfigError) or strip the Phase 6 reference so the test comment accurately
reflects determineStatus's mapping.

In `@internal/app/middleware/logging.go`:
- Around line 229-237: The redaction loop currently compares the raw key string
k (from strings.Cut(pair, "=")) against sensitiveQueryKeys, which allows
percent-encoded keys to bypass detection; update the logic in the loop that sets
k (and uses pair) to URL-decode the key (use url.QueryUnescape or equivalent)
before doing the sensitive-key comparison in the sensitiveQueryKeys loop and use
the decoded key only for the equality checks (keep the original pair/value
intact for reconstruction), and handle any decode errors by treating the key as
non-sensitive (i.e., fall back to the original k) so existing behavior is
preserved when decoding fails.

In `@pkg/envresolver/resolver.go`:
- Around line 32-34: The current use of os.Getenv(name) in resolver.go (the v :=
os.Getenv(name); v != "" check) conflates unset and explicitly empty environment
variables; change the lookup in the resolver function to use os.LookupEnv(name)
so you can detect existence (if exists { return v }) and thus return an
explicitly set empty string, or if the behavior was intentional add a clarifying
comment on the same check explaining why empty values should fall through to
defaults; update the code paths that reference this branch (the os.Getenv(...)
check) accordingly.

In `@test/scripts/auth/auth-env-fatal.sh`:
- Line 32: The MISSING_VAR assignment uses date +%s%N which breaks on macOS
because %N (nanoseconds) is unsupported; change the assignment of MISSING_VAR
(currently "OLLA_TEST_MISSING_TOKEN_$(date +%s%N)") to use a cross-platform
timestamp (e.g., seconds-only: $(date +%s)) or another portable uniqueness
method so the script runs on macOS and Linux for the auth-env-fatal.sh test.
🪄 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: be3f5d1a-c529-46df-9223-4960b0a57c4b

📥 Commits

Reviewing files that changed from the base of the PR and between 6d6ac4d and 10ad1e0.

📒 Files selected for processing (71)
  • config/profiles/litellm.yaml
  • config/profiles/llamacpp.yaml
  • config/profiles/ollama.yaml
  • config/profiles/openai-compatible.yaml
  • config/profiles/vllm.yaml
  • docs/content/configuration/endpoint-auth-remote.md
  • docs/content/configuration/endpoint-auth.md
  • docs/content/configuration/overview.md
  • docs/content/configuration/practices/security.md
  • docs/content/configuration/reference.md
  • docs/content/faq.md
  • docs/content/index.md
  • docs/content/integrations/backend/llamacpp.md
  • docs/content/integrations/backend/lmdeploy.md
  • docs/content/integrations/backend/lmstudio.md
  • docs/content/integrations/backend/ollama.md
  • docs/content/integrations/backend/vllm.md
  • docs/content/integrations/frontend/openwebui.md
  • docs/mkdocs.yml
  • internal/adapter/discovery/auth.go
  • internal/adapter/discovery/auth_test.go
  • internal/adapter/discovery/http_client.go
  • internal/adapter/discovery/http_client_test.go
  • internal/adapter/discovery/repository.go
  • internal/adapter/discovery/repository_test.go
  • internal/adapter/health/checker.go
  • internal/adapter/health/client.go
  • internal/adapter/health/client_auth_test.go
  • internal/adapter/health/client_classify_test.go
  • internal/adapter/health/client_ratelimit_test.go
  • internal/adapter/health/client_transport_test.go
  • internal/adapter/health/types.go
  • internal/adapter/proxy/config/unified.go
  • internal/adapter/proxy/core/common.go
  • internal/adapter/proxy/core/common_auth_test.go
  • internal/adapter/proxy/core/common_test.go
  • internal/adapter/proxy/core/retry.go
  • internal/adapter/proxy/core/retry_safety_test.go
  • internal/adapter/proxy/olla/service.go
  • internal/adapter/proxy/olla/service_retry.go
  • internal/adapter/proxy/olla/service_transport_test.go
  • internal/adapter/proxy/sherpa/service.go
  • internal/adapter/proxy/sherpa/service_retry.go
  • internal/adapter/proxy/sherpa/service_transport_test.go
  • internal/app/handlers/handler_auth_routes_test.go
  • internal/app/middleware/logging.go
  • internal/app/middleware/logging_test.go
  • internal/config/types.go
  • internal/config/types_test.go
  • internal/core/constants/auth.go
  • internal/core/constants/auth_test.go
  • internal/core/domain/auth_hint_test.go
  • internal/core/domain/endpoint.go
  • internal/core/domain/endpoint_test.go
  • internal/core/domain/healthcheck.go
  • internal/core/domain/json_safety_test.go
  • internal/core/domain/model.go
  • internal/core/domain/profile_config.go
  • internal/logger/styled_plain.go
  • makefile
  • pkg/envresolver/platform_test.go
  • pkg/envresolver/resolver.go
  • pkg/envresolver/resolver_test.go
  • test/cmd/mockbackend/main.go
  • test/manual/config.auth.yaml
  • test/scripts/auth/auth-api-key.sh
  • test/scripts/auth/auth-basic.sh
  • test/scripts/auth/auth-bearer.sh
  • test/scripts/auth/auth-env-fatal.sh
  • test/scripts/auth/auth-headers-only.sh
  • test/scripts/auth/lib.sh

Comment thread internal/app/middleware/logging.go Resolved
Comment thread pkg/envresolver/resolver.go Resolved
Comment thread test/scripts/auth/auth-env-fatal.sh Resolved

@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

🤖 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 `@test/scripts/auth/auth-env-fatal.sh`:
- Around line 111-116: The test currently treats any non-zero EXIT_CODE as a
successful "fail-fast" startup, which yields false positives when timeout (exit
code 124) occurs; update the conditional around EXIT_CODE to treat 124 as a
timeout failure instead of a valid non-zero failure: use EXIT_CODE to explicitly
detect timeout (124) and call fail with a message about the timeout, otherwise
if EXIT_CODE is a non-124 non-zero value call pass, and if EXIT_CODE is 0 call
fail that startup did not abort; reference EXIT_CODE and the pass/fail helpers
when making the change.
🪄 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: 13c6afdd-b511-4799-9c60-f9a82313c49c

📥 Commits

Reviewing files that changed from the base of the PR and between 10ad1e0 and 1189dfb.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (30)
  • CLAUDE.md
  • docs/content/development/setup.md
  • go.mod
  • internal/adapter/discovery/auth.go
  • internal/adapter/discovery/auth_test.go
  • internal/adapter/discovery/repository_test.go
  • internal/adapter/health/checker.go
  • internal/adapter/health/client.go
  • internal/adapter/health/client_auth_test.go
  • internal/adapter/health/client_ratelimit_test.go
  • internal/adapter/health/client_transport_test.go
  • internal/adapter/health/types.go
  • internal/adapter/proxy/core/common.go
  • internal/adapter/proxy/core/common_auth_test.go
  • internal/adapter/proxy/core/common_test.go
  • internal/adapter/proxy/core/retry.go
  • internal/adapter/proxy/core/retry_safety_test.go
  • internal/adapter/proxy/olla/service_transport_test.go
  • internal/adapter/proxy/sherpa/service_transport_test.go
  • internal/app/handlers/handler_auth_routes_test.go
  • internal/app/middleware/logging.go
  • internal/app/middleware/logging_test.go
  • internal/core/constants/auth.go
  • internal/core/domain/endpoint.go
  • internal/core/domain/json_safety_test.go
  • internal/core/domain/profile_config.go
  • pkg/envresolver/resolver.go
  • pkg/envresolver/resolver_test.go
  • test/cmd/mockbackend/main.go
  • test/scripts/auth/auth-env-fatal.sh
✅ Files skipped from review due to trivial changes (3)
  • docs/content/development/setup.md
  • go.mod
  • CLAUDE.md
🚧 Files skipped from review as they are similar to previous changes (23)
  • internal/adapter/health/types.go
  • internal/app/middleware/logging_test.go
  • internal/adapter/health/client_transport_test.go
  • internal/adapter/proxy/sherpa/service_transport_test.go
  • internal/core/domain/json_safety_test.go
  • internal/app/middleware/logging.go
  • internal/adapter/health/checker.go
  • internal/adapter/discovery/repository_test.go
  • test/cmd/mockbackend/main.go
  • internal/core/constants/auth.go
  • internal/adapter/proxy/olla/service_transport_test.go
  • internal/adapter/health/client_auth_test.go
  • pkg/envresolver/resolver_test.go
  • internal/core/domain/endpoint.go
  • internal/adapter/proxy/core/common_test.go
  • internal/adapter/proxy/core/retry.go
  • internal/adapter/discovery/auth_test.go
  • pkg/envresolver/resolver.go
  • internal/adapter/proxy/core/common.go
  • internal/app/handlers/handler_auth_routes_test.go
  • internal/adapter/health/client_ratelimit_test.go
  • internal/adapter/health/client.go
  • internal/core/domain/profile_config.go

Comment thread test/scripts/auth/auth-env-fatal.sh Resolved

@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.

🧹 Nitpick comments (1)
docs/content/configuration/endpoint-auth.md (1)

222-222: ⚡ Quick win

Optional: Add comma for readability.

The compound sentence "Olla removes it so the injected credential cannot leak back out" would read more smoothly with a comma before "so": "Olla removes it, so the injected credential cannot leak back out".

Suggested improvement
-backend and that backend echoes the header back in its response, Olla removes it so the injected
+backend and that backend echoes the header back in its response, Olla removes it, so the injected
 credential cannot leak back out. The strip is keyed on the header *name* you configured, not on
🤖 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 `@docs/content/configuration/endpoint-auth.md` at line 222, In the sentence
containing "Olla removes it so the injected credential cannot leak back out",
insert a comma after "it" so it reads "Olla removes it, so the injected
credential cannot leak back out" to improve readability.
🤖 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.

Nitpick comments:
In `@docs/content/configuration/endpoint-auth.md`:
- Line 222: In the sentence containing "Olla removes it so the injected
credential cannot leak back out", insert a comma after "it" so it reads "Olla
removes it, so the injected credential cannot leak back out" to improve
readability.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 38b96ffe-df84-4c69-aad5-3e7d9d9e815f

📥 Commits

Reviewing files that changed from the base of the PR and between 1189dfb and 450596a.

📒 Files selected for processing (3)
  • docs/content/configuration/endpoint-auth.md
  • internal/adapter/proxy/core/common_auth_test.go
  • test/scripts/auth/auth-env-fatal.sh
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/scripts/auth/auth-env-fatal.sh

@thushan thushan removed the work in progress We're working on it label Jun 4, 2026
@thushan
thushan merged commit 2ab9aa4 into main Jun 4, 2026
7 checks passed
@thushan
thushan deleted the feature/local-auth branch June 4, 2026 07:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

configuration Configuration bug or issue documentation Improvements or additions to documentation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant