Commit Graph
3 Commits
Author SHA1 Message Date
Arun Babu Neelicattu e8000b458d feat(server): parse and propagate cloud model token limits (#3568)
Parse context window and completion token limits across multiple provider payload structures (top-level fields, top_provider, and per_request_limits), resolving numeric string values gracefully. Propagate discovered limits into ModelInfo and /v1/models response serialization.
2026-09-18 00:10:14 +00:00
Joseph MelberandRamakrishnan Sivakumar f174a054c4 feat(cloud): relay Anthropic-wire-format providers through /v1/messages (#3223)
* feat(cloud): configurable auth header name and prefix per provider

Some OpenAI-compatible gateways authenticate with a differently-named
header and no "Bearer " prefix. Add optional auth_header_name and
auth_header_prefix to the cloud provider record, defaulting to the
previously hardcoded Authorization/Bearer so existing providers and
config files are unaffected.

install() now takes an options struct rather than a run of positional
strings, and the insecure-http opt-in uses a dedicated setter so a
partial update cannot silently reset the auth header to its default.

* fix(cloud): validate auth headers and stop re-install clobbering them

Address review feedback on the per-provider auth header settings.

Validate auth_header_name as a non-empty RFC 7230 token and reject
control characters in auth_header_prefix, at /v1/install and again in
load_from_config() for values arriving from a hand-edited config.json.
This closes the CRLF header-injection path and the empty-name case that
produced a malformed ": Bearer <key>" line, sending requests out
effectively unauthenticated. A bad value on disk falls back to the
default rather than disabling the provider.

InstallOptions fields are now optional and applied only when the request
supplies them, so a re-install that omits the auth flags — the desktop
add-provider form, or a CLI call that changes only --base-url — keeps
the provider's configured header instead of silently resetting it to
Authorization/Bearer and 401ing against the gateway.

Surface auth_header_prefix alongside auth_header_name in system-info and
the install response, and print both from `cloud list` when either is
non-default, quoting the prefix so an empty one is visible.

discover_models() and ResolvedCreds take the registry's AuthHeader
struct rather than two loose strings, and the three outbound auth sites
share one header-building helper.

* docs(cloud): explain the auth-header concept once

The comment-slop pre-commit hook flagged the auth header name/prefix
concept as re-explained at three sites. Keep the explanation on
CloudProviderRegistry::Record, where the fields are declared, and point
at it from the others.

* test(cloud): run the cloud discovery policy test in CI

The auth-header construction it covers was untested in packaging CI.

* feat(cloud): relay Anthropic-wire-format providers through /v1/messages

Some providers serve their models over the Anthropic Messages wire format
rather than OpenAI chat completions. Add a per-provider wire_format field
(default "openai") and, when it is "anthropic", relay /v1/messages to the
provider's /messages endpoint byte-for-byte, rewriting only the model id.

Passing the body through rather than converting it is both smaller and
lossless: thinking blocks, tool use, cache control, and future Anthropic
fields all survive. The OpenAI-shaped endpoints reject these providers with
a 400 pointing at /v1/messages, since the provider does not serve that shape.

* fix(cloud): send anthropic-version on discovery too

An anthropic-wire-format provider was only sent anthropic-version on the
/v1/messages relay, so a strict gateway rejected GET /models and the
provider registered zero models -- leaving the relay path unreachable.
Extract CloudServer::upstream_headers() so relay and discovery build the
same header map and cannot drift.

Document that the wire format and the auth header are independent
settings that usually go together, since the Anthropic API authenticates
with x-api-key rather than Authorization: Bearer.

* docs(cloud): trim restated wire-format and validator comments

* test(cloud): cover upstream header and URL construction

Adds the /v1-stripping upstream_url() helper so a gateway serving the
OpenAI shape at a base with no version segment is addressed correctly,
and unit-tests it alongside the default-auth-header case.

* docs(cloud): tighten anthropic wire-format prose

* docs(cloud): tighten wire-format comments

* refactor(cloud): build relay errors with the shared Anthropic helper

The relay hardcoded its own status-to-error-type mapping, duplicating
build_anthropic_error() and flattening 529 to a generic api_error.

* refactor(cloud): tighten upstream URL joining and relay ownership

Match /v1 on a segment boundary so an endpoint like /v1x is not
mis-joined, drop a redundant normalization now handled by upstream_url,
and move the relay context into the streaming provider instead of
copying it twice.

* fix(cloud): address review feedback on the Anthropic wire-format relay

- Forward `anthropic-beta` / `anthropic-version` from the client, and
  reattach `?beta=true` to the upstream URL where the API reads it.
- Start the upstream request before the handler returns so a non-200 is
  relayed as a real status instead of a 200 with an error body; httplib
  commits the status line only after the handler returns, so a chunked
  content provider cannot influence it.
- Relay `retry-after`, `request-id` and `anthropic-ratelimit-*` back to
  the client, which requires capturing response headers in HttpClient.
- Reject a registry entry with an empty checkpoint with an actionable
  500, matching what CloudServer::load() does for the OpenAI endpoints.
- Emit X-Lemonade-Warning on the relay path too, not just the converted
  one.
- Document that /chat/completions against an anthropic-wire provider
  reports its 400 as an SSE error frame when stream is true.

* fix(cloud): revert the threaded Anthropic streaming relay

The threaded handoff let the relay report a real upstream status on a
streaming request, but it blocked the handler before it returned — a
window where neither DataSink::is_writable nor ~Response's resource
releaser exists yet. A client that disconnected in that window stranded
the worker thread on an untimed wait with the upstream transfer still
open, permanently.

Measured against a hung upstream, 260 aborted streaming requests: the
server wedged at health=000 with 512 upstream connections held and never
recovered. The same load on the pre-change relay kept health=200 and held
zero connections.

Streaming goes back to doing all of its blocking inside the content
provider, where the peer is observable on every iteration. The cost is
that an upstream non-200 is again reported as an SSE error event on a
200; the docs now state that directly rather than claiming the status is
preserved on both paths.

The non-streaming path keeps the real status and the relayed
retry-after / request-id / anthropic-ratelimit-* headers.

* fix(http): honor the 0-means-default timeout convention on POST

HttpClient::get treated timeout_seconds=0 as "use default_timeout_seconds_",
but post, post_multipart, and post_stream passed it straight to CURLOPT_TIMEOUT,
where curl reads 0 as "no timeout". forward_request, post_with_auth, and the
router's streaming calls all default to 0, so a silent upstream held the calling
httplib worker indefinitely. The pool is bounded, so enough stalled requests
left the server unable to answer anything, including /health.

This also made global_timeout inert: it is pushed into set_default_timeout,
which only get consulted.

post_stream bounds silence rather than total duration, since a flat timeout
would cut off a long but healthy generation. kNoTimeout is the explicit opt-out
now that 0 has a meaning.

* fix(cloud): trim oversized test file-header comments

check_comment_slop's MAX_BLOCK_LINES=12 flags the file-header blocks
added in efb47a5e (review-fix commit). Trims restated per-function
walkthroughs, keeping the one non-obvious invariant per file, matching
the diff the reviewer verified in PR #3223.

---------

Co-authored-by: Ramakrishnan Sivakumar <[email protected]>
2026-08-26 11:15:35 +00:00
Mario LimoncielloandClaude 6c75ea4983 fix(security): harden HTTP redirects by trust boundary (#2634)
* fix(security): restrict libcurl redirect protocols to HTTPS only

Fixes SWSPLAT-24200 by adding security restrictions to all CURLOPT_FOLLOWLOCATION
usage in HttpClient to prevent SSRF, protocol downgrade attacks, and redirect-loop DoS.

Changes:
- Add CURLOPT_MAXREDIRS=5L to limit redirect chains
- Add CURLOPT_PROTOCOLS_STR="https" to restrict initial protocol
- Add CURLOPT_REDIR_PROTOCOLS_STR="https" to restrict redirect protocols

This prevents:
- HTTPS→HTTP downgrade attacks during backend binary downloads
- FTP/FILE protocol SSRF to internal network endpoints
- Infinite redirect loops causing DoS

Applied to all three locations that use CURLOPT_FOLLOWLOCATION:
1. HttpClient::get() - line 375
2. HttpClient::download_attempt() - line 683
3. HttpClient::download_attempt() HEAD request - line 842

Co-Authored-By: Claude <[email protected]>

* fix(security): harden HTTP redirects by trust boundary

Fixes SWSPLAT-24200 by splitting HttpClient security restrictions by
trust boundary so loopback backend RPC keeps working over http.

Policies (HttpSecurityPolicy):

- External hosts (HF, GitHub, release CDNs): https-only for the initial
  request and every redirect hop, MAXREDIRS=5.
- Lemonade-managed loopback backends: http only, redirects disabled
  entirely.
- Opt-in plaintext endpoints (cloud allow_insecure_http): http+https,
  bounded redirects.

A shared helper (apply_http_security_policy) applies the curl options
and checks each setopt return value, so a restriction that fails to
apply fails closed.

Added test for HTTPS-to-HTTP protocol downgrade rejection under the
external policy.

* fix(cloud): use correct security policy for loopback provider discovery

* fix(cloud): forward allow_insecure_http to discovery in refresh_cloud_models

refresh_cloud_models checked allow_insecure_http before proceeding but
then called discover_models() without passing it, so discovery fell back
to the ExternalHttpsOnly policy and rejected loopback/opted-in http://
providers with "Unsupported protocol".

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(cloud): derive discovery policy from scheme and opt-in

An HTTPS provider with a stale allow_insecure_http=true was selecting
AllowInsecureHttp, which permits redirect downgrades to http on the
Bearer-carrying discovery request. Derive the policy from both the URL
scheme and the opt-in so HTTPS providers stay HTTPS-only, extracted into
CloudServer::discovery_policy() with focused regression tests.

Also treat CURLE_UNSUPPORTED_PROTOCOL and CURLE_URL_MALFORMAT as
permanent download failures so the retry loop stops immediately and
preserves any existing partial file.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-07-14 00:02:35 +00:00