mooncak397 Claude Opus 5.5 commited on
Commit
e7ab12a
·
1 Parent(s): d49e34a

M6 fixes after Ivy's blackbox test: 503 on missing model config (F1), TRUST_PROXY (F2), control characters in email (F3)

Browse files

- F1: SystemExit from app/llm.py in /chat gives 503 model_unavailable with the BUSY text.
- F2: TRUST_PROXY (default true, HF proxy); false = socket address. uvicorn runs with
--no-proxy-headers, because app/guards.py reads X-Forwarded-For itself.
- F3: the email field rejects every control character, not only CR and LF.
Blackbox: strict xfail markers removed; the F1 test expects 503, the F2 test sets TRUST_PROXY=false.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

.env.example CHANGED
@@ -13,5 +13,6 @@ MODEL_JUDGE=gemma-4-31b-it
13
  # TURNSTILE_SECRET= # Cloudflare Turnstile; unset = check skipped (dev only)
14
  # RESEND_API_KEY= # unset = /contact answers 503
15
  # CONTACT_TO= # the one recipient (the Resend account address)
 
16
  # CONTACT_FROM= # default: Recruiter assistant <onboarding@resend.dev>
17
  # Limits (defaults): SESSIONS_PER_IP_HOUR=10 CHAT_PER_IP_HOUR=20 CHAT_PER_DAY=140 CONTACT_PER_IP_DAY=1 CONTACT_PER_DAY=5
 
13
  # TURNSTILE_SECRET= # Cloudflare Turnstile; unset = check skipped (dev only)
14
  # RESEND_API_KEY= # unset = /contact answers 503
15
  # CONTACT_TO= # the one recipient (the Resend account address)
16
+ # TRUST_PROXY=true # true behind the HF proxy (client IP = last X-Forwarded-For entry); false = socket address
17
  # CONTACT_FROM= # default: Recruiter assistant <onboarding@resend.dev>
18
  # Limits (defaults): SESSIONS_PER_IP_HOUR=10 CHAT_PER_IP_HOUR=20 CHAT_PER_DAY=140 CONTACT_PER_IP_DAY=1 CONTACT_PER_DAY=5
Dockerfile CHANGED
@@ -11,5 +11,7 @@ COPY --chown=user app ./app
11
  COPY --chown=user profile ./profile
12
  COPY --chown=user prompts ./prompts
13
  EXPOSE 7860
 
 
14
  # exactly 1 worker: chat sessions live in process memory (ADR-010)
15
- CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
 
11
  COPY --chown=user profile ./profile
12
  COPY --chown=user prompts ./prompts
13
  EXPOSE 7860
14
+ # TRUST_PROXY defaults to true (HF proxy sets X-Forwarded-For); set TRUST_PROXY=false when no proxy is in front.
15
+ # --no-proxy-headers: app/guards.py reads X-Forwarded-For itself; uvicorn must not rewrite the client address.
16
  # exactly 1 worker: chat sessions live in process memory (ADR-010)
17
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1", "--no-proxy-headers"]
README.md CHANGED
@@ -12,7 +12,7 @@ Every prompt version will be scored against a fixed golden set, and the score hi
12
 
13
  ## Server (M6)
14
 
15
- `uv run uvicorn app.main:app --port 7860 --workers 1` (exactly 1 worker: chat history lives in process memory, ADR-010).
16
 
17
  - `POST /session` with `{}` (or `{"turnstile_token": "..."}` when `TURNSTILE_SECRET` is set) returns `{"token", "expires_in", "turns_left"}`.
18
  - `POST /chat` with `Authorization: Bearer <token>` and exactly `{"message": "..."}` returns `{"reply", "show_form", "lang", "turns_left"}`. Any other field gives 422, a missing or forged token 401 `invalid_session`, an expired or lost session 401 `session_expired`, more than 1,000 characters 413, a running request for the same session 409.
 
12
 
13
  ## Server (M6)
14
 
15
+ `uv run uvicorn app.main:app --port 7860 --workers 1 --no-proxy-headers` (exactly 1 worker: chat history lives in process memory, ADR-010).
16
 
17
  - `POST /session` with `{}` (or `{"turnstile_token": "..."}` when `TURNSTILE_SECRET` is set) returns `{"token", "expires_in", "turns_left"}`.
