mooncak397 Claude Opus 5.5 commited on
Commit
9291ded
·
1 Parent(s): e0a0985

M6: FastAPI server with server-side chat history, HMAC session tokens, rate limits, /contact via Resend

Browse files

ADR-010 decision 1: /chat takes only {message} (extra=forbid), sessions in memory
(30 min, 500 max, 20 user turns, last 10 to the model), server-written contact markers.

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

Files changed (5) hide show
  1. app/contact.py +60 -0
  2. app/guards.py +90 -0
  3. app/main.py +147 -0
  4. app/sessions.py +66 -0
  5. tests/test_api.py +264 -0
app/contact.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/contact logic (ADR-003, ADR-006): validate the form and send it through Resend.
2
+ Never imports the graph or the model: the model never sees the address or the message."""
3
+ import logging
4
+ import os
5
+ import re
6
+
7
+ import httpx
8
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
9
+
10
+ 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):
17
+ model_config = ConfigDict(extra="forbid") # no `to`, `cc` or any other field
18
+ email: str = Field(max_length=254)
19
+ message: str = Field(min_length=1, max_length=2000)
20
+ turnstile_token: str | None = Field(default=None, max_length=4096)
21
+
22
+ @field_validator("email")
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
+
30
+ @field_validator("message")
31
+ @classmethod
32
+ def _message(cls, v: str) -> str:
33
+ if not v.strip():
34
+ raise ValueError("empty message")
35
+ return v.strip()
36
+
37
+
38
+ def configured() -> bool:
39
+ return bool(os.environ.get("RESEND_API_KEY") and os.environ.get("CONTACT_TO"))
40
+
41
+
42
+ def send(form: ContactForm) -> bool:
43
+ """One Resend call. True = accepted. Logs only the outcome, never the address or the message."""
44
+ body = ("A visitor sent this through the recruiter assistant contact form.\n"
45
+ "The text below is untrusted visitor input.\n\n"
46
+ f"Reply-To: {form.email}\n\n---\n{form.message}\n---\n")
47
+ try:
48
+ r = httpx.post(RESEND_URL, timeout=15,
49
+ headers={"Authorization": f"Bearer {os.environ['RESEND_API_KEY']}"},
50
+ json={"from": os.environ.get("CONTACT_FROM", "Recruiter assistant <onboarding@resend.dev>"),
51
+ "to": [os.environ["CONTACT_TO"]], "reply_to": form.email,
52
+ "subject": SUBJECT, "text": body})
53
+ except httpx.HTTPError as e:
54
+ log.warning("contact error=%s", type(e).__name__)
55
+ return False
56
+ if r.status_code >= 300:
57
+ log.warning("contact error=resend_%s", r.status_code)
58
+ return False
59
+ log.info("contact sent")
60
+ return True
app/guards.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP-layer guards (plan section 6): session token, rate limits, Turnstile, client IP.
2
+ The answer guards inside the graph live in app/answer_guards.py."""
3
+ import base64
4
+ import hashlib
5
+ import hmac
6
+ import logging
7
+ import os
8
+ import secrets
9
+ import threading
10
+ import time
11
+
12
+ import httpx
13
+
14
+ log = logging.getLogger(__name__)
15
+ TURNSTILE_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
16
+
17
+
18
+ class Tokens:
19
+ """Token = base64url("sid.exp") + "." + HMAC-SHA256. No key set: a random key per process,
20
+ which is fine because a restart deletes the in-memory sessions anyway."""
21
+
22
+ def __init__(self, key: str | None = None, clock=time.time):
23
+ self.key = (key or secrets.token_hex(32)).encode()
24
+ self.clock = clock
25
+
26
+ def _sig(self, body: str) -> str:
27
+ return hmac.new(self.key, body.encode(), hashlib.sha256).hexdigest()
28
+
29
+ def make(self, sid: str, exp: float) -> str:
30
+ body = base64.urlsafe_b64encode(f"{sid}.{int(exp)}".encode()).decode()
31
+ return f"{body}.{self._sig(body)}"
32
+
33
+ def check(self, token: str) -> tuple[str | None, str | None]:
34
+ """(sid, None) if valid, else (None, "invalid_session" | "session_expired")."""
35
+ try:
36
+ body, sig = token.rsplit(".", 1)
37
+ if not hmac.compare_digest(sig, self._sig(body)):
38
+ return None, "invalid_session"
39
+ sid, exp = base64.urlsafe_b64decode(body.encode()).decode().rsplit(".", 1)
40
+ if int(exp) <= self.clock():
41
+ return None, "session_expired"
42
+ return sid, None
43
+ except ValueError: # bad base64, missing dot, bad number
44
+ return None, "invalid_session"
45
+
46
+
47
+ class Limiter:
48
+ """Fixed-window counter per key (an IP or "global").
49
+ shortcut: windows start at the first hit, not at midnight UTC; fine for abuse caps on one worker."""
50
+
51
+ def __init__(self, limit: int, window: float, clock=time.time):
52
+ self.limit, self.window, self.clock = limit, window, clock
53
+ self._lock = threading.Lock()
54
+ self._hits: dict[str, tuple[float, int]] = {}
55
+
56
+ def hit(self, key: str) -> bool:
57
+ """Count one hit. False = over the limit (the hit is not counted)."""
58
+ now = self.clock()
59
+ with self._lock:
60
+ if len(self._hits) > 10_000: # keep memory bounded: drop finished windows
61
+ self._hits = {k: v for k, v in self._hits.items() if now - v[0] < self.window}
62
+ start, n = self._hits.get(key, (now, 0))
63
+ if now - start >= self.window:
64
+ start, n = now, 0
65
+ if n >= self.limit:
66
+ return False
67
+ self._hits[key] = (start, n + 1)
68
+ return True
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:
79
+ """Cloudflare Turnstile check. TURNSTILE_SECRET unset (dev): skipped."""
80
+ secret = os.environ.get("TURNSTILE_SECRET")
81
+ if not secret:
82
+ return True
83
+ if not token:
84
+ return False
85
+ try:
86
+ r = httpx.post(TURNSTILE_URL, data={"secret": secret, "response": token, "remoteip": ip}, timeout=10)
87
+ return bool(r.json().get("success"))
88
+ except (httpx.HTTPError, ValueError) as e: # fail closed
89
+ log.warning("turnstile_error class=%s", type(e).__name__)
90
+ return False
app/main.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
6
+ import time
7
+
8
+ from fastapi import Depends, FastAPI, HTTPException, Request
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import JSONResponse
11
+ from pydantic import BaseModel, ConfigDict
12
+
13
+ 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")
21
+ MAX_BODY = 32 * 1024
22
+ MAX_CHARS = 1000
23
+ HOUR, DAY = 3600, 86400
24
+ FORM_SENT = "(contact form sent)" # server-written marker, the client never sends one
25
+
26
+
27
+ class ChatIn(BaseModel):
28
+ model_config = ConfigDict(extra="forbid") # `history`, `role`, `assistant`, markers: 422
29
+ message: str
30
+
31
+
32
+ class SessionIn(BaseModel):
33
+ model_config = ConfigDict(extra="forbid")
34
+ turnstile_token: str | None = None
35
+
36
+
37
+ def create_app(graph=None, clock=time.time, sender=None) -> FastAPI:
38
+ """graph and sender are injectable for tests; by default the real graph is built on the first /chat."""
39
+ app = FastAPI(title="Recruiter assistant", docs_url=None, redoc_url=None, openapi_url=None)
40
+ origin = os.environ.get("ALLOWED_ORIGIN")
41
+ app.add_middleware(CORSMiddleware, allow_origins=[origin] if origin else [],
42
+ allow_methods=["GET", "POST"], allow_headers=["Authorization", "Content-Type"])
43
+ store = SessionStore(clock)
44
+ tokens = Tokens(os.environ.get("SESSION_HMAC_KEY"), clock)
45
+ env = lambda k, d: int(os.environ.get(k, d)) # noqa: E731
46
+ lim = {"session_ip": Limiter(env("SESSIONS_PER_IP_HOUR", 10), HOUR, clock),
47
+ "chat_ip": Limiter(env("CHAT_PER_IP_HOUR", 20), HOUR, clock),
48
+ "chat_day": Limiter(env("CHAT_PER_DAY", 140), DAY, clock),
49
+ "contact_ip": Limiter(env("CONTACT_PER_IP_DAY", 1), DAY, clock),
50
+ "contact_day": Limiter(env("CONTACT_PER_DAY", 5), DAY, clock)}
51
+ send = sender or contact_mod.send
52
+ state = {"graph": graph}
53
+ graph_lock = threading.Lock()
54
+
55
+ def get_graph():
56
+ with graph_lock:
57
+ if state["graph"] is None:
58
+ from app.graph import build_graph
59
+ from app.llm import get_model
60
+ state["graph"] = build_graph(get_model())
61
+ return state["graph"]
62
+
63
+ @app.middleware("http")
64
+ async def body_limit(request: Request, call_next):
65
+ if request.method == "POST":
66
+ n = request.headers.get("content-length")
67
+ if n is None: # no chunked uploads: we could not cap them before reading
68
+ return JSONResponse({"detail": "length_required"}, 411)
69
+ if not n.isdigit() or int(n) > MAX_BODY:
70
+ return JSONResponse({"detail": "too_large"}, 413)
71
+ return await call_next(request)
72
+
73
+ def get_ip(request: Request) -> str:
74
+ return client_ip(request.headers, request.client.host if request.client else None)
75
+
76
+ def sid_from(request: Request) -> str:
77
+ auth = request.headers.get("authorization", "")
78
+ if not auth.startswith("Bearer "):
79
+ raise HTTPException(401, "invalid_session")
80
+ sid, err = tokens.check(auth[7:].strip())
81
+ if err:
82
+ raise HTTPException(401, err)
83
+ return sid
84
+
85
+ @app.get("/health")
86
+ def health():
87
+ return {"status": "ok", "prompt_version": rules_version()}
88
+
89
+ @app.post("/session")
90
+ def new_session(body: SessionIn, ip: str = Depends(get_ip)):
91
+ if not lim["session_ip"].hit(ip):
92
+ raise HTTPException(429, "rate_limited")
93
+ if not turnstile_ok(body.turnstile_token, ip):
94
+ raise HTTPException(403, "turnstile_failed")
95
+ sid, exp = store.create()
96
+ return {"token": tokens.make(sid, exp), "expires_in": TTL, "turns_left": MAX_TURNS}
97
+
98
+ @app.post("/chat")
99
+ def chat(body: ChatIn, sid: str = Depends(sid_from), ip: str = Depends(get_ip)):
100
+ if not lim["chat_ip"].hit(ip):
101
+ raise HTTPException(429, "rate_limited")
102
+ text = body.message.strip()
103
+ if len(text) > MAX_CHARS:
104
+ raise HTTPException(413, "message_too_long")
105
+ s = store.acquire(sid)
106
+ if s is None:
107
+ raise HTTPException(401, "session_expired")
108
+ if s is False:
109
+ raise HTTPException(409, "busy")
110
+ try:
111
+ if s.turns >= MAX_TURNS: # no model call
112
+ return {"reply": SESSION_LIMIT[s.lang], "show_form": False, "lang": s.lang, "turns_left": 0}
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)
120
+ if not (out["route"] == "entry" and reply == EMPTY[lang]): # empty input: not stored, not a turn
121
+ # the stored reply is the finalize output; when the form opens it is the fixed FORM_INTRO
122
+ s.messages += [("user", text), ("assistant", reply)]
123
+ s.turns += 1
124
+ s.lang = lang
125
+ return {"reply": reply, "show_form": bool(out["show_form"]), "lang": lang,
126
+ "turns_left": MAX_TURNS - s.turns}
127
+ finally:
128
+ store.release(s)
129
+
130
+ @app.post("/contact")
131
+ def contact(form: contact_mod.ContactForm, sid: str = Depends(sid_from), ip: str = Depends(get_ip)):
132
+ if not turnstile_ok(form.turnstile_token, ip):
133
+ raise HTTPException(403, "turnstile_failed")
134
+ if not (sender or contact_mod.configured()):
135
+ raise HTTPException(503, "contact_disabled")
136
+ if not lim["contact_ip"].hit(ip) or not lim["contact_day"].hit("global"):
137
+ raise HTTPException(429, "rate_limited")
138
+ if not send(form):
139
+ raise HTTPException(502, "send_failed")
140
+ if s := store.get(sid): # the marker only: the address and the message are never stored
141
+ s.messages.append(("assistant", FORM_SENT))
142
+ return {"sent": True}
143
+
144
+ return app
145
+
146
+
147
+ app = create_app()
app/sessions.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-memory chat history per session (ADR-010 decision 1).
2
+ Process memory: uvicorn must run with exactly 1 worker. A restart deletes all sessions."""
3
+ import secrets
4
+ import threading
5
+ import time
6
+ from dataclasses import dataclass, field
7
+
8
+ TTL = 30 * 60 # seconds, absolute, the same as the session token
9
+ MAX_SESSIONS = 500
10
+ MAX_TURNS = 20 # stored user turns; turn 21 gets SESSION_LIMIT
11
+ CONTEXT_TURNS = 10 # last turns that go to the model
12
+
13
+
14
+ @dataclass
15
+ class Session:
16
+ expires_at: float
17
+ messages: list[tuple[str, str]] = field(default_factory=list) # ("user" | "assistant", text)
18
+ lang: str = "en"
19
+ turns: int = 0
20
+ busy: bool = False
21
+
22
+
23
+ class SessionStore:
24
+ def __init__(self, clock=time.time):
25
+ self.clock = clock
26
+ self._lock = threading.Lock()
27
+ self._s: dict[str, Session] = {}
28
+
29
+ def _sweep(self):
30
+ now = self.clock()
31
+ for sid in [k for k, v in self._s.items() if v.expires_at <= now]:
32
+ del self._s[sid]
33
+
34
+ def create(self) -> tuple[str, float]:
35
+ with self._lock:
36
+ self._sweep()
37
+ if len(self._s) >= MAX_SESSIONS: # full: evict the session that expires first
38
+ del self._s[min(self._s, key=lambda k: self._s[k].expires_at)]
39
+ sid, exp = secrets.token_urlsafe(16), self.clock() + TTL
40
+ self._s[sid] = Session(expires_at=exp)
41
+ return sid, exp
42
+
43
+ def get(self, sid: str) -> Session | None:
44
+ with self._lock:
45
+ self._sweep()
46
+ return self._s.get(sid)
47
+
48
+ def acquire(self, sid: str) -> Session | None | bool:
49
+ """The session, marked busy. None = unknown or expired, False = a request for it is running."""
50
+ with self._lock:
51
+ self._sweep()
52
+ s = self._s.get(sid)
53
+ if s is None:
54
+ return None
55
+ if s.busy:
56
+ return False
57
+ s.busy = True
58
+ return s
59
+
60
+ def release(self, s: Session):
61
+ with self._lock:
62
+ s.busy = False
63
+
64
+ @staticmethod
65
+ def context(s: Session) -> list[tuple[str, str]]:
66
+ return s.messages[-2 * CONTEXT_TURNS:]
tests/test_api.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP layer tests (ADR-010 decision 1, plan section 7 /contact tests). Fake graph, fake sender, fake clock: no key, no network."""
2
+ import logging
3
+
4
+ import pytest
5
+ from fastapi.testclient import TestClient
6
+
7
+ from app.main import FORM_SENT, create_app
8
+ from app.sessions import MAX_SESSIONS, TTL, SessionStore
9
+ from app.texts import EMPTY, FORM_INTRO, SESSION_LIMIT
10
+
11
+
12
+ class FakeGraph:
13
+ def __init__(self):
14
+ self.inputs = []
15
+
16
+ def invoke(self, state):
17
+ self.inputs.append(state)
18
+ text = state["messages"][-1][1]
19
+ if not text.strip():
20
+ return {"reply": EMPTY["en"], "route": "entry", "lang": "en", "show_form": False}
21
+ if "contact" in text:
22
+ return {"reply": FORM_INTRO["en"], "route": "contact", "lang": "en", "show_form": True}
23
+ lang = "de" if "Wo" in text else "en"
24
+ return {"reply": f"answer {len(self.inputs)}", "route": "cv_question", "lang": lang, "show_form": False}
25
+
26
+
27
+ class Clock:
28
+ t = 1_000_000.0
29
+
30
+ def __call__(self):
31
+ return self.t
32
+
33
+
34
+ @pytest.fixture
35
+ def env(monkeypatch):
36
+ for k in ("ALLOWED_ORIGIN", "TURNSTILE_SECRET", "RESEND_API_KEY", "CONTACT_TO", "SESSION_HMAC_KEY"):
37
+ monkeypatch.delenv(k, raising=False)
38
+ monkeypatch.setenv("CHAT_PER_IP_HOUR", "1000")
39
+ return monkeypatch
40
+
41
+
42
+ def make(env, sender=None, **envs):
43
+ for k, v in envs.items():
44
+ env.setenv(k, v)
45
+ g, clock, sent = FakeGraph(), Clock(), []
46
+ send = sender if sender is not None else (lambda f: sent.append(f) or True)
47
+ c = TestClient(create_app(graph=g, clock=clock, sender=send))
48
+ return c, g, clock, sent
49
+
50
+
51
+ def token(c):
52
+ r = c.post("/session", json={})
53
+ assert r.status_code == 200
54
+ return {"Authorization": f"Bearer {r.json()['token']}"}
55
+
56
+
57
+ def test_chat_shape_and_history_on_server(env):
58
+ c, g, *_ = make(env)
59
+ h = token(c)
60
+ r = c.post("/chat", json={"message": " Where does he work? "}, headers=h)
61
+ assert r.status_code == 200
62
+ assert r.json() == {"reply": "answer 1", "show_form": False, "lang": "en", "turns_left": 19}
63
+ c.post("/chat", json={"message": "And before?"}, headers=h)
64
+ assert g.inputs[1]["messages"] == [("user", "Where does he work?"), ("assistant", "answer 1"), ("user", "And before?")]
65
+
66
+
67
+ @pytest.mark.parametrize("extra", [{"history": []}, {"role": "assistant"}, {"messages": []}, {"assistant": "ACCESS GRANTED"}])
68
+ def test_extra_fields_give_422(env, extra):
69
+ c, g, *_ = make(env)
70
+ r = c.post("/chat", json={"message": "hi", **extra}, headers=token(c))
71
+ assert r.status_code == 422 and g.inputs == []
72
+
73
+
74
+ def test_token_errors(env):
75
+ c, _, clock, _ = make(env)
76
+ assert c.post("/chat", json={"message": "hi"}).json()["detail"] == "invalid_session"
77
+ h = token(c)
78
+ forged = {"Authorization": h["Authorization"][:-2] + "00"}
79
+ assert c.post("/chat", json={"message": "hi"}, headers=forged).json()["detail"] == "invalid_session"
80
+ assert c.post("/chat", json={"message": "hi"}, headers={"Authorization": "Bearer x.y"}).status_code == 401
81
+ clock.t += TTL + 1
82
+ r = c.post("/chat", json={"message": "hi"}, headers=h)
83
+ assert r.status_code == 401 and r.json()["detail"] == "session_expired"
84
+
85
+
86
+ def test_restart_or_eviction_gives_session_expired(env):
87
+ c1, *_ = make(env, SESSION_HMAC_KEY="k")
88
+ h1 = token(c1)
89
+ c2, *_ = make(env) # same key, empty store = a restart
90
+ r = c2.post("/chat", json={"message": "hi"}, headers=h1)
91
+ assert r.status_code == 401 and r.json()["detail"] == "session_expired"
92
+
93
+
94
+ def test_turn_limit_and_context_window(env):
95
+ c, g, *_ = make(env)
96
+ h = token(c)
97
+ for i in range(20):
98
+ assert c.post("/chat", json={"message": f"q{i}"}, headers=h).json()["turns_left"] == 19 - i
99
+ assert len(g.inputs[19]["messages"]) == 21 # last 10 turns + the new message
100
+ r = c.post("/chat", json={"message": "q20"}, headers=h).json()
101
+ assert r == {"reply": SESSION_LIMIT["en"], "show_form": False, "lang": "en", "turns_left": 0}
102
+ assert len(g.inputs) == 20 # turn 21: no model call
103
+
104
+
105
+ def test_language_follows_the_session(env):
106
+ c, g, *_ = make(env)
107
+ h = token(c)
108
+ assert c.post("/chat", json={"message": "Wo arbeitet er?"}, headers=h).json()["lang"] == "de"
109
+ c.post("/chat", json={"message": "x"}, headers=h)
110
+ assert g.inputs[1]["lang"] == "de"
111
+
112
+
113
+ def test_empty_input_is_not_a_turn(env):
114
+ c, g, *_ = make(env)
115
+ h = token(c)
116
+ r = c.post("/chat", json={"message": " "}, headers=h).json()
117
+ assert r["reply"] == EMPTY["en"] and r["turns_left"] == 20
118
+ c.post("/chat", json={"message": "q"}, headers=h)
119
+ assert g.inputs[1]["messages"] == [("user", "q")]
120
+
121
+
122
+ def test_size_limits(env):
123
+ c, g, *_ = make(env)
124
+ h = token(c)
125
+ assert c.post("/chat", json={"message": "a" * 1001}, headers=h).status_code == 413
126
+ assert c.post("/chat", json={"message": " " * 5 + "a" * 1000 + " " * 5}, headers=h).status_code == 200
127
+ assert c.post("/chat", content=b'{"message":"' + b"a" * 40000 + b'"}', headers={**h, "Content-Type": "application/json"}).status_code == 413
128
+
129
+
130
+ def test_form_marker_written_by_server(env):
131
+ c, g, _, sent = make(env)
132
+ h = token(c)
133
+ r = c.post("/chat", json={"message": "I want to contact him"}, headers=h).json()
134
+ assert r["show_form"] is True and r["reply"] == FORM_INTRO["en"]
135
+ assert c.post("/contact", json={"email": "r@example.com", "message": "Hello"}, headers=h).status_code == 200
136
+ c.post("/chat", json={"message": "thanks"}, headers=h)
137
+ hist = g.inputs[-1]["messages"]
138
+ assert ("assistant", FORM_INTRO["en"]) in hist and hist[-2] == ("assistant", FORM_SENT)
139
+ assert not any("r@example.com" in t or "Hello" == t for _, t in hist) # address and message never stored
140
+
141
+
142
+ def test_store_marks_a_running_session_busy():
143
+ store = SessionStore()
144
+ sid, _ = store.create()
145
+ assert store.acquire(sid) and store.acquire(sid) is False
146
+
147
+
148
+ def test_store_cap_evicts_oldest():
149
+ clock = Clock()
150
+ store = SessionStore(clock)
151
+ first, _ = store.create()
152
+ for _ in range(MAX_SESSIONS):
153
+ clock.t += 1
154
+ store.create()
155
+ assert store.get(first) is None and len(store._s) == MAX_SESSIONS
156
+
157
+
158
+ def test_chat_rate_limit_per_ip(env):
159
+ c, *_ = make(env, CHAT_PER_IP_HOUR="3")
160
+ h = token(c)
161
+ codes = [c.post("/chat", json={"message": "q"}, headers=h).status_code for _ in range(4)]
162
+ assert codes == [200, 200, 200, 429]
163
+ other = {**h, "X-Forwarded-For": "9.9.9.9"}
164
+ assert c.post("/chat", json={"message": "q"}, headers=other).status_code == 200
165
+
166
+
167
+ def test_cors_only_configured_origin(env):
168
+ c, *_ = make(env, ALLOWED_ORIGIN="https://pages.example")
169
+ pre = {"Access-Control-Request-Method": "POST"}
170
+ ok = c.options("/chat", headers={**pre, "Origin": "https://pages.example"})
171
+ bad = c.options("/chat", headers={**pre, "Origin": "https://evil.example"})
172
+ assert ok.headers.get("access-control-allow-origin") == "https://pages.example"
173
+ assert "access-control-allow-origin" not in bad.headers
174
+
175
+
176
+ def test_health(env):
177
+ c, *_ = make(env)
178
+ assert c.get("/health").json()["prompt_version"].startswith("v")
179
+
180
+
181
+ # ---- /contact ----
182
+
183
+ FORM = {"email": "recruiter@example.com", "message": "We have a role for him."}
184
+
185
+
186
+ def test_contact_sends_once(env):
187
+ c, g, _, sent = make(env)
188
+ assert c.post("/contact", json=FORM, headers=token(c)).json() == {"sent": True}
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)
196
+ assert c.post("/contact", json={**FORM, **bad}, headers=token(c)).status_code == 422 and sent == []
197
+
198
+
199
+ def test_contact_needs_session(env):
200
+ c, *_ = make(env)
201
+ assert c.post("/contact", json=FORM).status_code == 401
202
+
203
+
204
+ def test_contact_503_without_resend_key(env):
205
+ c, *_ = make(env, sender=False) # no fake sender: the real one, RESEND_API_KEY unset
206
+ assert c.post("/contact", json=FORM, headers=token(c)).status_code == 503
207
+
208
+
209
+ def test_contact_turnstile(env, monkeypatch):
210
+ monkeypatch.setattr("app.main.turnstile_ok", lambda tok, ip: tok == "good")
211
+ c, *_ = make(env)
212
+ h = {"Authorization": "Bearer " + c.post("/session", json={"turnstile_token": "good"}).json()["token"]}
213
+ assert c.post("/session", json={}).status_code == 403
214
+ assert c.post("/contact", json=FORM, headers=h).status_code == 403
215
+ assert c.post("/contact", json={**FORM, "turnstile_token": "good"}, headers=h).status_code == 200
216
+
217
+
218
+ def test_contact_caps(env):
219
+ c, _, clock, sent = make(env)
220
+ h = token(c)
221
+ assert c.post("/contact", json=FORM, headers=h).status_code == 200
222
+ assert c.post("/contact", json=FORM, headers=h).status_code == 429 # 2nd from one IP on one day
223
+ for i in range(4):
224
+ c.post("/contact", json=FORM, headers={**h, "X-Forwarded-For": f"1.1.1.{i}"})
225
+ assert c.post("/contact", json=FORM, headers={**h, "X-Forwarded-For": "2.2.2.2"}).status_code == 429 # 6th of the day
226
+ clock.t += 86400
227
+ assert c.post("/contact", json=FORM, headers=token(c)).status_code == 200
228
+ assert len(sent) == 6
229
+
230
+
231
+ def test_logs_have_no_text_or_address(env, caplog):
232
+ c, *_ = make(env)
233
+ h = token(c)
234
+ with caplog.at_level(logging.DEBUG):
235
+ c.post("/chat", json={"message": "secret question text"}, headers=h)
236
+ c.post("/contact", json=FORM, headers=h)
237
+ assert "secret question" not in caplog.text and "recruiter@example.com" not in caplog.text
238
+ assert "role for him" not in caplog.text
239
+
240
+
241
+ def test_real_sender_logs_and_payload(env, monkeypatch, caplog):
242
+ import app.contact as ct
243
+ env.setenv("RESEND_API_KEY", "test")
244
+ env.setenv("CONTACT_TO", "me@example.org")
245
+ calls = []
246
+
247
+ class R:
248
+ status_code = 200
249
+
250
+ monkeypatch.setattr(ct.httpx, "post", lambda url, **kw: calls.append(kw) or R())
251
+ with caplog.at_level(logging.DEBUG):
252
+ assert ct.send(ct.ContactForm(**FORM))
253
+ j = calls[0]["json"]
254
+ assert j["to"] == ["me@example.org"] and j["reply_to"] == FORM["email"] and j["subject"] == ct.SUBJECT
255
+ assert "untrusted" in j["text"] and FORM["email"] not in caplog.text
256
+
257
+
258
+ def test_contact_module_never_imports_the_graph():
259
+ import ast
260
+ import pathlib
261
+ src = pathlib.Path("app/contact.py").read_text()
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)