Skip to content

Add localhost reverse proxy for LLM gateway - #5035

Merged
yrobla merged 4 commits into
mainfrom
yrobla/thv-5029-llm-proxy
Apr 27, 2026
Merged

yrobla merged 4 commits into
mainfrom
yrobla/thv-5029-llm-proxy

Conversation

@yrobla

@yrobla yrobla commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements a localhost reverse proxy that bridges AI tools using static API keys (e.g. Cursor) to an OIDC-protected LLM gateway.

New `pkg/llm/proxy` package:

  • `proxy.go`: `httputil.ReverseProxy` wrapper that strips incoming `Authorization` headers, injects fresh OIDC tokens, and forwards to the configured gateway. Binds listener in `New()` so `Addr()` is valid before `Start()`. Loopback guard rejects non-localhost listen addresses. SSE streaming works without buffering (`FlushInterval: -1`). Graceful 5-second shutdown on context cancellation.

CLI wiring (`cmd/thv/app/llm.go`):

  • `thv llm proxy start`: runs in the foreground (blocking), consistent with all other `thv proxy` commands. Users who want background execution can use shell backgrounding (`thv llm proxy start &`) or a process manager.

No daemon/PID-file machinery — the proxy lifecycle follows the same foreground pattern as `thv proxy stdio` and `thv proxy tunnel`.

Fixes #5029

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (`task test`)
  • E2E tests (`task test-e2e`)
  • Linting (`task lint-fix`)
  • Manual testing (describe below)

API Compatibility

  • This PR does not break the `v1beta1` API, OR the `api-break-allowed` label is applied and the migration guidance is described above.

Changes

File Change
`pkg/llm/proxy/proxy.go` New: reverse proxy with token injection, listener binding, graceful shutdown
`pkg/llm/proxy/proxy_test.go` New: unit tests for loopback guard, token injection, streaming, error paths, ErrTokenRequired
`cmd/thv/app/llm.go` New `thv llm proxy start` command (foreground, blocking)

Does this introduce a user-facing change?

Yes. `thv llm proxy start` starts a localhost reverse proxy on `127.0.0.1:14000` (configurable) that transparently injects OIDC tokens for AI tools configured to use a static API key endpoint.

Special notes for reviewers

The proxy intentionally has no `stop` subcommand or PID-file daemon — this matches how all other ToolHive proxy commands work (`thv proxy stdio`, `thv proxy tunnel`). Users signal termination with Ctrl+C or their process manager.

@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Apr 23, 2026
@yrobla
yrobla requested a review from Copilot April 23, 2026 15:14
@codecov

codecov Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.88136% with 32 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.75%. Comparing base (624c6d0) to head (42dfab0).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/llm/proxy/proxy.go 72.04% 17 Missing and 9 partials ⚠️
pkg/llm/tokensource.go 42.85% 3 Missing and 1 partial ⚠️
pkg/networking/utilities.go 88.88% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5035      +/-   ##
==========================================
- Coverage   69.81%   69.75%   -0.07%     
==========================================
  Files         560      561       +1     
  Lines       56488    56606     +118     
==========================================
+ Hits        39439    39486      +47     
- Misses      14030    14083      +53     
- Partials     3019     3037      +18     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@yrobla
yrobla force-pushed the yrobla/thv-5029-llm-proxy branch from 52dcb1f to 44162cb Compare April 23, 2026 15:21
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 23, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds an LLM localhost reverse proxy and daemon lifecycle to bridge static-key AI tools (e.g., Cursor) to an OIDC-protected LLM gateway.

Changes:

  • Introduces pkg/llm/proxy reverse proxy that strips incoming Authorization, injects fresh OIDC tokens, and forwards to the gateway (including SSE passthrough).
  • Adds daemon management (PID file, start detached, stop) with Unix/Windows process handling and log redirection.
  • Wires new CLI commands: thv llm proxy start [--foreground] and thv llm proxy stop.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
pkg/llm/proxy/proxy.go Reverse proxy implementation + loopback guard + graceful shutdown.
pkg/llm/proxy/proxy_test.go Unit tests for loopback guard, auth injection/stripping, forwarding behavior, SSE/error passthrough.
pkg/llm/proxy/daemon.go PID/log file paths, running detection, detached start, stop behavior.
pkg/llm/proxy/daemon_unix.go Unix process liveness + SysProcAttr for detaching.
pkg/llm/proxy/daemon_windows.go Windows process liveness + SysProcAttr for detaching.
pkg/llm/proxy/daemon_test.go Unit tests for PID-file lifecycle and guardrails.
cmd/thv/app/llm.go CLI wiring for starting/stopping proxy (foreground/background).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/daemon_windows.go Resolved
Comment thread pkg/llm/proxy/daemon.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 23, 2026
@yrobla
yrobla requested a review from Copilot April 23, 2026 15:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 6 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/daemon.go Resolved
Comment thread pkg/llm/proxy/daemon.go Resolved
Comment thread pkg/llm/proxy/daemon.go Resolved
Comment thread pkg/llm/proxy/proxy_test.go Resolved
@yrobla
yrobla force-pushed the yrobla/thv-5029-llm-proxy branch from f38837e to d778f95 Compare April 23, 2026 15:49
@yrobla
yrobla requested a review from Copilot April 23, 2026 15:49
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 23, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 6 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/llm/proxy/proxy_test.go Resolved
Comment thread pkg/llm/proxy/proxy_test.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/daemon.go Resolved
Comment thread cmd/thv/app/llm.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/daemon.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
jerm-dro
jerm-dro previously approved these changes Apr 23, 2026
Comment thread cmd/thv/app/llm.go Resolved
Comment thread pkg/llm/proxy/daemon.go Resolved
@github-actions github-actions Bot added the size/M Medium PR: 300-599 lines changed label Apr 24, 2026
@yrobla
yrobla requested a review from Copilot April 24, 2026 11:27
JAORMX
JAORMX previously requested changes Apr 24, 2026

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Solid work on the scope trim since the last push. Dropping the daemon lifecycle and running the proxy in the foreground only was the right call. Requesting changes on two axes.