18
  - `POST /chat` with `Authorization: Bearer <token>` and exactly `{"message": "..."}` returns `{"reply", "show_form", "lang", "turns_left"}`. Any other field gives 422, a missing or forged token 401 `invalid_session`, an expired or lost session 401 `session_expired`, more than 1,000 characters 413, a running request for the same session 409.
app/contact.py CHANGED
@@ -11,6 +11,7 @@ log = logging.getLogger(__name__)
11
  RESEND_URL = "https://api.resend.com/emails"
12
  SUBJECT = "Recruiter assistant: new contact request" # fixed, so no header injection
13
  EMAIL = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")
 
14
 
15
 
16
  class ContactForm(BaseModel):
@@ -23,7 +24,7 @@ class ContactForm(BaseModel):
23
  @classmethod
24
  def _email(cls, v: str) -> str:
25
  v = v.strip()
26
- if "\r" in v or "\n" in v or not EMAIL.fullmatch(v):
27
  raise ValueError("invalid email")
28
  return v
29
 
 
11
  RESEND_URL = "https://api.resend.com/emails"
12
  SUBJECT = "Recruiter assistant: new contact request" # fixed, so no header injection
13
  EMAIL = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")
14
+ CONTROL = re.compile(r"[\x00-\x1f\x7f]") # NUL, CR, LF and every other control character
15
 
16
 
17
  class ContactForm(BaseModel):
 
24
  @classmethod
25
  def _email(cls, v: str) -> str:
26
  v = v.strip()
27
+ if CONTROL.search(v) or not EMAIL.fullmatch(v):
28
  raise ValueError("invalid email")
29
  return v
30
 
app/guards.py CHANGED
@@ -69,10 +69,13 @@ class Limiter:
69
 
70
 
71
  def client_ip(headers, peer: str | None) -> str:
72
- # Behind the HF proxy the LAST X-Forwarded-For entry is the one the proxy added;
73
- # earlier entries come from the client and can be forged.
 
74
  xff = headers.get("x-forwarded-for")
75
- return xff.split(",")[-1].strip() if xff else (peer or "unknown")
 
 
76
 
77
 
78
  def turnstile_ok(token: str | None, ip: str) -> bool:
 
69
 
70
 
71
  def client_ip(headers, peer: str | None) -> str:
72
+ # TRUST_PROXY (default true: the Space is behind the HF proxy): the LAST X-Forwarded-For entry
73
+ # is the one the proxy added; earlier entries come from the client and can be forged.
74
+ # Without a proxy any client can set the header, so TRUST_PROXY=false uses the socket address only.
75
  xff = headers.get("x-forwarded-for")
76
+ if xff and os.environ.get("TRUST_PROXY", "true").lower() not in ("0", "false", "no"):
77
+ return xff.split(",")[-1].strip()
78
+ return peer or "unknown"
79
 
80
 
81
  def turnstile_ok(token: str | None, ip: str) -> bool:
app/main.py CHANGED
@@ -1,5 +1,5 @@
1
  """FastAPI app (plan section 3, ADR-010 decision 1). Run with exactly 1 worker: sessions live in process memory.
2
- uv run uvicorn app.main:app --port 7860 --workers 1"""
3
  import logging
4
  import os
5
  import threading
@@ -14,7 +14,7 @@ from app import contact as contact_mod
14
  from app.guards import Limiter, Tokens, client_ip, turnstile_ok
15
  from app.prompts import rules_version
16
  from app.sessions import MAX_TURNS, TTL, SessionStore
17
- from app.texts import EMPTY, SESSION_LIMIT
18
 
19
  logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s") # Space logs: no message text
20
  log = logging.getLogger("app.main")
@@ -113,7 +113,12 @@ def create_app(graph=None, clock=time.time, sender=None) -> FastAPI:
113
  if not lim["chat_day"].hit("global"):
114
  raise HTTPException(429, "daily_limit")
115
  t0 = time.time()
116
- out = get_graph().invoke({"messages": [*store.context(s), ("user", text)], "lang": s.lang})
 
 
 
 
 
117
  reply, lang = out["reply"], out["lang"]
118
  log.info("chat route=%s lang=%s form=%s ms=%d", out["route"], lang, out["show_form"],
119
  (time.time() - t0) * 1000)
 
1
  """FastAPI app (plan section 3, ADR-010 decision 1). Run with exactly 1 worker: sessions live in process memory.
2
+ uv run uvicorn app.main:app --port 7860 --workers 1 --no-proxy-headers"""
3
  import logging
4
  import os
5
  import threading
 
