headers: Judge-Zuordnung über den Target-Slot, Werte entschärfen, Drops loggen

X-Junction-Judge-Served kam aus einem Namensvergleich zwischen dem
antwortenden Endpoint und dem Judge-Ziel. Nennen Judge und Worker
denselben Endpoint (oder überlappen sich ihre Pools), meldete auch der
Worker "Judge-Served: 1". Jetzt setzt der Target-Loop ein Thread-lokales
Flag für den Judge-Slot; forward_step zählt nur diesen. Der Worker-
Fallback nach einem ausgefallenen Judge bleibt damit 0.

j_hdrs_add prüft Header-Namen und entschärft Steuerzeichen in Werten
(CR/LF und andere Kontrollbytes werden zu Leerzeichen), sodass ein Wert
keine zweite Header-Zeile erzeugen kann. Eine volle Headerliste (96)
verwirft weiterhin, loggt aber Name und Kapazität über einen Hook; auch
entschärfte Werte werden geloggt, gedeckelt auf die ersten fünf und
jeden hundertsten Fall.

Tests: Judge/Worker auf demselben Endpoint mit cachebedingt scheiterndem
Judge -> Worker antwortet, Served bleibt 0. Stub mit 110 Headern + einem
Steuerzeichen: Antwort bleibt 200, der Wert kommt als "a b" an, kein
Rohbyte beim Client, Log nennt header_control_chars und headers_dropped
mit max=96.

Tests: 475 OK, 0 FAIL.
This commit is contained in:
Hermes committed 2026-11-18 08:10:01 +00:00
1 parent f2f6097038
commit e5571456ee
7 files changed
+169 -21

No files matched your search