Reuse. The whole reason we're building this inside ToolHive and not as a standalone binary is that we already have the pieces. RFC-0070 §Alternatives Considered is explicit about this. So when we ship a second copy of something that already exists, the RFC's own argument for why this lives here starts to wobble. Two spots in the current diff:

  • checkLoopback in proxy.go:78 reinvents a narrow version of helpers already in pkg/networking/utilities.go (IsPrivateIP, AddressReferencesPrivateIp, IsLocalhost). RFC-0070 §Validation explicitly named ValidateLoopbackAddress as the shared helper. It never got added.
  • TokenSource construction is built twice in cmd/thv/app/llm.go: runLLMToken (lines 211-243) and runLLMProxyForeground (lines 335-360) have identical GetSystemSecretsProvider → NewScopedProvider(ScopeLLM) → updater → NewTokenSource pipelines, with a copy-pasted updater closure. thv llm setup will be the third caller when it lands.

Easier to consolidate now. Two callers today, three inevitable.

RFC compliance. Two gaps that matter:

  • Token-fetch failure now distinguishes ErrTokenRequired (good), but still returns 502 and writes err.Error() into the response body. RFC §Proxy is explicit: 401 + OpenAI-compatible JSON schema. Without this, the daemon silently stops working days later (rotated refresh token) and Cursor users see "Bad Gateway" with zero path to recovery. Writing err.Error() into the body also leaks internal error detail to whatever is on the other end.
  • No Host-header allowlist. DNS rebinding turns the proxy into an auth oracle for browser JS. Four-line fix, directly in RFC §Threat Model.
  • Minor: /healthz endpoint from RFC §Proxy isn't implemented. RFC also specified pkg/llm/internal/proxy.go; PR uses non-internal pkg/llm/proxy/. Either fix the layout or update the RFC.

Housekeeping. A few meta items:

  • The PR is behind main (mergeStateStatus: BEHIND, merge-base is 854e0ab7, main is at 68f4c2f1). Please rebase onto current main before merge so the diff view stops showing phantom deletions of pkg/llm/manage.go, pkg/oidc/*, and test/e2e/cli_llm_config_test.go from #5049.
  • Please squash the two "changes from review" fixups into the original commit.
  • Per .claude/rules/pr-creation.md, optional PR sections should be filled in or removed. The empty <details> block, the empty Changes table row, and the unused Does this introduce a user-facing change? section all want deletion.

Happy to re-review once the blockers land.

Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/llm/proxy/proxy_test.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
Comment thread pkg/llm/proxy/proxy_test.go Resolved
Comment thread pkg/llm/proxy/proxy_test.go Resolved
@yrobla
yrobla force-pushed the yrobla/thv-5029-llm-proxy branch from ec3b77e to 3862722 Compare April 24, 2026 13:22
taskbot added 2 commits April 24, 2026 15:22
Implements a background daemon that bridges AI tools using static API
keys (e.g. Cursor) to an OIDC-protected LLM gateway.

New pkg/llm/proxy package:
- proxy.go: httputil.ReverseProxy wrapper that strips incoming
  Authorization headers, injects fresh OIDC tokens, and forwards to
  the configured gateway. Binds listener in New() so Addr() is valid
  before Start(). Loopback guard rejects non-localhost listen addrs.
  SSE streaming works without buffering (FlushInterval: -1). Graceful
  5-second shutdown on context cancellation.
- daemon.go: PID-file lifecycle (IsRunning, Stop, StartDetached).
  StartDetached forks the current binary with TOOLHIVE_DETACHED=1,
  redirecting stdout/stderr to the XDG log file.
- daemon_unix.go / daemon_windows.go: platform-specific processAlive
  and SysProcAttr helpers via build tags.

CLI wiring (cmd/thv/app/llm.go):
- thv llm proxy start [--foreground]: background by default, foreground
  with --foreground or when running as detached child.
- thv llm proxy stop: sends SIGTERM via process.KillProcess and removes
  PID file.

Closes: #5029
@yrobla
yrobla force-pushed the yrobla/thv-5029-llm-proxy branch from 3862722 to f408829 Compare April 24, 2026 13:27
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/M Medium PR: 300-599 lines changed labels Apr 24, 2026
@yrobla
yrobla force-pushed the yrobla/thv-5029-llm-proxy branch from f408829 to f7d71bd Compare April 24, 2026 13:30
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 24, 2026
@yrobla
yrobla requested review from JAORMX and Copilot April 24, 2026 13:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/networking/utilities.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
Comment thread pkg/llm/proxy/proxy.go Resolved
@yrobla
yrobla force-pushed the yrobla/thv-5029-llm-proxy branch from f7d71bd to 54a617c Compare April 24, 2026 13:45
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 24, 2026
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 27, 2026
@yrobla
yrobla merged commit d8d58ca into main Apr 27, 2026
43 checks passed
@yrobla
yrobla deleted the yrobla/thv-5029-llm-proxy branch April 27, 2026 06:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

thv llm: localhost reverse proxy for proxy-mode tools

5 participants