14
  from app.guards import Limiter, Tokens, client_ip, turnstile_ok
15
  from app.prompts import rules_version
16
  from app.sessions import MAX_TURNS, TTL, SessionStore
17
+ from app.texts import BUSY, EMPTY, SESSION_LIMIT
18
 
19
  logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s") # Space logs: no message text
20
  log = logging.getLogger("app.main")
 
113
  if not lim["chat_day"].hit("global"):
114
  raise HTTPException(429, "daily_limit")
115
  t0 = time.time()
116
+ try:
117
+ graph = get_graph()
118
+ except SystemExit as e: # app/llm.py: model name or key missing; a config error, not a crash
119
+ log.error("model_config_missing %s", type(e).__name__)
120
+ return JSONResponse({"detail": "model_unavailable", "reply": BUSY[s.lang]}, 503)
121
+ out = graph.invoke({"messages": [*store.context(s), ("user", text)], "lang": s.lang})
122
  reply, lang = out["reply"], out["lang"]
123
  log.info("chat route=%s lang=%s form=%s ms=%d", out["route"], lang, out["show_form"],
124
  (time.time() - t0) * 1000)
tests/blackbox/test_m6_blackbox.py CHANGED
@@ -39,7 +39,8 @@ class Server:
39
  e.pop("CONTACT_TO", None)
40
  e.update(env)
41
  self.log = open(f"/tmp/bb-{self.port}.log", "w")
42
- self.p = subprocess.Popen([sys.executable, "-m", "uvicorn", "app.main:app", "--port", str(self.port), "--workers", "1"],
 
43
  cwd=ROOT, env=e, stdout=self.log, stderr=subprocess.STDOUT)
44
  self.url = f"http://127.0.0.1:{self.port}"
45
  for _ in range(100):
@@ -267,9 +268,8 @@ def test_concurrent_same_session_409():
267
 
268
 
269
  # ---- rate limits (no model call: use /session and failing chats) ----
270
- @pytest.mark.xfail(strict=True, reason='F2: client_ip trusts last XFF entry; a direct (non-proxy) client rotates it')
271
  def test_session_rate_limit_and_xff():
272
- s = Server(SESSIONS_PER_IP_HOUR="3")
273
  try:
274
  codes = [httpx.post(s.url + "/session", json={}).status_code for _ in range(5)]
275
  assert codes == [200, 200, 200, 429, 429], codes
@@ -413,7 +413,6 @@ def test_error_bodies(srv):
413
  assert not srv.logtext().count("Traceback") or print("TRACEBACK IN LOG")
414
 
415
 
416
- @pytest.mark.xfail(strict=True, reason='F1: missing model key -> SystemExit in the request -> 500 (expected 503)')
417
  def test_missing_model_key_no_500_no_leak():
418
  if not REAL:
419
  pytest.skip("real model")
@@ -421,8 +420,9 @@ def test_missing_model_key_no_500_no_leak():
421
  try:
422
  t = s.session()
423
  r = s.chat(t, {"message": "Which languages does Christopher use?"})
424
- assert r.status_code < 500, f"BUG {r.status_code} {r.text[:200]}"
425
- clean(r)
 
426
  assert httpx.get(s.url + "/health").status_code == 200, "server dead after missing key"
427
  finally:
428
  s.stop()
@@ -441,7 +441,6 @@ def test_wrong_model_key_no_leak():
441
  s.stop()
442
 
443
 
444
- @pytest.mark.xfail(strict=True, reason="F3: NUL byte accepted in email (EMAIL regex allows control chars other than CR/LF)")
445
  def test_contact_email_nul_byte(srv):
446
  r = contact(srv, srv.session(), {**GOOD, "email": "a@b.co\x00"})
447
  assert r.status_code == 422
 
39
  e.pop("CONTACT_TO", None)
40
  e.update(env)
41
  self.log = open(f"/tmp/bb-{self.port}.log", "w")
42
+ self.p = subprocess.Popen([sys.executable, "-m", "uvicorn", "app.main:app", "--port", str(self.port), "--workers", "1",
43
+ "--no-proxy-headers"], # the documented run command (README, Dockerfile)
44
  cwd=ROOT, env=e, stdout=self.log, stderr=subprocess.STDOUT)
45
  self.url = f"http://127.0.0.1:{self.port}"
46
  for _ in range(100):
 
268
 
269
 
270
  # ---- rate limits (no model call: use /session and failing chats) ----
 
