Enhance API and configuration for Telegram miniapp
- Added support for CORS origins and a new environment variable for miniapp access control. - Implemented date validation for API requests to ensure correct date formats. - Updated FastAPI app to allow access without Telegram initData for local development. - Enhanced error handling and logging for better debugging. - Added tests for API functionality and Telegram initData validation. - Updated README with new environment variable details and testing instructions. - Modified Docker and Git ignore files to include additional directories and files.
This commit is contained in:
101
api/app.py
101
api/app.py
@@ -1,4 +1,6 @@
|
||||
"""FastAPI app: /api/duties and static webapp."""
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import config
|
||||
@@ -6,15 +8,68 @@ from fastapi import FastAPI, Header, HTTPException, Query, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from db.session import get_session
|
||||
from db.session import session_scope
|
||||
from db.repository import get_duties
|
||||
from db.schemas import DutyWithUser
|
||||
from api.telegram_auth import validate_init_data
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# ISO date YYYY-MM-DD
|
||||
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
|
||||
|
||||
def _validate_duty_dates(from_date: str, to_date: str) -> None:
|
||||
"""Raise HTTPException 400 if dates are invalid or from_date > to_date."""
|
||||
if not _DATE_RE.match(from_date) or not _DATE_RE.match(to_date):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Параметры from и to должны быть в формате YYYY-MM-DD",
|
||||
)
|
||||
if from_date > to_date:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Дата from не должна быть позже to",
|
||||
)
|
||||
|
||||
|
||||
def _fetch_duties_response(from_date: str, to_date: str) -> list[DutyWithUser]:
|
||||
"""Fetch duties in range and return list of DutyWithUser. Uses config.DATABASE_URL."""
|
||||
with session_scope(config.DATABASE_URL) as session:
|
||||
rows = get_duties(session, from_date=from_date, to_date=to_date)
|
||||
return [
|
||||
DutyWithUser(
|
||||
id=duty.id,
|
||||
user_id=duty.user_id,
|
||||
start_at=duty.start_at,
|
||||
end_at=duty.end_at,
|
||||
full_name=full_name,
|
||||
)
|
||||
for duty, full_name in rows
|
||||
]
|
||||
|
||||
|
||||
def _is_private_client(client_host: str | None) -> bool:
|
||||
"""True if client is localhost or private LAN (dev / same-machine access)."""
|
||||
if not client_host:
|
||||
return False
|
||||
if client_host in ("127.0.0.1", "::1"):
|
||||
return True
|
||||
parts = client_host.split(".")
|
||||
if len(parts) == 4: # IPv4
|
||||
try:
|
||||
a, b, c, d = (int(x) for x in parts)
|
||||
if (a == 10) or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168):
|
||||
return True
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
app = FastAPI(title="Duty Teller API")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_origins=config.CORS_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
@@ -28,47 +83,25 @@ def list_duties(
|
||||
to_date: str = Query(..., description="ISO date YYYY-MM-DD", alias="to"),
|
||||
x_telegram_init_data: str | None = Header(None, alias="X-Telegram-Init-Data"),
|
||||
) -> list[DutyWithUser]:
|
||||
_validate_duty_dates(from_date, to_date)
|
||||
log.info("GET /api/duties from %s, has initData: %s", request.client.host if request.client else "?", bool((x_telegram_init_data or "").strip()))
|
||||
init_data = (x_telegram_init_data or "").strip()
|
||||
if not init_data:
|
||||
# Allow access from localhost without Telegram initData (local dev only)
|
||||
client_host = request.client.host if request.client else None
|
||||
if client_host in ("127.0.0.1", "::1"):
|
||||
session = get_session(config.DATABASE_URL)
|
||||
try:
|
||||
rows = get_duties(session, from_date=from_date, to_date=to_date)
|
||||
return [
|
||||
DutyWithUser(
|
||||
id=duty.id,
|
||||
user_id=duty.user_id,
|
||||
start_at=duty.start_at,
|
||||
end_at=duty.end_at,
|
||||
full_name=full_name,
|
||||
)
|
||||
for duty, full_name in rows
|
||||
]
|
||||
finally:
|
||||
session.close()
|
||||
if _is_private_client(client_host) or config.MINI_APP_SKIP_AUTH:
|
||||
if config.MINI_APP_SKIP_AUTH:
|
||||
log.warning("duties: allowing without initData (MINI_APP_SKIP_AUTH is set)")
|
||||
return _fetch_duties_response(from_date, to_date)
|
||||
log.warning("duties: no X-Telegram-Init-Data header (client=%s)", client_host)
|
||||
raise HTTPException(status_code=403, detail="Откройте календарь из Telegram")
|
||||
username = validate_init_data(init_data, config.BOT_TOKEN)
|
||||
if username is None:
|
||||
log.warning("duties: initData validation failed (invalid signature or no username)")
|
||||
raise HTTPException(status_code=403, detail="Неверные данные авторизации")
|
||||
if not config.can_access_miniapp(username):
|
||||
log.warning("duties: username not in allowlist")
|
||||
raise HTTPException(status_code=403, detail="Доступ запрещён")
|
||||
session = get_session(config.DATABASE_URL)
|
||||
try:
|
||||
rows = get_duties(session, from_date=from_date, to_date=to_date)
|
||||
return [
|
||||
DutyWithUser(
|
||||
id=duty.id,
|
||||
user_id=duty.user_id,
|
||||
start_at=duty.start_at,
|
||||
end_at=duty.end_at,
|
||||
full_name=full_name,
|
||||
)
|
||||
for duty, full_name in rows
|
||||
]
|
||||
finally:
|
||||
session.close()
|
||||
return _fetch_duties_response(from_date, to_date)
|
||||
|
||||
|
||||
webapp_path = Path(__file__).resolve().parent.parent / "webapp"
|
||||
|
||||
103
api/test_app.py
Normal file
103
api/test_app.py
Normal file
@@ -0,0 +1,103 @@
|
||||
"""Tests for FastAPI app /api/duties."""
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from api.app import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_duties_invalid_date_format(client):
|
||||
r = client.get("/api/duties", params={"from": "2025-01-01", "to": "invalid"})
|
||||
assert r.status_code == 400
|
||||
assert "YYYY-MM-DD" in r.json()["detail"]
|
||||
|
||||
|
||||
def test_duties_from_after_to(client):
|
||||
r = client.get("/api/duties", params={"from": "2025-02-01", "to": "2025-01-01"})
|
||||
assert r.status_code == 400
|
||||
assert "from" in r.json()["detail"].lower() or "позже" in r.json()["detail"]
|
||||
|
||||
|
||||
@patch("api.app._is_private_client")
|
||||
@patch("api.app.config.MINI_APP_SKIP_AUTH", False)
|
||||
def test_duties_403_without_init_data_from_public_client(mock_private, client):
|
||||
"""Without initData and without private IP / skip-auth, should get 403."""
|
||||
mock_private.return_value = False # simulate public client
|
||||
r = client.get(
|
||||
"/api/duties",
|
||||
params={"from": "2025-01-01", "to": "2025-01-31"},
|
||||
)
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
@patch("api.app.config.MINI_APP_SKIP_AUTH", True)
|
||||
@patch("api.app._fetch_duties_response")
|
||||
def test_duties_200_when_skip_auth(mock_fetch, client):
|
||||
mock_fetch.return_value = []
|
||||
r = client.get(
|
||||
"/api/duties",
|
||||
params={"from": "2025-01-01", "to": "2025-01-31"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json() == []
|
||||
mock_fetch.assert_called_once_with("2025-01-01", "2025-01-31")
|
||||
|
||||
|
||||
@patch("api.app.validate_init_data")
|
||||
def test_duties_403_when_init_data_invalid(mock_validate, client):
|
||||
mock_validate.return_value = None
|
||||
r = client.get(
|
||||
"/api/duties",
|
||||
params={"from": "2025-01-01", "to": "2025-01-31"},
|
||||
headers={"X-Telegram-Init-Data": "some=data&hash=abc"},
|
||||
)
|
||||
assert r.status_code == 403
|
||||
assert "авторизации" in r.json()["detail"] or "Неверные" in r.json()["detail"]
|
||||
|
||||
|
||||
@patch("api.app.validate_init_data")
|
||||
@patch("api.app.config.can_access_miniapp")
|
||||
def test_duties_403_when_username_not_allowed(mock_can_access, mock_validate, client):
|
||||
mock_validate.return_value = "someuser"
|
||||
mock_can_access.return_value = False
|
||||
with patch("api.app._fetch_duties_response") as mock_fetch:
|
||||
r = client.get(
|
||||
"/api/duties",
|
||||
params={"from": "2025-01-01", "to": "2025-01-31"},
|
||||
headers={"X-Telegram-Init-Data": "user=xxx&hash=yyy"},
|
||||
)
|
||||
assert r.status_code == 403
|
||||
assert "Доступ запрещён" in r.json()["detail"]
|
||||
mock_fetch.assert_not_called()
|
||||
|
||||
|
||||
@patch("api.app.validate_init_data")
|
||||
@patch("api.app.config.can_access_miniapp")
|
||||
def test_duties_200_with_allowed_user(mock_can_access, mock_validate, client):
|
||||
mock_validate.return_value = "alloweduser"
|
||||
mock_can_access.return_value = True
|
||||
with patch("api.app._fetch_duties_response") as mock_fetch:
|
||||
mock_fetch.return_value = [
|
||||
{
|
||||
"id": 1,
|
||||
"user_id": 10,
|
||||
"start_at": "2025-01-15T09:00:00",
|
||||
"end_at": "2025-01-15T18:00:00",
|
||||
"full_name": "Иван Иванов",
|
||||
}
|
||||
]
|
||||
r = client.get(
|
||||
"/api/duties",
|
||||
params={"from": "2025-01-01", "to": "2025-01-31"},
|
||||
headers={"X-Telegram-Init-Data": "user=xxx&hash=yyy"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert len(r.json()) == 1
|
||||
assert r.json()[0]["full_name"] == "Иван Иванов"
|
||||
mock_fetch.assert_called_once_with("2025-01-01", "2025-01-31")
|
||||
84
api/test_telegram_auth.py
Normal file
84
api/test_telegram_auth.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""Tests for api.telegram_auth.validate_init_data."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
import pytest
|
||||
|
||||
from api.telegram_auth import validate_init_data
|
||||
|
||||
|
||||
def _make_init_data(user: dict | None, bot_token: str) -> str:
|
||||
"""Build initData string with valid HMAC for testing."""
|
||||
params = {}
|
||||
if user is not None:
|
||||
params["user"] = quote(json.dumps(user))
|
||||
pairs = sorted(params.items())
|
||||
data_string = "\n".join(f"{k}={v}" for k, v in pairs)
|
||||
secret_key = hmac.new(
|
||||
b"WebAppData",
|
||||
msg=bot_token.encode(),
|
||||
digestmod=hashlib.sha256,
|
||||
).digest()
|
||||
computed = hmac.new(
|
||||
secret_key,
|
||||
msg=data_string.encode(),
|
||||
digestmod=hashlib.sha256,
|
||||
).hexdigest()
|
||||
params["hash"] = computed
|
||||
return "&".join(f"{k}={v}" for k, v in sorted(params.items()))
|
||||
|
||||
|
||||
def test_valid_payload_returns_username():
|
||||
bot_token = "123:ABC"
|
||||
user = {"id": 123, "username": "testuser", "first_name": "Test"}
|
||||
init_data = _make_init_data(user, bot_token)
|
||||
assert validate_init_data(init_data, bot_token) == "testuser"
|
||||
|
||||
|
||||
def test_valid_payload_username_lowercase():
|
||||
bot_token = "123:ABC"
|
||||
user = {"id": 123, "username": "TestUser", "first_name": "Test"}
|
||||
init_data = _make_init_data(user, bot_token)
|
||||
assert validate_init_data(init_data, bot_token) == "testuser"
|
||||
|
||||
|
||||
def test_invalid_hash_returns_none():
|
||||
bot_token = "123:ABC"
|
||||
user = {"id": 123, "username": "testuser"}
|
||||
init_data = _make_init_data(user, bot_token)
|
||||
# Tamper with hash
|
||||
init_data = init_data.replace("hash=", "hash=x")
|
||||
assert validate_init_data(init_data, bot_token) is None
|
||||
|
||||
|
||||
def test_wrong_bot_token_returns_none():
|
||||
bot_token = "123:ABC"
|
||||
user = {"id": 123, "username": "testuser"}
|
||||
init_data = _make_init_data(user, bot_token)
|
||||
assert validate_init_data(init_data, "other:token") is None
|
||||
|
||||
|
||||
def test_missing_user_returns_none():
|
||||
bot_token = "123:ABC"
|
||||
init_data = _make_init_data(None, bot_token) # no user key
|
||||
assert validate_init_data(init_data, bot_token) is None
|
||||
|
||||
|
||||
def test_user_without_username_returns_none():
|
||||
bot_token = "123:ABC"
|
||||
user = {"id": 123, "first_name": "Test"} # no username
|
||||
init_data = _make_init_data(user, bot_token)
|
||||
assert validate_init_data(init_data, bot_token) is None
|
||||
|
||||
|
||||
def test_empty_init_data_returns_none():
|
||||
assert validate_init_data("", "token") is None
|
||||
assert validate_init_data(" ", "token") is None
|
||||
|
||||
|
||||
def test_empty_bot_token_returns_none():
|
||||
user = {"id": 1, "username": "u"}
|
||||
init_data = _make_init_data(user, "token")
|
||||
assert validate_init_data(init_data, "") is None
|
||||
Reference in New Issue
Block a user