+51 -2
View File
@@ -164,11 +164,60 @@ int j_hdrs_count(const j_hdrs *h, const char *name)
return n;
}
static void (*g_hdr_note)(const char *event, const char *name);
void j_hdrs_set_note_hook(void (*fn)(const char *event, const char *name))
{
g_hdr_note = fn;
}
static void hdr_note(const char *event, const char *name)
{
if (g_hdr_note) g_hdr_note(event, name);
}
/* A header name is a token: no whitespace, no colon, no control bytes. Rejecting
* the whole header is safer than rewriting its name into a different one. */
static int hdr_name_ok(const char *name)
{
if (!name || !name[0]) return 0;
for (const unsigned char *p = (const unsigned char *)name; *p; p++) {
if (*p <= 0x20 || *p >= 0x7f || *p == ':') return 0;
}
return 1;
}
/* CR/LF in a value would end the header and start an injected one. Other control
* bytes are invalid in a field value too; replace them with a space. Tabs stay. */
static int hdr_value_clean(char *dst, size_t cap, const char *src)
{
size_t o = 0;
int dirty = 0;
for (const unsigned char *p = (const unsigned char *)(src ? src : "");
*p && o + 1 < cap; p++) {
unsigned char c = *p;
if (c == '\r' || c == '\n' || (c < 0x20 && c != '\t') || c == 0x7f) {
c = ' ';
dirty = 1;
}
dst[o++] = (char)c;
}
dst[o] = '\0';
return dirty;
}
void j_hdrs_add(j_hdrs *h, const char *name, const char *value)
{
if (h->n >= J_MAX_HDRS) return; /* dropping beats corrupting */
if (!hdr_name_ok(name)) { hdr_note("header_name_rejected", name); return; }
if (h->n >= J_MAX_HDRS) { /* dropping beats corrupting */
hdr_note("headers_dropped", name);
return;
}
char clean[J_HDR_VALUE];
if (hdr_value_clean(clean, sizeof clean, value))
hdr_note("header_control_chars", name);
snprintf(h->it[h->n].name, J_HDR_NAME, "%s", name);
snprintf(h->it[h->n].value, J_HDR_VALUE, "%s", value);
snprintf(h->it[h->n].value, J_HDR_VALUE, "%s", clean);
h->n++;
}
+4
View File
@@ -48,6 +48,10 @@ int j_buf_ensure(j_conn *c, j_buf *b, size_t from, size_t n, double idle_s,
double deadline, char *err, size_t errlen);
void j_hdrs_init(j_hdrs *h);
/* Optional observer for header problems: a full array (dropped), an invalid name
* (rejected) or control characters in a value (neutralised). junction logs these
* so a missing/rewritten header is not silent. */
void j_hdrs_set_note_hook(void (*fn)(const char *event, const char *name));
int j_hdrs_find(const j_hdrs *h, const char *name, char *out, size_t outlen);
int j_hdrs_count(const j_hdrs *h, const char *name);
void j_hdrs_add(j_hdrs *h, const char *name, const char *value);
+22 -16
View File
@@ -82,6 +82,7 @@ static __thread double t_heartbeat_started;
/* Judge/review metadata for the response headers. Set before the target loop and
* read by forward_step, sse_open and review_serve. Thread-local like the rest. */
static __thread int t_judge_active;
static __thread int t_judge_call; /* the current target slot is the judge */
static __thread int t_judge_served;
static __thread int t_judge_step;
static __thread int t_judge_every;
@@ -1981,20 +1982,6 @@ static const j_pool *find_pool(const char *name)
return NULL;
}
/* Did this endpoint actually serve the judge step (endpoint or one of its pool
* members)? Used for X-Junction-Judge-Served; a worker fallback stays 0. */
static int judge_endpoint_matches(const char *name)
{
if (!t_judge_active) return 0;
const j_pool *p = find_pool(t_judge_target);
if (p) {
for (int i = 0; i < p->count; i++)
if (!strcmp(p->targets[i], name)) return 1;
return 0;
}
return !strcmp(t_judge_target, name);
}
/* The same metadata on every path: normal JSON responses get it in forward_step,
* review_serve builds its own head, and sse_open writes the planned part. */
static void add_route_meta_headers(j_hdrs *h)
@@ -3088,8 +3075,10 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq,
char msbuf[32];
snprintf(msbuf, sizeof msbuf, "%ld", (long)((now_s() - req_started) * 1000.0));
if (r.status >= 200 && r.status < 300 &&
t_judge_active && judge_endpoint_matches(ep->name))
/* Attribute the answer to the slot it came from, not to an endpoint name:
* a judge and a worker may share an endpoint, and a worker fallback after a
* failed judge must not claim the judge served. */
if (r.status >= 200 && r.status < 300 && t_judge_active && t_judge_call)
t_judge_served = 1;
j_hdrs_set(&r.hdrs, "X-Junction-Endpoint", ep->name);
j_hdrs_set(&r.hdrs, "X-Junction-Ms", msbuf);
@@ -3767,6 +3756,18 @@ static const char *request_session(const j_hdrs *h, char *buf, size_t buflen)
return NULL;
}
/* Header problems are otherwise invisible: a dropped header looks like a provider
* that never sent it. Cap the log at five lines plus every hundredth to keep a
* hostile upstream from flooding the log. */
static void hdr_note(const char *event, const char *name)
{
static unsigned long seen;
seen++;
if (seen <= 5 || seen % 100 == 0)
jlog(event, "name=%s max=%d total=%lu",
name && name[0] ? name : "?", J_MAX_HDRS, seen);
}
static void handle_client_inner(j_conn *client)
{
j_buf buf;
@@ -3776,6 +3777,7 @@ static void handle_client_inner(j_conn *client)
int flight_leader = 0;
j_buf_init(&buf);
t_judge_active = 0;
t_judge_call = 0;
t_judge_served = 0;
t_judge_step = 0;
t_judge_every = 0;
@@ -4402,6 +4404,9 @@ static void handle_client_inner(j_conn *client)
* ein großes den vollen. Der Judge bekommt den vollen Rumpf mit dem
* Cache-Marker; fällt er aus, sieht der Worker wieder den normalen Rumpf. */
int judge_target = judge_turn && t < judge_slots;
/* forward_step reads this, not the endpoint name: the same endpoint may
* be both the judge and the worker. The worker fallback clears it. */
t_judge_call = judge_target;
int judge_body_used = judge_target && judge_body != NULL;
const char *send_body = judge_body_used ? judge_body
: ((ep_compresses && comp_body) ? comp_body : out_body);
@@ -4747,6 +4752,7 @@ int main(int argc, char **argv)
return 0;
}
j_mcp_set_log(mcp_log_bridge);
j_hdrs_set_note_hook(hdr_note);
g_started_at = now_s();
if (port_override) CFG.listen_port = port_override;
+32
View File
@@ -18,6 +18,8 @@ JP2=$((PORT+274))
JP3=$((PORT+275))
JJ2=$((PORT+276))
JP4=$((PORT+277))
JB=$((PORT+278))
JBJ=$((PORT+279))
tests/stub $JW "WORKER" > "$TMP/judge_worker.log" 2>&1 &
PIDS+=($!)
@@ -28,10 +30,13 @@ PIDS+=($!)
STUB_STATE="$TMP/judge_bad.state" tests/stub $JF "BADJUDGE" --fail-n 100 \
> "$TMP/judge_bad.log" 2>&1 &
PIDS+=($!)
STUB_FAIL_CACHE=1 tests/stub $JB "OVERLAP" > "$TMP/judge_overlap_stub.log" 2>&1 &
PIDS+=($!)
wait_port $JW 10 || bad "the judge worker stub did not come up"
wait_port $JJ 10 || bad "the judge stub did not come up"
wait_port $JJ2 10 || bad "the second judge stub did not come up"
wait_port $JF 10 || bad "the failing judge stub did not come up"
wait_port $JB 10 || bad "the overlap judge stub did not come up"
cat > "$TMP/judge.conf" <<CFG
listen 127.0.0.1:$JP
@@ -174,6 +179,33 @@ contains "$(cat "$TMP/judge_fb.log")" "upstream_error endpoint=badjudge" \
contains "$(cat "$TMP/judge_fb.log")" "served_by endpoint=worker" \
"the fallback is visible in the log"
# Judge und Worker können denselben Endpoint nennen. Fällt der Judge aus und
# bedient der Worker, darf X-Junction-Judge-Served nicht 1 werden — die alte
# Namensprüfung hielt den Worker für den Judge. Der Stub scheitert nur, wenn der
# Judge-Rumpf den cache_control-Marker trägt.
cat > "$TMP/judge_overlap.conf" <<CFG
listen 127.0.0.1:$JBJ
queue_timeout 10
retry_num 0
models allow "vm-overlap" "OVERLAP"
endpoint both { base http://127.0.0.1:$JB/v1; context 8000; timeout 10; cooldown 0 }
req for "vm-overlap" judge every 1 both as "judge-model" cache 1h pass both as "worker-model"
CFG
./junction --config "$TMP/judge_overlap.conf" > "$TMP/judge_overlap.log" 2>&1 &
PIDS+=($!)
wait_port "$JBJ" 10 || bad "the overlap-judge instance did not come up"
judge_ask "$JBJ" "vm-overlap" "$SYS" "overlap turn"
[ "$JNAME" = "OVERLAP" ] && ok "the worker fallback on the judge's endpoint serves" \
|| bad "the overlap fallback got '$JNAME'"
[ "$JJUDGE" = "both" ] && ok "the overlap fallback still names the attempted judge" \
|| bad "overlap judge header is '$JJUDGE'"
[ "$JJSERVED" = "0" ] && ok "a worker on the judge's endpoint does not claim the judge served" \
|| bad "overlap judge served header is '$JJSERVED'"
[ "$JCACHE" = "0" ] && ok "the overlap worker fallback has no judge cache marker" \
|| bad "the overlap worker received cache_control"
contains "$(cat "$TMP/judge_overlap.log")" "served_by endpoint=both" \
"the overlap fallback is visible in the log"
# Ein Pool als Judge: das erste Mitglied fällt aus, das zweite bedient den Turn.
cat > "$TMP/judge_pool.conf" <<CFG
listen 127.0.0.1:$JP3
+37
View File
@@ -19,6 +19,8 @@ RS=$((PORT+288))
RSJ=$((PORT+289))
RU=$((PORT+290))
RUJ=$((PORT+291))
RHP=$((PORT+292))
RHPJ=$((PORT+293))
STUB_STATE="$TMP/review.state" STUB_ANSWERS="first answer|second answer|third answer" \
tests/stub $RW "REVIEWER" > "$TMP/review_stub.log" 2>&1 &
@@ -38,12 +40,16 @@ PIDS+=($!)
STUB_STATE="$TMP/review_usage.state" STUB_ANSWERS="usage one|usage two|usage three" \
STUB_USAGE=1 tests/stub $RU "USAGE" > "$TMP/review_usage_stub.log" 2>&1 &
PIDS+=($!)
STUB_MANY_HEADERS=110 STUB_BAD_HEADER=1 tests/stub $RHP "HEADERS" \
> "$TMP/review_headers_stub.log" 2>&1 &
PIDS+=($!)
wait_port $RW 10 || bad "the review stub did not come up"
wait_port $RT 10 || bad "the tool-review stub did not come up"
wait_port $RB 10 || bad "the 400 stub did not come up"
wait_port $RA 10 || bad "the content-array stub did not come up"
wait_port $RS 10 || bad "the strict stub did not come up"
wait_port $RU 10 || bad "the usage stub did not come up"
wait_port $RHP 10 || bad "the header stub did not come up"
cat > "$TMP/review.conf" <<CFG
listen 127.0.0.1:$RJ
@@ -295,6 +301,37 @@ contains "$USSE" '"usage":{"prompt_tokens":3600,"completion_tokens":900,"cached_
contains "$USSE" '"cost_usd":0.005400' "the final stream chunk sums the cost"
contains "$USSE" '"review_rounds":2' "the final stream chunk names the rounds"
# Header-Werte werden entschärft und eine volle Headerliste wird sichtbar
# verworfen: ein eingebettetes Steuerzeichen darf keine zweite Header-Zeile
# erzeugen, und >96 Header dürfen nicht still verschwinden.
cat > "$TMP/review_headers.conf" <<CFG
listen 127.0.0.1:$RHPJ
queue_timeout 10
models allow "vm-headers" "HEADERS"
endpoint h { base http://127.0.0.1:$RHP/v1; context 8000; timeout 10 }
req for "vm-headers" check none pass h
CFG
./junction --config "$TMP/review_headers.conf" > "$TMP/review_headers.log" 2>&1 &
PIDS+=($!)
wait_port "$RHPJ" 10 || bad "the header instance did not come up"
HH=$(curl -s -D "$TMP/review_headers_h.txt" -m 20 -X POST -H 'Content-Type: application/json' \
-d '{"model":"vm-headers","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \
"http://127.0.0.1:$RHPJ/v1/chat/completions")
contains "$HH" "served by HEADERS" "the many-header response is still served"
tr -d '\r' < "$TMP/review_headers_h.txt" | grep -qi '^X-Stub-Bad: a b$' \
&& ok "a control character in a header value becomes a space" \
|| bad "the control character was not neutralised"
if LC_ALL=C grep -q $'\001' "$TMP/review_headers_h.txt"; then
bad "the raw control character reached the client"
else
ok "the raw control character does not reach the client"
fi
contains "$(cat "$TMP/review_headers.log")" "header_control_chars name=X-Stub-Bad" \
"the sanitised header is logged"
contains "$(cat "$TMP/review_headers.log")" "headers_dropped name=X-Stub-Many-" \
"a full header list logs what was dropped"
contains "$(cat "$TMP/review_headers.log")" "max=96" "the drop log names the capacity"
# Konfigurationsfehler müssen laut sein.
printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n}\nreq for "vm" review 5 pass e\n' \
> "$TMP/review_bad_count.conf"
+1 -1
View File
@@ -71,7 +71,7 @@ log_has() {
# answer requests with somebody else's config), so fail loudly and early.
# 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem
# Test benutzt, also darf er die Suite nicht aufhalten.
for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8208 9443 9990 9991 9992 9993 9994 9995 9996; do
for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8208 9443 9990 9991 9992 9993 9994 9995 9996; do
if ss -tln 2>/dev/null | grep -q ":$port "; then
echo "port $port is busy — a leftover junction/stub is still running:"
ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /'
+22 -2
View File
@@ -283,6 +283,12 @@ int main(int argc, char **argv)
if (reject_so && *reject_so && counts &&
strstr(req + head_len, "\"stream_options\""))
forced = 400;
/* A judge call carries cache_control when the rule asks for it. This lets
* a test fail the judge while the worker (same endpoint) still serves. */
const char *fail_cache = getenv("STUB_FAIL_CACHE");
if (fail_cache && *fail_cache && counts &&
strstr(req + head_len, "\"cache_control\""))
forced = 503;
if (delay > 0) {
struct timespec ts = { (time_t)delay, (time_t)((delay - (time_t)delay) * 1e9) };
@@ -348,7 +354,20 @@ int main(int argc, char **argv)
find_header(req, "anthropic-version", av, sizeof av);
int av_count = count_header(req, "anthropic-version");
char body[4096];
char many[4096] = "";
const char *many_env = getenv("STUB_MANY_HEADERS");
if (many_env && *many_env) {
long count = strtol(many_env, NULL, 10);
size_t mo = 0;
for (long i = 0; i < count && mo + 48 < sizeof many; i++)
mo += (size_t)snprintf(many + mo, sizeof many - mo,
"X-Stub-Many-%ld: v\r\n", i);
}
const char *bad_env = getenv("STUB_BAD_HEADER");
const char *bad_header = (bad_env && *bad_env)
? "X-Stub-Bad: a\001b\r\n" : "";
char body[8192];
if (forced) {
/* Retry-After: standardmäßig 0 — der Stub weiß nicht, wie lange ein echtes
* Kontingent braucht; die 0 macht klar, dass sofort weiterversucht werden
@@ -492,12 +511,13 @@ int main(int argc, char **argv)
"X-Stub-XApi-Key: %s\r\n"
"X-Stub-Anthropic-Version: %s\r\n"
"X-Stub-Anthropic-Versions: %d\r\n"
"%s%s"
"Connection: close\r\n\r\n%s",
strlen(b), name, body_len, custom, static_hdr, fwd, model, authhdr,
reasoning, accept, effort, effort[0] ? 1 : 0, thinking,
has_reasoning ? 1 : 0, has_cache_control ? 1 : 0,
has_review ? 1 : 0, has_prev ? 1 : 0,
xapi, av, av_count, b);
xapi, av, av_count, bad_header, many, b);
}
if (j_conn_write(&client, body, strlen(body), ioerr, sizeof ioerr) < 0)
fprintf(stderr, "stub write failed: %s\n", ioerr);