diff --git a/.gitignore b/.gitignore index c119c9a..30b128b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ *.o junction tests/stub +tests/oauth_probe junction.conf # Python bytecode from the test helpers diff --git a/Makefile b/Makefile index 0daa533..229b3a3 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ LDFLAGS ?= PREFIX ?= /usr/local J_WITH_TLS ?= auto -SRC = src/mesh.c src/mcp.c src/control.c src/control_ops.c src/compress.c src/price.c src/models.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/effort.c src/judge.c src/review.c src/junction.c +SRC = src/oauth.c src/mesh.c src/mcp.c src/control.c src/control_ops.c src/compress.c src/price.c src/models.c src/config.c src/conn.c src/http.c src/cache.c src/opencode.c src/effort.c src/judge.c src/review.c src/junction.c OBJ = $(SRC:.c=.o) TOOLS = tools/junction-wol diff --git a/README.md b/README.md index 5f26366..723ae10 100644 --- a/README.md +++ b/README.md @@ -757,6 +757,34 @@ Endpoint: | `auth_basic ` | HTTP Basic instead of a bearer token (opencode wants this) | | `pass_cmd ` | stdout is the password — opencode makes a new one on every start | | `base_cmd ` | stdout is the base URL — the background server binds a random port. The health check and the request path both use this value, not the static `base`, so a service that restarts on a new port is picked up without restarting junction | + | `oauth` | `on` / `off` — the key is a Claude subscription token, not an API key (see below) | + +### Claude subscription tokens (`oauth on`) + +A `CLAUDE_CODE_OAUTH_TOKEN` (`sk-ant-oat01…`) is not an API key. Anthropic accepts it +only on requests that carry Claude Code's system prompt; with an ordinary body a +current model answers `429 rate_limit_error` with the message `Error` — the same +status and the same shape a real quota exhaustion has. An endpoint that "works +sometimes" is usually this, not a limit. + +`oauth on` puts that system prompt in place, and only for the endpoints that ask for +it. Which models are gated is not uniform: retired names such as +`claude-haiku-4-5-20251001` still answer without the prompt, so a test against one of +them proves nothing. `claude-sonnet-5-5`, `claude-haiku-5-5`, `claude-opus-5` and +`claude-opus-4-8` are gated (measured 2026-11-24, each case repeated). + +The client's own system prompt is kept, not replaced: + +* `/v1/messages` — the marker becomes the first block of `system`, the client's text + follows as further blocks, `cache_control` included. +* `/v1/chat/completions` — the system content must be the marker *alone* there, so + the client's system text moves into the conversation as a user message before the + first turn. Appending it to the marker, or adding a second block, is rejected. + +The marker is matched byte for byte server-side; a missing final period or a trailing +newline is worth the same as no marker at all. Nothing is rewritten for an endpoint +without this line, and a body junction cannot parse goes upstream unchanged — the +provider then answers as it would have without junction. With `kind opencode`, the bridge carries the client's reasoning effort into the session: `reasoning_effort` (Chat Completions), `reasoning.effort` (Responses), an diff --git a/config.example b/config.example index cc0ea29..bdc83f0 100644 --- a/config.example +++ b/config.example @@ -154,6 +154,24 @@ endpoint opencode-go { # header "anthropic-version: 2023-06-01" # } +# A Claude subscription token (CLAUDE_CODE_OAUTH_TOKEN, sk-ant-oat01…) is not an API +# key: Anthropic accepts it only on requests that carry Claude Code's system prompt. +# Without that prompt a current model answers 429 rate_limit_error "Error", which is +# indistinguishable from an exhausted quota — so the endpoint looks broken at random. +# `oauth on` puts the prompt in place and keeps the client's own system text (native +# path: as further blocks; /v1/chat/completions: as a user message before the first +# turn). Nothing is rewritten without this line. See src/oauth.c for the measurements. +# endpoint claude-abo { +# base https://api.anthropic.com/v1 +# kind anthropic +# oauth on +# context 200000 +# timeout 900 +# idle_timeout 120 +# api_key_env CLAUDE_CODE_OAUTH_TOKEN +# header "anthropic-version: 2023-06-01" +# } + # --------------------------------------------------------------------------- mcp # # This turns junction into an MCP server itself: an agent connects to diff --git a/src/config.c b/src/config.c index 89bc3a3..ceece8c 100644 --- a/src/config.c +++ b/src/config.c @@ -778,6 +778,16 @@ static int endpoint_kw(j_endpoint *ep, char **w, int n, int lineno, char *err, s else goto bad; return 0; } + if (!strcmp(k, "oauth")) { + /* oauth on|off — der Schlüssel ist ein Abo-Token (sk-ant-oat01…), kein API-Key. + * Anthropic nimmt so einen Token nur mit dem Claude-Code-Systemprompt an; oauth.c + * setzt ihn. Nicht raten: nur wer es hier anschaltet, bekommt den Marker. */ + if (n != 2) goto bad; + if (!strcmp(w[1], "on")) ep->oauth = 1; + else if (!strcmp(w[1], "off")) ep->oauth = 0; + else goto bad; + return 0; + } if (!strcmp(k, "max_model_inflight")) { /* max_model_inflight 1 — eine Anfrage je Modell gleichzeitig, der Rest wartet. * Für Boxen gedacht, die ein Modell im Speicher halten: die zweite Anfrage diff --git a/src/config.h b/src/config.h index b227675..0e1c4a6 100644 --- a/src/config.h +++ b/src/config.h @@ -203,6 +203,14 @@ typedef struct { * /models Geld kostet oder das absichtlich schläft). */ int probe_on; + /* 1 = der Schlüssel ist ein OAuth-Token aus einem Claude-Abo (sk-ant-oat01…), kein + * API-Key. Anthropic nimmt so einen Token nur auf Anfragen an, die den Claude-Code- + * Systemprompt tragen; ohne ihn antwortet der Dienst mit 429, was wie ein + * aufgebrauchtes Kontingent aussieht. Gesetzt wird der Marker in oauth.c — nur hier, + * nie geraten: ein falscher Raten würde Prompts für Konten umschreiben, die ihn + * nie gebraucht hätten. */ + int oauth; + /* runtime state — not from the file */ double offline_until; double cooldown_until; diff --git a/src/junction.c b/src/junction.c index e65890c..efc9f1c 100644 --- a/src/junction.c +++ b/src/junction.c @@ -24,6 +24,7 @@ void j_control_ops_install(void); #include "conn.h" #include "http.h" #include "effort.h" +#include "oauth.h" #include #include @@ -2978,6 +2979,32 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, } } + /* An OAuth token from a Claude subscription is only accepted on requests that + * carry Claude Code's system prompt; without it the API answers 429, which reads + * like an exhausted quota. The rewrite goes last, after the model and effort + * rewrites, so it only has to move the system prompt and never fights another + * transformation for the same bytes. Endpoints opt in with `oauth on`. */ + if (ep->oauth && out_body && out_len && + (!strncmp(rq->path, "/v1/messages", 12) || + !strncmp(rq->path, "/v1/chat/completions", 20))) { + int compat = strncmp(rq->path, "/v1/messages", 12) != 0; + if (j_oauth_needed(out_body, out_len, compat)) { + char *marked = NULL; + size_t marked_len = 0; + /* 0 = rewritten, 1 = already correct, -1 = not ours. Only 0 replaces the + * body; anything else goes upstream as the client wrote it. */ + if (j_oauth_body(out_body, out_len, compat, &marked, &marked_len) == 0) { + free(body_alloc); + body_alloc = marked; + out_body = marked; + out_len = marked_len; + } + /* On failure the original body goes upstream unchanged: the provider then + * answers exactly as it would have without junction, which is more useful + * than a request junction invented. */ + } + } + j_conn up = J_CONN_INIT; if (j_conn_open(&up, host, port, tls, tls ? ep->tls_verify : 0, ep->tls_ca, ep->connect_timeout_ms > 0 ? ep->connect_timeout_ms : CFG.connect_timeout_ms, diff --git a/src/oauth.c b/src/oauth.c new file mode 100644 index 0000000..1ebc89c --- /dev/null +++ b/src/oauth.c @@ -0,0 +1,615 @@ +/* junction/oauth.c — make an Anthropic OAuth token usable as an endpoint key. + * + * Why this exists: Claude accounts have two kinds of credential, and they are not + * interchangeable. An API key (`sk-ant-api…`) is a plain bearer token and works for + * any request. An OAuth token from a Claude subscription (`sk-ant-oat01…`) is only + * accepted on requests that look like they come from Claude Code itself; sent with an + * ordinary body, Anthropic answers `429 rate_limit_error` with the message "Error" — + * a rate limit that is not one, reported identically to a real quota exhaustion, so + * the operator sees an endpoint that "sometimes works". + * + * Measured against api.anthropic.com on 2026-11-24, every case repeated at least twice. + * + * Which models are gated is not uniform, and that is the trap: the model names that + * used to be current (`claude-haiku-4-5-20251001`) answer 200 without the marker, so a + * test against one of them proves nothing. The current ones — `claude-sonnet-5-5`, + * `claude-haiku-5-5`, `claude-opus-5`, `claude-opus-4-8` — answer 429 without it and + * 200 with it. Assume every current model is gated and check a gated one. + * + * body native /v1/messages /v1/chat/completions + * no system at all 429 429 + * system = 429 429 + * system = 200 200 + * system = [, ] 200 429 + * system = [, ] 429 429 + * + * The marker is one exact string, matched byte for byte. A trailing newline, a missing + * final period, a leading space, a reworded variant, lower case, or the marker merged + * with other text into one block all fail — "almost right" is worth nothing here. + * Its position is "first": later blocks are free, earlier ones are not. The + * `anthropic-beta: oauth-2025-04-20` header is *not* what decides this — the body is; + * the header was present in every trial and removing it changed nothing. + * + * The two paths therefore need different things, and this is where a plausible guess + * goes wrong: + * + * native the marker leads a LIST of blocks, and the client's own system prompt + * follows it as further blocks. Nothing is lost. + * compat the system content must be the marker ALONE. A second block, or the marker + * with text appended, gives 429 invalid_request_error. There is nowhere to + * keep the client's system text in the system slot, so it moves into the + * conversation as its own user message before the first turn — measured to + * be accepted, and it keeps the operator's instructions instead of dropping + * them silently. + * + * So this module does exactly one thing: make the request look like a Claude Code + * request, without inventing, dropping or reordering anything the client sent. + * + * It runs only for endpoints that opt in (`oauth on`), never by guessing from the key's + * shape: a wrong guess here would rewrite prompts for accounts that never needed it. + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include + +#include "oauth.h" + +/* The exact string Anthropic's gate looks for. Changing a byte breaks it. */ +const char j_oauth_marker[] = + "You are a Claude agent, built on Anthropic's Claude Agent SDK."; + +typedef struct { + char *buf; + size_t len; + size_t cap; +} ob; + +static int ob_app(ob *b, const char *s, size_t n) +{ + if (n > b->cap - b->len - 1) return -1; + memcpy(b->buf + b->len, s, n); + b->len += n; + b->buf[b->len] = '\0'; + return 0; +} + +static int ob_apps(ob *b, const char *s) +{ + return ob_app(b, s, strlen(s)); +} + +/* JSON-escape a raw string into the buffer, quotes included. */ +static int ob_json_string(ob *b, const char *s, size_t n) +{ + if (ob_app(b, "\"", 1) != 0) return -1; + for (size_t i = 0; i < n; i++) { + unsigned char c = (unsigned char)s[i]; + char tmp[8]; + size_t tn = 1; + switch (c) { + case '"': tmp[0] = '\\'; tmp[1] = '"'; tn = 2; break; + case '\\': tmp[0] = '\\'; tmp[1] = '\\'; tn = 2; break; + case '\n': tmp[0] = '\\'; tmp[1] = 'n'; tn = 2; break; + case '\r': tmp[0] = '\\'; tmp[1] = 'r'; tn = 2; break; + case '\t': tmp[0] = '\\'; tmp[1] = 't'; tn = 2; break; + default: + if (c < 0x20) { + snprintf(tmp, sizeof tmp, "\\u%04x", (unsigned)c); + tn = strlen(tmp); + } else { + tmp[0] = (char)c; + } + break; + } + if (ob_app(b, tmp, tn) != 0) return -1; + } + return ob_app(b, "\"", 1); +} + +static const char *skip_ws(const char *p, const char *end) +{ + while (p < end && isspace((unsigned char)*p)) p++; + return p; +} + +static const char *skip_string(const char *p, const char *end) +{ + if (p >= end || *p != '"') return NULL; + p++; + while (p < end) { + if (*p == '\\') { + if (p + 1 >= end) return NULL; + p += 2; + continue; + } + if (*p == '"') return p + 1; + p++; + } + return NULL; +} + +/* Skip one JSON value. Strings are skipped whole, so a brace inside a prompt never + * ends the enclosing object early. */ +static const char *skip_value(const char *p, const char *end) +{ + p = skip_ws(p, end); + if (p >= end) return NULL; + if (*p == '"') return skip_string(p, end); + if (*p != '{' && *p != '[') { + while (p < end && *p != ',' && *p != '}' && *p != ']' && + !isspace((unsigned char)*p)) + p++; + return p; + } + char stack[64]; + int depth = 0; + while (p < end) { + if (*p == '"') { + p = skip_string(p, end); + if (!p) return NULL; + continue; + } + if (*p == '{' || *p == '[') { + if (depth >= (int)sizeof stack) return NULL; + stack[depth++] = *p++; + } else if (*p == '}' || *p == ']') { + if (depth == 0) return NULL; + char open = stack[--depth]; + if ((*p == '}' && open != '{') || (*p == ']' && open != '[')) return NULL; + p++; + if (depth == 0) return p; + } else { + p++; + } + } + return NULL; +} + +/* Locate a top-level field. Nested objects are skipped as a whole. */ +static int obj_field(const char *body, const char *end, const char *name, + const char **ks_out, const char **vs_out, const char **ve_out) +{ + const char *p = skip_ws(body, end); + if (p >= end || *p != '{') return 0; + p++; + size_t nm = strlen(name); + for (;;) { + p = skip_ws(p, end); + if (p >= end || *p == '}' || *p != '"') return 0; + const char *ks = p; + const char *ke = skip_string(p, end); + if (!ke) return 0; + size_t klen = (size_t)((ke - 1) - (ks + 1)); + p = skip_ws(ke, end); + if (p >= end || *p != ':') return 0; + p = skip_ws(p + 1, end); + const char *vs = p; + const char *ve = skip_value(p, end); + if (!ve) return 0; + if (klen == nm && memcmp(ks + 1, name, nm) == 0) { + if (ks_out) *ks_out = ks; + if (vs_out) *vs_out = vs; + if (ve_out) *ve_out = ve; + return 1; + } + p = skip_ws(ve, end); + if (p < end && *p == ',') { p++; continue; } + return 0; + } +} + +/* Is the JSON value VS..VE the string LIT, byte for byte? */ +static int value_is_string(const char *vs, const char *ve, const char *lit) +{ + if (!vs || vs >= ve || *vs != '"') return 0; + const char *se = skip_string(vs, ve); + if (!se) return 0; + size_t n = (size_t)((se - 1) - (vs + 1)); + return n == strlen(lit) && memcmp(vs + 1, lit, n) == 0; +} + +/* Is this message object's role "system"? Reads the VALUE of the role field. + * Checking the field NAME instead — comparing the key "role" against "system" — is a + * mistake that compiles, never matches, and silently leaves the client's system + * message in place while adding a second one. */ +static int message_is_system(const char *obj, const char *end) +{ + const char *vs = NULL, *ve = NULL; + return obj_field(obj, end, "role", NULL, &vs, &ve) && + value_is_string(vs, ve, "system"); +} + +/* Does the value start with a string that is exactly the marker? */ +static int string_is_marker(const char *vs, const char *ve) +{ + return value_is_string(vs, ve, j_oauth_marker); +} + +/* Does this system value already lead with the marker? + * + * Both shapes count: a plain string equal to the marker, and an array whose FIRST + * block carries the marker as its text. Without the array case the rewrite wrapped a + * body that was already correct and produced two marker blocks — accepted by the API, + * so it would have hidden as a cosmetic bug in a doubled prompt. */ +static int value_leads_with_marker(const char *vs, const char *ve) +{ + if (!vs || vs >= ve) return 0; + if (*vs == '"') return string_is_marker(vs, ve); + if (*vs != '[') return 0; + + const char *end = ve - 1; /* the ']' */ + const char *p = skip_ws(vs + 1, end); + if (p >= end || *p != '{') return 0; + const char *be = skip_value(p, end); + if (!be) return 0; + const char *ts = NULL, *te = NULL; + if (!obj_field(p, be, "text", NULL, &ts, &te)) return 0; + return string_is_marker(ts, te); +} + +/* Decode a JSON string token into raw bytes. Returns length or -1. */ +static long decode_string(const char *vs, const char *ve, char *out, size_t cap) +{ + if (!vs || vs >= ve || *vs != '"') return -1; + const char *p = vs + 1; + const char *q = ve - 1; + size_t o = 0; + while (p < q) { + unsigned char c = (unsigned char)*p++; + if (c == '\\' && p < q) { + char e = *p++; + switch (e) { + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'b': c = '\b'; break; + case 'f': c = '\f'; break; + case 'u': { + /* Junction never needs the code point itself, only a faithful copy. + * Without a UTF-8 encoder, keep the escape as written. */ + if (q - p < 4) return -1; + if (o + 6 >= cap) return -1; + out[o++] = '\\'; + out[o++] = 'u'; + for (int k = 0; k < 4; k++) out[o++] = *p++; + continue; + } + default: c = (unsigned char)e; break; + } + } + if (o + 1 >= cap) return -1; + out[o++] = (char)c; + } + out[o] = '\0'; + return (long)o; +} + +int j_oauth_is_marker(const char *s, size_t n) +{ + size_t m = strlen(j_oauth_marker); + return n == m && memcmp(s, j_oauth_marker, m) == 0; +} + +/* ------------------------------------------------------------ native Messages API + * + * `system` may be a string or an array of blocks. The result is always an array whose + * first block is the marker. Everything the client wrote follows unchanged, including + * its cache_control markers and any other block types. + */ +/* Returns 0 when the body was rewritten into OUT, 1 when it already led with the + * marker (nothing written), -1 when the shape is not one this can touch. Keeping + * "nothing to do" distinct from "done" matters: a caller that treats every 0 as + * "use *out" would otherwise send an empty body upstream. */ +static int native_with_marker(const char *body, const char *end, ob *out) +{ + /* A Messages request without a messages array is not a chat request: a token + * count, a batch entry, something else with a `system`-shaped field. Rewriting it + * would put a prompt where the provider expects a number. Leave it alone. */ + if (!obj_field(body, end, "messages", NULL, NULL, NULL)) return -1; + + const char *sys_k = NULL, *sys_vs = NULL, *sys_ve = NULL; + int has_sys = obj_field(body, end, "system", &sys_k, &sys_vs, &sys_ve); + if (has_sys && value_leads_with_marker(sys_vs, sys_ve)) return 1; + + /* Walk the object and replace only the system field (or add it). */ + const char *p = skip_ws(body, end); + if (p >= end || *p != '{') return -1; + p++; + if (ob_apps(out, "{") != 0) return -1; + int first = 1; + int emitted_sys = 0; + + for (;;) { + p = skip_ws(p, end); + if (p >= end) return -1; + if (*p == '}') break; + if (*p != '"') return -1; + const char *ks = p; + const char *ke = skip_string(p, end); + if (!ke) return -1; + p = skip_ws(ke, end); + if (p >= end || *p != ':') return -1; + const char *colon = p; + p = skip_ws(p + 1, end); + const char *vs = p; + const char *ve = skip_value(p, end); + if (!ve) return -1; + + size_t klen = (size_t)((ke - 1) - (ks + 1)); + int is_sys = (klen == 6 && memcmp(ks + 1, "system", 6) == 0); + + if (!first && ob_apps(out, ",") != 0) return -1; + first = 0; + + if (is_sys) { + emitted_sys = 1; + if (ob_app(out, ks, (size_t)(ke - ks)) != 0) return -1; + if (ob_app(out, colon, 1) != 0) return -1; + if (ob_apps(out, "[{\"type\":\"text\",\"text\":") != 0) return -1; + if (ob_json_string(out, j_oauth_marker, strlen(j_oauth_marker)) != 0) + return -1; + if (ob_apps(out, "}") != 0) return -1; + if (vs < ve && *vs == '"') { + /* A string becomes a second block; its decoded bytes are re-encoded. */ + size_t cap = (size_t)(ve - vs) + 1; + char *raw = malloc(cap); + if (!raw) return -1; + long n = decode_string(vs, ve, raw, cap); + if (n < 0 || (n == 0)) { + /* An empty system string adds no block. */ + free(raw); + } else { + if (ob_apps(out, ",{\"type\":\"text\",\"text\":") != 0 || + ob_json_string(out, raw, (size_t)n) != 0 || + ob_apps(out, "}") != 0) { + free(raw); + return -1; + } + free(raw); + } + } else if (vs < ve && *vs == '[') { + /* Array of blocks: append its members after the marker block. */ + const char *q = skip_ws(vs + 1, ve); + if (q < ve - 1) { + if (ob_apps(out, ",") != 0) return -1; + /* Copy everything between the brackets verbatim. */ + const char *inner_end = ve - 1; + while (inner_end > q && isspace((unsigned char)inner_end[-1])) + inner_end--; + if (ob_app(out, q, (size_t)(inner_end - q)) != 0) return -1; + } + } else if (!(ve - vs == 4 && memcmp(vs, "null", 4) == 0)) { + /* null means "no system prompt" and is fine to replace with the marker + * alone. Anything else here (a number, a boolean) is not a body this + * module understands: leave it to the provider. */ + return -1; + } + if (ob_apps(out, "]") != 0) return -1; + } else { + if (ob_app(out, ks, (size_t)(ve - ks)) != 0) return -1; + } + + p = skip_ws(ve, end); + if (p < end && *p == ',') { p++; continue; } + if (p < end && *p == '}') break; + return -1; + } + + if (!emitted_sys) { + if (!first && ob_apps(out, ",") != 0) return -1; + if (ob_apps(out, "\"system\":[{\"type\":\"text\",\"text\":") != 0) return -1; + if (ob_json_string(out, j_oauth_marker, strlen(j_oauth_marker)) != 0) return -1; + if (ob_apps(out, "}]") != 0) return -1; + } + return ob_apps(out, "}"); +} + +/* ------------------------------------------------------------- OpenAI-compatible + * + * Here the system content must be the marker and nothing else: a second block, or the + * marker with text appended, is rejected with 429 invalid_request_error. The client's + * own system text is therefore carried over as its own user message right before the + * first real turn — measured to be accepted, and it keeps the operator's instructions + * instead of silently dropping them. + */ +static int compat_with_marker(const char *body, const char *end, ob *out) +{ + const char *msgs_k = NULL, *msgs_vs = NULL, *msgs_ve = NULL; + if (!obj_field(body, end, "messages", &msgs_k, &msgs_vs, &msgs_ve)) return -1; + if (msgs_vs >= msgs_ve || *msgs_vs != '[') return -1; + + /* Collect the client's system messages and note the first non-system one. */ + struct { const char *s; size_t n; } carrier[8]; + size_t carrier_n = 0; + int already_marked = 0; + + const char *p = skip_ws(msgs_vs + 1, msgs_ve); + const char *arr_end = msgs_ve - 1; /* the ']' */ + while (p < arr_end) { + p = skip_ws(p, arr_end); + if (p >= arr_end || *p != '{') break; + const char *me = skip_value(p, arr_end); + if (!me) return -1; + + const char *cs = NULL, *ce = NULL; + int is_sys = message_is_system(p, me); + if (is_sys && carrier_n < sizeof carrier / sizeof carrier[0]) { + if (obj_field(p, me, "content", NULL, &cs, &ce) && cs < ce) { + if (cs < ce && *cs == '"') { + carrier[carrier_n].s = cs; + carrier[carrier_n].n = (size_t)(ce - cs); + carrier_n++; + if (value_leads_with_marker(cs, ce)) already_marked = 1; + } else if (*cs == '[') { + /* Array content on the compat path is rejected anyway; pass the + * message through untouched and let the provider answer. */ + return -1; + } + } + } + p = me; + p = skip_ws(p, arr_end); + if (p < arr_end && *p == ',') p++; + } + if (already_marked && carrier_n == 1) return 1; /* already exactly right */ + + /* Rebuild: the marker system message, then a user message per carrier (its text + * decoded and re-encoded), then every non-system message unchanged. */ + const char *mk = skip_ws(body, end); + if (mk >= end || *mk != '{') return -1; + mk++; + if (ob_apps(out, "{") != 0) return -1; + int first = 1, inserted = 0; + + for (;;) { + mk = skip_ws(mk, end); + if (mk >= end) return -1; + if (*mk == '}') break; + if (*mk != '"') return -1; + const char *ks = mk; + const char *ke = skip_string(mk, end); + if (!ke) return -1; + mk = skip_ws(ke, end); + if (mk >= end || *mk != ':') return -1; + const char *colon = mk; + mk = skip_ws(mk + 1, end); + const char *vs = mk; + const char *ve = skip_value(mk, end); + if (!ve) return -1; + size_t klen = (size_t)((ke - 1) - (ks + 1)); + int is_msgs = (klen == 8 && memcmp(ks + 1, "messages", 8) == 0); + + if (!first && ob_apps(out, ",") != 0) return -1; + first = 0; + if (!is_msgs) { + if (ob_app(out, ks, (size_t)(ve - ks)) != 0) return -1; + } else { + if (ob_app(out, ks, (size_t)(ke - ks)) != 0) return -1; + if (ob_app(out, colon, 1) != 0) return -1; + if (ob_apps(out, "[{\"role\":\"system\",\"content\":") != 0) return -1; + if (ob_json_string(out, j_oauth_marker, strlen(j_oauth_marker)) != 0) + return -1; + if (ob_apps(out, "}") != 0) return -1; + inserted = 1; + + /* The client's system text, each as its own user message. */ + for (size_t i = 0; i < carrier_n; i++) { + size_t cap = carrier[i].n + 1; + char *raw = malloc(cap); + if (!raw) return -1; + long n = decode_string(carrier[i].s, carrier[i].n + carrier[i].s, + raw, cap); + if (n < 0) { free(raw); return -1; } + if (n > 0 && !j_oauth_is_marker(raw, (size_t)n)) { + if (ob_apps(out, ",{\"role\":\"user\",\"content\":") != 0 || + ob_json_string(out, raw, (size_t)n) != 0 || + ob_apps(out, "}") != 0) { + free(raw); + return -1; + } + } + free(raw); + } + + /* Every non-system message, byte for byte. */ + const char *q = skip_ws(vs + 1, ve); + const char *ae = ve - 1; + while (q < ae) { + q = skip_ws(q, ae); + if (q >= ae || *q != '{') break; + const char *me = skip_value(q, ae); + if (!me) return -1; + int is_sys = message_is_system(q, me); + if (!is_sys) { + if (ob_apps(out, ",") != 0) return -1; + if (ob_app(out, q, (size_t)(me - q)) != 0) return -1; + } + q = me; + q = skip_ws(q, ae); + if (q < ae && *q == ',') q++; + } + if (ob_apps(out, "]") != 0) return -1; + } + mk = skip_ws(ve, end); + if (mk < end && *mk == ',') { mk++; continue; } + if (mk < end && *mk == '}') break; + return -1; + } + if (!inserted) return -1; /* a chat body without messages is not ours */ + return ob_apps(out, "}"); +} + +int j_oauth_body(const char *body, size_t len, int compat, char **out, + size_t *outlen) +{ + if (out) *out = NULL; + if (outlen) *outlen = 0; + if (!body || len == 0) return -1; + + const char *end = body + len; + const char *p = skip_ws(body, end); + if (p >= end || *p != '{') return -1; + + /* Nothing but the two chat paths knows where a system prompt lives. */ + ob b; + b.len = 0; + b.cap = len + 1024; + b.buf = malloc(b.cap); + if (!b.buf) return -1; + b.buf[0] = '\0'; + + int rc = compat ? compat_with_marker(body, end, &b) + : native_with_marker(body, end, &b); + /* 0 = rewritten, 1 = already correct, -1 = not ours. Only 0 hands back a body; + * the caller keeps its original for the other two. */ + if (rc != 0) { + free(b.buf); + return rc; + } + if (out) *out = b.buf; + else free(b.buf); + if (outlen) *outlen = b.len; + return 0; +} + +int j_oauth_needed(const char *body, size_t len, int compat) +{ + if (!body || len == 0) return 0; + const char *end = body + len; + const char *p = skip_ws(body, end); + if (p >= end || *p != '{') return 0; + + if (!compat) { + const char *vs = NULL, *ve = NULL; + /* Without messages this is not a chat request — see native_with_marker. */ + if (!obj_field(body, end, "messages", NULL, NULL, NULL)) return 0; + if (!obj_field(body, end, "system", NULL, &vs, &ve)) return 1; + return !value_leads_with_marker(vs, ve); + } + + /* Compat: needed unless the first system message is exactly the marker. */ + const char *vs = NULL, *ve = NULL; + if (!obj_field(body, end, "messages", NULL, &vs, &ve)) return 0; + if (vs >= ve || *vs != '[') return 0; + const char *q = skip_ws(vs + 1, ve); + const char *ae = ve - 1; + while (q < ae) { + q = skip_ws(q, ae); + if (q >= ae || *q != '{') break; + const char *me = skip_value(q, ae); + if (!me) return 0; + const char *cs = NULL, *ce = NULL; + int is_sys = message_is_system(q, me); + if (is_sys) { + if (!obj_field(q, me, "content", NULL, &cs, &ce)) return 1; + return !value_leads_with_marker(cs, ce); + } + q = me; + q = skip_ws(q, ae); + if (q < ae && *q == ',') q++; + } + return 1; /* no system message at all: the marker still has to go in */ +} diff --git a/src/oauth.h b/src/oauth.h new file mode 100644 index 0000000..f4e5f59 --- /dev/null +++ b/src/oauth.h @@ -0,0 +1,42 @@ +/* junction/oauth.h — the OAuth-token gate on Anthropic requests. + * + * An Anthropic OAuth token (sk-ant-oat01…) is accepted only on requests that carry a + * specific system prompt; see oauth.c for the measurements. These functions put that + * prompt in place and nothing else. + */ +#ifndef JUNCTION_OAUTH_H +#define JUNCTION_OAUTH_H + +#include + +/* The exact string the gate looks for. Exposed for tests; do not edit it. */ +extern const char j_oauth_marker[]; + +/* 1 when S of length N is exactly the marker. */ +int j_oauth_is_marker(const char *s, size_t n); + +/* Does this body still need the marker? + * + * COMPAT = 0 for the native Messages API (`system` at the top level), 1 for the + * OpenAI-compatible path (`/v1/chat/completions`, system as a message). + * Returns 1 when a rewrite would change something, 0 when the body is already usable + * or is not a chat body this function understands. A body that is not JSON, or has no + * messages, is left alone (0) rather than guessed at. */ +int j_oauth_needed(const char *body, size_t len, int compat); + +/* Rewrite the body so the marker leads the system prompt. + * + * Returns 0 and a malloc'ed body in *out / *outlen when the body was rewritten, + * 1 when it already led with the marker (nothing written, caller sends its own body), + * -1 when the body is not a shape this can touch (same: caller sends the original). + * Distinguishing 0 from 1 is not cosmetic — a caller that used *out on every success + * would send an empty body. Check j_oauth_needed first and skip the call when it says + * no; these two then only differ for a body that changed underneath. + * On the native path the client's system prompt is kept as the following blocks. + * On the compat path, where the system content must be the marker alone, the client's + * system text becomes its own user message before the first turn. + * The caller owns *out. */ +int j_oauth_body(const char *body, size_t len, int compat, char **out, + size_t *outlen); + +#endif diff --git a/tests/oauth-only.sh b/tests/oauth-only.sh new file mode 100755 index 0000000..2c533d9 --- /dev/null +++ b/tests/oauth-only.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Nur den OAuth-Abschnitt fahren, ohne die ~150 s der vollen Suite. Für die Arbeit an +# tests/oauth.sh selbst; die Suite bindet die Datei unverändert ein. +set -uo pipefail +cd "$(dirname "$0")/.." +TMP=$(mktemp -d) +PORT=8135 +PIDS=() +FAILED=0 +cleanup() { for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null; done; rm -rf "$TMP"; } +trap cleanup EXIT + +ok() { printf ' OK %s\n' "$1"; } +bad() { printf ' FAIL %s\n' "$1"; FAILED=1; } +contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; } +wait_port() { + local port=$1 limit=$(( ${2:-10} * 20 )) i=0 + while [ "$i" -lt "$limit" ]; do + if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then exec 3>&-; return 0; fi + sleep 0.05; i=$((i+1)) + done + echo " (port $port never came up)" >&2 + return 1 +} + +# shellcheck source=tests/oauth.sh +. tests/oauth.sh + +echo +if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi +exit "$FAILED" diff --git a/tests/oauth.sh b/tests/oauth.sh new file mode 100644 index 0000000..7b3b74e --- /dev/null +++ b/tests/oauth.sh @@ -0,0 +1,201 @@ +#!/bin/bash +# Wird von tests/run.sh eingebunden: wird der Claude-Code-Systemprompt gesetzt, wenn +# der Endpunkt einen OAuth-Token trägt — und nur dann? +# +# Warum das ein eigener Test ist: ein OAuth-Token ohne diesen Prompt beantwortet +# Anthropic mit 429 rate_limit_error. Das sieht aus wie ein aufgebrauchtes Kontingent, +# nicht wie ein fehlender Prompt — der Fehler wurde deshalb lange für ein Limit +# gehalten. Der Test prüft die Bytes, die upstream ankommen, nicht nur dass "200" zurück +# kommt: ein zufriedener Proxy mit falschem Rumpf ist der eigentliche Fehlerfall. + +echo "== OAuth-Token: Claude-Code-Systemprompt ==" + +OEP=$((PORT+310)) +OSP=$((PORT+311)) +MARKER="You are a Claude agent, built on Anthropic's Claude Agent SDK." + +# --- 1. Das Modul allein, ohne junction. Der Rewrite muss die JSON-Struktur erhalten, +# nicht bloß die Marke irgendwo einfügen. +PROBE=tests/oauth_probe +if [ ! -x "$PROBE" ] || [ tests/oauth_probe.c -nt "$PROBE" ] || [ src/oauth.c -nt "$PROBE" ]; then + cc -std=c99 -O2 -Wall -Wextra -Isrc -o "$PROBE" tests/oauth_probe.c src/oauth.c || \ + bad "the oauth probe did not build" +fi + +# Ein Muss-Fall: natives Format, kein system-Feld. Die Marke muss als erster Block +# entstehen, alles andere unangetastet bleiben. +IN='{"model":"m","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}' +OUT=$(printf '%s' "$IN" | "$PROBE" native) +if python3 - "$OUT" "$MARKER" <<'PY' +import json, sys +d = json.loads(sys.argv[1]) +assert d["system"][0]["text"] == sys.argv[2], d["system"] +assert len(d["system"]) == 1, d["system"] +assert d["messages"] == [{"role": "user", "content": "hi"}] +assert d["max_tokens"] == 8 +PY +then ok "native body without system gets the marker as its only block" +else bad "native body without system was not rewritten correctly: $OUT" +fi + +# Der Systemprompt des Clients muss als folgender Block erhalten bleiben — ihn zu +# ersetzen würde die Anweisungen des Operators stillschweigend löschen. +IN='{"model":"m","system":"Sei knapp.","messages":[]}' +OUT=$(printf '%s' "$IN" | "$PROBE" native) +if python3 - "$OUT" "$MARKER" <<'PY' +import json, sys +d = json.loads(sys.argv[1]) +assert [b["text"] for b in d["system"]] == [sys.argv[2], "Sei knapp."], d["system"] +PY +then ok "the client's system prompt survives as the following block" +else bad "the client's system prompt was lost: $OUT" +fi + +# cache_control gehört zum Prompt-Caching des Clients und darf nicht verloren gehen. +IN='{"model":"m","system":[{"type":"text","text":"A","cache_control":{"type":"ephemeral"}}],"messages":[]}' +OUT=$(printf '%s' "$IN" | "$PROBE" native) +if python3 - "$OUT" <<'PY' +import json, sys +d = json.loads(sys.argv[1]) +assert d["system"][0]["type"] == "text" +assert d["system"][1]["cache_control"] == {"type": "ephemeral"}, d["system"] +PY +then ok "cache_control on the client's system block is preserved" +else bad "cache_control was dropped: $OUT" +fi + +# Ein Rumpf, der schon stimmt, darf nicht ein zweites Mal umschrieben werden: die Marke +# zweimal im Prompt ist ein doppelter Prompt, kein doppelter Schutz. +printf '%s' '{"model":"m","system":[{"type":"text","text":"'"$MARKER"'"}],"messages":[]}' \ + | "$PROBE" native > /dev/null +[ $? -eq 3 ] && ok "an already marked body is left alone" \ + || bad "an already marked body was rewritten again" + +# Die Marke muss exakt sein. Fast richtig ist falsch — das ist der Unterschied zwischen +# 200 und 429, und ein Test, der "enthält Claude agent" prüft, würde ihn nicht sehen. +printf '%s' '{"model":"m","system":"'"${MARKER%.}"'","messages":[]}' \ + | "$PROBE" native > /dev/null +[ $? -eq 0 ] && ok "a marker missing its final period is still corrected" \ + || bad "a body with an almost-marker was not corrected" + +# OpenAI-kompatibler Pfad: dort darf der Systeminhalt NUR die Marke sein. Der Prompt des +# Clients wird deshalb zur eigenen user-Nachricht — erhalten, nicht gelöscht. +IN='{"model":"m","messages":[{"role":"system","content":"Sei knapp."},{"role":"user","content":"hallo"}]}' +OUT=$(printf '%s' "$IN" | "$PROBE" compat) +if python3 - "$OUT" "$MARKER" <<'PY' +import json, sys +d = json.loads(sys.argv[1]) +msgs = d["messages"] +assert msgs[0] == {"role": "system", "content": sys.argv[2]}, msgs +assert msgs[1] == {"role": "user", "content": "Sei knapp."}, msgs +assert msgs[2] == {"role": "user", "content": "hallo"}, msgs +assert len(msgs) == 3, msgs +PY +then ok "on the compat path the client's system text becomes its own user message" +else bad "the compat path did not carry the system prompt over: $OUT" +fi + +# Kaputte oder fremde Rümpfe werden nicht angefasst: ein Proxy, der bei unerwartetem +# JSON einen leeren Rumpf schickt, bricht jede Anfrage. Ein Rumpf ohne messages ist +# keine Chat-Anfrage (Token-Zählung, Batch-Eintrag) und darf keinen Prompt bekommen. +for BAD_BODY in 'not json' '{"model":"m"}' '{"model":"m","system":7,"messages":[]}' ''; do + printf '%s' "$BAD_BODY" | "$PROBE" native > /dev/null + rc=$? + [ "$rc" -eq 4 ] || bad "a body that is not ours was mishandled (rc=$rc): $BAD_BODY" +done +ok "foreign or malformed bodies are left to the provider" + +# --- 2. Durch junction hindurch: kommt der umgeschriebene Rumpf beim Endpunkt an, und +# bleibt ein Endpunkt ohne oauth on unberührt? +# Beide Endpunkte schreiben mit. Der zweite ist die wichtigere Hälfte: ein Marker, der +# bei jedem Konto gesetzt wird, wäre schlimmer als keiner. +BODYFILE="$TMP/oauth-bodies" +PLAINFILE="$TMP/plain-bodies" +: > "$BODYFILE" +: > "$PLAINFILE" +STUB_BODY_FILE="$BODYFILE" tests/stub $OSP "OAUTH" & PIDS+=($!) +wait_port $OSP 10 || bad "the oauth stub did not come up" + +STUB_BODY_FILE="$PLAINFILE" tests/stub $((OSP+1)) "OAUTH2" & PIDS+=($!) +wait_port $((OSP+1)) 10 || bad "the second oauth stub did not come up" + +cat > "$TMP/oauth.conf" < "$TMP/oauth.log" 2>&1 & +PIDS+=($!) +wait_port $OEP 10 || bad "junction did not come up for the oauth test" + +# Der Stub schreibt den Rumpf mit, weil er in einem Header nicht zu prüfen ist. +R=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' \ + -d '{"model":"claude-x","max_tokens":16,"system":"Sei knapp.","messages":[{"role":"user","content":"hi"}]}' \ + "http://127.0.0.1:$OEP/v1/messages") +contains "$R" "200 OK" "the request to the oauth endpoint is accepted" + +if [ -s "$BODYFILE" ] && python3 - "$BODYFILE" "$MARKER" <<'PY' +import json, sys +lines = [l for l in open(sys.argv[1]) if l.strip()] +assert lines, "no body reached the stub" +d = json.loads(lines[-1]) +assert d["system"][0]["text"] == sys.argv[2], d["system"] +assert d["system"][1]["text"] == "Sei knapp.", d["system"] +PY +then ok "junction put the marker upstream, keeping the client's system prompt" +else bad "the body that reached the endpoint is wrong: $(tail -1 "$BODYFILE" 2>/dev/null)" +fi + +# Gegenprobe: derselbe Rumpf an einen Endpunkt ohne "oauth on" muss unverändert bleiben. +curl -s -m 10 -o /dev/null -X POST -H 'Content-Type: application/json' \ + -d '{"model":"claude-plain-y","max_tokens":16,"system":"Sei knapp.","messages":[{"role":"user","content":"hi"}]}' \ + "http://127.0.0.1:$OEP/v1/messages" + +if [ -s "$PLAINFILE" ] && python3 - "$PLAINFILE" "$MARKER" <<'PY' +import json, sys +bodies = [json.loads(l) for l in open(sys.argv[1]) if l.strip()] +assert bodies, "no body reached the plain endpoint" +with_marker = [b for b in bodies if sys.argv[2] in json.dumps(b)] +assert not with_marker, with_marker +assert bodies[-1]["system"] == "Sei knapp.", bodies[-1].get("system") +PY +then ok "an endpoint without oauth on is not rewritten" +else bad "an endpoint without oauth on got the marker anyway: $(cat "$PLAINFILE" 2>/dev/null)" +fi + +# /v1/chat/completions durch den markierten Endpunkt: der Compat-Pfad muss auch dort +# greifen, nicht nur auf dem nativen Pfad. +curl -s -m 10 -o /dev/null -X POST -H 'Content-Type: application/json' \ + -d '{"model":"claude-z","messages":[{"role":"system","content":"Sei knapp."},{"role":"user","content":"hi"}]}' \ + "http://127.0.0.1:$OEP/v1/chat/completions" + +if python3 - "$BODYFILE" "$MARKER" <<'PY' +import json, sys +# The compat bodies are the ones without a top-level "system" key; a plain +# substring test would match the role value {"role":"system",...}. +bodies = [json.loads(l) for l in open(sys.argv[1]) if l.strip()] +compat = [b for b in bodies if "system" not in b and "messages" in b] +assert compat, [list(b) for b in bodies] +d = compat[-1] +msgs = d["messages"] +assert msgs[0] == {"role": "system", "content": sys.argv[2]}, msgs +assert msgs[1]["role"] == "user" and msgs[1]["content"] == "Sei knapp.", msgs +PY +then ok "the compat path through junction keeps the system prompt as a user message" +else bad "/v1/chat/completions was not rewritten: $(tail -1 "$BODYFILE" 2>/dev/null)" +fi diff --git a/tests/oauth_probe.c b/tests/oauth_probe.c new file mode 100644 index 0000000..d956c7a --- /dev/null +++ b/tests/oauth_probe.c @@ -0,0 +1,43 @@ +/* tests/oauth_probe.c — run the OAuth rewrite on stdin, print the result on stdout. + * + * oauth_probe native < body.json > rewritten.json + * oauth_probe compat < body.json > rewritten.json + * + * Exit 0 = rewritten, 3 = unchanged (already usable or not a shape it touches). + * Lets a test look at the exact bytes the module produces without starting junction, + * so a broken rewrite is visible as a JSON diff and not as "the API answered 429 + * again" — the failure mode this module exists for looks identical to a quota error. + */ +#include +#include +#include + +#include "../src/oauth.h" + +int main(int argc, char **argv) +{ + int compat = (argc > 1 && !strcmp(argv[1], "compat")); + + size_t cap = 1 << 16, len = 0; + char *buf = malloc(cap); + if (!buf) return 2; + size_t r; + while ((r = fread(buf + len, 1, cap - len, stdin)) > 0) { + len += r; + if (len == cap) { + cap *= 2; + char *nb = realloc(buf, cap); + if (!nb) { free(buf); return 2; } + buf = nb; + } + } + + char *out = NULL; + size_t out_len = 0; + int rc = j_oauth_body(buf, len, compat, &out, &out_len); + free(buf); + if (rc != 0) return rc == 1 ? 3 : 4; /* 3 = already marked, 4 = not a body we touch */ + fwrite(out, 1, out_len, stdout); + free(out); + return 0; +} diff --git a/tests/run.sh b/tests/run.sh index 2528631..50638c9 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -959,6 +959,12 @@ fi # shellcheck source=tests/judge.sh . "$(dirname "$0")/judge.sh" +# OAuth-Token: Anthropic nimmt einen Abo-Token nur mit dem Claude-Code-Systemprompt an +# und antwortet sonst mit 429, was wie ein Kontingent aussieht. +echo "== OAuth-Token ==" +# shellcheck source=tests/oauth.sh +. "$(dirname "$0")/oauth.sh" + # Self-Review: N versteckte Runden, nur die letzte Antwort geht an den Client. # shellcheck source=tests/review.sh . "$(dirname "$0")/review.sh" diff --git a/tests/stub.c b/tests/stub.c index defb928..55ef41a 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -299,6 +299,23 @@ int main(int argc, char **argv) nanosleep(&ts, NULL); } + /* STUB_BODY_FILE=: write the request body verbatim. A test that has to + * check JSON *structure* (is the marker the first system block, did the + * client's prompt survive) cannot do it from a header, and dumping the whole + * body into a header would break on a real prompt. Append, so a test can see + * every request of one run. */ + const char *body_file = getenv("STUB_BODY_FILE"); + if (body_file && *body_file && body_len > 0) { + int bfd = open(body_file, O_WRONLY | O_CREAT | O_APPEND, 0600); + if (bfd >= 0) { + if (flock(bfd, LOCK_EX) == 0) { + (void)!write(bfd, req + head_len, (size_t)body_len); + (void)!write(bfd, "\n", 1); + } + close(bfd); + } + } + char custom[256] = "", static_hdr[256] = "", fwd[256] = "", accept[128] = ""; char effort[64] = "", thinking[64] = "", xapi[128] = "", av[64] = ""; /* the model field as it arrived, so the tests can see a rewrite (and a