Debian Codegraph @

tests/test_openapi_cache_root_path.py

raw
1 from fastapi import FastAPI
2 from fastapi.testclient import TestClient
3
4
5 def test_root_path_does_not_persist_across_requests():
6 app = FastAPI()
7
8 @app.get("/")
9 def read_root(): # pragma: no cover
10 return {"ok": True}
11
12 # Attacker request with a spoofed root_path
13 attacker_client = TestClient(app, root_path="/evil-api")
14 response1 = attacker_client.get("/openapi.json")
15 data1 = response1.json()
16 assert any(s.get("url") == "/evil-api" for s in data1.get("servers", []))
17
18 # Subsequent legitimate request with no root_path
19 clean_client = TestClient(app)
20 response2 = clean_client.get("/openapi.json")
21 data2 = response2.json()
22 servers = [s.get("url") for s in data2.get("servers", [])]
23 assert "/evil-api" not in servers
24
25
26 def test_multiple_different_root_paths_do_not_accumulate():
27 app = FastAPI()
28
29 @app.get("/")
30 def read_root(): # pragma: no cover
31 return {"ok": True}
32
33 for prefix in ["/path-a", "/path-b", "/path-c"]:
34 c = TestClient(app, root_path=prefix)
35 c.get("/openapi.json")
36
37 # A clean request should not have any of them
38 clean_client = TestClient(app)
39 response = clean_client.get("/openapi.json")
40 data = response.json()
41 servers = [s.get("url") for s in data.get("servers", [])]
42 for prefix in ["/path-a", "/path-b", "/path-c"]:
43 assert prefix not in servers, (
44 f"root_path '{prefix}' leaked into clean request: {servers}"
45 )
46
47
48 def test_legitimate_root_path_still_appears():
49 app = FastAPI()
50
51 @app.get("/")
52 def read_root(): # pragma: no cover
53 return {"ok": True}
54
55 client = TestClient(app, root_path="/api/v1")
56 response = client.get("/openapi.json")
57 data = response.json()
58 servers = [s.get("url") for s in data.get("servers", [])]
59 assert "/api/v1" in servers
60
61
62 def test_configured_servers_not_mutated():
63 configured_servers = [{"url": "https://prod.example.com"}]
64 app = FastAPI(servers=configured_servers)
65
66 @app.get("/")
67 def read_root(): # pragma: no cover
68 return {"ok": True}
69
70 # Request with a rogue root_path
71 attacker_client = TestClient(app, root_path="/evil")
72 attacker_client.get("/openapi.json")
73
74 # The original servers list must be untouched
75 assert configured_servers == [{"url": "https://prod.example.com"}]