Author SHA1 Message Date
ahp 8a585fc718 fix(deploy): persist the Whisper cache and clarify the compose env file
- HF_HOME=/data/huggingface on api and worker: the model cache sat in
  the container filesystem, so every recreate (down/up, --build, a new
  image) re-downloaded the model weights — and transcription failed
  outright wherever the Hugging Face Hub is unreachable
- the postgres healthcheck probes $POSTGRES_USER / $POSTGRES_DB instead
  of a hardcoded sokhan
- compose interpolates from the .env next to deploy/docker-compose.yml,
  not the one at the repo root: the quickstart in both READMEs and the
  .env.example header now say cp .env.example deploy/.env, and the
  missing-password error names that path
2026-11-26 16:26:03 +03:30
ahp 1304b13999 fix(deploy): pre-create /data owned by appuser in the backend image
Uploaded audio lives under DATA_DIR (/data, the sokhan-data named
volume). The image never created that directory, so Docker made the
mount point root-owned on first start and every upload failed with
PermissionError once the process runs as appuser.

Docker seeds a new named volume with the mount point's ownership, so
creating /data/audio in the image, owned by appuser, fixes fresh
installs without an entrypoint chown.
2026-11-26 16:25:33 +03:30
23 changed files with 42 additions and 525 deletions

No files matched your search

+1 -9
View File
@@ -1,5 +1,6 @@
# Sokhan configuration
# Copy this file to .env and adjust the values.
# For docker compose, copy it to deploy/.env instead.
# Every variable below has a working default for local development.
# --- Core ---
@@ -106,9 +107,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 +130,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.
+11 -23
View File
@@ -5,30 +5,18 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
## [Unreleased]
### Security
### Fixed
- **`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.
- Compose: the Whisper model cache now lives on the `sokhan-data` volume
(`HF_HOME=/data/huggingface`). Previously it sat in the container's own
filesystem, so every recreate (`down`/`up`, `--build`, a new image)
re-downloaded the weights — and transcription failed outright where the
Hugging Face Hub is unreachable.
- Compose: the postgres healthcheck probes the configured `POSTGRES_USER` and
`POSTGRES_DB` instead of a hardcoded `sokhan`.
- Quickstart (both READMEs) and `.env.example` now say to copy the env file to
`deploy/.env`; the missing-password error names that path too. Copying it to
the repo root left `POSTGRES_PASSWORD` unset for compose.
### Added
+5 -4
View File
@@ -145,6 +145,8 @@ faster-whisper، یک ورکر Celery، یک داشبورد Next.js که فار
```bash
git clone https://github.com/Abolfazlrwm/sokhan.git
cd sokhan
cp .env.example deploy/.env # compose فایل .env کنار فایل compose را می‌خواند
# در deploy/.env مقدار POSTGRES_PASSWORD را یک رمز طولانی و تصادفی بگذارید
docker compose -f deploy/docker-compose.yml up -d --build
```
@@ -152,7 +154,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
- API و مستندات: http://localhost:8000/docs
ورکر مدل Whisper تنظیم‌شده را در اولین رونویسی دانلود می‌کند
(`WHISPER_MODEL_SIZE`، پیش‌فرض `small`). برای فعال‌کردن خلاصه‌سازی،
(`WHISPER_MODEL_SIZE`، پیش‌فرض `small`) و آن را روی ولوم `sokhan-data`
(`HF_HOME=/data/huggingface`) نگه می‌دارد، پس ساخت دوبارهٔ کانتینرها مدل را
دوباره دانلود نمی‌کند. برای فعال‌کردن خلاصه‌سازی،
`SUMMARY_ENABLED=true` و متغیرهای LLM خود را در فایل `.env` کنار
`docker-compose.yml` بگذارید. برای اعمال مهاجرت‌های اسکیما به‌صورت دستی:
@@ -225,12 +229,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) |
+5 -4
View File
@@ -143,6 +143,8 @@ default — a GPU is not required.
```bash
git clone https://github.com/Abolfazlrwm/sokhan.git
cd sokhan
cp .env.example deploy/.env # compose reads the .env next to the compose file
# edit deploy/.env and set POSTGRES_PASSWORD to a long random value
docker compose -f deploy/docker-compose.yml up -d --build
```
@@ -150,7 +152,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
- API and docs: http://localhost:8000/docs
The worker downloads the configured Whisper model on first transcription
(`WHISPER_MODEL_SIZE`, default `small`). To enable summaries, set
(`WHISPER_MODEL_SIZE`, default `small`) and caches it on the `sokhan-data`
volume (`HF_HOME=/data/huggingface`), so recreating the containers does not
download it again. To enable summaries, set
`SUMMARY_ENABLED=true` and your LLM variables in a `.env` file next to
`docker-compose.yml`. To apply schema migrations manually:
@@ -224,12 +228,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) |
+3 -3
View File
@@ -12,9 +12,9 @@ COPY alembic ./alembic
RUN pip install --no-cache-dir .
# Non-root runtime user; uvicorn binds 8000 (unprivileged) and the app keeps
# no local writable state (postgres via DATABASE_URL).
RUN useradd --system --uid 1000 --create-home appuser
RUN useradd --system --uid 1000 --create-home appuser \
&& mkdir -p /data/audio \
&& chown -R appuser:appuser /data
USER appuser
EXPOSE 8000
-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)
-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()
-5
View File
@@ -14,7 +14,6 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sokhan import __version__
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware
from sokhan.config import get_settings
from sokhan.db import configure, create_all
@@ -53,10 +52,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,
-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"
-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 -7
View File
@@ -5,12 +5,12 @@ services:
POSTGRES_USER: ${POSTGRES_USER:-sokhan}
# Required on purpose: shipping a default credential means every
# deployment that forgets the .env runs an open database.
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}
POSTGRES_DB: ${POSTGRES_DB:-sokhan}
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U sokhan"]
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 3s
retries: 10
@@ -33,10 +33,11 @@ services:
build:
context: ../backend
environment: &backend-env
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}@postgres:5432/${POSTGRES_DB:-sokhan}
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}@postgres:5432/${POSTGRES_DB:-sokhan}
REDIS_URL: redis://redis:6379/0
CELERY_ENABLED: "true"
DATA_DIR: /data
HF_HOME: /data/huggingface
SOKHAN_CORS_ORIGINS: ${SOKHAN_CORS_ORIGINS:-}
WHISPER_MODEL_SIZE: ${WHISPER_MODEL_SIZE:-medium}
WHISPER_DEVICE: ${WHISPER_DEVICE:-cpu}
@@ -48,15 +49,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:-}