Author SHA1 Message Date
ahp 53becfa1de fix(api): answer 503 when an upload cannot be stored
An unwritable DATA_DIR (a root-owned volume, a full disk, a read-only
mount) made POST /jobs and POST /v1/audio/transcriptions fail with a
bare 500 and a PermissionError traceback, with nothing in the response
telling the client it was a server-side storage problem.

- save_upload raises StorageUnavailableError on any OSError while
  creating DATA_DIR/audio or writing the file, and removes a partially
  written file first
- one app-level handler turns it into 503 with a short detail; the real
  error, including the path, goes only to the server log
- the API logs an error at startup when DATA_DIR is not writable, so a
  bad volume shows up before the first upload
2026-11-26 18:02:05 +03:30
24 changed files with 114 additions and 523 deletions

No files matched your search

-9
View File
@@ -106,9 +106,6 @@ LLM_MODEL=
# --- Telegram bot (optional) ---
TELEGRAM_BOT_TOKEN=
# Shared secret between the bot and the API; set the same value on both.
BOT_API_SECRET=
# URL the bot puts in messages so users can open their archive in the browser.
WEB_BASE_URL=http://localhost:3000
@@ -132,12 +129,6 @@ WEBHOOK_SIGNING_SECRET=
# best-effort and never flips the job status).
WEBHOOK_TIMEOUT_SECONDS=4.0
WEBHOOK_ATTEMPTS=2
# Allow callbacks to private/loopback addresses (trusted installs only).
WEBHOOK_ALLOW_PRIVATE_TARGETS=false
# --- Login brute-force guard ---
LOGIN_MAX_FAILURES=10
LOGIN_FAILURE_WINDOW_SECONDS=900
# --- Deployment (deploy/docker-compose.yml) ---
# Required: the compose file refuses to start without a real password.
+9 -25
View File
@@ -5,31 +5,6 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
## [Unreleased]
### Security
- **`POST /auth/telegram` could be used to take over any Telegram user's
account.** It minted a fresh API token for whatever `telegram_id` the
caller sent, with no proof the caller was the bot. It now requires the
`X-Bot-Secret` header to match the new `BOT_API_SECRET` (constant-time
compare; 403 on mismatch, 503 while unset). **Breaking for deployments
with the bot:** set the same `BOT_API_SECRET` on the API and the bot; the
bot refuses to start without it.
- Request bodies above `MAX_UPLOAD_MB` (plus 1 MiB multipart allowance) are
now refused with 413 by a middleware, up front from `Content-Length` or
mid-stream for chunked uploads. Before, the size check ran only after the
whole body had been spooled to disk and read into memory, so one
multi-gigabyte upload could exhaust the API container's disk or RAM.
- Webhook `callback_url`s can no longer target internal addresses. Any
user could point the worker at loopback, private, link-local (cloud
metadata) or LAN hosts. Literal private hosts are now rejected at upload
(422), every resolved address is checked again at connect time (defeating
DNS rebinding), redirects are not followed and proxy env vars are ignored.
**Breaking for receivers on private addresses:** set
`WEBHOOK_ALLOW_PRIVATE_TARGETS=true` on trusted single-tenant installs.
- `POST /auth/login` is throttled: after `LOGIN_MAX_FAILURES` (10) failures
per client address and email within `LOGIN_FAILURE_WINDOW_SECONDS` (900)
it answers 429 with `Retry-After`; a successful login clears the count.
### Added
- **Persian accuracy stack (v2)** — measured on the 12-clip Common Voice
@@ -99,6 +74,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
pyproject.toml files, web/package.json, the landing site copy, the demo
Space metadata and the fine-tuned model card.
### Fixed
- An upload the API cannot store (unwritable `DATA_DIR`, full disk,
read-only volume) now answers **503** with a short message on `POST /jobs`
and `POST /v1/audio/transcriptions`, instead of a 500 with a traceback in
the log. The real `OSError` is logged server-side, a partially written
file is removed, and the API logs an error at startup when `DATA_DIR`
is not writable.
## [1.4.1] - 2026-11-26
### Security
-3
View File
@@ -225,12 +225,9 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
| `LOW_CONFIDENCE_THRESHOLD` | `0.5` | اطمینان سگمنت زیرِ این مقدار پرچم بازبینی می‌گیرد |
| `STREAMING_DECODE` | `true` | خواندن بلاک‌به‌بلاک صدا (حافظهٔ اوج ∝ پنجره، نه طول فایل) |
| `WEBHOOK_SIGNING_SECRET` | خالی | رمز HMAC برای کال‌بک‌های پایان کار (`X-Sokhan-Signature`)؛ خالی یعنی بدون امضا |
| `WEBHOOK_ALLOW_PRIVATE_TARGETS` | `false` | اجازهٔ کال‌بک به نشانی‌های خصوصی/لوکال (فقط برای نصب تک‌کاربرهٔ مورد اعتماد) |
| `LOGIN_MAX_FAILURES` / `LOGIN_FAILURE_WINDOW_SECONDS` | `10` / `900` | تعداد ورود ناموفق برای هر نشانی و ایمیل پیش از `429`؛ `0` یعنی غیرفعال |
| `SUMMARY_ENABLED` | `false` | فلگ امکان خلاصه‌سازی با LLM |
| `LLM_API_BASE` / `LLM_API_KEY` / `LLM_MODEL` | خالی | endpoint سازگار با OpenAI |
| `TELEGRAM_BOT_TOKEN` | خالی | فعال‌سازی فرایند ربات |
| `BOT_API_SECRET` | خالی | رمز مشترکی که ربات به `POST /auth/telegram` می‌فرستد؛ روی API و ربات یک مقدار بگذارید، خالی یعنی ورود تلگرامی غیرفعال |
| `WEB_BASE_URL` | `http://localhost:3000` | لینک‌هایی که ربات می‌فرستد |
| `API_BASE_URL` | `http://localhost:8000` | آدرس API که ربات صدا می‌زند |
| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | آدرس API که اپ وب صدا می‌زند (زمان build) |
-3
View File
@@ -224,12 +224,9 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
| `LOW_CONFIDENCE_THRESHOLD` | `0.5` | segment confidence below which review flags apply |
| `STREAMING_DECODE` | `true` | decode audio block-by-block (peak RAM ∝ window, not file length) |
| `WEBHOOK_SIGNING_SECRET` | empty | HMAC secret for job-completion callbacks (`X-Sokhan-Signature`); empty sends them unsigned |
| `WEBHOOK_ALLOW_PRIVATE_TARGETS` | `false` | allow callbacks to private/loopback addresses (trusted single-tenant installs only) |
| `LOGIN_MAX_FAILURES` / `LOGIN_FAILURE_WINDOW_SECONDS` | `10` / `900` | failed logins per client address and email before `429`; `0` disables |
| `SUMMARY_ENABLED` | `false` | LLM summaries feature flag |
| `LLM_API_BASE` / `LLM_API_KEY` / `LLM_MODEL` | empty | OpenAI-compatible endpoint |
| `TELEGRAM_BOT_TOKEN` | empty | enables the bot process |
| `BOT_API_SECRET` | empty | shared secret the bot sends to `POST /auth/telegram`; set the same value on the API and the bot, empty disables Telegram login |
| `WEB_BASE_URL` | `http://localhost:3000` | links the bot sends |
| `API_BASE_URL` | `http://localhost:8000` | API address the bot calls |
| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | API address the web app calls (build-time) |
-40
View File
@@ -1,40 +0,0 @@
from fastapi import HTTPException
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Message, Receive, Scope, Send
MULTIPART_OVERHEAD_BYTES = 1024 * 1024
_DETAIL = "request body too large"
_PAYLOAD_TOO_LARGE = 413
class BodySizeLimitMiddleware:
def __init__(self, app: ASGIApp, max_body_bytes: int) -> None:
self.app = app
self.max_body_bytes = max_body_bytes
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
declared = dict(scope.get("headers") or []).get(b"content-length")
if declared is not None and declared.isdigit() and int(declared) > self.max_body_bytes:
response = JSONResponse(
{"detail": _DETAIL}, status_code=_PAYLOAD_TOO_LARGE
)
await response(scope, receive, send)
return
received = 0
async def limited_receive() -> Message:
nonlocal received
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > self.max_body_bytes:
raise HTTPException(_PAYLOAD_TOO_LARGE, _DETAIL)
return message
await self.app(scope, limited_receive, send)
-11
View File
@@ -44,14 +44,3 @@ def require_admin(x_admin_key: str | None = Header(default=None)) -> None:
)
if x_admin_key is None or not secrets.compare_digest(x_admin_key, settings.admin_api_key):
raise HTTPException(status.HTTP_403_FORBIDDEN, "invalid admin key")
def require_bot(x_bot_secret: str | None = Header(default=None)) -> None:
settings = get_settings()
if not settings.bot_api_secret:
raise HTTPException(
status.HTTP_503_SERVICE_UNAVAILABLE,
"telegram login disabled: set BOT_API_SECRET on the API and the bot",
)
if x_bot_secret is None or not secrets.compare_digest(x_bot_secret, settings.bot_api_secret):
raise HTTPException(status.HTTP_403_FORBIDDEN, "invalid bot secret")
+3 -38
View File
@@ -11,15 +11,12 @@ Deliberately lightweight for v1:
import re
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from sokhan.api.deps import require_bot
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
from sokhan.config import get_settings
from sokhan.core.throttle import FailureThrottle
from sokhan.db import get_db
from sokhan.models import User
from sokhan.schemas import AuthResponse
@@ -79,44 +76,12 @@ def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthRe
return AuthResponse(id=user.id, email=user.email, api_token=token)
_login_throttle: FailureThrottle | None = None
def get_login_throttle() -> FailureThrottle:
global _login_throttle
if _login_throttle is None:
settings = get_settings()
_login_throttle = FailureThrottle(
settings.login_max_failures, settings.login_failure_window_seconds
)
return _login_throttle
def reset_login_throttle() -> None:
global _login_throttle
_login_throttle = None
@router.post("/login", response_model=AuthResponse)
def login(
payload: Credentials, request: Request, session: Session = Depends(get_db)
) -> AuthResponse:
def login(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
email = payload.email.strip().lower()
throttle = get_login_throttle()
key = (request.client.host if request.client else "", email)
wait_seconds = throttle.retry_after(key)
if wait_seconds:
raise HTTPException(
status.HTTP_429_TOO_MANY_REQUESTS,
"too many failed login attempts, try again later",
headers={"Retry-After": str(wait_seconds)},
)
user = session.scalar(select(User).where(User.email == email))
if user is None or not verify_password(payload.password, user.password_hash):
throttle.record_failure(key)
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid credentials")
throttle.reset(key)
token = generate_token()
user.token_hash = token_hash(token)
@@ -132,7 +97,7 @@ def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> Auth
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
@router.post("/telegram", response_model=AuthResponse, dependencies=[Depends(require_bot)])
@router.post("/telegram", response_model=AuthResponse)
def telegram_login(payload: TelegramLogin, session: Session = Depends(get_db)) -> AuthResponse:
"""Register-or-login used by the Telegram bot.
+6 -7
View File
@@ -14,7 +14,6 @@ from sokhan.api.serializers import job_to_detail, job_to_out
from sokhan.config import get_settings
from sokhan.core.audio import delete_audio, probe_duration_seconds, save_upload
from sokhan.core.formats import to_docx, to_json_transcript, to_srt, to_txt, to_vtt
from sokhan.core.webhooks import callback_url_problem
from sokhan.db import get_db
from sokhan.models import Job, JobStatus, Segment, User
from sokhan.schemas import JobCreated, JobDetailOut, JobListResponse
@@ -54,16 +53,16 @@ def create_job(
if callback_url is not None:
callback_url = callback_url.strip() or None
settings = get_settings()
if callback_url:
if len(callback_url) > 2048:
if callback_url and (
len(callback_url) > 2048
or not callback_url.lower().startswith(("http://", "https://"))
):
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY,
"callback_url must be an http(s) URL of at most 2048 characters",
)
problem = callback_url_problem(callback_url, settings.webhook_allow_private_targets)
if problem:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, problem)
settings = get_settings()
data = file.file.read()
if not data:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "empty file")
-6
View File
@@ -74,8 +74,6 @@ class Settings(BaseSettings):
# Leave empty to disable the admin endpoints entirely.
admin_api_key: str = ""
bot_api_secret: str = ""
# LLM summaries (optional, behind a feature flag)
summary_enabled: bool = False
llm_api_base: str = ""
@@ -93,10 +91,6 @@ class Settings(BaseSettings):
webhook_signing_secret: str = ""
webhook_timeout_seconds: float = 4.0
webhook_attempts: int = 2
webhook_allow_private_targets: bool = False
login_max_failures: int = 10
login_failure_window_seconds: int = 900
@lru_cache(maxsize=1)
+22 -3
View File
@@ -25,6 +25,14 @@ ALLOWED_EXTENSIONS = {".mp3", ".m4a", ".mp4", ".wav", ".ogg", ".opus", ".webm",
_SAFE_SUFFIX = re.compile(r"^[a-z0-9]{1,8}$")
class StorageUnavailableError(Exception):
"""DATA_DIR cannot be written, e.g. a root-owned volume or a full disk.
It is a server fault, not a bad upload, so the API answers 503 and the
real OSError stays in the server log instead of reaching the client.
"""
def decode_to_mono_16k(path: str | Path) -> np.ndarray:
"""Decode any media file to mono float32 PCM at 16 kHz."""
return decode_audio(str(path), sampling_rate=SAMPLE_RATE)
@@ -102,12 +110,23 @@ def audio_dir() -> Path:
def save_upload(data: bytes, job_id: str, original_filename: str) -> Path:
"""Persist an upload under DATA_DIR/audio with a safe extension."""
"""Persist an upload under DATA_DIR/audio with a safe extension.
Raises StorageUnavailableError when the directory or file cannot be
written; a partially written file is removed first.
"""
suffix = Path(original_filename).suffix.lower()
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
suffix = ".bin"
path = audio_dir() / f"{job_id}{suffix}"
path.write_bytes(data)
try:
path = audio_dir() / f"{job_id}{suffix}"
except OSError as exc:
raise StorageUnavailableError(str(exc)) from exc
try:
path.write_bytes(data)
except OSError as exc:
delete_audio(path)
raise StorageUnavailableError(str(exc)) from exc
return path
-48
View File
@@ -1,48 +0,0 @@
import threading
import time
from collections import deque
from collections.abc import Callable, Hashable
class FailureThrottle:
def __init__(
self,
max_failures: int,
window_seconds: float,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.max_failures = max_failures
self.window_seconds = window_seconds
self._clock = clock
self._failures: dict[Hashable, deque[float]] = {}
self._lock = threading.Lock()
def _prune(self, key: Hashable, now: float) -> deque[float]:
stamps = self._failures.get(key)
if stamps is None:
return deque()
while stamps and now - stamps[0] >= self.window_seconds:
stamps.popleft()
if not stamps:
del self._failures[key]
return stamps
def retry_after(self, key: Hashable) -> int:
if self.max_failures <= 0:
return 0
with self._lock:
now = self._clock()
stamps = self._prune(key, now)
if len(stamps) < self.max_failures:
return 0
return max(1, int(stamps[0] + self.window_seconds - now + 0.999))
def record_failure(self, key: Hashable) -> None:
with self._lock:
now = self._clock()
self._prune(key, now)
self._failures.setdefault(key, deque()).append(now)
def reset(self, key: Hashable) -> None:
with self._lock:
self._failures.pop(key, None)
+1 -102
View File
@@ -21,17 +21,13 @@ transport so tests need no network.
import hashlib
import hmac
import http.client
import ipaddress
import json
import logging
import socket
import time
import urllib.error
import urllib.request
from collections.abc import Callable
from typing import Any
from urllib.parse import urlsplit
from sokhan.config import get_settings
@@ -93,99 +89,6 @@ def verify_signature(
return hmac.compare_digest(mac.hexdigest(), provided)
class BlockedTargetError(OSError):
pass
def is_public_address(address: str) -> bool:
ip = ipaddress.ip_address(address.split("%", 1)[0])
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
ip = ip.ipv4_mapped
return ip.is_global and not ip.is_multicast
def callback_url_problem(url: str, allow_private: bool) -> str | None:
try:
parts = urlsplit(url)
host = parts.hostname
parts.port # noqa: B018
except ValueError:
return "callback_url is not a valid URL"
if parts.scheme.lower() not in ("http", "https") or not host:
return "callback_url must be an http(s) URL with a host"
if allow_private:
return None
if host == "localhost" or host.endswith(".localhost"):
return "callback_url must point to a public address"
try:
if not is_public_address(host):
return "callback_url must point to a public address"
except ValueError:
pass
return None
def _guarded_create_connection(
address: tuple[str, int],
timeout: float | object = socket._GLOBAL_DEFAULT_TIMEOUT, # type: ignore[attr-defined]
source_address: tuple[str, int] | None = None,
*args: object,
**kwargs: object,
) -> socket.socket:
host, port = address
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
if not infos:
raise BlockedTargetError(f"{host} did not resolve")
for info in infos:
if not is_public_address(str(info[4][0])):
raise BlockedTargetError(f"{host} resolves to non-public address {info[4][0]}")
last_error: OSError | None = None
for info in infos:
try:
return socket.create_connection(
(str(info[4][0]), port), timeout, source_address # type: ignore[arg-type]
)
except OSError as exc:
last_error = exc
raise last_error or BlockedTargetError(f"could not connect to {host}")
class _GuardedHTTPConnection(http.client.HTTPConnection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._create_connection = _guarded_create_connection # type: ignore[assignment]
class _GuardedHTTPSConnection(http.client.HTTPSConnection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._create_connection = _guarded_create_connection # type: ignore[assignment]
class _GuardedHTTPHandler(urllib.request.HTTPHandler):
def http_open(self, req: urllib.request.Request) -> http.client.HTTPResponse:
return self.do_open(_GuardedHTTPConnection, req)
class _GuardedHTTPSHandler(urllib.request.HTTPSHandler):
def https_open(self, req: urllib.request.Request) -> http.client.HTTPResponse:
return self.do_open(_GuardedHTTPSConnection, req, context=self._context) # type: ignore[attr-defined]
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
return None
def _public_only_opener() -> urllib.request.OpenerDirector:
return urllib.request.build_opener(
urllib.request.ProxyHandler({}),
_GuardedHTTPHandler(),
_GuardedHTTPSHandler(),
_NoRedirectHandler(),
)
def _default_post(url: str, body: bytes, headers: dict[str, str], timeout: float) -> None:
request = urllib.request.Request(
url,
@@ -193,11 +96,7 @@ def _default_post(url: str, body: bytes, headers: dict[str, str], timeout: float
headers={"Content-Type": "application/json", **headers},
method="POST",
)
if get_settings().webhook_allow_private_targets:
opener = urllib.request.build_opener()
else:
opener = _public_only_opener()
with opener.open(request, timeout=timeout) as response:
with urllib.request.urlopen(request, timeout=timeout) as response:
response.read()
+19 -6
View File
@@ -10,12 +10,13 @@ import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sokhan import __version__
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware
from sokhan.config import get_settings
from sokhan.core.audio import StorageUnavailableError, audio_dir
from sokhan.db import configure, create_all
logger = logging.getLogger("sokhan")
@@ -28,6 +29,14 @@ def create_app() -> FastAPI:
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
configure()
create_all()
try:
audio_dir()
except OSError as exc:
logger.error(
"DATA_DIR is not writable (%s) - uploads will fail with 503 until "
"it is; in Docker check the volume is owned by the app user",
exc,
)
if not settings.celery_enabled:
logger.warning(
"CELERY_ENABLED=false - jobs run inline in the API process; "
@@ -53,10 +62,6 @@ def create_app() -> FastAPI:
for origin in os.getenv("SOKHAN_CORS_ORIGINS", "").split(",")
if origin.strip()
] or ["http://localhost:3000", "http://127.0.0.1:3000"]
app.add_middleware(
BodySizeLimitMiddleware,
max_body_bytes=settings.max_upload_mb * 1024 * 1024 + MULTIPART_OVERHEAD_BYTES,
)
app.add_middleware(
CORSMiddleware,
allow_origins=cors_origins,
@@ -73,6 +78,14 @@ def create_app() -> FastAPI:
app.include_router(routes_openai.router)
app.include_router(routes_admin.router)
@app.exception_handler(StorageUnavailableError)
async def storage_unavailable(request: Request, exc: StorageUnavailableError) -> JSONResponse:
logger.error("upload storage failed for %s %s: %s", request.method, request.url.path, exc)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={"detail": "upload storage is unavailable, try again later"},
)
@app.get("/")
def root() -> dict:
return {"name": "Sokhan API", "version": __version__, "docs": "/docs"}
-3
View File
@@ -29,18 +29,15 @@ def app(tmp_path, monkeypatch):
monkeypatch.setenv("PLAN_PRO_MAX_FILE_MINUTES", "180")
monkeypatch.setenv("PLAN_PRO_MONTHLY_MINUTES", "1200")
from sokhan.api.routes_auth import reset_login_throttle
from sokhan.config import get_settings
get_settings.cache_clear()
reset_login_throttle()
db.reset()
db.configure(f"sqlite:///{tmp_path / 'test.sqlite3'}")
db.create_all()
yield create_app()
db.reset()
get_settings.cache_clear()
reset_login_throttle()
@pytest.fixture()
+3 -33
View File
@@ -1,4 +1,3 @@
import pytest
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
@@ -52,43 +51,14 @@ def test_token_login_rejects_bad_code(client):
assert response.status_code == 401
BOT_SECRET = "bot-shared-secret"
@pytest.fixture()
def bot_secret(monkeypatch):
from sokhan.config import get_settings
monkeypatch.setenv("BOT_API_SECRET", BOT_SECRET)
get_settings.cache_clear()
yield {"X-Bot-Secret": BOT_SECRET}
get_settings.cache_clear()
def test_telegram_register_or_login(client, bot_secret):
body = {"telegram_id": 12345, "username": "amin"}
first = client.post("/auth/telegram", json=body, headers=bot_secret)
def test_telegram_register_or_login(client):
first = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
assert first.status_code == 200
second = client.post("/auth/telegram", json=body, headers=bot_secret)
second = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
assert second.status_code == 200
assert first.json()["id"] == second.json()["id"]
def test_telegram_login_rejects_callers_without_the_bot_secret(client, bot_secret):
body = {"telegram_id": 12345}
missing = client.post("/auth/telegram", json=body)
wrong = client.post("/auth/telegram", json=body, headers={"X-Bot-Secret": "guess"})
assert missing.status_code == 403
assert wrong.status_code == 403
def test_telegram_login_is_disabled_without_a_configured_secret(client):
response = client.post(
"/auth/telegram", json={"telegram_id": 12345}, headers={"X-Bot-Secret": ""}
)
assert response.status_code == 503
def test_jobs_require_token(client):
response = client.get("/jobs")
assert response.status_code == 401
-49
View File
@@ -1,49 +0,0 @@
import pytest
from fastapi.testclient import TestClient
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES
from sokhan.main import create_app
MIB = 1024 * 1024
@pytest.fixture()
def small_cap_client(app, monkeypatch):
from sokhan.config import get_settings
monkeypatch.setenv("MAX_UPLOAD_MB", "1")
get_settings.cache_clear()
with TestClient(create_app()) as test_client:
yield test_client
get_settings.cache_clear()
def test_declared_oversized_body_is_rejected_up_front(small_cap_client, auth):
too_big = b"\0" * (MIB + MULTIPART_OVERHEAD_BYTES + 1)
response = small_cap_client.post(
"/jobs", headers=auth, files={"file": ("big.wav", too_big, "audio/wav")}
)
assert response.status_code == 413
def test_chunked_oversized_body_is_cut_off_mid_stream(small_cap_client, auth):
def body():
for _ in range(4):
yield b"\0" * MIB
response = small_cap_client.post(
"/jobs",
headers={**auth, "Content-Type": "multipart/form-data; boundary=x"},
content=body(),
)
assert response.status_code == 413
def test_upload_under_the_cap_still_works(
small_cap_client, auth, wav_bytes, fake_engine, wait_for_job
):
response = small_cap_client.post(
"/jobs", headers=auth, files={"file": ("ok.wav", wav_bytes, "audio/wav")}
)
assert response.status_code == 201
job = wait_for_job(small_cap_client, auth, response.json()["id"])
assert job["status"] == "completed"
+51
View File
@@ -1,5 +1,8 @@
import io
import shutil
from pathlib import Path
import pytest
from docx import Document
@@ -188,3 +191,51 @@ def test_other_users_cannot_read_a_job(client, auth, wav_bytes, fake_engine):
assert client.get(f"/jobs/{job_id}", headers=headers).status_code == 404
assert client.get("/jobs", headers=headers).json()["total"] == 0
def _make_data_dir_unwritable(tmp_path):
"""Replace DATA_DIR with a plain file, so creating DATA_DIR/audio fails."""
shutil.rmtree(tmp_path / "data")
(tmp_path / "data").write_text("not a directory")
def test_upload_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = _upload(client, auth, wav_bytes)
assert response.status_code == 503
assert response.json() == {"detail": "upload storage is unavailable, try again later"}
# No job row is left behind for an upload that was never stored.
assert client.get("/jobs", headers=auth).json()["total"] == 0
def test_openai_endpoint_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = client.post(
"/v1/audio/transcriptions",
files={"file": ("test.wav", wav_bytes, "audio/wav")},
data={"language": "fa", "response_format": "json"},
headers=auth,
)
assert response.status_code == 503
def test_failed_write_removes_the_partial_file(app, tmp_path, monkeypatch):
from sokhan.core.audio import StorageUnavailableError, audio_dir, save_upload
def write_fails_midway(self, data):
self.open("wb").write(data[:1])
raise OSError(28, "No space left on device")
monkeypatch.setattr(Path, "write_bytes", write_fails_midway)
with pytest.raises(StorageUnavailableError):
save_upload(b"RIFF....", "job-1", "clip.wav")
assert list(audio_dir().iterdir()) == []
-55
View File
@@ -1,55 +0,0 @@
import pytest
from sokhan.core.throttle import FailureThrottle
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
WRONG = {"email": REGISTER["email"], "password": "wrong-pass"}
@pytest.fixture()
def tight_login_limit(app, monkeypatch):
from sokhan.api.routes_auth import reset_login_throttle
from sokhan.config import get_settings
monkeypatch.setenv("LOGIN_MAX_FAILURES", "3")
get_settings.cache_clear()
reset_login_throttle()
def test_login_is_throttled_after_repeated_failures(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
for _ in range(3):
assert client.post("/auth/login", json=WRONG).status_code == 401
blocked = client.post("/auth/login", json=REGISTER)
assert blocked.status_code == 429
assert int(blocked.headers["Retry-After"]) > 0
def test_successful_login_clears_the_failure_count(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
for _ in range(2):
client.post("/auth/login", json=WRONG)
assert client.post("/auth/login", json=REGISTER).status_code == 200
for _ in range(2):
assert client.post("/auth/login", json=WRONG).status_code == 401
def test_other_accounts_are_not_locked_out(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
other = {"email": "sara@example.org", "password": "parool-5678"}
client.post("/auth/register", json=other)
for _ in range(3):
client.post("/auth/login", json=WRONG)
assert client.post("/auth/login", json=other).status_code == 200
def test_throttle_window_slides():
now = [1000.0]
throttle = FailureThrottle(max_failures=2, window_seconds=60, clock=lambda: now[0])
throttle.record_failure("k")
throttle.record_failure("k")
assert throttle.retry_after("k") == 60
now[0] += 30
assert throttle.retry_after("k") == 30
now[0] += 30
assert throttle.retry_after("k") == 0
-50
View File
@@ -341,53 +341,3 @@ def test_dead_endpoint_does_not_fail_the_job(
detail = wait_for_job(client, auth, response.json()["id"])
assert detail["status"] == "completed"
assert "سلام بر تو" in detail["text"]
@pytest.mark.parametrize(
"url",
[
"http://127.0.0.1:6379/",
"http://localhost:8000/admin",
"http://169.254.169.254/latest/meta-data/",
"http://10.0.0.5/hook",
"http://[::1]/hook",
"http://[::ffff:192.168.1.1]/hook",
"https://",
],
)
def test_callback_url_to_private_targets_is_rejected(client, auth, wav_bytes, url):
response = _upload(client, auth, wav_bytes, callback_url=url)
assert response.status_code == 422
def test_private_callback_url_allowed_when_opted_in(
client, auth, wav_bytes, monkeypatch, fake_engine, wait_for_job
):
from sokhan.config import get_settings
from sokhan.core import webhooks
monkeypatch.setenv("WEBHOOK_ALLOW_PRIVATE_TARGETS", "true")
get_settings.cache_clear()
delivered: list[str] = []
monkeypatch.setattr(webhooks, "_default_post", lambda url, *rest: delivered.append(url))
response = _upload(client, auth, wav_bytes, callback_url="http://10.0.0.5/hook")
assert response.status_code == 201
wait_for_job(client, auth, response.json()["id"])
get_settings.cache_clear()
assert delivered == ["http://10.0.0.5/hook"]
def test_delivery_refuses_hosts_that_resolve_privately(monkeypatch):
import socket
import urllib.error
from sokhan.core import webhooks
def fake_getaddrinfo(host, port, *args, **kwargs):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))]
monkeypatch.setattr(webhooks.socket, "getaddrinfo", fake_getaddrinfo)
with pytest.raises(urllib.error.URLError) as caught:
webhooks._default_post("http://hooks.example/sokhan", b"{}", {}, 1.0)
assert isinstance(caught.value.reason, webhooks.BlockedTargetError)
-1
View File
@@ -50,7 +50,6 @@ class SokhanClient:
response = self._client.post(
f"{self.settings.api_base_url}/auth/telegram",
json={"telegram_id": telegram_id, "username": username},
headers={"X-Bot-Secret": self.settings.bot_api_secret},
)
if response.status_code != 200:
raise BackendError(f"register failed with status {response.status_code}")
-2
View File
@@ -9,7 +9,6 @@ class BotSettings:
telegram_bot_token: str
api_base_url: str
web_base_url: str
bot_api_secret: str = ""
def load_settings() -> BotSettings:
@@ -17,5 +16,4 @@ def load_settings() -> BotSettings:
telegram_bot_token=os.environ.get("TELEGRAM_BOT_TOKEN", ""),
api_base_url=os.environ.get("API_BASE_URL", "http://localhost:8000").rstrip("/"),
web_base_url=os.environ.get("WEB_BASE_URL", "http://localhost:3000").rstrip("/"),
bot_api_secret=os.environ.get("BOT_API_SECRET", ""),
)
-7
View File
@@ -30,13 +30,6 @@ def main() -> None:
file=sys.stderr,
)
raise SystemExit(1)
if not settings.bot_api_secret:
print(
"BOT_API_SECRET is not set. Set the same value on the API and the bot; "
"the API refuses Telegram logins without it.",
file=sys.stderr,
)
raise SystemExit(1)
bot = Bot(settings.telegram_bot_token)
dispatcher = Dispatcher()
-18
View File
@@ -88,21 +88,3 @@ def test_get_plans_parses_catalogue():
plans = client.get_plans()
assert [plan["code"] for plan in plans] == ["free", "pro"]
assert plans[1]["max_file_minutes"] == 180
def test_register_telegram_sends_the_bot_secret():
seen: dict[str, str | None] = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["secret"] = request.headers.get("X-Bot-Secret")
return httpx.Response(200, json={"id": "u1", "email": "tg", "api_token": "tok"})
settings = BotSettings(
telegram_bot_token="t",
api_base_url="http://api.test",
web_base_url="http://web.test",
bot_api_secret="shared",
)
with SokhanClient(settings, transport=httpx.MockTransport(handler)) as client:
assert client.register_telegram(42, None) == "tok"
assert seen["secret"] == "shared"
-4
View File
@@ -48,15 +48,11 @@ services:
LOW_CONFIDENCE_THRESHOLD: ${LOW_CONFIDENCE_THRESHOLD:-0.5}
STREAMING_DECODE: ${STREAMING_DECODE:-true}
WEBHOOK_SIGNING_SECRET: ${WEBHOOK_SIGNING_SECRET:-}
WEBHOOK_ALLOW_PRIVATE_TARGETS: ${WEBHOOK_ALLOW_PRIVATE_TARGETS:-false}
LOGIN_MAX_FAILURES: ${LOGIN_MAX_FAILURES:-10}
LOGIN_FAILURE_WINDOW_SECONDS: ${LOGIN_FAILURE_WINDOW_SECONDS:-900}
FREE_MINUTES_PER_USER_PER_MONTH: ${FREE_MINUTES_PER_USER_PER_MONTH:-30}
PLAN_FREE_MAX_FILE_MINUTES: ${PLAN_FREE_MAX_FILE_MINUTES:-10}
PLAN_PRO_MAX_FILE_MINUTES: ${PLAN_PRO_MAX_FILE_MINUTES:-180}
PLAN_PRO_MONTHLY_MINUTES: ${PLAN_PRO_MONTHLY_MINUTES:-1200}
ADMIN_API_KEY: ${ADMIN_API_KEY:-}
BOT_API_SECRET: ${BOT_API_SECRET:-}
MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200}
SUMMARY_ENABLED: ${SUMMARY_ENABLED:-false}
LLM_API_BASE: ${LLM_API_BASE:-}