commit
9c5fef1a4d
412 files changed
+94582
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Core configuration and security helpers."""
|
||||
@@ -0,0 +1,149 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
app_name: str = "Sakura Cloud"
|
||||
app_version: str = "0.1.0"
|
||||
api_prefix: str = "/api/v1"
|
||||
debug: bool = False
|
||||
environment: str = Field(default="development", validation_alias="SAKURA_ENV")
|
||||
auto_migrate_on_startup: bool = False
|
||||
|
||||
database_url: str = "postgresql+psycopg://sakura:sakura@localhost:5432/sakura_cloud"
|
||||
redis_url: str = "redis://localhost:6379/0"
|
||||
|
||||
storage_root: str = "data/sakura"
|
||||
log_dir: str = "data/sakura/logs"
|
||||
|
||||
minio_endpoint: str = "localhost:9000"
|
||||
minio_access_key: str = "minioadmin"
|
||||
minio_secret_key: str = "minioadmin"
|
||||
minio_bucket: str = "sakura-cloud"
|
||||
minio_secure: bool = False
|
||||
|
||||
jwt_secret_key: str = Field(default="change-this-secret-in-production", min_length=16)
|
||||
jwt_algorithm: str = "HS256"
|
||||
jwt_issuer: str = "sakura-cloud"
|
||||
jwt_audience: str = "sakura-cloud"
|
||||
jwt_access_token_expire_hours: int = 24
|
||||
jwt_refresh_token_expire_days: int = 30
|
||||
|
||||
default_storage_limit_gb: int = 5
|
||||
max_upload_size_mb: int = 100
|
||||
max_video_upload_size_mb: int = 2048
|
||||
video_storage_limit_gb: int = 30
|
||||
max_batch_size_mb: int = 500
|
||||
allowed_upload_mime_types: list[str] = [
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
"image/gif",
|
||||
"video/mp4",
|
||||
"video/webm",
|
||||
"video/quicktime",
|
||||
"video/x-m4v",
|
||||
"video/x-msvideo",
|
||||
"text/plain",
|
||||
]
|
||||
allowed_external_url_domains: list[str] = [
|
||||
"pixiv.net",
|
||||
"www.pixiv.net",
|
||||
"i.pximg.net",
|
||||
"pximg.net",
|
||||
"x.com",
|
||||
"twitter.com",
|
||||
]
|
||||
upload_chunk_size: int = 5 * 1024 * 1024
|
||||
temp_upload_ttl_hours: int = 24
|
||||
thumbnail_max_size: int = 640
|
||||
thumbnail_quality: int = 82
|
||||
fcm_enabled: bool = True
|
||||
firebase_credentials_path: str = ""
|
||||
firebase_credentials_json: str = ""
|
||||
ocr_enabled: bool = False
|
||||
ocr_language: str = "ch"
|
||||
ocr_max_image_dimension: int = 1800
|
||||
ocr_max_attempts: int = 3
|
||||
ocr_max_concurrency: int = 1
|
||||
|
||||
cors_origins: list[str] = [
|
||||
"http://localhost:5173",
|
||||
"http://127.0.0.1:5173",
|
||||
"http://localhost:5174",
|
||||
"http://127.0.0.1:5174",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"app://.",
|
||||
]
|
||||
admin_login_rate_limit_per_minute: int = 5
|
||||
admin_frontend_enabled: bool = True
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
@field_validator("cors_origins", mode="before")
|
||||
@classmethod
|
||||
def parse_cors_origins(cls, value: Any) -> list[str]:
|
||||
if isinstance(value, str):
|
||||
text = value.strip()
|
||||
if text.startswith("["):
|
||||
import json
|
||||
|
||||
return list(json.loads(text))
|
||||
return [item.strip() for item in text.split(",") if item.strip()]
|
||||
return value
|
||||
|
||||
@field_validator("allowed_upload_mime_types", "allowed_external_url_domains", mode="before")
|
||||
@classmethod
|
||||
def parse_string_list(cls, value: Any) -> list[str]:
|
||||
if isinstance(value, str):
|
||||
text = value.strip()
|
||||
if text.startswith("["):
|
||||
import json
|
||||
|
||||
return list(json.loads(text))
|
||||
return [item.strip() for item in text.split(",") if item.strip()]
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def reject_insecure_production_defaults(self) -> "Settings":
|
||||
if self.environment.lower() not in {"prod", "production"}:
|
||||
return self
|
||||
insecure: list[str] = []
|
||||
if self.jwt_secret_key == "change-this-secret-in-production":
|
||||
insecure.append("JWT_SECRET_KEY")
|
||||
if "sakura:sakura@" in self.database_url:
|
||||
insecure.append("DATABASE_URL")
|
||||
if self.minio_access_key == "minioadmin" or self.minio_secret_key == "minioadmin":
|
||||
insecure.append("MINIO_ACCESS_KEY/MINIO_SECRET_KEY")
|
||||
if insecure:
|
||||
raise ValueError(
|
||||
"Refusing to start production with insecure default credentials: "
|
||||
+ ", ".join(insecure)
|
||||
)
|
||||
return self
|
||||
|
||||
@property
|
||||
def default_storage_limit_bytes(self) -> int:
|
||||
return self.default_storage_limit_gb * 1024 * 1024 * 1024
|
||||
|
||||
@property
|
||||
def video_storage_limit_bytes(self) -> int:
|
||||
return self.video_storage_limit_gb * 1024 * 1024 * 1024
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
@@ -0,0 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from sakura_cloud.core.config import settings
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
log_dir = Path(settings.log_dir)
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
logger.remove()
|
||||
logger.add(sys.stderr, level="INFO", enqueue=True)
|
||||
logger.add(log_dir / "app.log", level="INFO", rotation="50 MB", retention=10, enqueue=True)
|
||||
logger.add(log_dir / "api.log", level="INFO", rotation="100 MB", retention=5, enqueue=True, filter=lambda r: r["extra"].get("kind") == "api")
|
||||
logger.add(log_dir / "sync.log", level="INFO", rotation="50 MB", retention=10, enqueue=True, filter=lambda r: r["extra"].get("kind") == "sync")
|
||||
logger.add(log_dir / "error.log", level="ERROR", rotation="50 MB", retention="30 days", enqueue=True)
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from pathlib import PurePath
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from sakura_cloud.core.config import settings
|
||||
|
||||
|
||||
def is_safe_upload_filename(file_name: str) -> bool:
|
||||
name = file_name.strip()
|
||||
if not name:
|
||||
return False
|
||||
path = PurePath(name)
|
||||
return path.name == name and name not in {".", ".."} and ".." not in path.parts
|
||||
|
||||
|
||||
def is_allowed_upload_mime(mime_type: str | None) -> bool:
|
||||
if not mime_type:
|
||||
return False
|
||||
return mime_type.lower().strip() in {item.lower() for item in settings.allowed_upload_mime_types}
|
||||
|
||||
|
||||
def is_allowed_external_url(url: str) -> bool:
|
||||
parsed = urlparse(url.strip())
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
return False
|
||||
host = parsed.hostname.rstrip(".").lower()
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
ip = None
|
||||
if ip is not None:
|
||||
return not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast)
|
||||
if host in {"localhost"} or host.endswith(".localhost"):
|
||||
return False
|
||||
allowed = {item.lower().strip().rstrip(".") for item in settings.allowed_external_url_domains}
|
||||
return any(host == domain or host.endswith(f".{domain}") for domain in allowed if domain)
|
||||
@@ -0,0 +1,70 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from sakura_cloud.core.config import settings
|
||||
|
||||
|
||||
pwd_context = CryptContext(schemes=["pbkdf2_sha256", "bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
return pwd_context.verify(password, password_hash)
|
||||
|
||||
|
||||
def create_token(subject: str, *, token_type: str, expires_delta: timedelta, token_version: int = 0) -> str:
|
||||
now = datetime.now(timezone.utc)
|
||||
payload: dict[str, Any] = {
|
||||
"sub": subject,
|
||||
"type": token_type,
|
||||
"tv": token_version,
|
||||
"iss": settings.jwt_issuer,
|
||||
"aud": settings.jwt_audience,
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int((now + expires_delta).timestamp()),
|
||||
}
|
||||
return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
|
||||
|
||||
|
||||
def create_access_token(subject: str, token_version: int = 0) -> str:
|
||||
return create_token(
|
||||
subject,
|
||||
token_type="access",
|
||||
expires_delta=timedelta(hours=settings.jwt_access_token_expire_hours),
|
||||
token_version=token_version,
|
||||
)
|
||||
|
||||
|
||||
def create_refresh_token(subject: str, token_version: int = 0) -> str:
|
||||
return create_token(
|
||||
subject,
|
||||
token_type="refresh",
|
||||
expires_delta=timedelta(days=settings.jwt_refresh_token_expire_days),
|
||||
token_version=token_version,
|
||||
)
|
||||
|
||||
|
||||
def decode_token(token: str) -> dict[str, Any]:
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
settings.jwt_secret_key,
|
||||
algorithms=[settings.jwt_algorithm],
|
||||
audience=settings.jwt_audience,
|
||||
issuer=settings.jwt_issuer,
|
||||
)
|
||||
except JWTError as exc:
|
||||
raise ValueError("Invalid token") from exc
|
||||
if "exp" not in payload:
|
||||
raise ValueError("Invalid token")
|
||||
if payload.get("type") not in {"access", "refresh"}:
|
||||
raise ValueError("Invalid token")
|
||||
return payload
|
||||
Reference in new issue
Block a user