github-actions[bot] commited on
Commit
07c5dd2
·
1 Parent(s): c2188fb

deploy: backend from ef76a7e

Browse files
main.py CHANGED
@@ -443,6 +443,9 @@ ROLE_POLICIES: Dict[str, Set[str]] = {
443
  "/api/rag/lesson": ALL_APP_ROLES,
444
  "/api/rag/generate-problem": TEACHER_OR_ADMIN,
445
  "/api/rag/analysis-context": TEACHER_OR_ADMIN,
 
 
 
446
  "/api/feedback/import-grounded": TEACHER_OR_ADMIN,
447
  "/api/feedback/import-grounded/summary": TEACHER_OR_ADMIN,
448
  "/api/import-grounded/access-audit": TEACHER_OR_ADMIN,
@@ -480,6 +483,8 @@ ROLE_POLICIES: Dict[str, Set[str]] = {
480
  "/api/admin/model-config/reset": ADMIN_ONLY,
481
  "/api/lessons/videos/search": ALL_APP_ROLES,
482
  "/api/lesson/personalized": ALL_APP_ROLES,
 
 
483
  "/api/quiz-battle/generate": ALL_APP_ROLES,
484
  "/api/quiz-battle/ingest-pdf": TEACHER_OR_ADMIN,
485
  "/api/quiz-battle/bank-status": TEACHER_OR_ADMIN,
 
443
  "/api/rag/lesson": ALL_APP_ROLES,
444
  "/api/rag/generate-problem": TEACHER_OR_ADMIN,
445
  "/api/rag/analysis-context": TEACHER_OR_ADMIN,
446
+ "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
447
+ "/api/rag/documents/by-source": ADMIN_ONLY,
448
+ "/api/rag/documents/all": ADMIN_ONLY,
449
  "/api/feedback/import-grounded": TEACHER_OR_ADMIN,
450
  "/api/feedback/import-grounded/summary": TEACHER_OR_ADMIN,
451
  "/api/import-grounded/access-audit": TEACHER_OR_ADMIN,
 
483
  "/api/admin/model-config/reset": ADMIN_ONLY,
484
  "/api/lessons/videos/search": ALL_APP_ROLES,
485
  "/api/lesson/personalized": ALL_APP_ROLES,
486
+ "/api/at-risk/resolve": ALL_APP_ROLES,
487
+ "/api/at-risk/fallback/{uid}/{topic_id}": ALL_APP_ROLES,
488
  "/api/quiz-battle/generate": ALL_APP_ROLES,
489
  "/api/quiz-battle/ingest-pdf": TEACHER_OR_ADMIN,
490
  "/api/quiz-battle/bank-status": TEACHER_OR_ADMIN,
routes/at_risk_resolution.py CHANGED
@@ -9,7 +9,7 @@ import logging
9
  from datetime import datetime, timezone
10
  from typing import Any, Optional
11
 
12
- from fastapi import APIRouter, HTTPException
13
  from pydantic import BaseModel, Field
14
 
15
  from services.ai_client import CHAT_MODEL
@@ -64,6 +64,16 @@ class ResolveResponse(BaseModel):
64
  fallback_generated: int = 0
65
 
66
 
 
 
 
 
 
 
 
 
 
 
67
  # ─── Resolution Logic ──────────────────────────────────────────────
68
 
69
  def _resolve_topic(
@@ -261,8 +271,9 @@ def _generate_fallback_content(
261
  # ─── Endpoints ─────────────────────────────────────────────────────
262
 
263
  @router.post("/resolve", response_model=ResolveResponse)
264
- async def resolve_at_risk_topics(request: ResolveRequest):
265
  """Resolve flagged topics into resolution states and generate fallback content."""
 
266
  try:
267
  firestore_client = fs.client()
268
  except Exception:
@@ -311,8 +322,9 @@ async def resolve_at_risk_topics(request: ResolveRequest):
311
 
312
 
313
  @router.get("/fallback/{uid}/{topic_id}")
314
- async def get_fallback_content(uid: str, topic_id: str):
315
  """Fetch cached fallback study brief for a flagged topic."""
 
316
  try:
317
  firestore_client = fs.client()
318
  except Exception:
 
9
  from datetime import datetime, timezone
10
  from typing import Any, Optional
11
 
12
+ from fastapi import APIRouter, HTTPException, Request
13
  from pydantic import BaseModel, Field
14
 
15
  from services.ai_client import CHAT_MODEL
 
64
  fallback_generated: int = 0
65
 
66
 
67
+ def _require_student_or_staff_access(uid: str, request: Request) -> None:
68
+ user = getattr(request.state, "user", None)
69
+ role = getattr(user, "role", None)
70
+ if role in {"teacher", "admin"}:
71
+ return
72
+ if role == "student" and getattr(user, "uid", None) == uid:
73
+ return
74
+ raise HTTPException(status_code=403, detail="Forbidden for this student")
75
+
76
+
77
  # ─── Resolution Logic ──────────────────────────────────────────────
78
 
79
  def _resolve_topic(
 
271
  # ─── Endpoints ─────────────────────────────────────────────────────
272
 
273
  @router.post("/resolve", response_model=ResolveResponse)
274
+ async def resolve_at_risk_topics(request: ResolveRequest, http_request: Request):
275
  """Resolve flagged topics into resolution states and generate fallback content."""
276
+ _require_student_or_staff_access(request.uid, http_request)
277
  try:
278
  firestore_client = fs.client()
279
  except Exception:
 
322
 
323
 
324
  @router.get("/fallback/{uid}/{topic_id}")
325
+ async def get_fallback_content(uid: str, topic_id: str, request: Request):
326
  """Fetch cached fallback study brief for a flagged topic."""
327
+ _require_student_or_staff_access(uid, request)
328
  try:
329
  firestore_client = fs.client()
330
  except Exception:
tests/role_policy_expectations.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent auth contract and route registry reviewed for regression tests."""
2
+
3
+ ALL_ROLES = frozenset({"student", "teacher", "admin"})
4
+ TEACHER_ADMIN = frozenset({"teacher", "admin"})
5
+ ADMIN_ONLY = frozenset({"admin"})
6
+
7
+ # Curated contract values, intentionally literal and independent of main.ROLE_POLICIES.
8
+ EXPECTED_ROLE_POLICIES = {
9
+ "/api/chat": ALL_ROLES,
10
+ "/api/chat/stream": ALL_ROLES,
11
+ "/api/verify-solution": ALL_ROLES,
12
+ "/api/predict-risk": TEACHER_ADMIN,
13
+ "/api/predict-risk/batch": TEACHER_ADMIN,
14
+ "/api/learning-path": ALL_ROLES,
15
+ "/api/analytics/daily-insight": TEACHER_ADMIN,
16
+ "/api/analytics/class/{class_id}": TEACHER_ADMIN,
17
+ "/api/analytics/class/{class_id}/students": TEACHER_ADMIN,
18
+ "/api/analytics/class/{class_id}/topics": TEACHER_ADMIN,
19
+ "/api/analytics/class/{class_id}/refresh-insights": TEACHER_ADMIN,
20
+ "/api/analytics/class/{class_id}/invalidate-cache": ALL_ROLES,
21
+ "/api/intervention/generate": TEACHER_ADMIN,
22
+ "/api/intervention/{student_id}": TEACHER_ADMIN,
23
+ "/api/intervention/{student_id}/step/{step_number}/complete": ALL_ROLES,
24
+ "/api/intervention/{student_id}/export-pdf": TEACHER_ADMIN,
25
+ "/api/pipeline/event": ALL_ROLES,
26
+ "/api/pipeline/profile/{student_id}": ALL_ROLES,
27
+ "/api/pipeline/profile/{student_id}/recompute": TEACHER_ADMIN,
28
+ "/api/pipeline/admin/backfill": ADMIN_ONLY,
29
+ "/api/upload/class-records": TEACHER_ADMIN,
30
+ "/api/class-section/{class_section_id}": TEACHER_ADMIN,
31
+ "/api/upload/class-records/risk-refresh/recent": TEACHER_ADMIN,
32
+ "/api/import/student-accounts/preview": TEACHER_ADMIN,
33
+ "/api/import/student-accounts/commit": TEACHER_ADMIN,
34
+ "/api/admin/users": ADMIN_ONLY,
35
+ "/api/admin/users/bulk-action": ADMIN_ONLY,
36
+ "/api/admin/school-analytics": ADMIN_ONLY,
37
+ "/api/teacher/create-student-account": TEACHER_ADMIN,
38
+ "/api/upload/course-materials": TEACHER_ADMIN,
39
+ "/api/upload/course-materials/recent": TEACHER_ADMIN,
40
+ "/api/teacher-materials/upload": TEACHER_ADMIN,
41
+ "/api/course-materials/topics": TEACHER_ADMIN,
42
+ "/api/quiz/generate": ALL_ROLES,
43
+ "/api/quiz/generate-async": ALL_ROLES,
44
+ "/api/quiz/preview": ALL_ROLES,
45
+ "/api/lesson/generate": TEACHER_ADMIN,
46
+ "/api/lesson/generate-async": TEACHER_ADMIN,
47
+ "/api/rag/lesson": ALL_ROLES,
48
+ "/api/rag/generate-problem": TEACHER_ADMIN,
49
+ "/api/rag/analysis-context": TEACHER_ADMIN,
50
+ "/api/rag/documents/by-subject/{subject}": ADMIN_ONLY,
51
+ "/api/rag/documents/by-source": ADMIN_ONLY,
52
+ "/api/rag/documents/all": ADMIN_ONLY,
53
+ "/api/feedback/import-grounded": TEACHER_ADMIN,
54
+ "/api/feedback/import-grounded/summary": TEACHER_ADMIN,
55
+ "/api/import-grounded/access-audit": TEACHER_ADMIN,
56
+ "/api/quiz/student-competency": TEACHER_ADMIN,
57
+ "/api/calculator/evaluate": ALL_ROLES,
58
+ "/api/diagnostic/generate": ALL_ROLES,
59
+ "/api/diagnostic/submit": ALL_ROLES,
60
+ "/api/diagnostic/analyze": ALL_ROLES,
61
+ "/api/student/competency-analysis": TEACHER_ADMIN,
62
+ "/api/risk/train-model": ADMIN_ONLY,
63
+ "/api/predict-risk/enhanced": TEACHER_ADMIN,
64
+ "/api/quiz/calibrate-difficulty": TEACHER_ADMIN,
65
+ "/api/quiz/adaptive-select": TEACHER_ADMIN,
66
+ "/api/learning/recommend-topics": TEACHER_ADMIN,
67
+ "/api/analytics/student-summary": ALL_ROLES,
68
+ "/api/analytics/class-insights": TEACHER_ADMIN,
69
+ "/api/analytics/refresh-cache": ADMIN_ONLY,
70
+ "/api/testing/reset-data": ALL_ROLES,
71
+ "/api/hf/monitoring": ADMIN_ONLY,
72
+ "/api/dev/generate-mock-data": ADMIN_ONLY,
73
+ "/api/analytics/config": TEACHER_ADMIN,
74
+ "/api/analytics/imported-class-overview": TEACHER_ADMIN,
75
+ "/api/analytics/topic-mastery": TEACHER_ADMIN,
76
+ "/api/automation/diagnostic-completed": ADMIN_ONLY,
77
+ "/api/automation/quiz-submitted": ADMIN_ONLY,
78
+ "/api/automation/student-enrolled": ADMIN_ONLY,
79
+ "/api/automation/data-imported": ADMIN_ONLY,
80
+ "/api/automation/content-updated": ADMIN_ONLY,
81
+ "/api/admin/model-config": ADMIN_ONLY,
82
+ "/api/admin/upload-pdf": ADMIN_ONLY,
83
+ "/api/admin/reingest-pdf": ADMIN_ONLY,
84
+ "/api/admin/delete-file": ADMIN_ONLY,
85
+ "/api/admin/model-config/profile": ADMIN_ONLY,
86
+ "/api/admin/model-config/override": ADMIN_ONLY,
87
+ "/api/admin/model-config/reset": ADMIN_ONLY,
88
+ "/api/lessons/videos/search": ALL_ROLES,
89
+ "/api/lesson/personalized": ALL_ROLES,
90
+ "/api/at-risk/resolve": ALL_ROLES,
91
+ "/api/at-risk/fallback/{uid}/{topic_id}": ALL_ROLES,
92
+ "/api/quiz-battle/generate": ALL_ROLES,
93
+ "/api/quiz-battle/ingest-pdf": TEACHER_ADMIN,
94
+ "/api/quiz-battle/bank-status": TEACHER_ADMIN,
95
+ "/api/class-records/upload": TEACHER_ADMIN,
96
+ }
97
+
98
+ # Fixed route/method manifest. New endpoints require an explicit review and
99
+ # classification; no route becomes public merely by being absent from policy.
100
+ EXPECTED_REGISTERED_ROUTE_METHODS = {
101
+ "/openapi.json": frozenset({"GET", "HEAD"}),
102
+ "/docs": frozenset({"GET", "HEAD"}),
103
+ "/docs/oauth2-redirect": frozenset({"GET", "HEAD"}),
104
+ "/redoc": frozenset({"GET", "HEAD"}),
105
+ "/api/rag/health": frozenset({"GET"}),
106
+ "/api/rag/lesson": frozenset({"POST"}),
107
+ "/api/rag/generate-problem": frozenset({"POST"}),
108
+ "/api/rag/analysis-context": frozenset({"POST"}),
109
+ "/api/rag/documents": frozenset({"GET"}),
110
+ "/api/rag/documents/by-subject/{subject}": frozenset({"DELETE"}),
111
+ "/api/rag/documents/by-source": frozenset({"DELETE"}),
112
+ "/api/rag/documents/all": frozenset({"DELETE"}),
113
+ "/api/admin/model-config": frozenset({"GET"}),
114
+ "/api/admin/model-config/profile": frozenset({"POST"}),
115
+ "/api/admin/model-config/override": frozenset({"POST"}),
116
+ "/api/admin/model-config/reset": frozenset({"DELETE"}),
117
+ "/api/admin/reingest-status": frozenset({"GET"}),
118
+ "/api/admin/upload-pdf": frozenset({"POST"}),
119
+ "/api/admin/reingest-pdf": frozenset({"POST"}),
120
+ "/api/admin/delete-file": frozenset({"POST"}),
121
+ "/api/admin/dashboard-analytics": frozenset({"GET"}),
122
+ "/api/admin/school-analytics": frozenset({"GET"}),
123
+ "/api/curriculum/subjects": frozenset({"GET"}),
124
+ "/api/curriculum/subjects/{subject_id}": frozenset({"GET"}),
125
+ "/api/curriculum/subjects/{subject_id}/topics": frozenset({"GET"}),
126
+ "/api/curriculum/subjects/{subject_id}/topics/{topic_id}": frozenset({"GET"}),
127
+ "/api/diagnostic/generate": frozenset({"POST"}),
128
+ "/api/diagnostic/submit": frozenset({"POST"}),
129
+ "/api/diagnostic/analyze": frozenset({"POST"}),
130
+ "/api/diagnostic/results/{user_id}": frozenset({"GET"}),
131
+ "/api/lessons/videos/search": frozenset({"POST"}),
132
+ "/api/quiz-battle/generate": frozenset({"POST"}),
133
+ "/api/quiz-battle/ingest-pdf": frozenset({"POST"}),
134
+ "/api/quiz-battle/bank-status": frozenset({"GET"}),
135
+ "/api/quiz-battle/results": frozenset({"GET"}),
136
+ "/api/teacher-materials/upload": frozenset({"POST"}),
137
+ "/api/teacher-materials/{moduleId}/generate-quiz": frozenset({"POST"}),
138
+ "/api/templates/class-records": frozenset({"GET"}),
139
+ "/api/class-records/upload": frozenset({"POST"}),
140
+ "/api/class-records/intervention-plan": frozenset({"POST"}),
141
+ "/api/class-records": frozenset({"GET"}),
142
+ "/api/class-records/{uploadId}/students": frozenset({"GET"}),
143
+ "/api/class-records/{uploadId}/ai-report": frozenset({"POST"}),
144
+ "/api/risk/compute": frozenset({"POST"}),
145
+ "/api/risk/compute/batch": frozenset({"POST"}),
146
+ "/api/tutor-checkin": frozenset({"POST"}),
147
+ "/api/practice/generate": frozenset({"POST"}),
148
+ "/api/practice/submit": frozenset({"POST"}),
149
+ "/api/practice/stats/{userId}": frozenset({"GET"}),
150
+ "/api/practice/history/{userId}": frozenset({"GET"}),
151
+ "/api/try-it-yourself/resolve-question": frozenset({"POST"}),
152
+ "/api/try-it-yourself/use-hint": frozenset({"POST"}),
153
+ "/api/try-it-yourself/complete-session": frozenset({"POST"}),
154
+ "/api/try-it-yourself/generate-round": frozenset({"POST"}),
155
+ "/api/try-it-yourself/shadow-retry": frozenset({"POST"}),
156
+ "/api/admin/ai-monitoring/summary": frozenset({"GET"}),
157
+ "/api/admin/ai-monitoring/refresh": frozenset({"POST"}),
158
+ "/api/analytics/class/{class_id}": frozenset({"GET"}),
159
+ "/api/analytics/class/{class_id}/students": frozenset({"GET"}),
160
+ "/api/analytics/class/{class_id}/topics": frozenset({"GET"}),
161
+ "/api/analytics/class/{class_id}/refresh-insights": frozenset({"POST"}),
162
+ "/api/analytics/class/{class_id}/invalidate-cache": frozenset({"POST"}),
163
+ "/api/intervention/generate": frozenset({"POST"}),
164
+ "/api/intervention/{student_id}": frozenset({"GET"}),
165
+ "/api/intervention/{student_id}/step/{step_number}/complete": frozenset({"POST"}),
166
+ "/api/intervention/{student_id}/export-pdf": frozenset({"GET"}),
167
+ "/api/pipeline/event": frozenset({"POST"}),
168
+ "/api/pipeline/nudge/{student_id}": frozenset({"POST"}),
169
+ "/api/pipeline/profile/{student_id}": frozenset({"GET"}),
170
+ "/api/pipeline/profile/{student_id}/recompute": frozenset({"POST"}),
171
+ "/api/pipeline/admin/backfill": frozenset({"POST"}),
172
+ "/api/deepseek/weakness-detection": frozenset({"POST"}),
173
+ "/api/deepseek/module-preview": frozenset({"POST"}),
174
+ "/api/deepseek/study-tips": frozenset({"POST"}),
175
+ "/api/at-risk/resolve": frozenset({"POST"}),
176
+ "/api/at-risk/fallback/{uid}/{topic_id}": frozenset({"GET"}),
177
+ "/api/curriculum/generate-module": frozenset({"POST"}),
178
+ "/api/mastery/record": frozenset({"POST"}),
179
+ "/api/jev/verify": frozenset({"POST"}),
180
+ "/health": frozenset({"GET"}),
181
+ "/api/memory/health": frozenset({"GET"}),
182
+ "/debug/scope-info": frozenset({"GET"}),
183
+ "/": frozenset({"GET"}),
184
+ "/api/chat": frozenset({"POST"}),
185
+ "/api/chat/stream": frozenset({"POST"}),
186
+ "/api/verify-solution": frozenset({"POST"}),
187
+ "/api/predict-risk": frozenset({"POST"}),
188
+ "/api/predict-risk/batch": frozenset({"POST"}),
189
+ "/api/learning-path": frozenset({"POST"}),
190
+ "/api/analytics/daily-insight": frozenset({"POST"}),
191
+ "/api/import/student-accounts/preview": frozenset({"POST"}),
192
+ "/api/import/student-accounts/commit": frozenset({"POST"}),
193
+ "/api/admin/audit-log": frozenset({"POST"}),
194
+ "/api/admin/users": frozenset({"GET", "PATCH", "POST", "DELETE"}),
195
+ "/api/admin/users/bulk-action": frozenset({"POST"}),
196
+ "/api/teacher/create-student-account": frozenset({"POST"}),
197
+ "/api/upload/class-records/risk-refresh/recent": frozenset({"GET"}),
198
+ "/api/class-section/{class_section_id}": frozenset({"DELETE"}),
199
+ "/api/upload/class-records": frozenset({"POST"}),
200
+ "/api/upload/course-materials": frozenset({"POST"}),
201
+ "/api/upload/course-materials/recent": frozenset({"GET"}),
202
+ "/api/course-materials/topics": frozenset({"GET"}),
203
+ "/api/lesson/generate": frozenset({"POST"}),
204
+ "/api/lesson-plans/{lesson_id}/publish": frozenset({"POST"}),
205
+ "/api/lesson/generate-async": frozenset({"POST"}),
206
+ "/api/feedback/import-grounded": frozenset({"POST"}),
207
+ "/api/feedback/import-grounded/summary": frozenset({"GET"}),
208
+ "/api/import-grounded/access-audit": frozenset({"GET"}),
209
+ "/api/quiz/generate": frozenset({"POST"}),
210
+ "/api/quiz/preview": frozenset({"POST"}),
211
+ "/api/quiz/generate-async": frozenset({"POST"}),
212
+ "/api/tasks/{task_id}": frozenset({"GET"}),
213
+ "/api/tasks": frozenset({"GET"}),
214
+ "/api/tasks/{task_id}/cancel": frozenset({"POST"}),
215
+ "/api/hf/monitoring": frozenset({"GET"}),
216
+ "/api/quiz/topics": frozenset({"GET"}),
217
+ "/api/quiz/student-competency": frozenset({"POST"}),
218
+ "/api/calculator/evaluate": frozenset({"POST"}),
219
+ "/api/student/competency-analysis": frozenset({"POST"}),
220
+ "/api/risk/train-model": frozenset({"POST"}),
221
+ "/api/predict-risk/enhanced": frozenset({"POST"}),
222
+ "/api/quiz/calibrate-difficulty": frozenset({"POST"}),
223
+ "/api/quiz/adaptive-select": frozenset({"POST"}),
224
+ "/api/learning/recommend-topics": frozenset({"POST"}),
225
+ "/api/analytics/student-summary": frozenset({"GET"}),
226
+ "/api/analytics/class-insights": frozenset({"POST"}),
227
+ "/api/analytics/refresh-cache": frozenset({"POST"}),
228
+ "/api/dev/generate-mock-data": frozenset({"POST"}),
229
+ "/api/testing/reset-data": frozenset({"POST"}),
230
+ "/api/analytics/config": frozenset({"GET"}),
231
+ "/api/analytics/imported-class-overview": frozenset({"GET"}),
232
+ "/api/analytics/topic-mastery": frozenset({"GET"}),
233
+ "/api/automation/diagnostic-completed": frozenset({"POST"}),
234
+ "/api/automation/quiz-submitted": frozenset({"POST"}),
235
+ "/api/automation/student-enrolled": frozenset({"POST"}),
236
+ "/api/automation/data-imported": frozenset({"POST"}),
237
+ "/api/automation/content-updated": frozenset({"POST"}),
238
+ "/api/lesson/diagnostic": frozenset({"POST"}),
239
+ "/api/lessons/generate": frozenset({"POST"}),
240
+ "/api/progress/evaluate": frozenset({"POST"}),
241
+ "/api/quiz/adaptive": frozenset({"POST"}),
242
+ "/api/learning/path": frozenset({"POST"}),
243
+ "/api/lesson/personalized": frozenset({"POST"}),
244
+ }
245
+
246
+ PUBLIC_ROUTE_EXCEPTIONS = {
247
+ ("GET", "/openapi.json"): "OpenAPI schema endpoint",
248
+ ("HEAD", "/openapi.json"): "OpenAPI schema endpoint",
249
+ ("GET", "/docs"): "Swagger UI endpoint",
250
+ ("HEAD", "/docs"): "Swagger UI endpoint",
251
+ ("GET", "/docs/oauth2-redirect"): "Swagger OAuth redirect endpoint",
252
+ ("HEAD", "/docs/oauth2-redirect"): "Swagger OAuth redirect endpoint",
253
+ ("GET", "/redoc"): "ReDoc endpoint",
254
+ ("HEAD", "/redoc"): "ReDoc endpoint",
255
+ ("GET", "/health"): "Unauthenticated liveness endpoint",
256
+ ("GET", "/"): "Unauthenticated API identity endpoint",
257
+ ("GET", "/api/rag/health"): "Unauthenticated RAG health endpoint",
258
+ ("GET", "/api/templates/class-records"): "Unauthenticated static import template",
259
+ ("GET", "/api/quiz/topics"): "Public topic catalog",
260
+ ("POST", "/api/jev/verify"): "Public verification endpoint; service controls availability",
261
+ ("GET", "/debug/scope-info"): "Non-API diagnostic route bypasses AuthMiddleware",
262
+ }
263
+
264
+ # AuthMiddleware authenticates these endpoints, but they have no route-specific
265
+ # role restriction. Keep that distinct from endpoints with in-handler guards.
266
+ AUTHENTICATED_ROUTE_EXCEPTIONS = {
267
+ ("GET", "/api/curriculum/subjects"): "Authenticated curriculum catalog; no role restriction",
268
+ ("GET", "/api/curriculum/subjects/{subject_id}"): "Authenticated curriculum catalog; no role restriction",
269
+ ("GET", "/api/curriculum/subjects/{subject_id}/topics"): "Authenticated curriculum catalog; no role restriction",
270
+ ("GET", "/api/curriculum/subjects/{subject_id}/topics/{topic_id}"): "Authenticated curriculum catalog; no role restriction",
271
+ ("GET", "/api/memory/health"): "Authenticated health endpoint; no role restriction",
272
+ ("GET", "/api/rag/documents"): "Authenticated RAG document listing; no role restriction",
273
+ ("POST", "/api/curriculum/generate-module"): "Authenticated module generation; no role restriction",
274
+ ("POST", "/api/deepseek/module-preview"): "Authenticated preview generation; no role restriction",
275
+ ("POST", "/api/deepseek/study-tips"): "Authenticated study tips; no role restriction",
276
+ ("POST", "/api/deepseek/weakness-detection"): "Authenticated weakness detection; no role restriction",
277
+ ("POST", "/api/learning/path"): "Authenticated learning path; no role restriction",
278
+ ("POST", "/api/lesson/diagnostic"): "Authenticated diagnostic lesson; no role restriction",
279
+ ("POST", "/api/lessons/generate"): "Authenticated lesson generation; no role restriction",
280
+ ("POST", "/api/mastery/record"): "Authenticated mastery record; no role restriction",
281
+ ("POST", "/api/progress/evaluate"): "Authenticated progress evaluation; no role restriction",
282
+ ("POST", "/api/quiz/adaptive"): "Authenticated adaptive quiz; no role restriction",
283
+ ("POST", "/api/risk/compute"): "Authenticated risk computation; no role restriction",
284
+ ("POST", "/api/risk/compute/batch"): "Authenticated batch risk computation; no role restriction",
285
+ ("POST", "/api/tutor-checkin"): "Authenticated tutor check-in; no role restriction",
286
+ }
287
+
288
+ # These routes perform an explicit handler-level ownership or role check.
289
+ HANDLER_GUARDED_ROUTE_EXCEPTIONS = {
290
+ ("GET", "/api/diagnostic/results/{user_id}"): "student UID ownership check",
291
+ ("POST", "/api/pipeline/event"): "student event owner check",
292
+ ("POST", "/api/pipeline/nudge/{student_id}"): "student target ownership check",
293
+ ("POST", "/api/admin/audit-log"): "admin/teacher role check",
294
+ ("GET", "/api/admin/reingest-status"): "admin role check",
295
+ ("GET", "/api/admin/dashboard-analytics"): "admin role check",
296
+ ("GET", "/api/admin/ai-monitoring/summary"): "admin role check",
297
+ ("POST", "/api/admin/ai-monitoring/refresh"): "admin role check",
298
+ ("GET", "/api/quiz-battle/results"): "teacher/admin role check",
299
+ ("POST", "/api/teacher-materials/{moduleId}/generate-quiz"): "teacher/admin role check",
300
+ ("POST", "/api/class-records/intervention-plan"): "teacher/admin role check",
301
+ ("GET", "/api/class-records"): "teacher/admin role check",
302
+ ("GET", "/api/class-records/{uploadId}/students"): "teacher/admin role check",
303
+ ("POST", "/api/class-records/{uploadId}/ai-report"): "teacher/admin role check",
304
+ ("POST", "/api/class-records/upload"): "teacher/admin role check",
305
+ ("POST", "/api/practice/generate"): "authenticated user and owner checks",
306
+ ("POST", "/api/practice/submit"): "authenticated user and owner checks",
307
+ ("GET", "/api/practice/stats/{userId}"): "authenticated user and owner checks",
308
+ ("GET", "/api/practice/history/{userId}"): "authenticated user and owner checks",
309
+ ("POST", "/api/tasks/{task_id}/cancel"): "task owner or admin check",
310
+ ("GET", "/api/tasks/{task_id}"): "task owner or admin check",
311
+ ("GET", "/api/tasks"): "task owner filtering or admin check",
312
+ ("POST", "/api/lesson-plans/{lesson_id}/publish"): "teacher/admin role and lesson owner check",
313
+ ("POST", "/api/try-it-yourself/resolve-question"): "authenticated user ownership check",
314
+ ("POST", "/api/try-it-yourself/use-hint"): "authenticated user ownership check",
315
+ ("POST", "/api/try-it-yourself/complete-session"): "authenticated user ownership check",
316
+ ("POST", "/api/try-it-yourself/generate-round"): "authenticated user ownership check",
317
+ ("POST", "/api/try-it-yourself/shadow-retry"): "authenticated user ownership check",
318
+ }
tests/test_api.py CHANGED
@@ -197,6 +197,36 @@ class TestAuthMiddleware:
197
  assert len(data["materials"]) == 1
198
  assert data["materials"][0]["materialId"] == "mat-auth-1"
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
  # ─── Chat Endpoint ─────────────────────────────────────────────
202
 
 
197
  assert len(data["materials"]) == 1
198
  assert data["materials"][0]["materialId"] == "mat-auth-1"
199
 
200
+ class TestRequestTimeoutBoundary:
201
+ def test_request_timeout_is_terminal_504(self):
202
+ from starlette.requests import Request
203
+ from starlette.responses import Response
204
+
205
+ request = Request({
206
+ "type": "http",
207
+ "asgi": {"version": "3.0"},
208
+ "http_version": "1.1",
209
+ "method": "POST",
210
+ "scheme": "http",
211
+ "path": "/api/chat",
212
+ "raw_path": b"/api/chat",
213
+ "query_string": b"",
214
+ "headers": [],
215
+ "client": ("testclient", 50000),
216
+ "server": ("testserver", 80),
217
+ })
218
+ middleware = main_module.RequestMiddleware(app)
219
+
220
+ async def slow_handler(_request):
221
+ await asyncio.sleep(0.02)
222
+ return Response("late response")
223
+
224
+ with patch.object(main_module, "REQUEST_TIMEOUT_SECONDS", 0.001):
225
+ response = asyncio.run(middleware.dispatch(request, slow_handler))
226
+
227
+ assert response.status_code == 504
228
+ assert json.loads(response.body)["detail"] == "Request timed out after 0.001s"
229
+
230
 
231
  # ─── Chat Endpoint ─────────────────────────────────────────────
232
 
tests/test_audit_remediation.py CHANGED
@@ -14,10 +14,61 @@ from fastapi.testclient import TestClient
14
 
15
  import main as main_module
16
  from main import app, resolve_required_roles, ROLE_POLICIES
 
 
 
 
 
 
 
17
 
18
 
19
  class TestRolePolicyMatching:
20
- """Verify GATE-01: parameterized route matching."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def test_literal_routes_resolve_correctly(self):
23
  assert resolve_required_roles("/api/chat") == {"student", "teacher", "admin"}
@@ -35,6 +86,15 @@ class TestRolePolicyMatching:
35
  assert resolve_required_roles("/api/nonexistent/unknown") is None
36
  assert resolve_required_roles("/some/random/path") is None
37
 
 
 
 
 
 
 
 
 
 
38
 
39
  class TestPipelineProfileOwnership:
40
  """Verify GATE-02: student can only access own profile, teacher/admin can access any."""
@@ -82,6 +142,86 @@ class TestPipelineProfileOwnership:
82
  assert response.json()["student_id"] == "student_B"
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  class TestDiagnosticResultsEndpoint:
86
  """Verify GATE-05: /api/diagnostic/results/{user_id} in canonical diagnostic router."""
87
 
 
14
 
15
  import main as main_module
16
  from main import app, resolve_required_roles, ROLE_POLICIES
17
+ from backend.tests.role_policy_expectations import (
18
+ EXPECTED_REGISTERED_ROUTE_METHODS,
19
+ EXPECTED_ROLE_POLICIES,
20
+ AUTHENTICATED_ROUTE_EXCEPTIONS,
21
+ HANDLER_GUARDED_ROUTE_EXCEPTIONS,
22
+ PUBLIC_ROUTE_EXCEPTIONS,
23
+ )
24
 
25
 
26
  class TestRolePolicyMatching:
27
+ """Verify independently reviewed policy and route classification contracts."""
28
+
29
+ def test_production_role_policies_match_reviewed_expected_table(self):
30
+ assert ROLE_POLICIES == EXPECTED_ROLE_POLICIES
31
+
32
+ def test_registered_route_methods_match_reviewed_manifest(self):
33
+ discovered = {}
34
+ for registered in app.routes:
35
+ route_collection = getattr(registered, "original_router", None)
36
+ candidates = route_collection.routes if route_collection is not None else [registered]
37
+ for route in candidates:
38
+ path = getattr(route, "path", None)
39
+ methods = getattr(route, "methods", None)
40
+ if path and methods:
41
+ discovered.setdefault(path, set()).update(methods)
42
+
43
+ actual = {path: frozenset(methods) for path, methods in discovered.items()}
44
+ assert actual == EXPECTED_REGISTERED_ROUTE_METHODS
45
+
46
+ def test_every_registered_method_has_policy_or_reviewed_exception(self):
47
+ registered_methods = {
48
+ (method, path)
49
+ for path, methods in EXPECTED_REGISTERED_ROUTE_METHODS.items()
50
+ for method in methods
51
+ }
52
+ policy_methods = {
53
+ (method, path)
54
+ for path, methods in EXPECTED_REGISTERED_ROUTE_METHODS.items()
55
+ if path in EXPECTED_ROLE_POLICIES
56
+ for method in methods
57
+ }
58
+ reviewed_exceptions = (
59
+ set(PUBLIC_ROUTE_EXCEPTIONS)
60
+ | set(AUTHENTICATED_ROUTE_EXCEPTIONS)
61
+ | set(HANDLER_GUARDED_ROUTE_EXCEPTIONS)
62
+ )
63
+ unclassified = sorted(registered_methods - policy_methods - reviewed_exceptions)
64
+
65
+ assert not unclassified, f"Registered routes lack a role policy or reviewed exception: {unclassified}"
66
+ assert not (set(PUBLIC_ROUTE_EXCEPTIONS) & set(HANDLER_GUARDED_ROUTE_EXCEPTIONS))
67
+ assert not (set(PUBLIC_ROUTE_EXCEPTIONS) & set(AUTHENTICATED_ROUTE_EXCEPTIONS))
68
+ assert not (set(AUTHENTICATED_ROUTE_EXCEPTIONS) & set(HANDLER_GUARDED_ROUTE_EXCEPTIONS))
69
+ assert all(PUBLIC_ROUTE_EXCEPTIONS.values())
70
+ assert all(AUTHENTICATED_ROUTE_EXCEPTIONS.values())
71
+ assert all(HANDLER_GUARDED_ROUTE_EXCEPTIONS.values())
72
 
73
  def test_literal_routes_resolve_correctly(self):
74
  assert resolve_required_roles("/api/chat") == {"student", "teacher", "admin"}
 
86
  assert resolve_required_roles("/api/nonexistent/unknown") is None
87
  assert resolve_required_roles("/some/random/path") is None
88
 
89
+ def test_missing_bearer_is_denied_before_handler(self):
90
+ client = TestClient(app)
91
+ with patch.object(main_module, "_firebase_ready", True), \
92
+ patch.object(main_module, "_init_firebase_admin"):
93
+ response = client.get("/api/admin/model-config")
94
+
95
+ assert response.status_code == 401
96
+ assert response.json()["detail"] == "Missing or invalid Authorization bearer token"
97
+
98
 
99
  class TestPipelineProfileOwnership:
100
  """Verify GATE-02: student can only access own profile, teacher/admin can access any."""
 
142
  assert response.json()["student_id"] == "student_B"
143
 
144
 
145
+ class TestRagAdminPolicy:
146
+ @pytest.mark.parametrize(
147
+ "path",
148
+ [
149
+ "/api/rag/documents/all",
150
+ "/api/rag/documents/by-source?source_file=curriculum.pdf",
151
+ "/api/rag/documents/by-subject/General%20Mathematics",
152
+ ],
153
+ )
154
+ def test_student_cannot_delete_rag_documents(self, path):
155
+ client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_A"})
156
+ with patch.object(main_module, "_firebase_ready", True), \
157
+ patch.object(main_module, "_init_firebase_admin"), \
158
+ patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_A", "role": "student"}), \
159
+ patch("routes.rag_routes.get_vectorstore_components") as vectorstore_components:
160
+ response = client.delete(path)
161
+
162
+ assert response.status_code == 403
163
+ vectorstore_components.assert_not_called()
164
+
165
+
166
+ class TestAtRiskOwnership:
167
+ @pytest.mark.parametrize(
168
+ ("method", "path", "payload"),
169
+ [
170
+ (
171
+ "post",
172
+ "/api/at-risk/resolve",
173
+ {"uid": "student_B", "flagged_topics": []},
174
+ ),
175
+ ("get", "/api/at-risk/fallback/student_B/algebra", None),
176
+ ],
177
+ )
178
+ def test_student_cannot_access_other_student_at_risk_data(self, method, path, payload):
179
+ client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_A"})
180
+ with patch.object(main_module, "_firebase_ready", True), \
181
+ patch.object(main_module, "_init_firebase_admin"), \
182
+ patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_A", "role": "student"}), \
183
+ patch("routes.at_risk_resolution.fs.client") as firestore_client:
184
+ response = getattr(client, method)(path, json=payload) if payload is not None else getattr(client, method)(path)
185
+
186
+ assert response.status_code == 403
187
+ firestore_client.assert_not_called()
188
+
189
+ @pytest.mark.parametrize(
190
+ ("method", "path", "payload"),
191
+ [
192
+ ("post", "/api/at-risk/resolve", {"uid": "student_A", "flagged_topics": []}),
193
+ ("get", "/api/at-risk/fallback/student_A/algebra", None),
194
+ ],
195
+ )
196
+ def test_student_can_access_own_at_risk_data(self, method, path, payload):
197
+ client = TestClient(app, headers={"Authorization": "Bearer mock_token_student_A"})
198
+ firestore = MagicMock()
199
+ fallback_doc = firestore.collection.return_value.document.return_value.collection.return_value.document.return_value.get.return_value
200
+ fallback_doc.exists = True
201
+ fallback_doc.to_dict.return_value = {"summary": "Owned fallback"}
202
+ with patch.object(main_module, "_firebase_ready", True), \
203
+ patch.object(main_module, "_init_firebase_admin"), \
204
+ patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "student_A", "role": "student"}), \
205
+ patch("routes.at_risk_resolution.fs.client", return_value=firestore):
206
+ response = getattr(client, method)(path, json=payload) if payload is not None else getattr(client, method)(path)
207
+
208
+ assert response.status_code == 200
209
+
210
+ def test_teacher_can_access_another_students_at_risk_data(self):
211
+ client = TestClient(app, headers={"Authorization": "Bearer mock_token_teacher_T"})
212
+ firestore = MagicMock()
213
+ fallback_doc = firestore.collection.return_value.document.return_value.collection.return_value.document.return_value.get.return_value
214
+ fallback_doc.exists = False
215
+ with patch.object(main_module, "_firebase_ready", True), \
216
+ patch.object(main_module, "_init_firebase_admin"), \
217
+ patch.object(main_module.firebase_auth, "verify_id_token", return_value={"uid": "teacher_T", "role": "teacher"}), \
218
+ patch("routes.at_risk_resolution.fs.client", return_value=firestore) as firestore_client:
219
+ response = client.get("/api/at-risk/fallback/student_B/algebra")
220
+
221
+ assert response.status_code == 404
222
+ firestore_client.assert_called_once()
223
+
224
+
225
  class TestDiagnosticResultsEndpoint:
226
  """Verify GATE-05: /api/diagnostic/results/{user_id} in canonical diagnostic router."""
227
 
tests/test_rag_lesson_jev.py CHANGED
@@ -109,3 +109,18 @@ def test_jev_exception_fails_open_cleanly(monkeypatch) -> None:
109
  assert response.status_code == 200
110
  assert response.json()["sections"][0]["content"] == "Generated introduction hallucination."
111
  assert response.json()["jevVerification"] is None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  assert response.status_code == 200
110
  assert response.json()["sections"][0]["content"] == "Generated introduction hallucination."
111
  assert response.json()["jevVerification"] is None
112
+
113
+
114
+ def test_empty_context_fails_closed_without_generated_grounding() -> None:
115
+ with patch("routes.rag_routes.retrieve_lesson_pdf_context", return_value=([], "general")), \
116
+ patch("routes.rag_routes._generate_text") as generate_text:
117
+ response = client.post("/api/rag/lesson", json=PAYLOAD)
118
+
119
+ assert response.status_code == 404
120
+ assert response.json()["detail"] == {
121
+ "error": "no_curriculum_context",
122
+ "message": "No curriculum content found for lesson 'Introduction to Rational Functions' (General Mathematics Q1). Please ensure the PDF has been ingested.",
123
+ "retrievalBand": "low",
124
+ "sources": [],
125
+ }
126
+ generate_text.assert_not_called()
tests/test_rag_pipeline.py CHANGED
@@ -44,6 +44,68 @@ class TestRetrieveCurriculumContext:
44
  )
45
  assert result == []
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  class TestDistanceToScore:
49
  def test_zero_distance_returns_one(self):
@@ -198,4 +260,4 @@ class TestSubjectNormalizationAndWhere:
198
  def test_vectorstore_dimension_alignment(self):
199
  from rag.vectorstore_loader import _get_collection_dimension, _resolve_vectorstore_dir
200
  dim = _get_collection_dimension(_resolve_vectorstore_dir())
201
- assert dim in (384, None)
 
44
  )
45
  assert result == []
46
 
47
+ def test_empty_exact_retrieval_runs_subject_quarter_and_general_fallbacks(self):
48
+ from rag import curriculum_rag
49
+
50
+ grounded_chunk = {
51
+ "content": "A linear equation has equal expressions on both sides.",
52
+ "source_file": "SHS_GM_Q1.pdf",
53
+ "score": 0.9,
54
+ "page": 2,
55
+ }
56
+ with patch.object(
57
+ curriculum_rag,
58
+ "retrieve_curriculum_context",
59
+ side_effect=[[], [], [], [], [], [grounded_chunk]],
60
+ ) as retrieve:
61
+ result, mode = curriculum_rag.retrieve_lesson_pdf_context(
62
+ topic="M11GM-Ia-1",
63
+ subject="General Mathematics",
64
+ quarter=3,
65
+ lesson_title="Linear Equations",
66
+ storage_path="curriculum/SHS_GM_Q1.pdf",
67
+ )
68
+
69
+ assert result == [grounded_chunk]
70
+ assert mode == "general"
71
+ assert [call.kwargs for call in retrieve.call_args_list] == [
72
+ {
73
+ "query": "Linear Equations",
74
+ "subject": "General Mathematics",
75
+ "quarter": 3,
76
+ "storage_path": "curriculum/SHS_GM_Q1.pdf",
77
+ "top_k": 8,
78
+ },
79
+ {
80
+ "query": "Linear Equations",
81
+ "subject": "General Mathematics",
82
+ "storage_path": "curriculum/SHS_GM_Q1.pdf",
83
+ "top_k": 8,
84
+ },
85
+ {
86
+ "query": "Linear Equations",
87
+ "storage_path": "curriculum/SHS_GM_Q1.pdf",
88
+ "top_k": 8,
89
+ },
90
+ {
91
+ "query": "Linear Equations",
92
+ "subject": "General Mathematics",
93
+ "quarter": 3,
94
+ "top_k": 8,
95
+ },
96
+ {
97
+ "query": "Linear Equations",
98
+ "subject": "General Mathematics",
99
+ "quarter": 1,
100
+ "top_k": 8,
101
+ },
102
+ {
103
+ "query": "Linear Equations",
104
+ "subject": "General Mathematics",
105
+ "top_k": 8,
106
+ },
107
+ ]
108
+
109
 
110
  class TestDistanceToScore:
111
  def test_zero_distance_returns_one(self):
 
260
  def test_vectorstore_dimension_alignment(self):
261
  from rag.vectorstore_loader import _get_collection_dimension, _resolve_vectorstore_dir
262
  dim = _get_collection_dimension(_resolve_vectorstore_dir())
263
+ assert dim in (384, None)