#!/bin/bash # junction test suite — stub endpoints only, no network, no models. ~150 s. set -uo pipefail cd "$(dirname "$0")/.." # Two sections on the same port is the most misleading failure this suite can # produce: the second listener dies with "Address already in use" and the checks # then blame its behaviour ("missing 'served by POOR'"). Two such collisions # happened on 2026-11-18. The scan is static, so it costs nothing. python3 "$(dirname "$0")/check_ports.py" || { echo "aborting: port collision in the test suite" >&2 exit 1 } # Hermetisch: dieser Lauf darf nicht davon abhängen, welche Schlüssel zufällig in der # Umgebung stehen. Sonst legt junction Endpunkte an, die kein Test erwartet. unset OPENCODE_GO_API_KEY OLLAMA_KEY ANTHROPIC_API_KEY CLAUDE_API_KEY 2>/dev/null || true for n in 1 2 3 4 5 6 7 8; do unset "OPENCODE_GO_API_KEY$n" "OLLAMA_KEY$n" "ANTHROPIC_API_KEY$n" "CLAUDE_API_KEY$n" 2>/dev/null || true done TMP=$(mktemp -d) PORT=8135 P_FAIL=9990; P_GATED=9991; P_DEAD=9992; P_SLOW=9993; P_PONDER=9994; P_SSE_NOT=9997; P_SSE_CAP=9998 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; } # Ältere Abschnitte rufen fail(); ohne diese Funktion blieb ein Fehlschlag # unbemerkt und die Suite meldete PASS. fail() { bad "$1"; } contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; } # Auf den Listener warten statt zu schlafen. Unter Last (parallel kompiliert, ein # Scrape dazwischen) war "junction nach 0,7 s erreichbar" nicht immer wahr, und dann # scheiterten Prüfungen, die mit dem Code nichts zu tun hatten. 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 # A bind failure is otherwise invisible: the stub dies and the check that # needed it fails with a message about the router's behaviour. Name the # process that holds the port (measured: a stub could not bind 8380 and # nothing said who had it). echo " (port $port never came up; listeners on it:)" >&2 ss -ltnp 2>/dev/null | grep ":$port " | sed 's/^/ /' >&2 || true return 1 } # Warten, bis eine Zeile im Log steht: ein Router, der nicht lauschen soll # (mesh ohne Geheimnis) oder nicht lauschen darf (Port belegt), ist nur am Log # zu erkennen. Ein fester sleep war hier reine Glueckssache. wait_log() { local file=$1 pat=$2 limit=$(( ${3:-10} * 20 )) i=0 while [ "$i" -lt "$limit" ]; do grep -q "$pat" "$file" 2>/dev/null && return 0 sleep 0.05; i=$((i+1)) done return 1 } # Hosts with a wide ephemeral range (1024-65535, common after PVE tuning) hand # out ports such as 8380 or 8154 to outgoing connections. The bind then fails # with EADDRINUSE and the suite blames the router; reserving the test ranges in # net.ipv4.ip_local_reserved_ports fixes it (see the note in tests/run.sh and # /etc/sysctl.d/90-junction-test-ports.conf on hosts that run this suite). case "$(cat /proc/sys/net/ipv4/ip_local_port_range 2>/dev/null)" in "1024"*) case "$(cat /proc/sys/net/ipv4/ip_local_reserved_ports 2>/dev/null)" in *8135-8440*) ;; *) echo "warning: ephemeral ports may take a test port (EADDRINUSE); reserve 8135-8440,9443,9990-9998,18000-18399" >&2 ;; esac ;; esac # Ein Port, der gerade freigegeben wurde, ist nicht sofort wieder belegbar: nach SIGTERM # hält junction den Listener noch restart_grace_s offen und antwortet "restarting". # Wer den Port wiederverwenden will, wartet, bis er wirklich frei ist. wait_port_free() { 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 sleep 0.05; i=$((i+1)) else return 0 fi done return 1 } # serviert wird vor dem Log-Eintrag: die Antwort ist beim Client, "served_by" folgt # einen Wimpernschlag später. Ein direkter grep verliert dieses Rennen je nach # Lastlage — deshalb kurz nachsehen statt sofort urteilen. log_has() { local file=$1 pat=$2 label=$3 i=0 while [ "$i" -lt 40 ]; do grep -q "$pat" "$file" 2>/dev/null && { ok "$label"; return 0; } sleep 0.05; i=$((i+1)) done bad "$label (no '$pat' in $file after 2 s)" } # A leftover process on a test port produces confusing failures (a stale junction can # 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 8379 8380 8381 8382 8383 8384 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 8429 8430 8431 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8204 8205 8206 8207 8208 8209 8210 9443 9990 9991 9992 9993 9994 9995 9996 9997 9998 8215 8216 18340; 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/^/ /' exit 1 fi done make -s >/dev/null || { echo "build failed"; exit 1; } TLSCC="-DJ_HAVE_TLS -lssl -lcrypto" [ -f /usr/include/openssl/ssl.h ] || TLSCC="" # Die Bibliotheken gehören hinter die Quellen: davor aufgelistet löst der Linker # SSL_pending nicht auf, und auf einem frischen Checkout (ohne fertiges tests/stub) # scheitert die Suite an einer Zeile, die nie jemand ausprobiert hat. # Nicht nur "fehlt es?" — auch "ist es älter als seine Quellen?". Ein von Hand ohne # -DJ_HAVE_TLS gebauter Stub blieb sonst liegen und die TLS-Abschnitte scheiterten an # einer Zeile, die niemand angefasst hat. if [ ! -x tests/stub ] || [ tests/stub.c -nt tests/stub ] || [ src/conn.c -nt tests/stub ]; then cc -std=c99 -O2 -Isrc -o tests/stub tests/stub.c src/conn.c $TLSCC || exit 1 fi tests/stub $P_FAIL "FAILING" --fail & PIDS+=($!) tests/stub $P_GATED "GATED" & PIDS+=($!) tests/stub $P_SLOW "SLOW" --delay 6 & PIDS+=($!) tests/stub $P_PONDER "PONDER" --delay 13 & PIDS+=($!) tests/stub $P_SSE_NOT "SSENOTE" --sse-no-te & PIDS+=($!) tests/stub $P_SSE_CAP "SSECAP" --sse-cap & PIDS+=($!) sleep 0.5 # a hook that refuses until a marker file exists (created after 3 s) cat > "$TMP/gate.sh" < "$TMP/open" ) & PIDS+=($!) cat > "$TMP/junction.conf" < "$TMP/router.log" 2>&1 & PIDS+=($!) sleep 0.7 REQ='{"model":"x","messages":[{"role":"user","content":"hi"}],"max_tokens":64}' echo "== 1. dead -> offline, failing -> cooldown, gated waits for its hook ==" R1=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' -d "$REQ" \ "http://127.0.0.1:$PORT/v1/chat/completions") contains "$R1" "served by GATED" "served by the gated endpoint once the hook opened" grep -q "offline endpoint=dead" "$TMP/router.log" && ok "unreachable endpoint marked offline" \ || bad "unreachable endpoint marked offline" grep -q "failed endpoint=failing" "$TMP/router.log" && ok "503 endpoint cooled down" \ || bad "503 endpoint cooled down" grep -q "waiting endpoint=gated" "$TMP/router.log" && ok "hook refusal retried, not fatal" \ || bad "hook refusal retried, not fatal" echo "== 2. /status ==" ST=$(curl -s -m 5 "http://127.0.0.1:$PORT/status") contains "$ST" '"name":"dead"' "status lists endpoints" OFF=$(printf '%s' "$ST" | sed -n 's/.*"name":"dead"[^}]*"offline_s":\([0-9]*\).*/\1/p') if [ -n "$OFF" ] && [ "$OFF" -gt 0 ]; then ok "dead endpoint holds an offline window (${OFF}s)"; else bad "offline_s=$OFF"; fi echo "== 3. slow endpoint, forced: 'still_working' must be logged ==" curl -s -m 5 -X POST "http://127.0.0.1:$PORT/admin/pause/gated" >/dev/null : > "$TMP/router.log" R3=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' -d "$REQ" \ "http://127.0.0.1:$PORT/v1/chat/completions") contains "$R3" "served by SLOW" "slow endpoint served" grep -q "still_working side=upstream" "$TMP/router.log" && ok "silence logged as still_working" \ || bad "silence logged as still_working" curl -s -m 5 -X POST "http://127.0.0.1:$PORT/admin/resume/gated" >/dev/null echo "== 4. rules: block, catch-all, context threshold ==" cat > "$TMP/rules.conf" <100000 pass big req for "blocked-*" block req for "*" pass small CFG ./junction --config "$TMP/rules.conf" > "$TMP/rules.log" 2>&1 & PIDS+=($!) sleep 0.7 R4a=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ -d '{"model":"blocked-model","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ "http://127.0.0.1:$((PORT+1))/v1/chat/completions") contains "$R4a" "blocked_by_rule" "block rule refuses" R4b=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \ -d '{"model":"anything","messages":[{"role":"user","content":"hi"}],"max_tokens":8}' \ "http://127.0.0.1:$((PORT+1))/v1/chat/completions") contains "$R4b" "served by GATED" "catch-all rule serves through the small endpoint" # "need" only ever uses a number the client wrote — no character counting, no default R4c=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' \ -d '{"model":"anything","messages":[{"role":"user","content":"hi"}],"max_tokens":120000}' \ "http://127.0.0.1:$((PORT+1))/v1/chat/completions") contains "$R4c" "served by SLOW" "declared max_tokens above the threshold picks the big endpoint" R4d=$(curl -s -m 30 -X POST -H 'Content-Type: application/json' \ -d '{"model":"anything","messages":[{"role":"user","content":"a long prompt with no token budget declared at all"}]}' \ "http://127.0.0.1:$((PORT+1))/v1/chat/completions") contains "$R4d" "served by GATED" "a request without max_tokens is not sized by guesswork" echo "== 5. model rewrite ('pass as ') ==" cat > "$TMP/rewrite.conf" < "$TMP/rewrite.log" 2>&1 & PIDS+=($!) sleep 0.7 R5=$(curl -s -m 20 -D- -X POST -H 'Content-Type: application/json' \ -d '{"model":"original-name","messages":[{"role":"user","content":"hi"}],"max_tokens":8,"reasoning_effort":"high"}' \ "http://127.0.0.1:$((PORT+2))/v1/chat/completions") contains "$R5" "served by GATED" "rewrite rule still serves" contains "$R5" "X-Stub-Model: STUB-MODEL-NAME" "the endpoint receives the rewritten model" contains "$R5" "X-Stub-Reasoning: high" "reasoning_effort survives the model rewrite" case "$R5" in *"original-name"*) bad "the client's model name leaked past the rewrite" ;; *) ok "the client's model name was replaced, not appended" ;; esac log_has "$TMP/rewrite.log" "served_by endpoint=echo" "rewrite logged a served_by line" echo "== 6. no rule matches -> 503, fast ==" cat > "$TMP/norule.conf" <100000 pass small CFG ./junction --config "$TMP/norule.conf" > "$TMP/norule.log" 2>&1 & PIDS+=($!) sleep 0.7 T0=$(date +%s%N) R6=$(curl -s -m 10 -X POST -H 'Content-Type: application/json' -d "$REQ" \ "http://127.0.0.1:$((PORT+3))/v1/chat/completions") MS=$(( ($(date +%s%N) - T0) / 1000000 )) contains "$R6" "no_matching_rule" "unmatched request refused" if [ "$MS" -lt 2000 ]; then ok "refusal in ${MS} ms"; else bad "refusal took ${MS} ms"; fi echo "== 7. config errors are loud ==" printf 'listen 127.0.0.1:8090\nendpoint x {\n base http://a/v1\n timout 5\n}\n' > "$TMP/bad.conf" OUT=$(./junction --config "$TMP/bad.conf" 2>&1) contains "$OUT" "unknown endpoint keyword 'timout'" "typo in an endpoint key is an error" printf 'listen 127.0.0.1:8090\nendpoint x {\n base http://a/v1\n}\nreq for "*" pass nope\n' > "$TMP/bad2.conf" OUT2=$(./junction --config "$TMP/bad2.conf" 2>&1) contains "$OUT2" "unknown endpoint 'nope'" "a rule may not pass to an unknown endpoint" # Ein zu langer Name wurde früher still abgeschnitten und konnte so auf einen # anderen Endpoint zeigen. Jetzt ist er ein Konfigurationsfehler. LONG=$(python3 -c "print('x' * 70)") printf 'listen 127.0.0.1:8090\nendpoint e { base http://a/v1 }\npool p e, %s\nreq for "*" pass p\n' "$LONG" > "$TMP/bad3.conf" OUT3=$(./junction --config "$TMP/bad3.conf" 2>&1) contains "$OUT3" "pool p: target" "an overlong pool target is rejected" printf 'listen 127.0.0.1:8090\nendpoint e { base http://a/v1 }\nreq for "*" pass %s\n' "$LONG" > "$TMP/bad4.conf" OUT4=$(./junction --config "$TMP/bad4.conf" 2>&1) contains "$OUT4" "rule target" "an overlong rule target is rejected" printf 'listen 127.0.0.1:8090\nendpoint e { base http://a/v1 }\nreq for "*" judge every 2 %s as "m" pass e\n' "$LONG" > "$TMP/bad5.conf" OUT5=$(./junction --config "$TMP/bad5.conf" 2>&1) contains "$OUT5" "judge target" "an overlong judge target is rejected" GOOD=$(python3 -c "print('y' * 63)") printf 'listen 127.0.0.1:8090\nendpoint %s { base http://a/v1 }\nreq for "*" pass %s\n' "$GOOD" "$GOOD" > "$TMP/long63.conf" OUT6=$(./junction --config "$TMP/long63.conf" --check 2>&1) contains "$OUT6" "config ok" "a 63-character target still fits" echo "== 8-10. features: chunked bodies, caching, header passthrough ==" FEAT=$((PORT+4)) cat > "$TMP/features.conf" < "$TMP/features.log" 2>&1 & PIDS+=($!) sleep 0.7 BODY='{"model":"x","messages":[{"role":"user","content":"chunked body arrives intact"}],"max_tokens":8}' C1=${BODY:0:16} C2=${BODY:16} RESP=$( { printf 'POST /v1/chat/completions HTTP/1.1\r\nHost: t\r\nContent-Type: application/json\r\n' printf 'Transfer-Encoding: chunked\r\n\r\n' printf '%x\r\n%s\r\n%x\r\n%s\r\n0\r\n\r\n' ${#C1} "$C1" ${#C2} "$C2" } | nc -w 5 127.0.0.1 "$FEAT" ) contains "$RESP" "served by GATED" "chunked request is decoded and forwarded" contains "$RESP" "X-Stub-Body-Len: ${#BODY}" "decoded body reached the endpoint byte-exact" # A gateway in front of the provider may strip Transfer-Encoding and leave the # chunk framing in the body. Relayed raw, the client reads the hex sizes as SSE # content and reports a truncated stream. SSE1=$(curl -sN --raw -m 15 -X POST -H 'Content-Type: application/json' \ -d '{"model":"streamnote","stream":true,"messages":[{"role":"user","content":"go"}]}' \ "http://127.0.0.1:$FEAT/v1/chat/completions") case "$SSE1" in data:*) ok "chunk framing without a TE header is removed" ;; *) bad "framing leaked: $(printf '%s' "$SSE1" | head -c 30 | tr -d '\r\n')" ;; esac contains "$SSE1" '"stub":"two"' "both events arrive" SSE2=$(curl -sN --raw -m 15 -X POST -H 'Content-Type: application/json' \ -d '{"model":"streamcap","stream":true,"messages":[{"role":"user","content":"go"}]}' \ "http://127.0.0.1:$FEAT/v1/chat/completions") case "$SSE2" in data:*) ok "Transfer-Encoding is matched case-blind" ;; *) bad "capital-Chunked missed: $(printf '%s' "$SSE2" | head -c 30 | tr -d '\r\n')" ;; esac # Two live streams used to read into the same static relay buffers: every # client got deltas from several completions, which splinter assembled into # text with words missing and sentences spliced in. The fake upstream tags # every delta with its completion id and index, so a mixture is visible. if RACE=$(python3 tests/stream_race.py ./junction 2>&1); then ok "concurrent streams keep their own bytes" else bad "concurrent streams mixed: $(printf '%s' "$RACE" | tail -3 | tr '\n' ' ')" fi echo "== 10c. management endpoints are loopback-only ==" MG=$((PORT+80)) cat > "$TMP/mgmt.conf" < "$TMP/mgmt.log" 2>&1 & PIDS+=($!) sleep 0.7 IP=$(ip -4 -o addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1) if [ -n "$IP" ]; then R=$(curl -s -o /dev/null -w '%{http_code}' "http://$IP:$MG/admin/pause/gated") [ "$R" = "403" ] && ok "pause from $IP is refused (403)" || bad "pause from $IP answered $R" R=$(curl -s -o /dev/null -w '%{http_code}' "http://$IP:$MG/metrics") [ "$R" = "403" ] && ok "/metrics from $IP is refused (403)" || bad "/metrics from $IP answered $R" R=$(curl -s -o /dev/null -w '%{http_code}' "http://$IP:$MG/spend") [ "$R" = "403" ] && ok "/spend from $IP is refused (403)" || bad "/spend from $IP answered $R" else echo " SKIP management-from-LAN (no non-loopback address)" fi R=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$MG/admin/pause/gated") [ "$R" = "200" ] && ok "pause from loopback still works" || bad "local pause answered $R" curl -s -o /dev/null "http://127.0.0.1:$MG/admin/resume/gated" echo "== 10d. an endpoint with no key never forwards the caller's Authorization ==" NK=$((PORT+81)) cat > "$TMP/nokey.conf" </dev/null || true ./junction --config "$TMP/nokey.conf" > "$TMP/nokey.log" 2>&1 & PIDS+=($!) sleep 0.7 NK_RESP=$(curl -s -m 10 -H 'Authorization: Bearer SUPER-SECRET-TOKEN' \ -H 'Content-Type: application/json' \ -d '{"model":"nokeytest","messages":[{"role":"user","content":"hi"}]}' \ "http://127.0.0.1:$NK/v1/chat/completions") case "$NK_RESP" in *"served by GATED"*) bad "client Authorization reached the endpoint" ;; *) ok "request failed instead of forwarding the client token" ;; esac grep -q "no_key endpoint=nokey" "$TMP/nokey.log" && ok "the missing key is logged" \ || bad "missing key not logged" # same request twice: the second must come out of the cache (own body — the chunked # request above already filled the cache for its own body) # Temperatur 0, weil der Cache sonst bewusst nicht greift (siehe Abschnitt 22). CBODY='{"model":"cachemodel","messages":[{"role":"user","content":"cache me once"}],"max_tokens":8,"temperature":0}' R1=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ "http://127.0.0.1:$FEAT/v1/chat/completions") contains "$R1" "X-Junction-Cache: miss" "first request is a cache miss" R2=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ "http://127.0.0.1:$FEAT/v1/chat/completions") contains "$R2" "X-Junction-Cache: hit" "identical second request is a cache hit" R3=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ "http://127.0.0.1:$FEAT/v1/chat/completions") contains "$R3" "X-Junction-Cache: hit" "third request still a hit" curl -s -m 5 -X POST "http://127.0.0.1:$FEAT/admin/flush/cache" >/dev/null R4=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ "http://127.0.0.1:$FEAT/v1/chat/completions") contains "$R4" "X-Junction-Cache: miss" "flush clears the cache" R5=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' \ -H 'Cache-Control: no-cache' -d "$CBODY" "http://127.0.0.1:$FEAT/v1/chat/completions") contains "$R5" "X-Junction-Cache: off" "client no-cache bypasses the cache" R6=$(curl -s -m 10 -D- -X POST -H 'Content-Type: application/json' -H 'X-Custom: abc123' \ -d '{"model":"y","messages":[{"role":"user","content":"header check"}],"max_tokens":8}' \ "http://127.0.0.1:$FEAT/v1/chat/completions") contains "$R6" "X-Stub-Custom: abc123" "client header reaches the endpoint" contains "$R6" "X-Stub-Static: yes" "endpoint 'header' line is injected" contains "$R6" "X-Junction-Endpoint: gated" "response names the serving endpoint" contains "$R6" "X-Stub-Xff: " "X-Forwarded-For reaches the endpoint" echo "== 11. TLS listener ==" if command -v openssl >/dev/null 2>&1 && [ -f /usr/include/openssl/ssl.h ]; then openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TMP/key.pem" -out "$TMP/cert.pem" \ -days 1 -subj "/CN=localhost" >/dev/null 2>&1 TLSP=$((PORT+5)) cat > "$TMP/tls.conf" < "$TMP/tls.log" 2>&1 & PIDS+=($!) sleep 0.8 TS=$(curl -sk -m 10 "https://127.0.0.1:$TLSP/status") contains "$TS" '"listener":{"tls":true}' "TLS listener answers https" TR=$(curl -sk -m 10 -X POST -H 'Content-Type: application/json' \ -d '{"model":"z","messages":[{"role":"user","content":"tls"}],"max_tokens":8}' \ "https://127.0.0.1:$TLSP/v1/chat/completions") contains "$TR" "served by GATED" "request over TLS reaches the endpoint" echo "== 12. TLS upstream (https endpoint) ==" ./tests/stub 9443 SECURE --tls "$TMP/cert.pem" "$TMP/key.pem" > "$TMP/stubtls.log" 2>&1 & PIDS+=($!) sleep 0.8 cat > "$TMP/tlsup.conf" < "$TMP/tlsup.log" 2>&1 & PIDS+=($!) sleep 0.8 US=$(curl -s -m 15 -X POST -H 'Content-Type: application/json' \ -d '{"model":"s","messages":[{"role":"user","content":"over tls"}],"max_tokens":8}' \ "http://127.0.0.1:$((PORT+6))/v1/chat/completions") contains "$US" "served by SECURE" "request served by an https endpoint" for _try in 1 2 3 4 5 6 7 8 9 10; do grep -q "tls=1" "$TMP/tlsup.log" && break sleep 0.1 done grep -q "tls=1" "$TMP/tlsup.log" && ok "log marks the TLS connection" || bad "log marks the TLS connection" # verification must actually be enforced: the same self-signed peer, tls_verify on cat > "$TMP/tlsverify.conf" < "$TMP/tlsverify.log" 2>&1 & PIDS+=($!) sleep 0.8 VS=$(curl -s -m 15 -o /dev/null -w '%{http_code}' -X POST \ -H 'Content-Type: application/json' -d '{"model":"s","max_tokens":8}' \ "http://127.0.0.1:$((PORT+7))/v1/chat/completions") if [ "$VS" = "503" ]; then ok "self-signed cert refused when verification is on"; else bad "unverified TLS accepted (got $VS)"; fi grep -q "tls_verify_failed" "$TMP/tlsverify.log" && ok "failure names the certificate problem" || bad "failure names the certificate problem" else echo " SKIP (no OpenSSL headers)" fi echo "== 13. concurrency: two slow requests run at the same time ==" CONC=$((PORT+8)) cat > "$TMP/conc.conf" < "$TMP/conc.log" 2>&1 & PIDS+=($!) sleep 0.7 T0=$(date +%s%N) curl -s -m 40 -X POST -H 'Content-Type: application/json' \ -d '{"model":"a","messages":[{"role":"user","content":"one"}],"max_tokens":8}' \ "http://127.0.0.1:$CONC/v1/chat/completions" > "$TMP/c1.out" & C1=$! curl -s -m 40 -X POST -H 'Content-Type: application/json' \ -d '{"model":"b","messages":[{"role":"user","content":"two"}],"max_tokens":8}' \ "http://127.0.0.1:$CONC/v1/chat/completions" > "$TMP/c2.out" & C2=$! wait "$C1" "$C2" MS=$(( ($(date +%s%N) - T0) / 1000000 )) contains "$(cat "$TMP/c1.out")" "served by SLOW" "first of the pair was served" contains "$(cat "$TMP/c2.out")" "served by SLOW" "second of the pair was served" if [ "$MS" -lt 11000 ]; then ok "both took ${MS} ms together (one 6 s delay, not two)"; else bad "serialised: ${MS} ms"; fi echo "== 14. a waiting streamer is told why it waits ==" QUEUE=$((PORT+9)) cat > "$TMP/queue.conf" < "$TMP/queue.log" 2>&1 & PIDS+=($!) sleep 0.7 curl -s -m 40 -X POST -H 'Content-Type: application/json' \ -d '{"model":"first","messages":[{"role":"user","content":"blocker"}],"max_tokens":8}' \ "http://127.0.0.1:$QUEUE/v1/chat/completions" > "$TMP/q1.out" & Q1=$! sleep 0.6 Q2=$(curl -sN -m 40 -X POST -H 'Accept: text/event-stream' \ -H 'Content-Type: application/json' \ -d '{"model":"second","stream":true,"messages":[{"role":"user","content":"waiter"}]}' \ "http://127.0.0.1:$QUEUE/v1/chat/completions") wait "$Q1" contains "$Q2" ": junction: waiting for a free slot" "the waiting stream carries a status comment" contains "$Q2" ": junction: still waiting" "and keeps saying so while it waits" contains "$Q2" "served by SLOW" "the real answer arrives in the same stream" case "$(cat "$TMP/q1.out")" in *junction:*) bad "a non-streaming caller saw injected text" ;; *) ok "the silent caller got no injected text" ;; esac grep -q "queued" "$TMP/queue.log" && ok "the queue is logged" || bad "the queue is logged" echo "== 15. a stream stays alive while the model is thinking ==" HB=$((PORT+10)) cat > "$TMP/hb.conf" < "$TMP/hb.log" 2>&1 & PIDS+=($!) sleep 0.7 HB_OUT=$(curl -sN -m 40 -X POST -H 'Accept: text/event-stream' -H 'Content-Type: application/json' \ -d '{"model":"thinker","stream":true,"messages":[{"role":"user","content":"think hard"}]}' \ "http://127.0.0.1:$HB/v1/chat/completions") contains "$HB_OUT" ": junction: model is still working" "a silent upstream produces heartbeats" contains "$HB_OUT" "served by PONDER" "and the answer still arrives after the silence" grep -q "still_working side=upstream" "$TMP/hb.log" && ok "the silence is logged as progress" \ || bad "the silence is logged as progress" # der stille Client bekommt weiterhin nichts injiziert HB_PLAIN=$(curl -s -m 40 -X POST -H 'Content-Type: application/json' \ -d '{"model":"quiet","messages":[{"role":"user","content":"no stream"}]}' \ "http://127.0.0.1:$HB/v1/chat/completions") case "$HB_PLAIN" in *junction:*) bad "a non-streaming caller received a heartbeat" ;; *) ok "no heartbeat without a stream" ;; esac echo "== 16. budgets: soft throttle, hard skip, least-usage, virtual keys ==" P_BUD1=9995; P_BUD2=9996 tests/stub $P_BUD1 "RICH" & PIDS+=($!) tests/stub $P_BUD2 "POOR" & PIDS+=($!) sleep 0.4 # usage_cmd: ein Skript, das eine Zeile key=value ausgibt — genau wie in Produktion cat > "$TMP/u90.sh" <<'EOS' #!/bin/sh echo "percent=90 used_usd=54 budget_usd=60 reset_s=0" EOS cat > "$TMP/u5.sh" <<'EOS' #!/bin/sh echo "percent=5 used_usd=3 budget_usd=60 reset_s=0" EOS chmod +x "$TMP/u90.sh" "$TMP/u5.sh" BUD=$((PORT+11)) cat > "$TMP/budget.conf" < "$TMP/budget.log" 2>&1 & PIDS+=($!) sleep 2.5 # der Usage-Faden muss mindestens einmal gelaufen sein B_RESP=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ -d '{"model":"ds4","messages":[{"role":"user","content":"balance"}]}' \ "http://127.0.0.1:$BUD/v1/chat/completions") contains "$B_RESP" "served by POOR" "least-usage picks the endpoint with more headroom" grep -q "usage endpoint=rich" "$TMP/budget.log" && ok "the usage command ran and was logged" \ || bad "the usage command ran and was logged" # hartes Limit: rich auf 96 % -> muss uebersprungen werden cat > "$TMP/u96.sh" <<'EOS' #!/bin/sh echo "percent=96 used_usd=58 budget_usd=60 reset_s=0" EOS chmod +x "$TMP/u96.sh" cat > "$TMP/hard.conf" < "$TMP/hard.log" 2>&1 & PIDS+=($!) sleep 2.5 H_RESP=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' \ -d '{"model":"ds4","messages":[{"role":"user","content":"skip"}]}' \ "http://127.0.0.1:$((PORT+12))/v1/chat/completions") contains "$H_RESP" "served by POOR" "an endpoint over its hard budget is skipped" # weiche Drosselung: 85 % bei soft 80 -> mindestens 1 s Verzoegerung cat > "$TMP/u85.sh" <<'EOS' #!/bin/sh echo "percent=85 used_usd=51 budget_usd=60 reset_s=0" EOS chmod +x "$TMP/u85.sh" cat > "$TMP/soft.conf" < "$TMP/soft.log" 2>&1 & PIDS+=($!) wait_port $((PORT+13)) 10 # Nicht schlafen und hoffen: warten, bis der Abruf den Prozentwert wirklich hat. # usage_poll steht auf 1 s; unter Last war "nach 2,5 s ist es da" nicht immer wahr, # und die Prüfung maß dann 8 ms statt der Drosselung. for _i in $(seq 1 100); do curl -s -m 2 "http://127.0.0.1:$((PORT+13))/status" | grep -q '"usage_percent":85' && break sleep 0.1 done T0=$(date +%s%N) curl -s -m 20 -X POST -H 'Content-Type: application/json' \ -d '{"model":"ds4","messages":[{"role":"user","content":"slow down"}]}' \ "http://127.0.0.1:$((PORT+13))/v1/chat/completions" >/dev/null T1=$(date +%s%N) ELAPSED_MS=$(( (T1 - T0) / 1000000 )) if [ "$ELAPSED_MS" -ge 1500 ]; then ok "soft budget delays the request (${ELAPSED_MS} ms)"; else bad "soft budget delays the request (${ELAPSED_MS} ms)"; fi # virtuelle Schluessel: Modell ausserhalb des allow-Globs -> 403 cat > "$TMP/vkey.conf" < "$TMP/vkey.log" 2>&1 & PIDS+=($!) sleep 0.8 VK_OK=$(curl -s -m 20 -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer vk-secret-123' \ -d '{"model":"ds4","messages":[{"role":"user","content":"allowed"}]}' \ "http://127.0.0.1:$((PORT+14))/v1/chat/completions") contains "$VK_OK" "served by RICH" "a vkey inside its allow-glob is served" VK_NO=$(curl -s -m 20 -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer vk-secret-123' \ -d '{"model":"gpt-6","messages":[{"role":"user","content":"denied"}]}' \ "http://127.0.0.1:$((PORT+14))/v1/chat/completions") [ "$VK_NO" = "403" ] && ok "a vkey outside its allow-glob is refused (403)" \ || bad "a vkey outside its allow-glob is refused (got $VK_NO)" # Konfigurationsfehler muessen laut sein printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n budget soft abc\n}\n' > "$TMP/badbudget.conf" OUT=$(./junction --config "$TMP/badbudget.conf" 2>&1) contains "$OUT" "bad arguments" "a non-numeric budget is rejected" printf 'endpoint e {\n base http://127.0.0.1:9995/v1\n offpeak 25:00-26:00\n}\n' > "$TMP/badoffpeak.conf" OUT=$(./junction --config "$TMP/badoffpeak.conf" 2>&1) contains "$OUT" "bad arguments" "an impossible offpeak window is rejected" # ctx-Filter und Vision-Routing liegen in einer eigenen Datei, damit run.sh lesbar bleibt. # shellcheck source=tests/ctx-vision.sh . "$(dirname "$0")/ctx-vision.sh" # Die opencode-Brücke, gegen einen Nachbau des Sitzungs-API. # shellcheck source=tests/opencode.sh . "$(dirname "$0")/opencode.sh" # Globale Modell-Politik: /v1/models filtern, Anfragen abweisen. # shellcheck source=tests/model-policy.sh . "$(dirname "$0")/model-policy.sh" # Virtuelle Modelle: Ketten-Grenzen in /v1/models und ctx-Überlauf über Regeln. # shellcheck source=tests/virtual-models.sh . "$(dirname "$0")/virtual-models.sh" # Effort: Anthropic output_config, OpenAI-kompatible unverändert. # shellcheck source=tests/effort.sh . "$(dirname "$0")/effort.sh" # Wenn kein Ziel den Kontext fasst: Fallback auf den ds41flash-Pool. # shellcheck source=tests/ctx-fallback.sh . "$(dirname "$0")/ctx-fallback.sh" # Gewichtung, Balance pro Regel und Zeitlimits. # shellcheck source=tests/balancing.sh . "$(dirname "$0")/balancing.sh" # Benannte Ketten und einzeilige Blöcke. # shellcheck source=tests/pools.sh . "$(dirname "$0")/pools.sh" # Wiederholung vor dem Failover, Schlüssel-Pool und /metrics. # shellcheck source=tests/retry-metrics.sh . "$(dirname "$0")/retry-metrics.sh" # Limits je virtuellem Schlüssel und das Spend-Log. # shellcheck source=tests/spend-vkey.sh . "$(dirname "$0")/spend-vkey.sh" # Warten auf die Rückkehr der Kette, statt sofort zu scheitern. # shellcheck source=tests/offline-wait.sh . "$(dirname "$0")/offline-wait.sh" # Wächter vor dem Weiterleiten. # shellcheck source=tests/guard.sh . "$(dirname "$0")/guard.sh" # Kürzen von Werkzeugausgaben. # shellcheck source=tests/compress.sh . "$(dirname "$0")/compress.sh" # Antwort-Cache und seine Grenze. # shellcheck source=tests/cache.sh . "$(dirname "$0")/cache.sh" # Single-Flight: gleiche Anfrage, ein Aufruf. # shellcheck source=tests/flight.sh . "$(dirname "$0")/flight.sh" # Verbrauch und Kosten pro Anfrage. # shellcheck source=tests/usage.sh . "$(dirname "$0")/usage.sh" # Mehrere Instanzen, gemeinsamer Cache, SO_REUSEPORT, Drain. # shellcheck source=tests/cluster.sh . "$(dirname "$0")/cluster.sh" # Eine Zeile je bedienter Anfrage (Status, Dauer, Regel, Cache-Quelle). # shellcheck source=tests/reqlog.sh . "$(dirname "$0")/reqlog.sh" # Retry-After des Anbieters statt eigener Wartezeit. # shellcheck source=tests/retry-after.sh . "$(dirname "$0")/retry-after.sh" # Ein Modell zur Zeit, mehrere Modelle parallel, Präfix weg. # shellcheck source=tests/local-pool.sh . "$(dirname "$0")/local-pool.sh" # Erreichbarkeit im Hintergrund prüfen: offline nehmen, dann wieder nachsehen. # shellcheck source=tests/probe.sh . "$(dirname "$0")/probe.sh" # Ein Schlüssel in der Umgebung ist ein Endpunkt. # shellcheck source=tests/env-providers.sh . "$(dirname "$0")/env-providers.sh" # junction als MCP-Server: Werkzeuge der angebundenen Server bündeln und # Aufrufe an den richtigen Server weiterreichen. Eigenes Programm, weil zwei # erfundene MCP-Server gebraucht werden. echo echo "== MCP ==" if python3 "$(dirname "$0")/mcp.py" > "$TMP/mcp.log" 2>&1; then ok "$(tail -1 "$TMP/mcp.log")" else fail "MCP-Prüfungen fehlgeschlagen:" sed 's/^/ /' "$TMP/mcp.log" | tail -12 fi # Umschlag: die Antwort muss die id der Anfrage tragen. Der Fehler dahinter # liess jeden Werkzeugaufruf mit einem Argument "id" (task_get, task_done ...) # im Client ewig haengen, weil die Antwort die id des Arguments trug. echo "== MCP-Umschlag ==" if python3 "$(dirname "$0")/mcp_envelope.py" > "$TMP/mcp_env.log" 2>&1; then grep -E '^ |^PASS' "$TMP/mcp_env.log" | sed 's/^/ /' else fail "Umschlag-Pruefungen fehlgeschlagen:" grep -vE '^\[jenv\]' "$TMP/mcp_env.log" | sed 's/^/ /' | tail -12 fi # Virtuelles Modell: jede N-te Anfrage einer Unterhaltung geht an den Judge. # 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" # Gleichzeitigkeit: viele Clients am selben MCP-Eingang, ein langsamer Server # darf die anderen nicht ausbremsen. Zaehlt die Abfragen an die Server mit. echo "== MCP unter Last ==" if python3 "$(dirname "$0")/mcp_concurrency.py" > "$TMP/mcp_conc.log" 2>&1; then grep -E '^ |^PASS' "$TMP/mcp_conc.log" | sed 's/^/ /' else fail "Gleichzeitigkeit fehlgeschlagen:" grep -vE '^\[jtest\]' "$TMP/mcp_conc.log" | sed 's/^/ /' | tail -14 fi # Fehlerhafte Anfragen: ein Parser darf an Garbage, die ein Peer schicken # kann, weder sterben noch hängen bleiben. echo echo "== Fehlerhafte Anfragen ==" if JUNCTION_BIN="$PWD/junction" python3 "$(dirname "$0")/malformed.py" \ > "$TMP/malformed.log" 2>&1; then ok "$(tail -1 "$TMP/malformed.log")" else fail "malformed-request probe failed:" sed 's/^/ /' "$TMP/malformed.log" | tail -12 fi # Steuerkanal: Regeln im Betrieb setzen und löschen, Endpunkte pausieren, # Konfiguration schreiben — jeweils mit Prüfung, dass der Router danach anders handelt. echo echo "== Steuerkanal ==" if JUNCTION_BIN="$PWD/junction" python3 "$(dirname "$0")/control.py" > "$TMP/control.log" 2>&1; then ok "$(tail -1 "$TMP/control.log")" else fail "Steuerkanal-Prüfungen fehlgeschlagen:" sed 's/^/ /' "$TMP/control.log" | tail -12 fi echo if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi exit "$FAILED"