Repository navigation
Expand file tree
/
Copy pathfastapi_app.py
More file actions
446 lines (360 loc) · 17.4 KB
/
Copy pathfastapi_app.py
File metadata and controls
446 lines (360 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
from __future__ import annotations
import asyncio
import logging
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import Depends, FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from unilimit.integrations.fastapi import RateLimitExceeded, setup
from portal import meeting_source, program_ingest, usage, youtube_caption_sync
from portal.auth import (
ADMIN_CSRF_COOKIE,
generate_admin_csrf_token,
get_csrf_session_id,
is_cookie_secure,
is_valid_admin_csrf_token,
require_owner_or_coordinator,
)
from portal.config import settings
from portal.exceptions import RedirectRequired
from portal.globals import asset_version_context
from portal.rate_limit import auth_rate_limiter, login_limiter, token_rate_limiter
from portal.routers.admin import router as admin_router
from portal.routers.api import router as api_router
from portal.routers.api_v1 import router as api_v1_router
from portal.routers.attendance import router as attendance_router
from portal.routers.auth import router as auth_router
from portal.routers.demo import router as demo_router
from portal.routers.developer import router as developer_router
from portal.routers.interpreter import router as interpreter_router
from portal.routers.listener import router as listener_router
from portal.routers.meeting_analysis import router as meeting_analysis_router
from portal.routers.meeting_source import router as meeting_source_router
from portal.routers.oauth import router as oauth_router
from portal.routers.program_ingest import router as program_ingest_router
from portal.routers.public import router as public_router
from portal.routers.translation_models import router as translation_models_router
from portal.routers.webhooks import router as webhooks_router
from portal.routers.youtube import router as youtube_router
from portal.security_headers import SecurityHeadersMiddleware, apply_security_headers, forwarded_https
from portal.websockets.handlers import router as ws_router
from portal.workspace_routing import WorkspaceRoutingMiddleware
"FastAPI entry point — sole backend for the Voxbento.\n\nStart with:\n uvicorn fastapi_app:app --host 0.0.0.0 --port 8000 --reload\n"
_BASE_DIR = Path(__file__).resolve().parent
templates = Jinja2Templates(
directory=str(_BASE_DIR / "portal" / "templates"), context_processors=[asset_version_context]
)
async def _rate_limit_cleanup_loop(interval_seconds: float = 300.0) -> None:
"""Periodically purge expired rate limit entries to prevent unbounded memory growth."""
while True:
await asyncio.sleep(interval_seconds)
for name, limiter in (("auth", auth_rate_limiter), ("token", token_rate_limiter)):
try:
await limiter.cleanup()
except Exception:
logging.exception("Rate limit cleanup error (%s)", name)
@asynccontextmanager
async def lifespan(app: FastAPI):
import httpx
import portal.globals as pg
from portal.globals import booths
from portal.tts import demo_gen as dg
from portal.tts.demo_gen import ensure_demo_generated
settings.validate_production_secrets()
pg.shared_http_client = httpx.AsyncClient(timeout=10.0)
# Generate landing page demo audio in the background on first startup.
# Uses local Supertonic — no external API key needed.
async with dg._generation_lock:
dg._generating = True
async def _gen():
try:
await ensure_demo_generated()
finally:
dg._generating = False
import portal.notifications as _notifications_mod
import portal.webhooks.worker as _webhook_worker_mod
# Reference via module attribute so test-time monkey-patching of
# portal.webhooks.worker.webhook_worker_loop is respected.
import portal.websockets.reaper as _reaper_mod
from portal.websockets.manager import manager
manager.set_membership_checker(_reaper_mod.check_booth_memberships)
manager.set_token_checker(_reaper_mod.check_booth_tokens)
reaper_task = asyncio.create_task(_reaper_mod.session_reaper_loop())
webhook_task = asyncio.create_task(_webhook_worker_mod.webhook_worker_loop())
notification_task = asyncio.create_task(_notifications_mod.notification_worker_loop())
rate_limit_cleanup_task = asyncio.create_task(_rate_limit_cleanup_loop())
ingest_task = asyncio.create_task(program_ingest.reconcile_loop()) if settings.program_ingest_enabled else None
meeting_task = asyncio.create_task(meeting_source.reconcile_loop())
attendance_task = asyncio.create_task(booths.attendance.run())
usage_task = asyncio.create_task(usage.meter.run())
listening_task = asyncio.create_task(usage.ListeningSampler(usage.meter).run())
# Restores saved YouTube caption choices after a restart and keeps them in step (#1087, plan 006).
captions_task = (
asyncio.create_task(youtube_caption_sync.reconcile_loop()) if settings.youtube_connect_enabled else None
)
# Bring back booths that were live before this restart, then keep saving them (TD-03).
recovery_task = None
if settings.booth_state_recovery_enabled:
from portal import booth_recovery
from portal.websockets.manager import schedule_participant_expiry
restored = await booth_recovery.restore(booths, max_age_seconds=settings.booth_state_max_age_seconds)
for booth_id, participant_id in restored:
schedule_participant_expiry(booth_id, participant_id, None, settings.booth_restart_grace_seconds)
recovery_task = asyncio.create_task(booth_recovery.run(booths))
dg.track_task(asyncio.create_task(_gen()))
logging.getLogger("uvicorn.access").addFilter(_UvicornTokenRedactor())
logging.getLogger("uvicorn.access").addFilter(_HealthCheckFilter())
yield
tasks_to_cancel = [
reaper_task,
webhook_task,
notification_task,
rate_limit_cleanup_task,
meeting_task,
attendance_task,
usage_task,
listening_task,
]
if ingest_task:
tasks_to_cancel.append(ingest_task)
if recovery_task:
tasks_to_cancel.append(recovery_task)
if captions_task:
tasks_to_cancel.append(captions_task)
for task in tasks_to_cancel:
task.cancel()
await asyncio.gather(*tasks_to_cancel, return_exceptions=True)
# The coordinator is gone; stop its caption senders so no posting task outlives the app.
await youtube_caption_sync.shutdown()
if pg.shared_http_client:
await pg.shared_http_client.aclose()
class _HealthCheckFilter(logging.Filter):
def filter(self, record):
try:
return record.getMessage().find("GET /healthz") == -1
except Exception:
return True
class _UvicornTokenRedactor(logging.Filter):
import re as _re
_TOKEN_RE = _re.compile(r"(?i)((?:^|&|\?)(?:token|client_secret|code|access_token|refresh_token|key)=)[^&\s]*")
def filter(self, record):
try:
message = record.getMessage()
except Exception:
return True
lowered = message.casefold()
if self._TOKEN_RE.search(message) and any(
x in lowered for x in ["/api/", "/embed/", "/overlay/", "/ws/", "/oauth/", "/internal/"]
):
if isinstance(record.msg, str):
record.msg = self._TOKEN_RE.sub(r"\1[REDACTED]", record.msg)
if isinstance(record.args, tuple):
record.args = tuple(
self._TOKEN_RE.sub(r"\1[REDACTED]", value) if isinstance(value, str) else value
for value in record.args
)
return True
# Pages and APIs of the signed-in management area. A CSRF token is issued for these only, so
# public pages, listener traffic and static files never pay for decoding the session cookie.
_CSRF_PATH_PREFIXES = (
"/admin",
"/api/admin",
"/workspace",
"/api/workspace",
"/mission-control",
"/api/rooms",
"/account",
)
def _is_management_path(path: str) -> bool:
return any(path == prefix or path.startswith(f"{prefix}/") for prefix in _CSRF_PATH_PREFIXES)
class AdminCSRFMiddleware(BaseHTTPMiddleware):
"""Keep a session-bound CSRF token in an HttpOnly cookie and on ``request.state`` for templates."""
async def dispatch(self, request: Request, call_next):
csrf_token = request.cookies.get(ADMIN_CSRF_COOKIE, "")
replace_csrf_cookie = False
if _is_management_path(request.url.path):
session_id = get_csrf_session_id(request)
if not is_valid_admin_csrf_token(csrf_token, session_id):
csrf_token = generate_admin_csrf_token(session_id)
replace_csrf_cookie = True
request.state.admin_csrf_token = csrf_token
response = await call_next(request)
if replace_csrf_cookie:
response.set_cookie(
key=ADMIN_CSRF_COOKIE,
value=csrf_token,
httponly=True,
secure=is_cookie_secure(request),
samesite="lax",
)
return response
app = FastAPI(title="Voxbento", version="1.0.0", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(WorkspaceRoutingMiddleware)
app.add_middleware(AdminCSRFMiddleware)
app.add_middleware(SecurityHeadersMiddleware)
setup(app, login_limiter)
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(request: Request, _=Depends(require_owner_or_coordinator)):
return get_swagger_ui_html(openapi_url="/openapi.json", title="Voxbento API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def get_open_api_endpoint(request: Request, _=Depends(require_owner_or_coordinator)):
return JSONResponse(get_openapi(title="Voxbento API", version="1.0.0", routes=app.routes))
@app.exception_handler(RedirectRequired)
async def redirect_required_handler(request: Request, exc: RedirectRequired):
return RedirectResponse(exc.url, status_code=exc.status_code)
# Write-only secrets (e.g. the YouTube relay key) must never be echoed back by a 422.
_REDACTED_INPUT_FIELDS = frozenset({"stream_key"})
def _contains_secret_field(value: object) -> bool:
if isinstance(value, dict):
return any(key in _REDACTED_INPUT_FIELDS or _contains_secret_field(item) for key, item in value.items())
if isinstance(value, (list, tuple)):
return any(_contains_secret_field(item) for item in value)
return False
@app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(request: Request, exc: RequestValidationError):
"""FastAPI's default 422, minus the rejected input wherever it is or contains a secret field.
A ``missing`` error reports the whole body as its input, so the check covers the value
as well as the error location.
"""
errors = []
for error in exc.errors():
if any(part in _REDACTED_INPUT_FIELDS for part in error.get("loc", ())) or _contains_secret_field(
error.get("input")
):
error = {key: value for key, value in error.items() if key != "input"}
errors.append(error)
return JSONResponse({"detail": jsonable_encoder(errors)}, status_code=422)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
headers = dict(exc.headers) if exc.headers else None
location = exc.headers.get("Location") if exc.headers else None
if location and exc.status_code in (301, 302, 303, 307, 308):
from portal.utils import safe_redirect
return safe_redirect(url=location, status_code=exc.status_code)
is_api = "/api/" in request.url.path or request.url.path.startswith("/api")
if "text/html" in request.headers.get("accept", "") and not is_api:
detail_msg = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
if exc.status_code == 400:
return templates.TemplateResponse(
request, "400.html", {"request": request, "detail": detail_msg, "status_code": 400}, status_code=400
)
if exc.status_code in (401, 403):
import urllib.parse
from fastapi import status
from portal.auth import get_current_user
from portal.utils import safe_redirect
if not request.url.path.startswith("/embed/"):
user = await get_current_user(request)
if not user:
next_url = request.url.path
if request.url.query:
next_url += f"?{request.url.query}"
return safe_redirect(
f"/login?next={urllib.parse.quote(next_url)}", status_code=status.HTTP_303_SEE_OTHER
)
return templates.TemplateResponse(
request, "403.html", {"request": request, "detail": detail_msg}, status_code=403
)
if exc.status_code == 404:
return templates.TemplateResponse(
request, "404.html", {"request": request, "detail": detail_msg}, status_code=404
)
if exc.status_code == 429:
return templates.TemplateResponse(
request, "429.html", {"request": request, "detail": detail_msg}, status_code=429
)
if exc.status_code >= 500:
return templates.TemplateResponse(
request, "500.html", {"request": request, "detail": detail_msg}, status_code=exc.status_code
)
return templates.TemplateResponse(
request,
"400.html",
{"request": request, "detail": detail_msg, "status_code": exc.status_code},
status_code=exc.status_code,
)
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code, headers=headers)
@app.exception_handler(RateLimitExceeded)
async def unilimit_rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded):
headers = dict(exc.headers) if hasattr(exc, "headers") and exc.headers else {}
if request.url.path == "/login":
form_data: dict[str, str] = {}
try:
form = await request.form()
email = form.get("email", "")
next_url = form.get("next_url", "")
form_data = {
"email": email.strip().lower() if isinstance(email, str) else "",
"next_url": next_url if isinstance(next_url, str) else "",
}
except Exception as parse_exc:
logging.debug("Could not parse login form on rate limit rejection: %s", parse_exc)
return templates.TemplateResponse(
request=request,
name="login.html",
context={
"error": "Too many attempts. Try again later.",
"email": form_data.get("email", ""),
"next_url": form_data.get("next_url", ""),
},
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
headers=headers,
)
if "text/html" in request.headers.get("accept", ""):
detail_msg = getattr(exc, "detail", "Too Many Requests")
return templates.TemplateResponse(
request, "429.html", {"request": request, "detail": detail_msg}, status_code=429, headers=headers
)
return JSONResponse(
{"detail": getattr(exc, "detail", "Too Many Requests")},
status_code=getattr(exc, "status_code", status.HTTP_429_TOO_MANY_REQUESTS),
headers=headers,
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
import logging
import traceback
traceback.print_exc()
logging.exception("Unhandled Server Error:")
if "text/html" in request.headers.get("accept", ""):
response = templates.TemplateResponse(
request, "500.html", {"request": request, "detail": "Internal Server Error"}, status_code=500
)
else:
response = JSONResponse({"detail": "Internal Server Error"}, status_code=500)
# Unhandled-error responses are built outside the middleware stack, so add the headers here.
is_https = request.url.scheme == "https" or forwarded_https(request.headers)
apply_security_headers(response.headers, path=request.url.path, is_https=is_https)
return response
app.mount("/static", StaticFiles(directory=_BASE_DIR / "portal" / "static"), name="static")
app.include_router(public_router)
app.include_router(auth_router)
app.include_router(developer_router)
app.include_router(oauth_router)
app.include_router(webhooks_router)
app.include_router(interpreter_router)
app.include_router(listener_router)
app.include_router(api_router)
app.include_router(api_v1_router)
app.include_router(admin_router)
app.include_router(program_ingest_router)
app.include_router(youtube_router)
app.include_router(meeting_source_router)
app.include_router(attendance_router)
app.include_router(translation_models_router)
app.include_router(meeting_analysis_router)
app.include_router(demo_router)
app.include_router(ws_router)
def main() -> None:
import uvicorn
uvicorn.run("fastapi_app:app", host=settings.host, port=settings.port, reload=settings.debug)
if __name__ == "__main__":
main()