Files
lemonade/test/cpp/test_anthropic_relay_headers.cpp
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

109 lines
4.6 KiB
C++

// Unit tests for the /v1/messages relay header allowlists.
//
// The relay rebuilds the request envelope rather than copying it, so these
// predicates are the only thing keeping a client's feature opt-in — or a
// provider's rate-limit window — from being silently dropped on the hop. The
// exclusions matter as much as the inclusions: forwarding a client's
// Authorization or the upstream Content-Length would break the relay outright.
//
// Checks use an explicit pass/fail counter (not assert()) so the test stays
// effective under the Release build the CI `default` preset uses, where
// -DNDEBUG would compile assert() to a no-op.
#include "lemon/anthropic_relay_headers.h"
#include <cstdio>
#include <string>
using lemon::anthropic::is_forwardable_request_header;
using lemon::anthropic::is_forwardable_response_header;
struct TestResult {
int passed = 0;
int failed = 0;
void check(bool condition, const std::string& name) {
printf("[%s] %s\n", condition ? "PASS" : "FAIL", name.c_str());
if (condition) {
++passed;
} else {
++failed;
}
}
};
static void test_request_headers(TestResult& r) {
r.check(is_forwardable_request_header("anthropic-beta"),
"anthropic-beta forwarded (SDK feature opt-ins)");
r.check(is_forwardable_request_header("anthropic-version"),
"anthropic-version forwarded (client pin beats the default)");
// The relay sets its own auth from the provider's configured header; a
// client value must never reach upstream.
r.check(!is_forwardable_request_header("authorization"),
"authorization not forwarded");
r.check(!is_forwardable_request_header("x-api-key"),
"x-api-key not forwarded");
// The body is re-serialized after the model rewrite, so a copied
// Content-Length would describe the wrong body.
r.check(!is_forwardable_request_header("content-length"),
"content-length not forwarded");
r.check(!is_forwardable_request_header("host"), "host not forwarded");
r.check(!is_forwardable_request_header("connection"),
"hop-by-hop connection not forwarded");
r.check(!is_forwardable_request_header("content-type"),
"content-type not forwarded (relay sets application/json)");
// The predicate takes an already-lowercased name; a caller that forgets to
// normalize should miss rather than match by accident.
r.check(!is_forwardable_request_header("Anthropic-Beta"),
"match is exact on the lowercased name");
r.check(!is_forwardable_request_header("anthropic-beta-extra"),
"no prefix match on request names");
r.check(!is_forwardable_request_header(""), "empty name not forwarded");
}
static void test_response_headers(TestResult& r) {
r.check(is_forwardable_response_header("retry-after"),
"retry-after relayed (SDK backoff)");
r.check(is_forwardable_response_header("request-id"),
"request-id relayed (escalation to the provider)");
// Prefix match: the family is open-ended, so naming each member would rot.
r.check(is_forwardable_response_header("anthropic-ratelimit-requests-reset"),
"anthropic-ratelimit-requests-reset relayed");
r.check(is_forwardable_response_header("anthropic-ratelimit-tokens-remaining"),
"anthropic-ratelimit-tokens-remaining relayed");
r.check(is_forwardable_response_header("anthropic-ratelimit-"),
"bare anthropic-ratelimit- prefix matches");
r.check(!is_forwardable_response_header("anthropic-ratelimi"),
"partial prefix does not match");
r.check(!is_forwardable_response_header("x-anthropic-ratelimit-requests-reset"),
"prefix is anchored at the start of the name");
// Relaying these would conflict with what httplib writes for the chunked
// SSE response the relay actually sends.
r.check(!is_forwardable_response_header("content-length"),
"content-length not relayed");
r.check(!is_forwardable_response_header("transfer-encoding"),
"transfer-encoding not relayed");
r.check(!is_forwardable_response_header("content-type"),
"content-type not relayed");
r.check(!is_forwardable_response_header("set-cookie"),
"set-cookie not relayed");
r.check(!is_forwardable_response_header(""), "empty name not relayed");
}
int main() {
TestResult r;
printf("=== Anthropic Relay Header Allowlist Unit Tests ===\n\n");
test_request_headers(r);
test_response_headers(r);
printf("\n%d/%d tests passed\n", r.passed, r.passed + r.failed);
return r.failed == 0 ? 0 : 1;
}