feat: SAC 0.7.2 security hardening (rate limit, JWT DB check, DOMPurify)
Path traversal fix in SPA fallback, admin-only host delete, login rate limit with 3 attempts and Telegram alert, JWT validated against active users in DB, and DOMPurify for agent report HTML. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+78
-64
@@ -1,64 +1,78 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.auth.jwt_auth import CurrentUser, create_access_token, get_current_user
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.services.user_auth import authenticate_user
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
username: str
|
||||
role: str
|
||||
|
||||
|
||||
class MeResponse(BaseModel):
|
||||
username: str
|
||||
role: str
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(body: LoginRequest, db: Session = Depends(get_db)) -> TokenResponse:
|
||||
settings = get_settings()
|
||||
if not settings.sac_admin_password and not _has_any_user(db):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="SAC UI users are not configured (run alembic upgrade and set SAC_ADMIN_PASSWORD for bootstrap)",
|
||||
)
|
||||
user = authenticate_user(db, body.username, body.password)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Invalid username or password")
|
||||
token = create_access_token(user.username, user.role)
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
username=user.username,
|
||||
role=user.role,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=MeResponse)
|
||||
def me(current_user: CurrentUser = Depends(get_current_user)) -> MeResponse:
|
||||
return MeResponse(username=current_user.username, role=current_user.role)
|
||||
|
||||
|
||||
def _has_any_user(db: Session) -> bool:
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.models.user import User
|
||||
|
||||
try:
|
||||
count = db.scalar(select(func.count()).select_from(User)) or 0
|
||||
return count > 0
|
||||
except Exception:
|
||||
db.rollback()
|
||||
return False
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
|
||||
from app.auth.jwt_auth import CurrentUser, create_access_token, get_current_user
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
from app.database import get_db
|
||||
|
||||
from app.services.login_rate_limit import (
|
||||
|
||||
ensure_login_allowed,
|
||||
|
||||
record_login_failure,
|
||||
|
||||
record_login_success,
|
||||
|
||||
)
|
||||
|
||||
from app.services.user_auth import authenticate_user
|
||||
|
||||
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
|
||||
username: str
|
||||
|
||||
password: str
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
|
||||
access_token: str
|
||||
|
||||
token_type: str = "bearer"
|
||||
|
||||
username: str
|
||||
|
||||
role: str
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class MeResponse(BaseModel):
|
||||
|
||||
username: str
|
||||
|
||||
role: str
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
|
||||
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)) -> TokenResponse:
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
if not settings.sac_admin_password and not _has_any_user(db):
|
||||
|
||||
raise HTTPException(
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from pydantic import BaseModel
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.auth.jwt_auth import get_current_user
|
||||
from app.auth.jwt_auth import get_current_user, require_admin
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.models import Event, Host
|
||||
@@ -91,7 +91,7 @@ class HostDeleteResponse(BaseModel):
|
||||
def delete_host(
|
||||
host_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_user: str = Depends(get_current_user),
|
||||
_user=Depends(require_admin),
|
||||
) -> HostDeleteResponse:
|
||||
result = delete_host_and_related(db, host_id)
|
||||
if result is None:
|
||||
|
||||
@@ -8,7 +8,7 @@ from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.auth.jwt_auth import verify_access_token
|
||||
from app.database import SessionLocal
|
||||
from app.database import SessionLocal, get_db
|
||||
from app.models import Event, Problem
|
||||
from app.config import get_settings
|
||||
from app.services.host_health import DAILY_REPORT_TYPES, HEARTBEAT_TYPE, count_stale_hosts
|
||||
@@ -66,8 +66,11 @@ async def _sse_generator():
|
||||
return
|
||||
|
||||
|
||||
def _sse_auth(token: str = Query(..., description="JWT access_token")) -> str:
|
||||
return verify_access_token(token)
|
||||
def _sse_auth(
|
||||
token: str = Query(..., description="JWT access_token"),
|
||||
db: Session = Depends(get_db),
|
||||
) -> str:
|
||||
return verify_access_token(token, db=db)
|
||||
|
||||
|
||||
@router.get("/events")
|
||||
|
||||
@@ -1,70 +1,171 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
|
||||
|
||||
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from jose import JWTError, jwt
|
||||
|
||||
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
|
||||
from app.database import get_db
|
||||
|
||||
|
||||
|
||||
from app.models.user import USER_ROLE_ADMIN, User
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
bearer_scheme = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
username: str
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
|
||||
|
||||
class CurrentUser:
|
||||
|
||||
|
||||
|
||||
username: str
|
||||
|
||||
|
||||
|
||||
role: str
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@property
|
||||
|
||||
|
||||
|
||||
def is_admin(self) -> bool:
|
||||
|
||||
|
||||
|
||||
return self.role == USER_ROLE_ADMIN
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def create_access_token(subject: str, role: str) -> str:
|
||||
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.jwt_expire_minutes)
|
||||
|
||||
|
||||
|
||||
payload = {"sub": subject, "role": role, "exp": expire}
|
||||
|
||||
|
||||
|
||||
|
||||
return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _user_from_db(db: Session, username: str) -> User:
|
||||
|
||||
|
||||
|
||||
normalized = username.strip()
|
||||
|
||||
|
||||
|
||||
user = db.scalar(select(User).where(func.lower(User.username) == normalized.lower()))
|
||||
|
||||
|
||||
|
||||
if user is None or not user.is_active:
|
||||
|
||||
|
||||
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
def _decode_current_user(token: str) -> CurrentUser:
|
||||
|
||||
|
||||
|
||||
return user
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _decode_current_user(token: str, db: Session | None = None) -> CurrentUser:
|
||||
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@@ -100,6 +100,11 @@ class Settings(BaseSettings):
|
||||
sac_events_retention_days: int = 90
|
||||
sac_problems_retention_days: int = 180
|
||||
|
||||
# UI login brute-force protection
|
||||
sac_login_max_failures: int = 3
|
||||
sac_login_failure_window_minutes: int = 15
|
||||
sac_login_alert_telegram: bool = True
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
|
||||
+9
-3
@@ -105,9 +105,15 @@ def create_app() -> FastAPI:
|
||||
def spa_fallback(spa_path: str) -> FileResponse:
|
||||
if spa_path.startswith("api/"):
|
||||
raise HTTPException(status_code=404, detail="Not Found")
|
||||
candidate = frontend_dist / spa_path
|
||||
if spa_path and candidate.is_file():
|
||||
return FileResponse(candidate)
|
||||
dist_root = frontend_dist.resolve()
|
||||
if spa_path:
|
||||
candidate = (frontend_dist / spa_path).resolve()
|
||||
try:
|
||||
candidate.relative_to(dist_root)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail="Not Found") from None
|
||||
if candidate.is_file():
|
||||
return FileResponse(candidate)
|
||||
index = frontend_dist / "index.html"
|
||||
if not index.is_file():
|
||||
raise HTTPException(status_code=404, detail="UI not built")
|
||||
|
||||
@@ -5,6 +5,7 @@ from app.models.notification_channel import NotificationChannel
|
||||
from app.models.notification_cooldown import NotificationCooldown
|
||||
from app.models.notification_policy import NotificationPolicy
|
||||
from app.models.problem import Problem, ProblemEvent
|
||||
from app.models.login_attempt import LoginAttempt
|
||||
from app.models.event_severity_override import EventSeverityOverride
|
||||
from app.models.user import User
|
||||
|
||||
@@ -19,4 +20,5 @@ __all__ = [
|
||||
"ProblemEvent",
|
||||
"User",
|
||||
"EventSeverityOverride",
|
||||
"LoginAttempt",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class LoginAttempt(Base):
|
||||
__tablename__ = "login_attempts"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
ip_address: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
username: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
success: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Rate limit failed SAC UI logins + optional Telegram alert."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models.login_attempt import LoginAttempt
|
||||
from app.services.telegram_notify import send_telegram_text
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LoginRateLimitConfig:
|
||||
max_failures: int
|
||||
window_minutes: int
|
||||
alert_telegram: bool
|
||||
|
||||
|
||||
def get_login_rate_limit_config() -> LoginRateLimitConfig:
|
||||
settings = get_settings()
|
||||
return LoginRateLimitConfig(
|
||||
max_failures=max(1, int(getattr(settings, "sac_login_max_failures", 3) or 3)),
|
||||
window_minutes=max(1, int(getattr(settings, "sac_login_failure_window_minutes", 15) or 15)),
|
||||
alert_telegram=bool(getattr(settings, "sac_login_alert_telegram", True)),
|
||||
)
|
||||
|
||||
|
||||
def client_ip_from_request(request: Request) -> str:
|
||||
forwarded = (request.headers.get("x-forwarded-for") or "").strip()
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()[:64]
|
||||
if request.client and request.client.host:
|
||||
return request.client.host[:64]
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _failure_count(db: Session, ip_address: str, *, since: datetime) -> int:
|
||||
return int(
|
||||
db.scalar(
|
||||
select(func.count())
|
||||
.select_from(LoginAttempt)
|
||||
.where(
|
||||
LoginAttempt.ip_address == ip_address,
|
||||
LoginAttempt.success.is_(False),
|
||||
LoginAttempt.created_at >= since,
|
||||
)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
|
||||
|
||||
def _alert_already_sent(db: Session, ip_address: str, *, since: datetime) -> bool:
|
||||
"""Avoid spamming Telegram on every subsequent 429."""
|
||||
row = db.scalar(
|
||||
select(LoginAttempt.username)
|
||||
.where(
|
||||
LoginAttempt.ip_address == ip_address,
|
||||
LoginAttempt.success.is_(False),
|
||||
LoginAttempt.created_at >= since,
|
||||
LoginAttempt.username == "__alert_sent__",
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
return row is not None
|
||||
|
||||
|
||||
def _send_login_bruteforce_alert(ip_address: str, username: str, failures: int) -> None:
|
||||
user_hint = username if username else "—"
|
||||
text = (
|
||||
f"⚠️ <b>SAC: подбор пароля UI</b>\n"
|
||||
f"IP: <code>{ip_address}</code>\n"
|
||||
f"Логин: <code>{user_hint}</code>\n"
|
||||
f"Неудачных попыток: {failures}\n"
|
||||
f"Дальнейший вход с этого IP временно заблокирован."
|
||||
)
|
||||
try:
|
||||
send_telegram_text(text, parse_mode="HTML")
|
||||
except Exception:
|
||||
logger.exception("failed to send SAC login brute-force Telegram alert")
|
||||
|
||||
|
||||
def ensure_login_allowed(db: Session, request: Request) -> str:
|
||||
"""Raise 429 if IP exceeded failed login threshold. Returns client IP."""
|
||||
cfg = get_login_rate_limit_config()
|
||||
ip_address = client_ip_from_request(request)
|
||||
since = datetime.now(timezone.utc) - timedelta(minutes=cfg.window_minutes)
|
||||
failures = _failure_count(db, ip_address, since=since)
|
||||
if failures >= cfg.max_failures:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Слишком много неудачных попыток входа. Повторите через {cfg.window_minutes} мин.",
|
||||
)
|
||||
return ip_address
|
||||
|
||||
|
||||
def record_login_success(db: Session, *, ip_address: str, username: str) -> None:
|
||||
db.add(
|
||||
LoginAttempt(
|
||||
ip_address=ip_address,
|
||||
username=username[:64],
|
||||
success=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def record_login_failure(
|
||||
db: Session,
|
||||
*,
|
||||
ip_address: str,
|
||||
username: str,
|
||||
request: Request | None = None,
|
||||
) -> None:
|
||||
del request # reserved
|
||||
cfg = get_login_rate_limit_config()
|
||||
since = datetime.now(timezone.utc) - timedelta(minutes=cfg.window_minutes)
|
||||
prior_failures = _failure_count(db, ip_address, since=since)
|
||||
|
||||
db.add(
|
||||
LoginAttempt(
|
||||
ip_address=ip_address,
|
||||
username=username[:64] if username else None,
|
||||
success=False,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
new_failures = prior_failures + 1
|
||||
if new_failures >= cfg.max_failures and cfg.alert_telegram and not _alert_already_sent(db, ip_address, since=since):
|
||||
db.add(
|
||||
LoginAttempt(
|
||||
ip_address=ip_address,
|
||||
username="__alert_sent__",
|
||||
success=False,
|
||||
)
|
||||
)
|
||||
_send_login_bruteforce_alert(ip_address, username, new_failures)
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Единый источник версии SAC (API, health, логи, OpenAPI)."""
|
||||
|
||||
APP_NAME = "Security Alert Center"
|
||||
APP_VERSION = "0.7.1"
|
||||
APP_VERSION = "0.7.2"
|
||||
APP_VERSION_LABEL = f"{APP_NAME} v.{APP_VERSION}"
|
||||
|
||||
Reference in New Issue
Block a user