271
  def test_session_rate_limit_and_xff():
272
+ s = Server(SESSIONS_PER_IP_HOUR="3", TRUST_PROXY="false") # direct clients: no proxy in front
273
  try:
274
  codes = [httpx.post(s.url + "/session", json={}).status_code for _ in range(5)]
275
  assert codes == [200, 200, 200, 429, 429], codes
 
413
  assert not srv.logtext().count("Traceback") or print("TRACEBACK IN LOG")
414
 
415
 
 
416
  def test_missing_model_key_no_500_no_leak():
417
  if not REAL:
418
  pytest.skip("real model")
 
420
  try:
421
  t = s.session()
422
  r = s.chat(t, {"message": "Which languages does Christopher use?"})
423
+ assert r.status_code == 503 and r.json()["detail"] == "model_unavailable", f"BUG {r.status_code} {r.text[:200]}"
424
+ for m in SECRET_MARKERS:
425
+ assert m not in r.text
426
  assert httpx.get(s.url + "/health").status_code == 200, "server dead after missing key"
427
  finally:
428
  s.stop()
 
441
  s.stop()
442
 
443
 
 
444
  def test_contact_email_nul_byte(srv):
445
  r = contact(srv, srv.session(), {**GOOD, "email": "a@b.co\x00"})
446
  assert r.status_code == 422
tests/test_api.py CHANGED
@@ -189,7 +189,7 @@ def test_contact_sends_once(env):
189
  assert len(sent) == 1 and sent[0].email == FORM["email"] and g.inputs == [] # no graph call
190
 
191
 
192
- @pytest.mark.parametrize("bad", [{"email": "nope"}, {"email": "a@b.c\r\nBcc: x@y.z"}, {"email": "a" * 250 + "@b.cc"},
193
  {"message": "x" * 2001}, {"message": " "}, {"to": "x@y.z"}, {"cc": "x@y.z"}])
194
  def test_contact_validation_422(env, bad):
195
  c, _, _, sent = make(env)
@@ -262,3 +262,19 @@ def test_contact_module_never_imports_the_graph():
262
  names = {a.name for n in ast.walk(ast.parse(src)) if isinstance(n, (ast.Import, ast.ImportFrom))
263
  for a in n.names} | {n.module for n in ast.walk(ast.parse(src)) if isinstance(n, ast.ImportFrom)}
264
  assert not any(x and ("graph" in x or "llm" in x) for x in names)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  assert len(sent) == 1 and sent[0].email == FORM["email"] and g.inputs == [] # no graph call
190
 
191
 
192
+ @pytest.mark.parametrize("bad", [{"email": "nope"}, {"email": "a@b.c\r\nBcc: x@y.z"}, {"email": "a@b.co\x00"}, {"email": "a\tb@c.de"}, {"email": "a" * 250 + "@b.cc"},
193
  {"message": "x" * 2001}, {"message": " "}, {"to": "x@y.z"}, {"cc": "x@y.z"}])
194
  def test_contact_validation_422(env, bad):
195
  c, _, _, sent = make(env)
 
262
  names = {a.name for n in ast.walk(ast.parse(src)) if isinstance(n, (ast.Import, ast.ImportFrom))
263
  for a in n.names} | {n.module for n in ast.walk(ast.parse(src)) if isinstance(n, ast.ImportFrom)}
264
  assert not any(x and ("graph" in x or "llm" in x) for x in names)
265
+
266
+
267
+ def test_trust_proxy_false_uses_socket_address(env):
268
+ c, *_ = make(env, CHAT_PER_IP_HOUR="1", TRUST_PROXY="false")
269
+ h = token(c)
270
+ assert c.post("/chat", json={"message": "q"}, headers=h).status_code == 200
271
+ assert c.post("/chat", json={"message": "q"}, headers={**h, "X-Forwarded-For": "9.9.9.9"}).status_code == 429
272
+
273
+
274
+ def test_missing_model_config_gives_503(env, monkeypatch):
275
+ def boom():
276
+ raise SystemExit("ANTHROPIC_API_KEY is not set.")
277
+ monkeypatch.setattr("app.llm.get_model", boom)
278
+ c = TestClient(create_app(clock=Clock())) # no fake graph: the real lazy build path
279
+ r = c.post("/chat", json={"message": "q"}, headers=token(c))
280
+ assert r.status_code == 503 and r.json()["detail"] == "model_unavailable" and "API_KEY" not in r.text