From 30f9a3c3254fe5bdee14e0e16036c603cb8c5f51 Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:34:20 +0800 Subject: [PATCH 1/2] fix(deploy): resolve startup crash and add single-image NAS deployment --- .dockerignore | 16 +++ .github/workflows/docker-publish.yml | 100 ++++++++++++++++ Dockerfile | 46 +++++++ README.md | 48 +++++--- backend/.env.example | 13 +- backend/Dockerfile | 28 ----- backend/app/config.py | 18 ++- backend/app/main.py | 29 ++++- backend/app/routers/health.py | 22 ++-- backend/app/routers/settings.py | 24 ++-- backend/tests/test_config.py | 171 +++++++++++++++++++++++++++ deploy/README.md | 126 ++++++++++++++++++++ deploy/docker-compose.yml | 41 +++++++ docker-compose.yml | 24 ++-- 14 files changed, 622 insertions(+), 84 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/docker-publish.yml create mode 100644 Dockerfile delete mode 100644 backend/Dockerfile create mode 100644 backend/tests/test_config.py create mode 100644 deploy/README.md create mode 100644 deploy/docker-compose.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9105f1a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.gitignore +.claude +.pytest_cache +**/.pytest_cache +**/__pycache__ +**/*.pyc +**/node_modules +**/.env +**/.env.* +!**/.env.example +frontend/dist +docs +backend/venv +venv +.venv diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml new file mode 100644 index 0000000..6723207 --- /dev/null +++ b/.github/workflows/docker-publish.yml @@ -0,0 +1,100 @@ +name: docker-publish + +on: + push: + branches: [main] + tags: ["v*"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + packages: write + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + cache-dependency-path: frontend/package-lock.json + + - name: Build frontend + working-directory: frontend + run: | + npm ci + npm run build + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build backend test image + uses: docker/build-push-action@v6 + with: + context: . + target: backend + load: true + tags: invoice-manager:ci-test + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Run backend tests + run: docker run --rm invoice-manager:ci-test python -m pytest -q + + image: + needs: test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GHCR + if: github.event_name != 'pull_request' + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Log in to Docker Hub + if: github.event_name != 'pull_request' && vars.DOCKERHUB_ENABLED == 'true' && vars.DOCKERHUB_NAMESPACE != '' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: | + ghcr.io/stone16/invoice-manager + name=docker.io/${{ vars.DOCKERHUB_NAMESPACE || 'placeholder' }}/invoice-manager,enable=${{ vars.DOCKERHUB_ENABLED == 'true' && vars.DOCKERHUB_NAMESPACE != '' }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }} + type=edge,branch=main + type=sha + + - name: Build and push Docker image + uses: docker/build-push-action@v6 + with: + context: . + target: app + platforms: ${{ github.event_name == 'pull_request' && 'linux/amd64' || 'linux/amd64,linux/arm64' }} + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8e71d80 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,46 @@ +# syntax=docker/dockerfile:1 + +FROM --platform=$BUILDPLATFORM node:20-alpine AS web +WORKDIR /web +COPY frontend/package*.json ./ +RUN npm ci +COPY frontend/ . +RUN npm run build + +FROM python:3.11-slim-bookworm AS backend +WORKDIR /app + +# Install system dependencies for PaddleOCR and PDF rendering with retry +RUN for i in 1 2 3 4 5; do \ + apt-get update && apt-get install -y --no-install-recommends \ + libgomp1 \ + libglib2.0-0 \ + libgl1 \ + libsm6 \ + libxext6 \ + libxrender1 \ + poppler-utils \ + && rm -rf /var/lib/apt/lists/* \ + && break; \ + if [ "$i" -eq 5 ]; then exit 1; fi; \ + sleep 15; \ + done + +# Install Python dependencies +COPY backend/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy backend application +COPY backend/ . + +EXPOSE 18080 + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "18080"] + +FROM backend AS app +COPY --from=web /web/dist /app/static +ENV INVOICE_ENV_FILE=/data/.env \ + DEBUG=false +VOLUME ["/data", "/root/.paddleocr"] +HEALTHCHECK --interval=15s --timeout=5s --start-period=60s --retries=5 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:18080/api/health', timeout=4)" diff --git a/README.md b/README.md index 95767ca..ce71409 100644 --- a/README.md +++ b/README.md @@ -204,28 +204,38 @@ ## 🚀 快速开始 | Quick Start -### 最简3步启动 | 3 Steps to Start +### 方式一:普通用户 / NAS 免构建部署(推荐) + +无需克隆代码,无需手工创建 `.env`,直接拉取单镜像即可启动(支持 x86_64 与 ARM64): ```bash -# 1. 克隆项目 | Clone -git clone https://github.com/YOUR_USERNAME/invoice_manager.git -cd invoice_manager +# 下载编排文件并启动(NAS 用户可直接复制 deploy/docker-compose.yml 到 Docker 项目面板) +curl -fsSLO https://raw.githubusercontent.com/stone16/Invoice-Manager/main/deploy/docker-compose.yml +docker compose up -d +``` -# 2. 配置LLM (可选) | Configure LLM (Optional) -# 在 backend/.env 中设置 API Key,或稍后在界面中配置 -# Set API Key in backend/.env, or configure later in UI +- 浏览器访问:`http://<设备或NAS的IP>:15173`(部署在 NAS 上请勿使用 `localhost`) +- API 文档:`http://<设备或NAS的IP>:15173/docs` +- 详细 NAS(绿联 / 群晖 / 威联通 / 飞牛 fnOS)图文步骤与 FAQ 请查看 **[`deploy/README.md`](deploy/README.md)**。 -# 3. 启动服务 | Start Services -docker-compose up -d +### 方式二:开发者源码启动 + +```bash +# 1. 克隆项目 | Clone +git clone https://github.com/stone16/Invoice-Manager.git +cd Invoice-Manager + +# 2. 启动服务(无需提前创建 backend/.env,LLM 可在界面「设置」中配置) +docker compose up -d --build ``` ### 访问地址 | Access URLs -| 服务 | 地址 | 说明 | -|-----|------|------| -| 前端界面 | http://localhost:15173 | 主操作界面 | -| 后端 API | http://localhost:18080 | REST API | -| API 文档 | http://localhost:18080/docs | Swagger UI | +| 服务 | 单镜像 / NAS 部署 | 开发者源码模式 | 说明 | +|-----|-----------------|--------------|------| +| 前端界面 | `http://:15173` | `http://localhost:15173` | 主操作界面 | +| API 文档 | `http://:15173/docs` | `http://localhost:18080/docs` | Swagger UI | +| 后端直连 | (同源 `/api`) | `http://localhost:18080` | 开发调试用 REST API | ### 配置 LLM | Configure LLM @@ -408,8 +418,7 @@ invoice_manager/ │ │ ├── schemas/ # Pydantic 数据验证 │ │ ├── config.py # 配置管理 │ │ └── main.py # 应用入口 -│ ├── requirements.txt -│ └── Dockerfile +│ └── requirements.txt │ ├── frontend/ # React 前端 │ ├── src/ @@ -439,7 +448,12 @@ invoice_manager/ │ ├── invoice-manager.pen # UI 设计稿 (Pencil) │ └── UI_REDESIGN.md # 设计规范文档 │ -├── docker-compose.yml # 容器编排 +├── deploy/ # NAS / 免构建单镜像部署 +│ ├── docker-compose.yml # 2 容器生产编排 +│ └── README.md # NAS 中文部署指南与 FAQ +│ +├── Dockerfile # 多阶段构建(web → backend → app) +├── docker-compose.yml # 开发者源码编排 └── README.md ``` diff --git a/backend/.env.example b/backend/.env.example index 43f2637..8ef202c 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,6 +1,11 @@ +# 可选文件:不创建也可直接启动;LLM 也可以在启动后通过 Web 界面「设置」配置并自动保存。 DATABASE_URL=postgresql+asyncpg://postgres:postgres@db:5432/invoice_db -OPENAI_API_KEY=your_openai_api_key_here -OPENAI_MODEL=gpt-4o-mini -# Optional: require token to configure LLM via API -LLM_CONFIG_TOKEN= + +# 如需通过环境变量预配置 LLM,取消注释并填入真实 API Key +# OPENAI_API_KEY= +# OPENAI_MODEL=gpt-4o-mini + +# 可选:管理员口令。设置后,通过界面或 API 修改 LLM 配置时需要输入该口令 +# LLM_CONFIG_TOKEN= + DEBUG=true diff --git a/backend/Dockerfile b/backend/Dockerfile deleted file mode 100644 index a03f37c..0000000 --- a/backend/Dockerfile +++ /dev/null @@ -1,28 +0,0 @@ -FROM python:3.11-slim-bookworm - -WORKDIR /app - -# Install system dependencies for PaddleOCR with retry -RUN for i in 1 2 3 4 5; do \ - apt-get update && apt-get install -y --no-install-recommends \ - libgomp1 \ - libglib2.0-0 \ - libgl1 \ - libsm6 \ - libxext6 \ - libxrender1 \ - poppler-utils \ - && rm -rf /var/lib/apt/lists/* \ - && break || sleep 15; \ - done - -# Install Python dependencies -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt - -# Copy application -COPY . . - -EXPOSE 18080 - -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "18080", "--reload"] diff --git a/backend/app/config.py b/backend/app/config.py index 2316285..5484840 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -1,6 +1,15 @@ -from pydantic_settings import BaseSettings, SettingsConfigDict +import os from functools import lru_cache from typing import Optional +from pydantic_settings import BaseSettings, SettingsConfigDict + + +def get_env_file_path() -> str: + """Return the configured .env file path (defaults to '.env').""" + return os.getenv("INVOICE_ENV_FILE") or ".env" + + +ENV_FILE = get_env_file_path() class Settings(BaseSettings): @@ -11,6 +20,9 @@ class Settings(BaseSettings): # Supported providers: openai, anthropic, google, qwen, deepseek, zhipu llm_provider: str = "" # Active provider (empty = not configured) + # Optional admin token for /api/settings/llm/configure + llm_config_token: str = "" + # OpenAI openai_api_key: str = "" openai_model: str = "gpt-4o-mini" @@ -55,7 +67,7 @@ class Settings(BaseSettings): # App debug: bool = True - model_config = SettingsConfigDict(env_file=".env") + model_config = SettingsConfigDict(env_file=ENV_FILE, extra="ignore") def get_active_llm_provider(self) -> Optional[str]: """Get the active LLM provider based on configuration.""" @@ -86,7 +98,7 @@ def is_llm_configured(self) -> bool: @lru_cache def get_settings() -> Settings: - return Settings() + return Settings(_env_file=get_env_file_path()) def clear_settings_cache(): diff --git a/backend/app/main.py b/backend/app/main.py index 928f932..5bb9a03 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,6 +1,8 @@ -from fastapi import FastAPI, Request +from pathlib import Path +from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import JSONResponse +from fastapi.responses import FileResponse, JSONResponse +from fastapi.staticfiles import StaticFiles from slowapi.errors import RateLimitExceeded from app.config import get_settings @@ -48,6 +50,23 @@ async def startup(): await conn.run_sync(Base.metadata.create_all) -@app.get("/") -async def root(): - return {"message": "发票管理系统 API", "version": "1.0.0"} +STATIC_DIR = (Path(__file__).resolve().parent.parent / "static").resolve() + +if STATIC_DIR.is_dir(): + assets_dir = STATIC_DIR / "assets" + if assets_dir.is_dir(): + app.mount("/assets", StaticFiles(directory=assets_dir), name="assets") + + @app.get("/{full_path:path}", include_in_schema=False) + async def serve_spa(full_path: str): + if full_path == "api" or full_path.startswith("api/"): + raise HTTPException(status_code=404, detail="Not Found") + if full_path: + candidate = (STATIC_DIR / full_path).resolve() + if STATIC_DIR in candidate.parents and candidate.is_file(): + return FileResponse(candidate) + return FileResponse(STATIC_DIR / "index.html") +else: + @app.get("/") + async def root(): + return {"message": "发票管理系统 API", "version": "1.0.0"} diff --git a/backend/app/routers/health.py b/backend/app/routers/health.py index c0a0491..2d409f3 100644 --- a/backend/app/routers/health.py +++ b/backend/app/routers/health.py @@ -1,4 +1,5 @@ from fastapi import APIRouter, Depends +from fastapi.responses import JSONResponse from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import text @@ -11,12 +12,17 @@ async def health_check(db: AsyncSession = Depends(get_db)): try: await db.execute(text("SELECT 1")) - db_status = "healthy" + return { + "status": "ok", + "database": "healthy", + "service": "发票管理系统", + } except Exception as e: - db_status = f"unhealthy: {str(e)}" - - return { - "status": "ok", - "database": db_status, - "service": "发票管理系统" - } + return JSONResponse( + status_code=503, + content={ + "status": "unhealthy", + "database": f"unhealthy: {str(e)}", + "service": "发票管理系统", + }, + ) diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index ae0b1fd..b98888a 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -7,6 +7,8 @@ from pydantic import BaseModel from fastapi import APIRouter, HTTPException, Header +from app import config as app_config + logger = logging.getLogger(__name__) @@ -16,13 +18,14 @@ def _update_env_file(updates: dict[str, str]) -> None: Preserves existing entries and comments, updates existing keys, and appends new keys at the end. """ - env_path = Path(__file__).parent.parent.parent / ".env" + env_path = Path(app_config.get_env_file_path()) + env_path.parent.mkdir(parents=True, exist_ok=True) # Read existing content existing_lines = [] existing_keys = set() if env_path.exists(): - with open(env_path, "r") as f: + with open(env_path, "r", encoding="utf-8") as f: for line in f: stripped = line.strip() # Track existing keys (ignore comments and empty lines) @@ -53,10 +56,10 @@ def _update_env_file(updates: dict[str, str]) -> None: new_lines.append(f"{key}={value}\n") # Write back - with open(env_path, "w") as f: + with open(env_path, "w", encoding="utf-8") as f: f.writelines(new_lines) - logger.info(f"Updated .env file with keys: {list(updates.keys())}") + logger.info(f"Updated .env file ({env_path}) with keys: {list(updates.keys())}") def _require_llm_config_token( @@ -79,7 +82,6 @@ def _require_llm_config_token( if not candidate or candidate != required_token: raise HTTPException(status_code=401, detail="未授权") -from app.config import get_settings, clear_settings_cache from app.services.llm_service import get_llm_service, reset_llm_service, PROVIDERS from app.services.model_registry import get_models_with_fallback @@ -143,7 +145,7 @@ class LLMConfigResponse(BaseModel): @router.get("/llm/status", response_model=LLMStatusResponse) async def get_llm_status(): """Get LLM configuration status.""" - settings = get_settings() + settings = app_config.get_settings() llm_service = get_llm_service() active_provider = settings.get_active_llm_provider() @@ -180,7 +182,7 @@ async def configure_llm( provider = request.provider.lower() _require_llm_config_token( - os.environ.get("LLM_CONFIG_TOKEN", ""), + app_config.get_settings().llm_config_token, x_llm_config_token, authorization, ) @@ -223,11 +225,11 @@ async def configure_llm( _update_env_file(env_updates) # Clear caches to reload settings - clear_settings_cache() + app_config.clear_settings_cache() reset_llm_service() # Verify configuration - new_settings = get_settings() + new_settings = app_config.get_settings() if not new_settings.is_llm_configured(): raise HTTPException(status_code=500, detail="配置失败,请检查API密钥是否正确") @@ -281,7 +283,7 @@ async def test_llm_connection(): def _get_provider_model(provider_name: str) -> Optional[str]: """Get the configured model for a provider.""" - settings = get_settings() + settings = app_config.get_settings() model_map = { "openai": settings.openai_model, "anthropic": settings.anthropic_model, @@ -295,7 +297,7 @@ def _get_provider_model(provider_name: str) -> Optional[str]: def _get_provider_base_url(provider_name: str) -> Optional[str]: """Get the configured base URL for a provider.""" - settings = get_settings() + settings = app_config.get_settings() url_map = { "openai": settings.openai_base_url, "anthropic": settings.anthropic_base_url, diff --git a/backend/tests/test_config.py b/backend/tests/test_config.py new file mode 100644 index 0000000..8b1b9a0 --- /dev/null +++ b/backend/tests/test_config.py @@ -0,0 +1,171 @@ +import importlib +from pathlib import Path + +from fastapi import FastAPI +from fastapi.testclient import TestClient + +import app.config as config_module +from app.database import get_db +from app.routers import health as health_router +from app.routers import settings as settings_router +from app.services.llm_service import reset_llm_service + + +def _clear_llm_env(monkeypatch): + for key in ( + "LLM_PROVIDER", + "LLM_CONFIG_TOKEN", + "OPENAI_API_KEY", + "OPENAI_MODEL", + "OPENAI_BASE_URL", + "DEEPSEEK_API_KEY", + "DEEPSEEK_MODEL", + "DEEPSEEK_BASE_URL", + ): + monkeypatch.delenv(key, raising=False) + + +def test_settings_ignores_llm_config_token_and_unknown_keys(tmp_path: Path, monkeypatch): + """Issue #13 regression: .env with LLM_CONFIG_TOKEN= and unknown keys must not crash.""" + _clear_llm_env(monkeypatch) + env_file = tmp_path / ".env" + env_file.write_text( + "LLM_CONFIG_TOKEN=\nUNKNOWN_KEY=1\nOPENAI_MODEL=custom-model\n", + encoding="utf-8", + ) + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + + reloaded = importlib.reload(config_module) + reloaded.clear_settings_cache() + try: + loaded = reloaded.get_settings() + assert loaded.llm_config_token == "" + assert loaded.openai_model == "custom-model" + finally: + reloaded.clear_settings_cache() + + +def test_settings_allows_missing_env_file(tmp_path: Path, monkeypatch): + """Missing .env file must load cleanly with defaults.""" + _clear_llm_env(monkeypatch) + missing_env = tmp_path / "does-not-exist" / ".env" + monkeypatch.setenv("INVOICE_ENV_FILE", str(missing_env)) + config_module.clear_settings_cache() + try: + loaded = config_module.get_settings() + assert loaded.llm_config_token == "" + assert loaded.is_llm_configured() is False + finally: + config_module.clear_settings_cache() + + +def test_update_env_file_creates_parent_and_persists(tmp_path: Path, monkeypatch): + """_update_env_file writes to INVOICE_ENV_FILE and auto-creates missing parent directories.""" + _clear_llm_env(monkeypatch) + target_env = tmp_path / "nested" / "data" / ".env" + monkeypatch.setenv("INVOICE_ENV_FILE", str(target_env)) + + settings_router._update_env_file({"LLM_PROVIDER": "deepseek", "DEEPSEEK_API_KEY": "sk-test-1"}) + assert target_env.is_file() + content = target_env.read_text(encoding="utf-8") + assert "LLM_PROVIDER=deepseek" in content + assert "DEEPSEEK_API_KEY=sk-test-1" in content + + # Update existing key and append another while preserving untouched keys + settings_router._update_env_file({"DEEPSEEK_API_KEY": "sk-test-2", "DEEPSEEK_MODEL": "deepseek-chat"}) + updated = target_env.read_text(encoding="utf-8") + assert "LLM_PROVIDER=deepseek" in updated + assert "DEEPSEEK_API_KEY=sk-test-2" in updated + assert "sk-test-1" not in updated + assert "DEEPSEEK_MODEL=deepseek-chat" in updated + + +def test_configure_llm_enforces_token_from_env_file(tmp_path: Path, monkeypatch): + """Admin token loaded from INVOICE_ENV_FILE must be enforced by configure_llm.""" + _clear_llm_env(monkeypatch) + env_file = tmp_path / "data" / ".env" + env_file.parent.mkdir(parents=True, exist_ok=True) + env_file.write_text("LLM_CONFIG_TOKEN=secret-from-file\n", encoding="utf-8") + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + config_module.clear_settings_cache() + reset_llm_service() + + test_app = FastAPI() + test_app.include_router(settings_router.router, prefix="/api/settings") + client = TestClient(test_app) + + payload = { + "provider": "deepseek", + "api_key": "sk-dummy-key", + "model": "deepseek-chat", + } + + try: + # Missing token -> 401 + resp_missing = client.post("/api/settings/llm/configure", json=payload) + assert resp_missing.status_code == 401 + + # Wrong token -> 401 + resp_wrong = client.post( + "/api/settings/llm/configure", + json=payload, + headers={"X-LLM-Config-Token": "wrong-token"}, + ) + assert resp_wrong.status_code == 401 + + # Correct token -> 200 and persisted to INVOICE_ENV_FILE + resp_ok = client.post( + "/api/settings/llm/configure", + json=payload, + headers={"X-LLM-Config-Token": "secret-from-file"}, + ) + assert resp_ok.status_code == 200 + assert resp_ok.json()["success"] is True + + persisted = env_file.read_text(encoding="utf-8") + assert "LLM_PROVIDER=deepseek" in persisted + assert "DEEPSEEK_API_KEY=sk-dummy-key" in persisted + finally: + # Clean up os.environ mutations made by configure_llm + _clear_llm_env(monkeypatch) + config_module.clear_settings_cache() + reset_llm_service() + + +def test_health_returns_503_when_db_unavailable(): + """Health check must return 503 with preserved JSON structure when DB fails.""" + test_app = FastAPI() + test_app.include_router(health_router.router, prefix="/api") + + class FailingSession: + async def execute(self, _stmt): + raise RuntimeError("connection refused") + + class HealthySession: + async def execute(self, _stmt): + return 1 + + async def override_failing_db(): + yield FailingSession() + + async def override_healthy_db(): + yield HealthySession() + + test_app.dependency_overrides[get_db] = override_failing_db + client = TestClient(test_app) + resp_fail = client.get("/api/health") + assert resp_fail.status_code == 503 + body_fail = resp_fail.json() + assert body_fail["status"] == "unhealthy" + assert body_fail["database"].startswith("unhealthy:") + assert body_fail["service"] == "发票管理系统" + + test_app.dependency_overrides[get_db] = override_healthy_db + resp_ok = client.get("/api/health") + assert resp_ok.status_code == 200 + body_ok = resp_ok.json() + assert body_ok == { + "status": "ok", + "database": "healthy", + "service": "发票管理系统", + } diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..eb48fb0 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,126 @@ +# NAS / Docker 免构建部署指南 + +面向普通用户与 NAS 用户的极简部署方案:**无需下载源码、无需手工建 `.env`、只需 2 个容器和 1 个端口**,同时支持 x86_64(`linux/amd64`)与 ARM64(`linux/arm64`)设备。 + +## 准备工作 + +- 一台已安装 Docker 的 NAS 或电脑(绿联、群晖、威联通、飞牛 fnOS、Linux、macOS、Windows 均可) +- 约 **3 GB** 可用磁盘空间(应用镜像 + 数据库 + OCR 模型缓存) + +--- + +## 第一步:在 NAS 中粘贴 Compose 启动 + +复制 [`deploy/docker-compose.yml`](./docker-compose.yml) 的全部内容,按你所用 NAS 系统执行以下 3–4 步即可: + +### 绿联 UGOS Pro +1. 打开 **Docker** 应用,切换到左侧 **项目**。 +2. 点击 **创建**,填写项目名称(如 `invoice-manager`)并选择存放路径。 +3. 将 `deploy/docker-compose.yml` 的内容粘贴到 Compose 配置框中。 +4. 点击 **立即部署**,等待镜像拉取并启动完成。 + +### 群晖 Synology(Container Manager) +1. 打开 **Container Manager**,进入 **项目** → 点击 **新增**。 +2. 填写项目名称(如 `invoice-manager`)与路径,来源选择 **创建 docker-compose.yml**。 +3. 粘贴 `deploy/docker-compose.yml` 的内容并点击 **下一步**。 +4. 确认后点击 **完成**,等待两个容器均为运行且健康状态。 + +### 威联通 QNAP(Container Station) +1. 打开 **Container Station**,进入 **应用程序** → 点击 **创建**。 +2. 输入应用程序名称(如 `invoice-manager`)。 +3. 在 YAML 编辑器中粘贴 `deploy/docker-compose.yml` 的内容。 +4. 点击 **创建**,等待拉取镜像并启动完成。 + +### 飞牛 fnOS +1. 打开 **Docker** 应用,进入 **Compose** → 点击 **新增项目**。 +2. 填写项目名称与存放路径,选择 **创建 docker-compose.yml**。 +3. 粘贴 `deploy/docker-compose.yml` 的内容,勾选 **创建项目后立即启动**。 +4. 点击 **完成**,等待容器启动完成。 + +### 命令行一键启动(Linux / macOS / Windows) + +```bash +curl -fsSLO https://raw.githubusercontent.com/stone16/Invoice-Manager/main/deploy/docker-compose.yml +docker compose up -d +``` + +> 默认镜像标签为 `:latest`(随正式 Release 发布)。如果想体验 `main` 分支最新开发版,启动前设置 `INVOICE_IMAGE=ghcr.io/stone16/invoice-manager:edge` 即可。 + +--- + +## 第二步:访问界面与首次使用 + +- **Web 界面**:`http://:15173`(例如 `http://192.168.1.100:15173`) +- **API 文档(Swagger)**:`http://:15173/docs` +- **健康检查**:`http://:15173/api/health` + +> ⚠️ **注意**:如果部署在 NAS 或远程服务器上,**请务必把地址中的 `` 换成 NAS 的局域网 IP 或域名,不要使用 `localhost`**(`localhost` 指的是你当前打开浏览器的电脑本身)。 + +### 纯 OCR 与 LLM 双源验证 +- **开箱即用(纯 OCR)**:不配置任何大模型 API Key 也可以直接上传发票。数电 PDF 发票会直接读取内嵌文字层,速度极快;图片或扫描件会自动下载中文 PaddleOCR 模型并识别。 +- **配置 LLM(可选增强)**:点击左侧边栏 **设置** → 选择模型提供商并填入 API Key → 先点 **测试配置** → 通过后点 **保存配置**。配置会自动写入容器持久卷 `/data/.env`,**重启或升级容器后不会丢失**。 + +--- + +## 数据持久化与升级 + +所有重要数据均保存在 3 个 Docker 卷中,不会随容器更新丢失: +- `db_data`:PostgreSQL 数据库(发票记录与原始文件) +- `app_data`:挂载到 `/data`,保存通过界面配置的 LLM 密钥(`/data/.env`) +- `ocr_models`:挂载到 `/root/.paddleocr`,缓存 PaddleOCR 模型文件 + +**升级到新版本**: +- **NAS 图形界面**:在「项目 / Compose」中找到 `invoice-manager`,点击 **更新 / 重新拉取镜像并重建** 即可。 +- **命令行**: + ```bash + docker compose pull && docker compose up -d + ``` + +--- + +## 常见问题(FAQ) + +### 1. 端口 `15173` 已被占用怎么办? +在 Compose 文件的 `app.ports` 中把左侧宿主机端口改成其他空闲端口即可,例如改成 `8088`: +```yaml +ports: + - "8088:18080" +``` +保存后重建,改用 `http://:8088` 访问。 + +### 2. 拉取 `ghcr.io` 镜像慢或拉取失败? +- 可在 NAS 的 Docker 设置中配置网络代理或镜像加速源。 +- 若维护者已开启 Docker Hub 同步,可将 `image:` 替换为对应的 Docker Hub 镜像地址(或设置环境变量 `INVOICE_IMAGE=/invoice-manager:latest`)。 + +### 3. PDF 电子发票能识别,但手机拍的图片 / 扫描件识别失败或进程崩溃? +部分老旧低功耗 NAS CPU(如 Intel J4125、N5105 等赛扬处理器)不支持 AVX 指令集,PaddlePaddle 预编译包在图片 OCR 时可能会因缺少 AVX 报错。 +- **数电 PDF 发票不受影响**:系统会优先通过 `pdfplumber` 直接读取 PDF 文字层,无需触发 PaddleOCR。 +- 若需处理图片/扫描件,建议在「设置」中配置支持看图(Vision)的 LLM 模型,或在支持 AVX 的设备上运行。 + +### 4. 忘记了设置的 `LLM_CONFIG_TOKEN` 管理员口令怎么重置? +- 如果口令写在 Compose 的 `environment` 中:直接修改或注释 `LLM_CONFIG_TOKEN` 一行,然后重建 `app` 容器。 +- 如果口令写在持久卷 `/data/.env` 中:进入容器终端或执行以下命令清除该行后重启 `app`: + ```bash + docker compose exec app sh -c 'sed -i "/^LLM_CONFIG_TOKEN=/d" /data/.env' + docker compose restart app + ``` + +--- + +## 维护者说明:自动发布到 GHCR 与 Docker Hub + +仓库已内置 [`.github/workflows/docker-publish.yml`](../.github/workflows/docker-publish.yml),推送 `main` 分支会发布 `:edge` 与 `:sha-*`,推送 `v*` 标签会发布语义化版本与 `:latest` 多架构镜像(`linux/amd64` + `linux/arm64`)。 + +### GHCR(默认启用) +- 使用内置 `GITHUB_TOKEN` 自动推送至 `ghcr.io/stone16/invoice-manager`。 +- **首次推送后务必检查**:在 GitHub Packages 中打开 `invoice-manager` → **Package settings** → 将可见性改为 **Public**,否则 NAS 用户匿名拉取会报权限错误。 + +### 开启 Docker Hub 自动推送(可选) +在 GitHub 仓库的 **Settings → Secrets and variables → Actions** 中添加以下配置后,工作流会自动同步推送到 Docker Hub: + +| 名称 | 类型 | 是否必填 | 说明 | +|---|---|---|---| +| `DOCKERHUB_ENABLED` | Variable | 启用时必填 | 设为 `true` 开启 Docker Hub 推送(默认关闭) | +| `DOCKERHUB_NAMESPACE` | Variable | 启用时必填 | Docker Hub 用户名或组织名(将推送至 `docker.io//invoice-manager`) | +| `DOCKERHUB_USERNAME` | Secret | 启用时必填 | Docker Hub 登录用户名 | +| `DOCKERHUB_TOKEN` | Secret | 启用时必填 | Docker Hub Access Token(Read/Write 权限,请勿使用登录密码) | diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml new file mode 100644 index 0000000..59c731f --- /dev/null +++ b/deploy/docker-compose.yml @@ -0,0 +1,41 @@ +# Invoice Manager · NAS / 单镜像免构建部署版 +# 无需克隆源码、无需手建 .env,在 NAS 的「Docker / 项目 / Compose」中直接粘贴即可启动。 +services: + db: + image: postgres:16-alpine + restart: unless-stopped + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres # 数据库不对外暴露端口,仅容器内部访问 + POSTGRES_DB: invoice_db + TZ: Asia/Shanghai + volumes: + - db_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U postgres -d invoice_db"] + interval: 5s + timeout: 5s + retries: 20 + start_period: 30s + + app: + image: ${INVOICE_IMAGE:-ghcr.io/stone16/invoice-manager:latest} + restart: unless-stopped + depends_on: + db: + condition: service_healthy + environment: + DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/invoice_db + TZ: Asia/Shanghai + # 可选:局域网多人使用时建议设置管理员口令,修改 LLM 配置时需输入 + # LLM_CONFIG_TOKEN: "change-me" + ports: + - "15173:18080" # 浏览器访问 http://:15173 + volumes: + - app_data:/data # 持久化保存界面中配置的 LLM 密钥 (/data/.env) + - ocr_models:/root/.paddleocr # 缓存 OCR 模型,避免重启重复下载 + +volumes: + db_data: + app_data: + ocr_models: diff --git a/docker-compose.yml b/docker-compose.yml index 1e8b7b9..ca064a1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,8 @@ -version: '3.8' - services: db: image: postgres:16-alpine container_name: invoice_db + restart: unless-stopped environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres @@ -13,18 +12,19 @@ services: ports: - "5435:5432" healthcheck: - test: ["CMD-SHELL", "pg_isready -U postgres"] + test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U postgres -d invoice_db"] interval: 5s timeout: 5s - retries: 5 + retries: 20 + start_period: 30s backend: build: - context: ./backend + context: . dockerfile: Dockerfile + target: backend container_name: invoice_backend - env_file: - - ./backend/.env + restart: unless-stopped environment: DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/invoice_db DEBUG: "true" @@ -36,6 +36,12 @@ services: depends_on: db: condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:18080/api/health', timeout=4)\""] + interval: 15s + timeout: 5s + retries: 5 + start_period: 30s command: uvicorn app.main:app --host 0.0.0.0 --port 18080 --reload frontend: @@ -43,13 +49,15 @@ services: context: ./frontend dockerfile: Dockerfile container_name: invoice_frontend + restart: unless-stopped volumes: - ./frontend:/app - /app/node_modules ports: - "15173:15173" depends_on: - - backend + backend: + condition: service_healthy environment: - VITE_API_URL=http://backend:18080 From c1ca829d06a514f8ec0f577c10924902b790a219 Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:11:37 +0800 Subject: [PATCH 2/2] fix(security,ci): harden env persistence, SPA routing, tests, and workflow --- .github/workflows/docker-publish.yml | 15 +- backend/app/main.py | 31 ++- backend/app/routers/settings.py | 48 ++++- backend/tests/test_config.py | 291 ++++++++++++++++++++++----- 4 files changed, 305 insertions(+), 80 deletions(-) diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 6723207..9cae94e 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -9,7 +9,6 @@ on: permissions: contents: read - packages: write jobs: test: @@ -40,8 +39,8 @@ jobs: target: backend load: true tags: invoice-manager:ci-test - cache-from: type=gha - cache-to: type=gha,mode=max + cache-from: type=gha,scope=backend + cache-to: type=gha,mode=max,scope=backend - name: Run backend tests run: docker run --rm invoice-manager:ci-test python -m pytest -q @@ -49,6 +48,9 @@ jobs: image: needs: test runs-on: ubuntu-latest + permissions: + contents: read + packages: write steps: - uses: actions/checkout@v4 @@ -80,10 +82,11 @@ jobs: images: | ghcr.io/stone16/invoice-manager name=docker.io/${{ vars.DOCKERHUB_NAMESPACE || 'placeholder' }}/invoice-manager,enable=${{ vars.DOCKERHUB_ENABLED == 'true' && vars.DOCKERHUB_NAMESPACE != '' }} + flavor: | + latest=auto tags: | type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} - type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }} type=edge,branch=main type=sha @@ -96,5 +99,5 @@ jobs: push: ${{ github.event_name != 'pull_request' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max + cache-from: type=gha,scope=app + cache-to: type=gha,mode=max,scope=app diff --git a/backend/app/main.py b/backend/app/main.py index 5bb9a03..0e14461 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -50,22 +50,35 @@ async def startup(): await conn.run_sync(Base.metadata.create_all) -STATIC_DIR = (Path(__file__).resolve().parent.parent / "static").resolve() - -if STATIC_DIR.is_dir(): - assets_dir = STATIC_DIR / "assets" +def mount_spa(target_app: FastAPI, static_dir: Path) -> None: + """Mount built SPA static assets and catch-all fallback on target_app.""" + resolved_static_dir = static_dir.resolve() + assets_dir = resolved_static_dir / "assets" if assets_dir.is_dir(): - app.mount("/assets", StaticFiles(directory=assets_dir), name="assets") + target_app.mount("/assets", StaticFiles(directory=assets_dir), name="assets") - @app.get("/{full_path:path}", include_in_schema=False) + @target_app.get("/{full_path:path}", include_in_schema=False) async def serve_spa(full_path: str): if full_path == "api" or full_path.startswith("api/"): raise HTTPException(status_code=404, detail="Not Found") if full_path: - candidate = (STATIC_DIR / full_path).resolve() - if STATIC_DIR in candidate.parents and candidate.is_file(): + try: + candidate = (resolved_static_dir / full_path).resolve() + is_safe_file = ( + resolved_static_dir in candidate.parents + and candidate.is_file() + ) + except (ValueError, OSError): + raise HTTPException(status_code=404, detail="Not Found") + if is_safe_file: return FileResponse(candidate) - return FileResponse(STATIC_DIR / "index.html") + return FileResponse(resolved_static_dir / "index.html") + + +STATIC_DIR = (Path(__file__).resolve().parent.parent / "static").resolve() + +if STATIC_DIR.is_dir(): + mount_spa(app, STATIC_DIR) else: @app.get("/") async def root(): diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index b98888a..71b0599 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -2,6 +2,7 @@ import logging import os +import tempfile from pathlib import Path from typing import Optional, List from pydantic import BaseModel @@ -16,22 +17,20 @@ def _update_env_file(updates: dict[str, str]) -> None: """Update .env file with new key-value pairs. Preserves existing entries and comments, updates existing keys, - and appends new keys at the end. + and appends new keys at the end. Writes atomically with 0o600 permissions. """ - env_path = Path(app_config.get_env_file_path()) + for key, value in updates.items(): + if "\r" in key or "\n" in key or "\r" in value or "\n" in value: + raise ValueError("Environment entries must not contain newline characters") + + env_path = Path(app_config.get_env_file_path()).expanduser() env_path.parent.mkdir(parents=True, exist_ok=True) # Read existing content existing_lines = [] - existing_keys = set() if env_path.exists(): with open(env_path, "r", encoding="utf-8") as f: for line in f: - stripped = line.strip() - # Track existing keys (ignore comments and empty lines) - if stripped and not stripped.startswith("#") and "=" in stripped: - key = stripped.split("=", 1)[0].strip() - existing_keys.add(key) existing_lines.append(line) # Update existing lines or mark keys as handled @@ -53,11 +52,34 @@ def _update_env_file(updates: dict[str, str]) -> None: # Append new keys that weren't in the file for key, value in updates.items(): if key not in updated_keys: + if new_lines and not new_lines[-1].endswith("\n"): + new_lines[-1] = new_lines[-1] + "\n" new_lines.append(f"{key}={value}\n") - # Write back - with open(env_path, "w", encoding="utf-8") as f: - f.writelines(new_lines) + # Atomically write back with 0o600 permissions + tmp_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=env_path.parent, + prefix=".env.", + suffix=".tmp", + delete=False, + ) as tmp_file: + tmp_path = Path(tmp_file.name) + tmp_file.writelines(new_lines) + tmp_file.flush() + os.fsync(tmp_file.fileno()) + os.chmod(tmp_path, 0o600) + os.replace(tmp_path, env_path) + except Exception: + if tmp_path is not None: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + raise logger.info(f"Updated .env file ({env_path}) with keys: {list(updates.keys())}") @@ -187,6 +209,10 @@ async def configure_llm( authorization, ) + for value in (request.provider, request.api_key, request.model, request.base_url): + if value is not None and ("\r" in value or "\n" in value): + raise HTTPException(status_code=400, detail="配置项不能包含换行符") + if provider not in PROVIDERS: raise HTTPException( status_code=400, diff --git a/backend/tests/test_config.py b/backend/tests/test_config.py index 8b1b9a0..3569fc7 100644 --- a/backend/tests/test_config.py +++ b/backend/tests/test_config.py @@ -1,53 +1,81 @@ -import importlib +import os +import stat from pathlib import Path +import pytest from fastapi import FastAPI from fastapi.testclient import TestClient import app.config as config_module from app.database import get_db +from app.main import mount_spa from app.routers import health as health_router from app.routers import settings as settings_router from app.services.llm_service import reset_llm_service +_LLM_ENV_KEYS = ( + "INVOICE_ENV_FILE", + "LLM_PROVIDER", + "LLM_CONFIG_TOKEN", + "OPENAI_API_KEY", + "OPENAI_MODEL", + "OPENAI_BASE_URL", + "ANTHROPIC_API_KEY", + "ANTHROPIC_MODEL", + "ANTHROPIC_BASE_URL", + "GOOGLE_API_KEY", + "GOOGLE_MODEL", + "GOOGLE_BASE_URL", + "QWEN_API_KEY", + "QWEN_MODEL", + "QWEN_BASE_URL", + "DEEPSEEK_API_KEY", + "DEEPSEEK_MODEL", + "DEEPSEEK_BASE_URL", + "ZHIPU_API_KEY", + "ZHIPU_MODEL", + "ZHIPU_BASE_URL", +) -def _clear_llm_env(monkeypatch): - for key in ( - "LLM_PROVIDER", - "LLM_CONFIG_TOKEN", - "OPENAI_API_KEY", - "OPENAI_MODEL", - "OPENAI_BASE_URL", - "DEEPSEEK_API_KEY", - "DEEPSEEK_MODEL", - "DEEPSEEK_BASE_URL", - ): - monkeypatch.delenv(key, raising=False) + +@pytest.fixture(autouse=True) +def _isolate_llm_env(): + """Snapshot and restore LLM-related env vars and caches around every test.""" + saved = {key: os.environ[key] for key in _LLM_ENV_KEYS if key in os.environ} + for key in _LLM_ENV_KEYS: + os.environ.pop(key, None) + config_module.clear_settings_cache() + reset_llm_service() + try: + yield + finally: + for key in _LLM_ENV_KEYS: + os.environ.pop(key, None) + for key, value in saved.items(): + os.environ[key] = value + config_module.clear_settings_cache() + reset_llm_service() def test_settings_ignores_llm_config_token_and_unknown_keys(tmp_path: Path, monkeypatch): """Issue #13 regression: .env with LLM_CONFIG_TOKEN= and unknown keys must not crash.""" - _clear_llm_env(monkeypatch) env_file = tmp_path / ".env" env_file.write_text( "LLM_CONFIG_TOKEN=\nUNKNOWN_KEY=1\nOPENAI_MODEL=custom-model\n", encoding="utf-8", ) monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) - - reloaded = importlib.reload(config_module) - reloaded.clear_settings_cache() + config_module.clear_settings_cache() try: - loaded = reloaded.get_settings() + loaded = config_module.get_settings() assert loaded.llm_config_token == "" assert loaded.openai_model == "custom-model" finally: - reloaded.clear_settings_cache() + config_module.clear_settings_cache() def test_settings_allows_missing_env_file(tmp_path: Path, monkeypatch): """Missing .env file must load cleanly with defaults.""" - _clear_llm_env(monkeypatch) missing_env = tmp_path / "does-not-exist" / ".env" monkeypatch.setenv("INVOICE_ENV_FILE", str(missing_env)) config_module.clear_settings_cache() @@ -60,19 +88,23 @@ def test_settings_allows_missing_env_file(tmp_path: Path, monkeypatch): def test_update_env_file_creates_parent_and_persists(tmp_path: Path, monkeypatch): - """_update_env_file writes to INVOICE_ENV_FILE and auto-creates missing parent directories.""" - _clear_llm_env(monkeypatch) + """_update_env_file writes atomically with 0o600 permissions and no leftover .tmp files.""" target_env = tmp_path / "nested" / "data" / ".env" monkeypatch.setenv("INVOICE_ENV_FILE", str(target_env)) settings_router._update_env_file({"LLM_PROVIDER": "deepseek", "DEEPSEEK_API_KEY": "sk-test-1"}) assert target_env.is_file() + assert stat.S_IMODE(target_env.stat().st_mode) == 0o600 + assert list(target_env.parent.glob("*.tmp")) == [] content = target_env.read_text(encoding="utf-8") assert "LLM_PROVIDER=deepseek" in content assert "DEEPSEEK_API_KEY=sk-test-1" in content - # Update existing key and append another while preserving untouched keys + # Loosen mode first, then verify update tightens back to 0o600 and preserves untouched keys + os.chmod(target_env, 0o644) settings_router._update_env_file({"DEEPSEEK_API_KEY": "sk-test-2", "DEEPSEEK_MODEL": "deepseek-chat"}) + assert stat.S_IMODE(target_env.stat().st_mode) == 0o600 + assert list(target_env.parent.glob("*.tmp")) == [] updated = target_env.read_text(encoding="utf-8") assert "LLM_PROVIDER=deepseek" in updated assert "DEEPSEEK_API_KEY=sk-test-2" in updated @@ -80,9 +112,26 @@ def test_update_env_file_creates_parent_and_persists(tmp_path: Path, monkeypatch assert "DEEPSEEK_MODEL=deepseek-chat" in updated +def test_update_env_file_cleans_temp_file_on_replace_failure(tmp_path: Path, monkeypatch): + """Failed atomic replace must remove temp file and leave existing .env intact.""" + target_env = tmp_path / ".env" + target_env.write_text("LLM_PROVIDER=openai\n", encoding="utf-8") + monkeypatch.setenv("INVOICE_ENV_FILE", str(target_env)) + + def _boom(_src, _dst): + raise OSError("simulated replace failure") + + monkeypatch.setattr(os, "replace", _boom) + + with pytest.raises(OSError, match="simulated replace failure"): + settings_router._update_env_file({"LLM_PROVIDER": "deepseek"}) + + assert target_env.read_text(encoding="utf-8") == "LLM_PROVIDER=openai\n" + assert list(tmp_path.glob("*.tmp")) == [] + + def test_configure_llm_enforces_token_from_env_file(tmp_path: Path, monkeypatch): """Admin token loaded from INVOICE_ENV_FILE must be enforced by configure_llm.""" - _clear_llm_env(monkeypatch) env_file = tmp_path / "data" / ".env" env_file.parent.mkdir(parents=True, exist_ok=True) env_file.write_text("LLM_CONFIG_TOKEN=secret-from-file\n", encoding="utf-8") @@ -100,36 +149,170 @@ def test_configure_llm_enforces_token_from_env_file(tmp_path: Path, monkeypatch) "model": "deepseek-chat", } - try: - # Missing token -> 401 - resp_missing = client.post("/api/settings/llm/configure", json=payload) - assert resp_missing.status_code == 401 - - # Wrong token -> 401 - resp_wrong = client.post( - "/api/settings/llm/configure", - json=payload, - headers={"X-LLM-Config-Token": "wrong-token"}, - ) - assert resp_wrong.status_code == 401 - - # Correct token -> 200 and persisted to INVOICE_ENV_FILE - resp_ok = client.post( - "/api/settings/llm/configure", - json=payload, - headers={"X-LLM-Config-Token": "secret-from-file"}, - ) - assert resp_ok.status_code == 200 - assert resp_ok.json()["success"] is True - - persisted = env_file.read_text(encoding="utf-8") - assert "LLM_PROVIDER=deepseek" in persisted - assert "DEEPSEEK_API_KEY=sk-dummy-key" in persisted - finally: - # Clean up os.environ mutations made by configure_llm - _clear_llm_env(monkeypatch) - config_module.clear_settings_cache() - reset_llm_service() + # Missing token -> 401 + resp_missing = client.post("/api/settings/llm/configure", json=payload) + assert resp_missing.status_code == 401 + + # Wrong token -> 401 + resp_wrong = client.post( + "/api/settings/llm/configure", + json=payload, + headers={"X-LLM-Config-Token": "wrong-token"}, + ) + assert resp_wrong.status_code == 401 + + # Correct token -> 200 and persisted to INVOICE_ENV_FILE + resp_ok = client.post( + "/api/settings/llm/configure", + json=payload, + headers={"X-LLM-Config-Token": "secret-from-file"}, + ) + assert resp_ok.status_code == 200 + assert resp_ok.json()["success"] is True + + persisted = env_file.read_text(encoding="utf-8") + assert "LLM_PROVIDER=deepseek" in persisted + assert "DEEPSEEK_API_KEY=sk-dummy-key" in persisted + + +@pytest.mark.parametrize( + "field,malicious_value", + [ + ("api_key", "sk-valid\nLLM_CONFIG_TOKEN=evil"), + ("api_key", "sk-valid\rLLM_CONFIG_TOKEN=evil"), + ("model", "deepseek-chat\nLLM_CONFIG_TOKEN=evil"), + ("base_url", "https://api.example.com/v1\r\nLLM_CONFIG_TOKEN=evil"), + ("provider", "deepseek\nLLM_CONFIG_TOKEN=evil"), + ], +) +def test_configure_llm_rejects_newline_injection( + tmp_path: Path, + monkeypatch, + field: str, + malicious_value: str, +): + """Newlines in any config field must be rejected with 400 before mutating env or .env.""" + env_file = tmp_path / ".env" + original_content = "LLM_CONFIG_TOKEN=real-secret\n" + env_file.write_text(original_content, encoding="utf-8") + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + config_module.clear_settings_cache() + reset_llm_service() + + test_app = FastAPI() + test_app.include_router(settings_router.router, prefix="/api/settings") + client = TestClient(test_app) + + payload = { + "provider": "deepseek", + "api_key": "sk-safe-key", + "model": "deepseek-chat", + "base_url": "https://api.deepseek.com", + } + payload[field] = malicious_value + + resp = client.post( + "/api/settings/llm/configure", + json=payload, + headers={"X-LLM-Config-Token": "real-secret"}, + ) + assert resp.status_code == 400 + assert resp.json()["detail"] == "配置项不能包含换行符" + assert env_file.read_text(encoding="utf-8") == original_content + assert "DEEPSEEK_API_KEY" not in os.environ + assert "LLM_PROVIDER" not in os.environ + + +def test_env_var_overrides_env_file_for_llm_config_token(tmp_path: Path, monkeypatch): + """Process env LLM_CONFIG_TOKEN must take precedence over .env file.""" + env_file = tmp_path / ".env" + env_file.write_text("LLM_CONFIG_TOKEN=from-file\n", encoding="utf-8") + monkeypatch.setenv("INVOICE_ENV_FILE", str(env_file)) + monkeypatch.setenv("LLM_CONFIG_TOKEN", "from-env") + config_module.clear_settings_cache() + reset_llm_service() + + assert config_module.get_settings().llm_config_token == "from-env" + + test_app = FastAPI() + test_app.include_router(settings_router.router, prefix="/api/settings") + client = TestClient(test_app) + + payload = { + "provider": "deepseek", + "api_key": "sk-env-precedence", + "model": "deepseek-chat", + } + + resp_file_token = client.post( + "/api/settings/llm/configure", + json=payload, + headers={"X-LLM-Config-Token": "from-file"}, + ) + assert resp_file_token.status_code == 401 + + resp_env_token = client.post( + "/api/settings/llm/configure", + json=payload, + headers={"X-LLM-Config-Token": "from-env"}, + ) + assert resp_env_token.status_code == 200 + assert resp_env_token.json()["success"] is True + + +@pytest.mark.parametrize( + "path,expected_statuses,expected_snippet,forbidden_snippet", + [ + ("/api", {404}, None, "SPA_INDEX"), + ("/api/not-exist", {404}, None, "SPA_INDEX"), + ("/docs", {200}, "swagger-ui", None), + ("/assets/app.js", {200}, "spa-app", None), + ("/favicon.ico", {200}, "ICONDATA", None), + ("/invoices/123", {200}, "SPA_INDEX", None), + ("/../static2/secret.txt", {200, 404}, None, "secret"), + ("/%2e%2e/static2/secret.txt", {200, 404}, None, "secret"), + ("/leak.txt", {200, 404}, None, "secret"), + ("/%00", {404}, None, None), + ], +) +def test_spa_static_routing_and_security( + tmp_path: Path, + tmp_path_factory: pytest.TempPathFactory, + path: str, + expected_statuses: set[int], + expected_snippet: str | None, + forbidden_snippet: str | None, +): + """SPA mount must preserve /api 404 & /docs 200, block traversal/symlink leaks, and never 500 on null byte.""" + static_dir = tmp_path / "static" + assets_dir = static_dir / "assets" + assets_dir.mkdir(parents=True) + (static_dir / "index.html").write_text("SPA_INDEX", encoding="utf-8") + (assets_dir / "app.js").write_text("console.log('spa-app');", encoding="utf-8") + (static_dir / "favicon.ico").write_bytes(b"ICONDATA") + + # Sibling directory with prefix collision (static2) + sibling_dir = tmp_path / "static2" + sibling_dir.mkdir() + (sibling_dir / "secret.txt").write_text("top-secret-sibling", encoding="utf-8") + + # Symlink inside static/ pointing outside tmp_path + outside_dir = tmp_path_factory.mktemp("outside_secret") + outside_secret = outside_dir / "secret.txt" + outside_secret.write_text("top-secret-symlink", encoding="utf-8") + (static_dir / "leak.txt").symlink_to(outside_secret) + + test_app = FastAPI() + mount_spa(test_app, static_dir) + client = TestClient(test_app, raise_server_exceptions=False) + + resp = client.get(path) + assert resp.status_code in expected_statuses + assert resp.status_code != 500 + if expected_snippet is not None: + assert expected_snippet in resp.text + if forbidden_snippet is not None: + assert forbidden_snippet.lower() not in resp.text.lower() def test_health_returns_503_when_db_unavailable():