Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat(doclib): require persistent local bearer authentication
myhloli4302bdd0741a
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.mdindex f7826e68..e1b20d81 100644--- a/docs/en/usage/cli_tools.md+++ b/docs/en/usage/cli_tools.md@@ -20,6 +20,18 @@ mineru server statusmineru server stop```+On first startup, Doclib generates a local token and saves it as `doclib.auth.token` in the active+`config.yaml`. Restarts and upgrades reuse it; the CLI reads and sends it automatically.+`MINERU_DOCLIB_AUTH_TOKEN` can override the file value. All UDS/TCP HTTP endpoints, including status,+export and shutdown, require a Bearer token. Integrations use `DoclibClient(base_url=..., token=...)`+or `Authorization: Bearer <token>`; discover the actual address from `doclib.endpoint.json`.+Programs sharing a token share full access to that document library.++Before upgrading from a version without authentication, stop the service using the previous CLI.+To rotate a token, stop the service, edit or remove `doclib.auth.token`, then start it and update+integrations. The configuration file is restricted with POSIX `0600` permissions or a protected+Windows DACL; startup fails if these protections cannot be enforced.+Run `mineru <command> --help` for the authoritative options of each command.## Parsing, reading, exporting, and waitingdiff --git a/docs/next/cli/mineru-server.md b/docs/next/cli/mineru-server.mdindex 4a75a0e4..09899ee1 100644--- a/docs/next/cli/mineru-server.md+++ b/docs/next/cli/mineru-server.md@@ -26,6 +26,7 @@启动时:1. 获取 `$MINERU_HOME/doclib.lock`,确保当前 home 只有一个 doclib owner。+ 在配置锁内初始化或复用持久的 `doclib.auth.token`,验证凭证文件权限后才继续启动。2. 清理 stale endpoint 和 UDS socket。3. 写入包含当前 PID、`server_id` 和空 transports 的启动阶段 endpoint。4. 绑定 UDS/TCP listener,并用实际 transports 更新 endpoint。@@ -39,6 +40,11 @@如需覆盖,可设置 `doclib.uds.*` / `doclib.tcp.*` 或对应环境变量,例如 `MINERU_DOCLIB_UDS_PATH`、`MINERU_DOCLIB_TCP_PORT`。+CLI 自动读取当前配置中的本机 token,状态和停止操作同样需要认证。认证失败保留+`invalid_doclib_token`,不能误报为服务未运行;旧 endpoint 返回 `doclib_upgrade_required`。+首次升级到认证版本前先用旧 CLI 停止旧服务;更换 token 时先 stop,再修改配置,最后 start。+token 不随普通重启变化,详见 [本机认证与二次开发](../sdk/doclib-client.md#本机认证与二次开发)。+关闭时:1. 停止后台任务。diff --git a/docs/next/config.md b/docs/next/config.mdindex 10b6c09f..39e35108 100644--- a/docs/next/config.md+++ b/docs/next/config.md@@ -44,6 +44,14 @@ loaded = load_config() # 按当前环境独立装载,不替换进程默认配依赖 `MINERU_HOME` 的默认路径在每次构造对象时解析。Doclib 的`create_app(cfg)` 会保存传入配置的独立副本,并使用其中的全局日志级别补全服务日志设置。+### Doclib 本机凭证++`doclib.auth.token` 是启动配置。标准服务首次启动时在配置锁内生成并写入实际配置文件,后续启动复用;+`MINERU_DOCLIB_AUTH_TOKEN` 可以覆盖文件值且不回写。普通 `load_config()` / `get_config()` 不生成凭证。+token 以 `SecretStr` 保存,repr/JSON 完全脱敏;不得放入运行时 `/configs` 或诊断输出。+显式 `create_app(cfg)` 需要宿主提供 token。轮换前先停止服务,修改或删除该字段后再启动。+文件权限、SDK 自动读取及直接 TCP 调用见 [Doclib SDK 本机认证](sdk/doclib-client.md#本机认证与二次开发)。+### 远程 VLM {#remote-vlm}`model.vlm` 是所有本地解析入口的 VLM 默认配置,适用于 API server、Pythondiff --git a/docs/next/decisions/0021-doclib-local-transport-discovery.md b/docs/next/decisions/0021-doclib-local-transport-discovery.mdindex 3fc4d4c1..4c962e5b 100644--- a/docs/next/decisions/0021-doclib-local-transport-discovery.md+++ b/docs/next/decisions/0021-doclib-local-transport-discovery.md@@ -3,6 +3,8 @@> 历史决策记录:保留当时的背景、状态和设计。当前接口与实现归属以 [开发入口](../README.md) 和现行规范为准;文中的历史模块路径不保证仍存在。状态: Accepted,已实现+认证与 endpoint 升级说明: “本地 TCP 不实现 token”及旧 endpoint 连接策略已由+[ADR-0035: Doclib 持久本机凭证](0035-doclib-persistent-token.md) 替代。日期: 2026-06-22相关文档: ../architecture.md, ../config.md, ../cli/mineru-server.md, ../sdk/doclib-client.mddiff --git a/docs/next/decisions/0035-doclib-persistent-token.md b/docs/next/decisions/0035-doclib-persistent-token.mdnew file mode 100644index 00000000..a08cc2dc--- /dev/null+++ b/docs/next/decisions/0035-doclib-persistent-token.md@@ -0,0 +1,41 @@+# ADR-0035: Doclib 持久本机凭证++状态: Accepted,已实现+日期: 2026-11-04++## 背景++Doclib 是本机单用户文档库,拥有服务账户的文件访问权限。UDS 的文件权限可以隔离其他账户,+TCP loopback 仅限制连接来源机器。读取正文、导出到指定路径和停止服务都需要统一的访问边界。+二次开发程序需要稳定凭证,不能要求每次服务重启后重新配置。++## 决策++- 标准启动首次生成 32 字节随机 token,并在配置锁内写入实际 `config.yaml` 的 `doclib.auth.token`。+ 已有值保持不变,普通配置读取和 SDK 构造不生成文件。环境变量 `MINERU_DOCLIB_AUTH_TOKEN`+ 按既有配置优先级覆盖文件值,不回写环境注入的凭证。+- token 属于启动配置,使用 `SecretStr` 隐藏 repr/JSON 正文;不进入 SQLite 运行时配置接口。+ 轮换采用 stop → 修改/删除配置值 → start,不热更新正在服务的实例。+- 全部 Doclib HTTP 接口使用 Bearer 认证,UDS/TCP 一致;状态、shutdown、OpenAPI 不例外。+ 在业务路由执行前拒绝缺失、重复或错误的 Authorization,不提供匿名降级。+- 配置正文写入前限制临时文件权限,再原子替换。POSIX 使用 `0600`,Windows 使用仅授权当前账户+ 与 SYSTEM 的受保护 DACL,并读回验证;父目录不能让其他普通账户替换文件。无法落实权限时失败。+- CLI/SDK 默认发现重新读取当前配置中的 token;显式地址必须同时提供显式 token。+ endpoint 升为 version 3,不存 token;`server_id` 继续每次启动变化。旧 version 1/2 仅保留诊断读取,+ SDK 返回 `doclib_upgrade_required`,升级前须先用旧 CLI 停止旧服务。+- 显式 `create_app(cfg)` 和 `DoclibServer` 要求宿主提供 token,保持实例配置独立。+- 保留认证调用者的扫描、路径读取、导出和 shutdown 能力。不增加用户角色、目录白名单或导出覆盖策略。+ Router 的可信内网共享模式不在本次变更范围内。++## 替代方案++- 每次启动轮换:会打断显式 TCP 集成,未采用。+- 仅 TCP 认证:会让两个 transport 的应用契约不同,未采用。+- token 复制到 endpoint:增加凭证副本及权限维护,未采用。+- 完整多用户权限系统:超出本机单用户产品边界,未采用。++## 影响++替代 [ADR-0021](0021-doclib-local-transport-discovery.md) 的“不实现 token”和旧 endpoint 连接决策。+现行构造参数、错误及二次开发示例见 [Doclib SDK](../sdk/doclib-client.md)。+验收覆盖持久化/并发初始化、无认证请求无副作用、SDK 自动携带/显式地址隔离、重启/轮换、文件权限和旧版本拒绝。diff --git a/docs/next/decisions/README.md b/docs/next/decisions/README.mdindex b6d3e835..a37b1043 100644--- a/docs/next/decisions/README.md+++ b/docs/next/decisions/README.md@@ -62,6 +62,7 @@| [ADR-0032](0032-ofd-native-fixed-layout-parsing.md) | Accepted | OFD 原生固定版式 Flash 解析 || [ADR-0033](0033-middle-json-inline-spans.md) | Accepted | Middle JSON 2.0 结构化行内 Span || [ADR-0034](0034-tsv-independent-file-suffix.md) | Accepted | TSV 独立文件后缀 |+| [ADR-0035](0035-doclib-persistent-token.md) | Accepted | Doclib 持久本机凭证(替代 ADR-0021 的无认证策略) |## 模板diff --git a/docs/next/errors.md b/docs/next/errors.mdindex e4055873..dd8b02b5 100644--- a/docs/next/errors.md+++ b/docs/next/errors.md@@ -29,6 +29,8 @@ API-backed parser 具有独立的业务错误与传输错误路径;不要只|---|---|| `page_range_invalid`、格式或参数错误 | 修正请求,不原样重试 || `invalid_api_key` | 检查目标服务及凭据;不可把推理服务 Key 用于 Tasks |+| Doclib `invalid_doclib_token` | 检查 `doclib.auth.token` 或显式客户端 token;HTTP 401,无匿名降级 |+| `doclib_upgrade_required` | 先用旧版本 CLI 停止旧 Doclib,再启动新版本服务 || `quality_tier_unavailable` | 核对目标服务能力及显式档位,不能静默改档 || CLI `parse_wait_timeout` | 解析继续执行;使用同一文档/任务引用查询 || Tasks 创建结果未知 | 不盲目重放;已有 ID 时查询原任务 |diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.mdindex fb79f6e2..346fe8b2 100644--- a/docs/next/sdk/doclib-client.md+++ b/docs/next/sdk/doclib-client.md@@ -40,6 +40,7 @@ class DoclibClient:endpoint_path: str | Path | None = None,socket_path: str | Path | None = None,base_url: str | None = None,+ token: str | None = None,timeout: int = 60,api_prefix: str = "/api/v1",) -> None: ...@@ -51,9 +52,11 @@ class DoclibClient:- 默认通过 `$MINERU_HOME/doclib.endpoint.json` 发现 doclib endpoint。- 默认发现不从启动配置推导 UDS 或 TCP;endpoint 文件不存在或无效时,方法调用抛出 `ServerNotRunningError`。- 默认发现会在首次请求前校验 endpoint 与 `/server/status` 的 `server_id`;不匹配的 transport 不会承载业务请求。-- version 1 endpoint 仅用于升级迁移,通过 endpoint/status PID 对应关系识别旧 server;version 2 的 PID 不参与身份判断。+- 当前 endpoint 为 version 3;旧 version 1/2 可用于诊断,但 SDK 拒绝连接并返回 `doclib_upgrade_required`,不会降级为匿名请求。- `socket_path` 表示显式 UDS endpoint;`base_url` 只表示显式 TCP endpoint,例如 `http://127.0.0.1:15980`。- 显式 `socket_path` / `base_url` 代表调用方明确选择的 server,不执行 endpoint `server_id` 校验。+- 默认发现从当前启动配置读取 `doclib.auth.token`,不使用可能早于首次服务启动的进程缓存;也可显式传入 `token`。+- 显式 `socket_path` / `base_url` 必须同时提供 `token`,不会自动将默认配置的凭证发送给其他目标。- `socket_path` 和 `base_url` 不能同时传入。- 无法连接任何候选 endpoint 时,方法调用抛出 `ServerNotRunningError`。- client 提供 `close()`,调用方在 finally 中释放;当前不提供上下文管理器。@@ -67,6 +70,44 @@ client = DoclibClient()status = client.get_server_status()```+## 本机认证与二次开发++首次正常启动服务会生成随机凭证并写入 `$MINERU_HOME/config.yaml` 的 `doclib.auth.token`;+`MINERU_CONFIG` 可指定其他配置文件。重启和升级复用已有凭证。`MINERU_DOCLIB_AUTH_TOKEN`+可覆盖文件值,环境注入的凭证不会回写文件。自定义 token 至少包含 32 个 ASCII Bearer 字符。++UDS 与 TCP 的全部 HTTP 接口都要求 `Authorization: Bearer <token>`,包括 status、shutdown、+读取、扫描、配置、导出和 OpenAPI 文档。缺失或错误凭证返回 HTTP 401、`invalid_doclib_token`,+不会执行对应业务操作。token 不写入 endpoint、URL、状态或日志;启动配置的 repr/JSON 完全隐藏正文。++直接使用 TCP 的集成程序可在受保护的配置中保存此稳定凭证:++```python+import os++from mineru.doclib.client import DoclibClient++client = DoclibClient(+ base_url="http://127.0.0.1:15980", # 实际端口以 endpoint discovery 为准+ token=os.environ["DOCLIB_TOKEN"],+)+try:+ status = client.get_server_status()+finally:+ client.close()+```++嵌入式 `create_app(cfg)` / `DoclibServer(..., config=cfg)` 需要宿主显式提供 `cfg.doclib.auth.token`,+不会为显式配置读取默认文件或生成临时 token。标准进程入口和无参数 `create_app()` 负责持久初始化。++更换凭证的顺序是:使用旧凭证 `mineru server stop`,修改配置或删除 `doclib.auth.token`,再+`mineru server start`。删除字段后会生成新凭证;其他集成程序需要同步更新。已有 SDK 对象保存构造时的+凭证,轮换后应重新构造。首次升级到认证版本前,应先用旧版本 CLI 停止旧服务。++凭证授予当前文档库的完整访问权限,共用凭证的程序属于同一个可信范围。配置文件使用 POSIX `0600`+或 Windows 受保护 DACL,普通其他账户不可读取;父目录也不能允许其他普通账户替换文件。权限设置或+验证失败时拒绝启动。建议继续使用 loopback,不将本机文档库直接暴露给不可信网络。+## Parse 方法当前稳定入口使用 typed request / response model:diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.mdindex 3afd1a9e..608bbc9e 100644--- a/docs/zh/usage/cli_tools.md+++ b/docs/zh/usage/cli_tools.md@@ -20,6 +20,16 @@ mineru server statusmineru server stop```+Doclib 首次启动自动生成本机 token,保存到实际 `config.yaml` 的 `doclib.auth.token`;+重启和升级保持不变,CLI 自动读取并携带。`MINERU_DOCLIB_AUTH_TOKEN` 可覆盖文件值。+UDS/TCP 的全部 HTTP 接口(包括状态、导出和 shutdown)都要求 Bearer token。+直接集成时使用 `DoclibClient(base_url=..., token=...)` 或 `Authorization: Bearer <token>`;+实际地址以 `doclib.endpoint.json` 为准。多个程序共用 token 就共享该文档库的完整权限。++首次升级到带认证的版本前,请先用旧 CLI 停止服务。轮换 token 时先停止服务,再修改或删除+`doclib.auth.token`,最后启动;集成程序同步更新凭证。配置文件需限制其他普通账户访问,+POSIX 使用 `0600`、Windows 使用受保护 DACL,权限无法落实时服务拒绝启动。+各命令的权威参数以 `mineru <command> --help` 为准。## 解析、阅读、导出与等待diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.pyindex 5226b633..3fde528f 100644--- a/mineru/cli/commands/server.py+++ b/mineru/cli/commands/server.py@@ -162,6 +162,10 @@ def _server_running() -> bool:c = DoclibClient(timeout=3)c.get_server_status()return True+ except MineruError as exc:+ if exc.code in {"invalid_doclib_token", "doclib_upgrade_required"}:+ raise+ return Falseexcept Exception:return Falsediff --git a/mineru/config.py b/mineru/config.pyindex da904c5b..09b18028 100644--- a/mineru/config.py+++ b/mineru/config.py@@ -7,6 +7,7 @@ import copyimport loggingimport osimport re+import secretsimport socketimport tempfileimport threading@@ -17,8 +18,9 @@ from urllib.parse import urlsplit, urlunsplitimport yamlfrom filelock import FileLock-from pydantic import BaseModel, Field, field_validator, model_validator-from pydantic_core import to_jsonable_python+from pydantic import BaseModel, Field, SecretStr, field_validator, model_validator++from .utils.private_file import create_private_tempfile, protect_private_file_logger = logging.getLogger(__name__)@@ -247,7 +249,7 @@ def _load_effective_config() -> LoadedConfig:base_config = Config(**raw_config)overrides, env_paths = _collect_env_overrides()if overrides:- base_config = Config(**_deep_merge(to_jsonable_python(base_config), overrides))+ base_config = Config(**_deep_merge(base_config.model_dump(), overrides))for path in env_paths:sources[path] = "env"return LoadedConfig(@@ -315,17 +317,58 @@ def update_config_file(patch: dict[str, Any], *, only_if_onnx_auto: bool = Falsereturn Falseupdated = _deep_merge(current, patch)- fd, tmp_path = tempfile.mkstemp(prefix=".config.", suffix=".tmp", dir=config_dir or None)- try:- with os.fdopen(fd, "w", encoding="utf-8") as file:- yaml.safe_dump(updated, file, allow_unicode=True, sort_keys=False)- os.replace(tmp_path, config_file)- finally:- if os.path.exists(tmp_path):- os.unlink(tmp_path)+ _write_config_file(config_file, updated)return True+def _write_config_file(config_file: str, config: dict[str, Any]) -> None:+ """在写入配置正文之前限制临时文件权限,原子替换后保留同样的私密权限。"""+ directory = os.path.dirname(config_file) or "."+ doclib = config.get("doclib")+ auth = doclib.get("auth") if isinstance(doclib, dict) else None+ if isinstance(auth, dict) and auth.get("token") is not None:+ fd, tmp_path = create_private_tempfile(directory)+ else:+ fd, tmp_path = tempfile.mkstemp(prefix=".config.", suffix=".tmp", dir=directory)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as file:+ yaml.safe_dump(config, file, allow_unicode=True, sort_keys=False)+ os.replace(tmp_path, config_file)+ finally:+ if os.path.exists(tmp_path):+ os.unlink(tmp_path)+++def load_doclib_server_config() -> LoadedConfig:+ """启动时在配置锁内生成或复用本机凭证;普通配置读取不生成文件或凭证。"""+ loaded = load_config()+ config_file = loaded.config_file+ os.makedirs(os.path.dirname(os.path.abspath(config_file)), mode=0o700, exist_ok=True)+ with FileLock(f"{config_file}.lock"):+ loaded = load_config()+ if os.path.isfile(config_file):+ protect_private_file(config_file)+ if loaded.config.doclib.auth.token is not None:+ validate_doclib_token(loaded.config.doclib.auth.token.get_secret_value())+ return loaded+ if os.path.isfile(config_file):+ with open(config_file, encoding="utf-8") as file:+ current = yaml.safe_load(file) or {}+ else:+ current = {}+ token = secrets.token_urlsafe(32)+ updated = _deep_merge(current, {"doclib": {"auth": {"token": token}}})+ _write_config_file(config_file, updated)+ return load_config()+++def validate_doclib_token(token: str) -> str:+ """校验本机凭证的长度和 HTTP Bearer 可用字符,错误消息不包含凭证。"""+ if not re.fullmatch(r"[A-Za-z0-9._~+/=-]{32,}", token):+ raise ValueError("Doclib token must contain at least 32 ASCII Bearer-token characters.")+ return token++def read_onnx_device_from_file() -> OnnxDevice:"""Re-read only the device choice after acquiring the cross-process selection lock."""path = get_config_file_path()@@ -553,6 +596,12 @@ class ModelConfig(BaseModel):return value+class DoclibAuthConfig(BaseModel):+ """保存跨服务重启稳定的本机凭证,默认序列化和 repr 都隐藏正文。"""++ token: SecretStr | None = Field(default=None, repr=False)++class DoclibConfig(BaseModel):"""Doclib startup configuration.@@ -561,6 +610,7 @@ class DoclibConfig(BaseModel):service."""+ auth: DoclibAuthConfig = Field(default_factory=DoclibAuthConfig)uds: UDSConfig = Field(default_factory=UDSConfig)tcp: TCPConfig = Field(default_factory=TCPConfig)log: LogConfig = Field(default_factory=LogConfig)@@ -611,11 +661,14 @@ _config_load_lock = threading.Lock()def PatchedConfig(**kwargs: Any) -> Config:"""在进程默认配置的独立副本上应用局部覆盖并重新校验。"""- merged = _deep_merge(to_jsonable_python(get_config()), kwargs)+ merged = _deep_merge(get_config().model_dump(), kwargs)return Config(**merged)__all__ = [+ "DoclibAuthConfig",+ "load_doclib_server_config",+ "validate_doclib_token","OnnxDevice","read_onnx_device_from_file","AutoBool",diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 917e2974..71ba4c96 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -19,7 +19,7 @@ from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponsefrom loguru import logger as loguru_logger-from ..config import Config, ConfigSource, LogConfig, LogLevel, _mineru_home, get_config, get_config_source+from ..config import Config, ConfigSource, LogConfig, LogLevel, _mineru_home, get_config_source, load_doclib_server_configfrom ..errors import MineruError, error_response, http_status_forfrom ..utils.async_utils import drain_futurefrom ..utils.logger import configure_global_log_level@@ -44,7 +44,7 @@ logger = logging.getLogger("mineru.doclib.app")def create_app(cfg: Config | None = None) -> FastAPI:"""使用独立启动配置快照创建应用,显式配置不触发进程默认配置加载。"""- cfg = (get_config() if cfg is None else cfg).model_copy(deep=True)+ cfg = (load_doclib_server_config().config if cfg is None else cfg).model_copy(deep=True)_setup_logging(cfg.doclib.log, global_level=cfg.log.level)state = AppState()state.config = cfg@@ -510,7 +510,7 @@ def main() -> None:configure_global_log_level()try:with doclib_home_lock():- cfg = get_config()+ cfg = load_doclib_server_config().configlog_source = get_config_source("doclib.log.level" if cfg.doclib.log.level is not None else "log.level")_run_server(cfg, log_source=log_source)except DoclibLockUnavailable:diff --git a/mineru/doclib/auth.py b/mineru/doclib/auth.pynew file mode 100644index 00000000..abbff7be--- /dev/null+++ b/mineru/doclib/auth.py@@ -0,0 +1,43 @@+"""Doclib 本机 HTTP 接口统一 Bearer 凭证校验。"""++from __future__ import annotations++import secrets++from pydantic import SecretStr+from starlette.requests import Request+from starlette.responses import JSONResponse+from starlette.types import ASGIApp, Receive, Scope, Send++from ..config import validate_doclib_token+from ..errors import MineruError, error_response+++class DoclibAuthMiddleware:+ """在路由和业务依赖执行前校验凭证,覆盖状态、文档和关闭等全部 HTTP 接口。"""++ def __init__(self, app: ASGIApp, *, token: SecretStr) -> None:+ """保存当前实例的凭证快照,配置更新须重启后生效。"""+ self.app = app+ self._token = validate_doclib_token(token.get_secret_value()).encode("ascii")++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ """拒绝缺失、重复或不匹配的授权头,认证失败不消费请求正文。"""+ if scope["type"] != "http":+ await self.app(scope, receive, send)+ return+ request = Request(scope)+ authorization = request.headers.getlist("authorization")+ scheme, _, value = authorization[0].partition(" ") if len(authorization) == 1 else ("", "", "")+ if scheme.lower() != "bearer" or not secrets.compare_digest(value.encode("utf-8"), self._token):+ response = JSONResponse(+ error_response(MineruError("invalid_doclib_token", "A valid Doclib Bearer token is required.")),+ status_code=401,+ headers={"WWW-Authenticate": "Bearer"},+ )+ await response(scope, receive, send)+ return+ await self.app(scope, receive, send)+++__all__ = ["DoclibAuthMiddleware"]diff --git a/mineru/doclib/client.py b/mineru/doclib/client.pyindex 7b7267d9..74c1dc3b 100644--- a/mineru/doclib/client.py+++ b/mineru/doclib/client.py@@ -10,12 +10,14 @@ import httpxfrom pydantic import BaseModelfrom pydantic_core import to_jsonable_python+from ..config import load_config, validate_doclib_tokenfrom ..errors import MineruError, ServerNotRunningErrorfrom ..parser.page_range import normalize_page_range_inputfrom ..types import Tierfrom .base import DoclibInterfacefrom .endpoint import (DOCLIB_UDS_BASE_URL,+ ENDPOINT_VERSION,EndpointInfo,EndpointTransport,default_endpoint_path,@@ -99,11 +101,19 @@ class DoclibClient(DoclibInterface):endpoint_path: str | Path | None = None,socket_path: str | Path | None = None,base_url: str | None = None,+ token: str | None = None,timeout: int = 60,api_prefix: str = "/api/v1",) -> None:+ """默认发现读取本机最新凭证,显式地址要求显式 token,避免向其他服务泄露凭证。"""if socket_path is not None and base_url is not None:raise ValueError("socket_path and base_url cannot both be provided.")+ if token is None and (socket_path is not None or base_url is not None):+ raise ValueError("An explicit token is required with socket_path or base_url.")+ if token is None:+ configured = load_config().config.doclib.auth.token+ token = configured.get_secret_value() if configured is not None else None+ self._token = validate_doclib_token(token) if token is not None else Noneself._clients, self._expected_endpoint = _build_clients(endpoint_path=endpoint_path,socket_path=socket_path,@@ -435,19 +445,30 @@ class DoclibClient(DoclibInterface):) -> httpx.Response:if not self._clients:raise ServerNotRunningError()+ if self._expected_endpoint is not None and self._expected_endpoint.version != ENDPOINT_VERSION:+ raise MineruError(+ "doclib_upgrade_required",+ "This Doclib server predates token authentication. Stop it with the previous CLI and start the updated server.",+ )+ if self._token is None:+ raise MineruError(+ "invalid_doclib_token",+ "Doclib token is missing. Start the updated server to generate doclib.auth.token, "+ "or provide an explicit token.",+ )clients = self._ordered_clients()instance_mismatch: _ServerInstanceMismatch | None = Nonefor client in clients:try:self._validate_server_instance(client)if method == "GET":- resp = client.get(path, params=params, headers=self._telemetry_headers())+ resp = client.get(path, params=params, headers=self._request_headers())elif method == "POST":- resp = client.post(path, params=params, json=json_data or {}, headers=self._telemetry_headers())+ resp = client.post(path, params=params, json=json_data or {}, headers=self._request_headers())elif method == "PUT":- resp = client.put(path, params=params, json=json_data or {}, headers=self._telemetry_headers())+ resp = client.put(path, params=params, json=json_data or {}, headers=self._request_headers())elif method == "DELETE":- resp = client.delete(path, params=params, headers=self._telemetry_headers())+ resp = client.delete(path, params=params, headers=self._request_headers())else:raise MineruError("internal_error", f"Unsupported client method: {method}")except httpx.ConnectError:@@ -475,7 +496,7 @@ class DoclibClient(DoclibInterface):resp = client.get(f"{self._api_prefix}/server/status",params={},- headers=self._telemetry_headers(),+ headers=self._request_headers(),)data = _decode_response(resp)if expected_endpoint.server_id is not None:@@ -500,6 +521,10 @@ class DoclibClient(DoclibInterface):"X-MinerU-Telemetry-Caller": ctx.caller,}+ def _request_headers(self) -> dict[str, str]:+ """状态探测和业务请求统一携带认证头,不将凭证放入 URL 或遥测字段。"""+ return {**self._telemetry_headers(), "Authorization": f"Bearer {self._token}"}+def _calling_route_method(self) -> Callable[..., Any]:import inspectdiff --git a/mineru/doclib/endpoint.py b/mineru/doclib/endpoint.pyindex ab68fddd..9a41024e 100644--- a/mineru/doclib/endpoint.py+++ b/mineru/doclib/endpoint.py@@ -33,7 +33,7 @@ class EndpointInfo:DOCLIB_UDS_BASE_URL = "http://mineru"-ENDPOINT_VERSION = 2+ENDPOINT_VERSION = 3LEGACY_ENDPOINT_VERSION = 1@@ -96,7 +96,7 @@ def read_endpoint_file(path: str | os.PathLike[str]) -> EndpointInfo | None:if parsed_pid is None:return Noneparsed_server_id = None- elif version == ENDPOINT_VERSION:+ elif version in (2, ENDPOINT_VERSION):if not isinstance(server_id, str) or not server_id:return Noneparsed_server_id = server_iddiff --git a/mineru/doclib/instance_lock.py b/mineru/doclib/instance_lock.pyindex e45122bc..f47796fd 100644--- a/mineru/doclib/instance_lock.py+++ b/mineru/doclib/instance_lock.py@@ -9,7 +9,7 @@ from pathlib import Pathfrom filelock import FileLock, Timeoutfrom ..config import _mineru_home-from .endpoint import ENDPOINT_VERSION, default_endpoint_path, read_endpoint_file+from .endpoint import default_endpoint_path, read_endpoint_fileDOCLIB_LOCK_FILENAME = "doclib.lock"@@ -23,7 +23,7 @@ def build_doclib_home_owned_message() -> str:"""Build the user-facing ownership message from current diagnostics."""home = default_doclib_lock_path().parentendpoint = read_endpoint_file(default_endpoint_path())- pid = endpoint.pid if endpoint is not None and endpoint.version == ENDPOINT_VERSION else None+ pid = endpoint.pid if endpoint is not None else Nonepid_detail = f" (reported PID {pid})" if pid is not None else ""return f"MinerU home [{home}] is currently owned by another doclib server process{pid_detail}."diff --git a/mineru/doclib/server.py b/mineru/doclib/server.pyindex 68831342..28be981c 100644--- a/mineru/doclib/server.py+++ b/mineru/doclib/server.py@@ -14,7 +14,7 @@ from fastapi import APIRouter, FastAPI, Requestfrom fastapi.responses import JSONResponsefrom pydantic import ValidationError-from ..config import Config+from ..config import Config, validate_doclib_tokenfrom ..errors import InvalidRequestError, MineruError, NotFoundError, error_response, http_status_forfrom ..filetypes import TEXT_EXTENSIONS, TEXT_FILE_TYPESfrom ..model.download import verify_model_repo@@ -35,6 +35,7 @@ from ..types import (Tier,)from ..version import __version__+from .auth import DoclibAuthMiddlewarefrom .background.parse_server_health import get_managed_parse_server_tierfrom .parse_server_state import ParseServerHealthfrom .base import AsyncDoclibInterface@@ -161,12 +162,16 @@ class DoclibServer(AsyncDoclibInterface):self.config = configself.health = healthself.state = state+ if config.doclib.auth.token is None:+ raise ValueError("DoclibServer requires doclib.auth.token; use the standard server startup to generate it.")+ validate_doclib_token(config.doclib.auth.token.get_secret_value())self.app = FastAPI(title=title,docs_url="/api/docs",redoc_url="/api/redoc",openapi_url="/api/openapi.json",)+ self.app.add_middleware(DoclibAuthMiddleware, token=config.doclib.auth.token)self.app.add_exception_handler(MineruError, _mineru_error_handler)self.app.add_exception_handler(Exception, _unexpected_error_handler)self.app.include_router(self._build_router())diff --git a/mineru/errors.py b/mineru/errors.pyindex 9aa9a4f1..727533dc 100644--- a/mineru/errors.py+++ b/mineru/errors.py@@ -67,6 +67,7 @@ _ERROR_TYPE_MAP: dict[str, ErrorType] = {"watch_not_found": "invalid_request_error",# authentication_error"invalid_api_key": "authentication_error",+ "invalid_doclib_token": "authentication_error",# permission_error"feature_requires_api_key": "permission_error","list_requires_api_key": "permission_error",@@ -100,6 +101,7 @@ _ERROR_TYPE_MAP: dict[str, ErrorType] = {"service_unavailable": "api_error","server_not_running": "api_error","server_instance_mismatch": "api_error",+ "doclib_upgrade_required": "api_error","server_busy": "api_error","remote_timeout": "api_error","remote_unreachable": "api_error",diff --git a/mineru/utils/private_file.py b/mineru/utils/private_file.pynew file mode 100644index 00000000..51369446--- /dev/null+++ b/mineru/utils/private_file.py@@ -0,0 +1,247 @@+"""为本机凭证配置提供 POSIX 权限和 Windows DACL 保护。"""++from __future__ import annotations++import os+import secrets+import stat+import tempfile+from pathlib import Path+++def protect_private_file(path: str | Path) -> None:+ """限制普通账户读取凭证文件;权限无法落实时失败,不降级为公开文件。"""+ path = Path(path).absolute()+ info = path.lstat()+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:+ raise PermissionError("Credential configuration must be a regular file without links.")+ if os.name == "nt":+ _protect_windows_file(path)+ return+ if info.st_uid != os.getuid():+ raise PermissionError("Credential configuration must be owned by the current user.")+ parent = path.parent.stat()+ if parent.st_uid not in {os.getuid(), 0}:+ raise PermissionError("Credential configuration directory must have a trusted owner.")+ if parent.st_mode & 0o022:+ raise PermissionError("Credential configuration directory must not be writable by other users.")+ os.chmod(path, 0o600)+ if stat.S_IMODE(path.stat().st_mode) != 0o600:+ raise PermissionError("The filesystem cannot enforce private credential configuration permissions.")+++def create_private_tempfile(directory: str) -> tuple[int, str]:+ """从创建时就限制凭证临时文件权限,防止先打开的其他账户句柄读取后写入的正文。"""+ if os.name != "nt":+ fd, path = tempfile.mkstemp(prefix=".config.", suffix=".tmp", dir=directory)+ try:+ protect_private_file(path)+ except BaseException:+ os.close(fd)+ os.unlink(path)+ raise+ return fd, path+ for _ in range(10):+ path = Path(directory).absolute() / f".config.{secrets.token_hex(12)}.tmp"+ try:+ fd = _protect_windows_file(path, create=True)+ except FileExistsError:+ continue+ assert fd is not None+ return fd, str(path)+ raise FileExistsError("Could not allocate a private configuration file.")+++def _protect_windows_file(path: Path, *, create: bool = False) -> int | None:+ """按当前账户和 SYSTEM 的受保护 DACL 创建或保护文件,并读回验证实际权限。"""+ import ctypes+ from ctypes import wintypes++ kernel = ctypes.WinDLL("kernel32", use_last_error=True)+ security = ctypes.WinDLL("advapi32", use_last_error=True)+ pointer = ctypes.c_void_p+ kernel.GetCurrentProcess.restype = wintypes.HANDLE+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel.CloseHandle.restype = wintypes.BOOL+ kernel.LocalFree.argtypes = [pointer]+ kernel.LocalFree.restype = pointer++ class SecurityAttributes(ctypes.Structure):+ """在 CreateFile 时传入 DACL,避免先创建公开文件再收紧权限的窗口。"""++ _fields_ = [("length", wintypes.DWORD), ("descriptor", pointer), ("inherit", wintypes.BOOL)]++ kernel.CreateFileW.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ wintypes.DWORD,+ ctypes.POINTER(SecurityAttributes),+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.HANDLE,+ ]+ kernel.CreateFileW.restype = wintypes.HANDLE+ security.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]+ security.OpenProcessToken.restype = wintypes.BOOL+ security.GetTokenInformation.argtypes = [+ wintypes.HANDLE,+ ctypes.c_int,+ pointer,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.DWORD),+ ]+ security.GetTokenInformation.restype = wintypes.BOOL+ security.ConvertSidToStringSidW.argtypes = [pointer, ctypes.POINTER(wintypes.LPWSTR)]+ security.ConvertSidToStringSidW.restype = wintypes.BOOL+ security.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ ctypes.POINTER(pointer),+ ctypes.POINTER(wintypes.DWORD),+ ]+ security.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL+ security.SetFileSecurityW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, pointer]+ security.SetFileSecurityW.restype = wintypes.BOOL+ security.GetFileSecurityW.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ pointer,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.DWORD),+ ]+ security.GetFileSecurityW.restype = wintypes.BOOL+ security.GetSecurityDescriptorDacl.argtypes = [+ pointer,+ ctypes.POINTER(wintypes.BOOL),+ ctypes.POINTER(pointer),+ ctypes.POINTER(wintypes.BOOL),+ ]+ security.GetSecurityDescriptorDacl.restype = wintypes.BOOL+ security.GetSecurityDescriptorOwner.argtypes = [pointer, ctypes.POINTER(pointer), ctypes.POINTER(wintypes.BOOL)]+ security.GetSecurityDescriptorOwner.restype = wintypes.BOOL+ security.GetSecurityDescriptorControl.argtypes = [pointer, ctypes.POINTER(wintypes.WORD), ctypes.POINTER(wintypes.DWORD)]+ security.GetSecurityDescriptorControl.restype = wintypes.BOOL++ def read_descriptor(target: Path) -> ctypes.Array:+ """读取文件或目录的所有者和 DACL;不支持安全描述符的文件系统直接失败。"""+ size = wintypes.DWORD()+ security.GetFileSecurityW(str(target), 0x00000005, None, 0, ctypes.byref(size))+ if not size.value:+ raise ctypes.WinError(ctypes.get_last_error())+ result = ctypes.create_string_buffer(size.value)+ if not security.GetFileSecurityW(str(target), 0x00000005, result, size, ctypes.byref(size)):+ raise ctypes.WinError(ctypes.get_last_error())+ return result++ def dacl_pointer(sd: object) -> int:+ """取得非空 DACL,避免将空 DACL 指针对应的全员访问误认为私密权限。"""+ present, defaulted, dacl = wintypes.BOOL(), wintypes.BOOL(), pointer()+ if not security.GetSecurityDescriptorDacl(sd, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted)):+ raise ctypes.WinError(ctypes.get_last_error())+ if not present.value or not dacl.value:+ raise PermissionError("Credential configuration requires an explicit DACL.")+ return dacl.value++ def sid_string(sid: int) -> str:+ """把系统 SID 转成稳定标识,并释放 Windows 分配的字符串。"""+ result = wintypes.LPWSTR()+ if not security.ConvertSidToStringSidW(sid, ctypes.byref(result)):+ raise ctypes.WinError(ctypes.get_last_error())+ try:+ return result.value+ finally:+ kernel.LocalFree(ctypes.cast(result, pointer))++ process_token = wintypes.HANDLE()+ sid_text = wintypes.LPWSTR()+ descriptor = pointer()+ created_handle = None+ created = False+ transferred = False+ try:+ # TOKEN_QUERY=0x0008,TokenUser=1;令牌用户的 SID 不依赖本地化用户名。+ if not security.OpenProcessToken(kernel.GetCurrentProcess(), 0x0008, ctypes.byref(process_token)):+ raise ctypes.WinError(ctypes.get_last_error())+ size = wintypes.DWORD()+ security.GetTokenInformation(process_token, 1, None, 0, ctypes.byref(size))+ if not size.value:+ raise ctypes.WinError(ctypes.get_last_error())+ user = ctypes.create_string_buffer(size.value)+ if not security.GetTokenInformation(process_token, 1, user, size, ctypes.byref(size)):+ raise ctypes.WinError(ctypes.get_last_error())+ sid = ctypes.cast(user, ctypes.POINTER(pointer)).contents.value+ if not security.ConvertSidToStringSidW(sid, ctypes.byref(sid_text)):+ raise ctypes.WinError(ctypes.get_last_error())+ # 父目录的所有者或写权限也不能让其他普通账户替换凭证文件。+ parent = read_descriptor(path.parent)+ trusted = {sid_text.value, "S-1-5-18", "S-1-5-32-544"}+ owner, defaulted = pointer(), wintypes.BOOL()+ if not security.GetSecurityDescriptorOwner(parent, ctypes.byref(owner), ctypes.byref(defaulted)):+ raise ctypes.WinError(ctypes.get_last_error())+ if sid_string(owner.value) not in trusted:+ raise PermissionError("Credential configuration directory must have a trusted owner.")+ if not create:+ existing = read_descriptor(path)+ if not security.GetSecurityDescriptorOwner(existing, ctypes.byref(owner), ctypes.byref(defaulted)):+ raise ctypes.WinError(ctypes.get_last_error())+ if sid_string(owner.value) not in trusted:+ raise PermissionError("Credential configuration must have a trusted owner.")+ parent_dacl = dacl_pointer(parent)+ count = ctypes.c_ushort.from_address(parent_dacl + 4).value+ ace = parent_dacl + 8+ for _ in range(count):+ ace_type = ctypes.c_ubyte.from_address(ace).value+ flags = ctypes.c_ubyte.from_address(ace + 1).value+ size = ctypes.c_ushort.from_address(ace + 2).value+ # 忽略仅继承的 ACE 和拒绝条目;未知的允许条目按不安全处理。+ if not flags & 0x08 and ace_type != 1:+ mask = ctypes.c_uint32.from_address(ace + 4).value+ if mask & 0x500D0156 and (ace_type != 0 or sid_string(ace + 8) not in trusted):+ raise PermissionError("Credential configuration directory must not be writable by other users.")+ ace += size+ expected = f"D:P(A;;FA;;;{sid_text.value})(A;;FA;;;SY)"+ if not security.ConvertStringSecurityDescriptorToSecurityDescriptorW(expected, 1, ctypes.byref(descriptor), None):+ raise ctypes.WinError(ctypes.get_last_error())+ if create:+ attributes = SecurityAttributes(ctypes.sizeof(SecurityAttributes), descriptor, False)+ # GENERIC_READ | GENERIC_WRITE,CREATE_NEW,FILE_ATTRIBUTE_NORMAL;句柄不向子进程继承。+ created_handle = kernel.CreateFileW(str(path), 0xC0000000, 0x00000007, ctypes.byref(attributes), 1, 0x80, None)+ if created_handle == pointer(-1).value:+ created_handle = None+ raise ctypes.WinError(ctypes.get_last_error())+ created = True+ # DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION 禁止重新继承公开权限。+ elif not security.SetFileSecurityW(str(path), 0x80000004, descriptor):+ raise ctypes.WinError(ctypes.get_last_error())+ actual = read_descriptor(path)+ control, revision = wintypes.WORD(), wintypes.DWORD()+ if not security.GetSecurityDescriptorControl(actual, ctypes.byref(control), ctypes.byref(revision)):+ raise ctypes.WinError(ctypes.get_last_error())+ expected_dacl, actual_dacl = dacl_pointer(descriptor), dacl_pointer(actual)+ expected_size = ctypes.c_ushort.from_address(expected_dacl + 2).value+ actual_size = ctypes.c_ushort.from_address(actual_dacl + 2).value+ if not control.value & 0x1000 or ctypes.string_at(actual_dacl, actual_size) != ctypes.string_at(+ expected_dacl, expected_size+ ):+ raise PermissionError("The filesystem cannot enforce private credential configuration permissions.")+ if create:+ import msvcrt++ fd = msvcrt.open_osfhandle(created_handle, os.O_RDWR | os.O_BINARY)+ transferred = True+ return fd+ return None+ finally:+ if created_handle is not None and not transferred:+ kernel.CloseHandle(created_handle)+ if created and not transferred:+ path.unlink(missing_ok=True)+ if descriptor:+ kernel.LocalFree(descriptor)+ if sid_text:+ kernel.LocalFree(ctypes.cast(sid_text, pointer))+ if process_token:+ kernel.CloseHandle(process_token)+++__all__ = ["create_private_tempfile", "protect_private_file"]diff --git a/tests/unittest/doclib_test_utils.py b/tests/unittest/doclib_test_utils.pyindex 3a80dc20..b1492ba6 100644--- a/tests/unittest/doclib_test_utils.py+++ b/tests/unittest/doclib_test_utils.py@@ -5,6 +5,8 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any+from pydantic import SecretStr+from mineru.config import Config, LogConfig, ManagedParseServerConfig, get_configfrom mineru.doclib.background.parse_server_health import ParseServerHealthCheckfrom mineru.doclib.core.db import DatabaseManager@@ -18,6 +20,16 @@ from mineru.doclib.services.parse_execution_svc import ParseExecutionServicefrom mineru.doclib.services.parse_queue_svc import ParseQueueServicefrom mineru.doclib.telemetry import TelemetryService+TEST_DOCLIB_TOKEN = "doclib-test-token-with-at-least-32-characters"+DOCLIB_AUTH_HEADERS = {"Authorization": f"Bearer {TEST_DOCLIB_TOKEN}"}+++def authenticated_doclib_config(config: Config) -> Config:+ """为显式组装的测试服务提供固定凭证,不读取或修改开发者的配置文件。"""+ config = config.model_copy(deep=True)+ config.doclib.auth.token = SecretStr(TEST_DOCLIB_TOKEN)+ return config+@dataclassclass ParseServices:@@ -71,7 +83,7 @@ def create_doclib_server(return DoclibServer(state,title=title,- config=(get_config() if config is None else config).model_copy(deep=True),+ config=authenticated_doclib_config(get_config() if config is None else config),health=ParseServerHealth() if health is None else health,)diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.pyindex e3e1fa44..55a2ba0d 100644--- a/tests/unittest/test_doclib_app_startup.py+++ b/tests/unittest/test_doclib_app_startup.py@@ -1,3 +1,4 @@+from doclib_test_utils import DOCLIB_AUTH_HEADERS, authenticated_doclib_configimport asyncioimport loggingimport subprocess@@ -121,7 +122,7 @@ def test_config_set_rejects_invalid_known_config_values(key: str, value: str, momonkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)cfg = PatchedConfig(doclib={"data_dir": str(tmp_path), "sqlite": {"path": str(tmp_path / "doclib.db")}})- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.put(f"/api/v1/configs/{key}", json={"value": value})config_response = client.get(f"/api/v1/configs/{key}")@@ -151,7 +152,7 @@ def test_config_set_managed_tier_rejects_missing_models(monkeypatch.setattr(model_download.get_config().model.vlm, "server_url", "")cfg = PatchedConfig(doclib={"data_dir": str(tmp_path), "sqlite": {"path": str(tmp_path / "doclib.db")}})- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.put("/api/v1/configs/parse_server.local.managed_tier", json={"value": tier})config_response = client.get("/api/v1/configs/parse_server.local.managed_tier")@@ -177,7 +178,7 @@ def test_config_set_managed_advanced_accepts_ready_standard_models(monkeypatch:monkeypatch.setattr(model_download.get_config().model.vlm, "server_url", "")cfg = PatchedConfig(doclib={"data_dir": str(tmp_path), "sqlite": {"path": str(tmp_path / "doclib.db")}})- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.put("/api/v1/configs/parse_server.local.managed_tier", json={"value": "advanced"})config_response = client.get("/api/v1/configs/parse_server.local.managed_tier")@@ -203,7 +204,7 @@ def test_config_set_managed_mode_rejects_missing_models_for_current_tier(monkeypatch.setattr(model_download.get_config().model, "base_dir", str(tmp_path / "models"))cfg = PatchedConfig(doclib={"data_dir": str(tmp_path), "sqlite": {"path": str(tmp_path / "doclib.db")}})- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.put("/api/v1/configs/parse_server.local.mode", json={"value": "managed"})config_response = client.get("/api/v1/configs/parse_server.local.mode")@@ -327,9 +328,9 @@ def test_explicit_app_configuration_is_copied_without_loading_defaults(tmp_path:"""显式配置路径不得再次装载进程默认配置。"""pytest.fail("explicit app configuration must not load defaults")- monkeypatch.setattr(doclib_app, "get_config", reject_default_configuration)+ monkeypatch.setattr(doclib_app, "load_doclib_server_config", reject_default_configuration)try:- app = doclib_app.create_app(cfg)+ app = doclib_app.create_app(authenticated_doclib_config(cfg))snapshot = app.state.doclib_state.configassert snapshot is not cfgassert logging.getLogger("mineru").level == logging.DEBUG@@ -480,7 +481,7 @@ def test_server_status_reports_configured_socket_path(monkeypatch, tmp_path) ->monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.get("/api/v1/server/status")assert response.status_code == 200@@ -522,11 +523,11 @@ def test_doclib_app_uses_lifespan_instead_of_deprecated_event_handlers(monkeypatmonkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)- app = doclib_app.create_app(cfg)+ app = doclib_app.create_app(authenticated_doclib_config(cfg))assert app.router.on_startup == []assert app.router.on_shutdown == []- with TestClient(app) as client:+ with TestClient(app, headers=DOCLIB_AUTH_HEADERS) as client:response = client.get("/api/v1/server/status")assert response.status_code == 200@@ -599,7 +600,7 @@ def test_managed_parse_server_startup_writes_stdout_and_stderr_logs(monkeypatch,)monkeypatch.setattr("mineru.doclib.background.parse_server_health.subprocess.Popen", _popen)- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.get("/api/v1/server/status")assert response.status_code == 200@@ -653,7 +654,7 @@ def test_managed_parse_server_startup_ignores_invalid_tier_override(monkeypatch,})- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:config_response = client.get("/api/v1/configs/parse_server.local.managed_tier")status_response = client.get("/api/v1/server/status")@@ -718,7 +719,7 @@ def test_managed_parse_server_shutdown_uses_health_proc(monkeypatch, tmp_path) -)monkeypatch.setattr("mineru.doclib.background.parse_server_health.subprocess.Popen", _popen)- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:state = client.app.state.doclib_stateassert not hasattr(state, "parse_server_proc")assert client.get("/api/v1/server/status").status_code == 200@@ -753,7 +754,7 @@ def test_startup_resets_running_scans_to_failed(monkeypatch, tmp_path) -> None:monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.get("/api/v1/server/status")assert response.status_code == 200@@ -779,7 +780,7 @@ def test_telemetry_observation_route_uses_context_headers(monkeypatch, tmp_path)monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)- with TestClient(doclib_app.create_app(cfg)) as client:+ with TestClient(doclib_app.create_app(authenticated_doclib_config(cfg)), headers=DOCLIB_AUTH_HEADERS) as client:response = client.post("/api/v1/observations",headers={"X-MinerU-Telemetry-Source": "cli", "X-MinerU-Telemetry-Caller": "agent"},diff --git a/tests/unittest/test_doclib_auth.py b/tests/unittest/test_doclib_auth.pynew file mode 100644index 00000000..20cacbdd--- /dev/null+++ b/tests/unittest/test_doclib_auth.py@@ -0,0 +1,327 @@+"""验证 Doclib 持久凭证、全部 HTTP 入口和 SDK 的认证边界。"""++from __future__ import annotations++import os+import stat+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from types import SimpleNamespace++import httpx+import pytest+import yaml+from doclib_test_utils import DOCLIB_AUTH_HEADERS, TEST_DOCLIB_TOKEN, authenticated_doclib_config+from fastapi.testclient import TestClient+from pydantic import SecretStr++from mineru import config as configuration+from mineru.cli.commands import server as server_commands+from mineru.config import Config, load_config, load_doclib_server_config, update_config_file+from mineru.doclib import client as client_module+from mineru.doclib.client import DoclibClient+from mineru.doclib.endpoint import EndpointTransport, write_endpoint_file+from mineru.doclib.parse_server_state import ParseServerHealth+from mineru.doclib.server import DoclibServer+from mineru.errors import MineruError+from mineru.utils.private_file import create_private_tempfile, protect_private_file+++def config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """隔离凭证配置和进程缓存,测试不得写入开发者的实际配置目录。"""+ monkeypatch.setenv("MINERU_HOME", str(tmp_path))+ monkeypatch.delenv("MINERU_CONFIG", raising=False)+ monkeypatch.delenv("MINERU_DOCLIB_AUTH_TOKEN", raising=False)+ monkeypatch.setattr(configuration, "_loaded_config", None)+ return tmp_path / "config.yaml"++[email protected]("authorization", [None, "Bearer incorrect-token"])+ ("method", "path"),+ [+ ("GET", "/api/v1/server/status"),+ ("GET", "/api/v1/docs/by-path"),+ ("GET", "/api/v1/files/by-path"),+ ("GET", "/api/v1/search"),+ ("GET", "/api/v1/content"),+ ("POST", "/api/v1/scans"),+ ("POST", "/api/v1/docs/example/exports"),+ ("PUT", "/api/v1/configs/parse_server.local.mode"),+ ("POST", "/api/v1/server/shutdown"),+ ("GET", "/api/docs"),+ ("GET", "/api/redoc"),+ ("GET", "/api/openapi.json"),+ ],+)+def test_all_doclib_http_surfaces_require_auth_before_business_state(+ tmp_path: Path, method: str, path: str, authorization: str | None+) -> None:+ """没有业务依赖仍应直接返回 401,不能读文件、导出、改配置或关闭服务。"""+ server = DoclibServer(object(), config=authenticated_doclib_config(Config()), health=ParseServerHealth())+ output = tmp_path / "export.txt"+ headers = {"Authorization": authorization} if authorization is not None else {}+ with TestClient(server.app) as client:+ response = client.request(method, path, headers=headers, json={"output": str(output), "path": str(tmp_path)})+ assert response.status_code == 401+ assert response.headers["www-authenticate"] == "Bearer"+ assert response.json()["error"]["code"] == "invalid_doclib_token"+ assert TEST_DOCLIB_TOKEN not in response.text+ assert not output.exists()+++def test_authenticated_shutdown_and_duplicate_authorization() -> None:+ """合法凭证保留 shutdown 能力,重复授权头即使都正确也拒绝执行。"""+ calls: list[bool] = []++ def shutdown() -> None:+ """记录安全的停止钩子,测试不得发送进程信号。"""+ calls.append(True)++ server = DoclibServer(+ SimpleNamespace(shutdown=shutdown), config=authenticated_doclib_config(Config()), health=ParseServerHealth()+ )+ assert TEST_DOCLIB_TOKEN not in repr(server.app.user_middleware)+ with TestClient(server.app) as client:+ duplicate = client.post("/api/v1/server/shutdown", headers=list(DOCLIB_AUTH_HEADERS.items()) * 2)+ assert duplicate.status_code == 401+ assert calls == []+ accepted = client.post("/api/v1/server/shutdown", headers=DOCLIB_AUTH_HEADERS)+ assert accepted.status_code == 200+ assert calls == [True]+++def test_server_requires_explicit_token_for_embedded_configuration() -> None:+ """嵌入式服务没有凭证时拒绝构造,不提供隐式匿名模式。"""+ with pytest.raises(ValueError, match="requires doclib.auth.token"):+ DoclibServer(object(), config=Config(), health=ParseServerHealth())+++def test_token_is_generated_once_and_preserves_existing_configuration(config_path: Path) -> None:+ """首次启动生成凭证,后续启动和其他配置更新保持凭证与原有设置。"""+ config_path.write_text("log:\n level: debug\nmodel:\n source: auto\n", encoding="utf-8")+ first = load_doclib_server_config()+ token = first.config.doclib.auth.token.get_secret_value()+ assert len(token) >= 32+ assert first.sources[("doclib", "auth", "token")] == "file"+ before = config_path.read_bytes()+ second = load_doclib_server_config()+ assert second.config.doclib.auth.token.get_secret_value() == token+ assert config_path.read_bytes() == before+ update_config_file({"model": {"source": "modelscope"}})+ raw = yaml.safe_load(config_path.read_text())+ assert raw["log"]["level"] == "debug"+ assert raw["model"]["source"] == "modelscope"+ assert raw["doclib"]["auth"]["token"] == token+ if os.name != "nt":+ assert stat.S_IMODE(config_path.stat().st_mode) == 0o600+++def test_concurrent_initialization_uses_one_persisted_token(config_path: Path) -> None:+ """并发启动竞争同一个配置锁时只产生一个有效凭证。"""+ with ThreadPoolExecutor(max_workers=4) as pool:+ loaded = list(pool.map(lambda _: load_doclib_server_config(), range(8)))+ tokens = {item.config.doclib.auth.token.get_secret_value() for item in loaded}+ assert len(tokens) == 1+ assert yaml.safe_load(config_path.read_text())["doclib"]["auth"]["token"] in tokens+++def test_configuration_reads_do_not_generate_credentials(config_path: Path) -> None:+ """普通 SDK 和配置读取没有生成凭证或配置文件的副作用。"""+ assert load_config().config.doclib.auth.token is None+ client = DoclibClient()+ client.close()+ assert not config_path.exists()+++def test_credentials_are_redacted_and_survive_config_overrides(config_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """日志用的 repr/JSON 隐藏凭证,环境覆盖和配置复制不把掩码误当真实凭证。"""+ config_path.write_text(yaml.safe_dump({"doclib": {"auth": {"token": TEST_DOCLIB_TOKEN}}}))+ monkeypatch.setenv("MINERU_LOG_LEVEL", "debug")+ loaded = load_doclib_server_config()+ assert loaded.config.doclib.auth.token.get_secret_value() == TEST_DOCLIB_TOKEN+ assert TEST_DOCLIB_TOKEN not in repr(loaded)+ assert TEST_DOCLIB_TOKEN not in loaded.config.model_dump_json()+ assert configuration.PatchedConfig(log={"level": "warning"}).doclib.auth.token.get_secret_value() == TEST_DOCLIB_TOKEN+++def test_environment_token_is_not_written_to_configuration(config_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """显式环境凭证覆盖文件值但不回写到磁盘,避免持久化部署注入的密钥。"""+ monkeypatch.setenv("MINERU_DOCLIB_AUTH_TOKEN", TEST_DOCLIB_TOKEN)+ loaded = load_doclib_server_config()+ assert loaded.config.doclib.auth.token.get_secret_value() == TEST_DOCLIB_TOKEN+ assert loaded.sources[("doclib", "auth", "token")] == "env"+ assert not config_path.exists()+++def test_generation_fails_before_writing_secret_when_permissions_fail(+ config_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """无法保护临时文件时拒绝启动,磁盘上不留下生成的凭证。"""++ def reject_permissions(directory: str) -> tuple[int, str]:+ """模拟文件系统无法创建私密临时文件,确认目标配置尚未写入。"""+ assert Path(directory) == config_path.parent+ assert not config_path.exists()+ raise PermissionError("private permissions unavailable")++ monkeypatch.setattr(configuration, "create_private_tempfile", reject_permissions)+ with pytest.raises(PermissionError, match="private permissions unavailable"):+ load_doclib_server_config()+ assert not config_path.exists()+ assert not list(config_path.parent.glob(".config.*.tmp"))++[email protected]("field", ["base_url", "socket_path"])+def test_explicit_endpoint_never_implicitly_uses_local_token(config_path: Path, field: str) -> None:+ """指定连接地址必须同时提供凭证,不能把本机 token 自动发给其他目标。"""+ load_doclib_server_config()+ value = "http://example.test" if field == "base_url" else "/tmp/other.sock"+ with pytest.raises(ValueError, match="explicit token"):+ DoclibClient(**{field: value})+++def test_sdk_loads_new_token_after_cached_configuration_and_authenticates_probe(+ config_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """CLI 启动前的旧配置缓存不遮蔽新凭证,状态身份校验和后续业务请求都带认证头。"""+ assert configuration.get_config().doclib.auth.token is None+ loaded = load_doclib_server_config()+ token = loaded.config.doclib.auth.token.get_secret_value()+ endpoint = config_path.parent / "doclib.endpoint.json"+ write_endpoint_file(+ endpoint, pid=123, server_id="server-123", transports=[EndpointTransport(type="tcp", base_url="http://local")]+ )+ requests: list[httpx.Request] = []++ def respond(request: httpx.Request) -> httpx.Response:+ """模拟会校验真实请求头的服务,身份探测和业务读取共用相同规则。"""+ requests.append(request)+ assert request.headers["authorization"] == f"Bearer {token}"+ assert token not in str(request.url)+ return httpx.Response(+ 200,+ json={+ "running": True,+ "pid": 123,+ "server_id": "server-123",+ "socket_path": "",+ "data_dir": "",+ "sqlite_path": "",+ "log_path": "",+ },+ )++ transport = httpx.Client(transport=httpx.MockTransport(respond), base_url="http://local")+ monkeypatch.setattr(client_module, "_client_for_transport", lambda *args, **kwargs: transport)+ client = DoclibClient()+ try:+ assert client.get_server_status().server_id == "server-123"+ finally:+ client.close()+ assert len(requests) == 2+++def test_sdk_missing_token_and_401_never_fall_back_to_anonymous(config_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """缺失凭证不发请求;认证失败不尝试其他 transport,更不能删除认证头重试。"""+ endpoint = config_path.parent / "doclib.endpoint.json"+ write_endpoint_file(+ endpoint,+ pid=123,+ server_id="server-123",+ transports=[+ EndpointTransport(type="tcp", base_url="http://first"),+ EndpointTransport(type="tcp", base_url="http://second"),+ ],+ )+ requests: list[httpx.Request] = []++ def reject(request: httpx.Request) -> httpx.Response:+ """两个候选服务均拒绝凭证,记录客户端是否错误地继续或降级。"""+ requests.append(request)+ return httpx.Response(401, json={"error": {"code": "invalid_doclib_token", "message": "invalid token"}})++ def transport(item: EndpointTransport, *, timeout: int) -> httpx.Client:+ """使用真实 httpx 请求组装与响应解码,仅替换网络传输。"""+ return httpx.Client(base_url=item.base_url, transport=httpx.MockTransport(reject), timeout=timeout)++ monkeypatch.setattr(client_module, "_client_for_transport", transport)+ for token in (None, TEST_DOCLIB_TOKEN):+ client = DoclibClient(token=token)+ try:+ with pytest.raises(MineruError) as error:+ client.get_server_status()+ assert error.value.code == "invalid_doclib_token"+ finally:+ client.close()+ if token is None:+ assert requests == []+ assert len(requests) == 1+ assert requests[0].url.host == "first"+ assert requests[0].headers["authorization"] == f"Bearer {TEST_DOCLIB_TOKEN}"+++def test_token_rotation_takes_effect_for_new_server_only() -> None:+ """配置修改不改变已启动实例的认证快照,重启后的实例仅接受新凭证。"""+ cfg = authenticated_doclib_config(Config())+ first = DoclibServer(SimpleNamespace(shutdown=lambda: None), config=cfg, health=ParseServerHealth())+ new_token = "replacement-token-with-at-least-32-characters"+ cfg.doclib.auth.token = SecretStr(new_token)+ second = DoclibServer(SimpleNamespace(shutdown=lambda: None), config=cfg, health=ParseServerHealth())+ with TestClient(first.app) as old, TestClient(second.app) as new:+ assert old.post("/api/v1/server/shutdown", headers=DOCLIB_AUTH_HEADERS).status_code == 200+ assert new.post("/api/v1/server/shutdown", headers=DOCLIB_AUTH_HEADERS).status_code == 401+ assert new.post("/api/v1/server/shutdown", headers={"Authorization": f"Bearer {new_token}"}).status_code == 200+++def test_cli_does_not_report_authentication_failure_as_stopped(monkeypatch: pytest.MonkeyPatch) -> None:+ """CLI 保留认证失败,不能误报停止或另启一个争抢目录的服务。"""++ def rejected_client(*args: object, **kwargs: object) -> None:+ """模拟 SDK 发现缺失凭证时的明确认证错误。"""+ raise MineruError("invalid_doclib_token", "missing token")++ monkeypatch.setattr(client_module, "DoclibClient", rejected_client)+ with pytest.raises(MineruError, match="missing token"):+ server_commands._server_running()+++def test_private_file_permissions_are_enforced(tmp_path: Path) -> None:+ """实际文件系统落实私密权限;Windows 分支通过 DACL 设置后的读回验证。"""+ path = tmp_path / "config.yaml"+ path.write_text("private test value", encoding="utf-8")+ protect_private_file(path)+ assert path.read_text() == "private test value"+ if os.name != "nt":+ assert stat.S_IMODE(path.stat().st_mode) == 0o600+++def test_private_tempfile_is_protected_before_any_content(tmp_path: Path) -> None:+ """真实临时文件在返回可写句柄前已经落实权限,正文随后才写入。"""+ fd, filename = create_private_tempfile(str(tmp_path))+ path = Path(filename)+ try:+ assert path.read_bytes() == b""+ if os.name != "nt":+ assert stat.S_IMODE(path.stat().st_mode) == 0o600+ with os.fdopen(fd, "w", encoding="utf-8") as stream:+ stream.write("private test content")+ assert path.read_text() == "private test content"+ finally:+ path.unlink(missing_ok=True)+++def test_custom_config_path_preserves_environment_placeholders(config_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """自定义配置首次生成凭证时保留环境占位符,不误写默认配置或展开其他秘密。"""+ custom = config_path.parent / "custom.yaml"+ custom.write_text("log:\n level: ${DOCLIB_TEST_LOG_LEVEL}\n", encoding="utf-8")+ monkeypatch.setenv("MINERU_CONFIG", str(custom))+ monkeypatch.setenv("DOCLIB_TEST_LOG_LEVEL", "debug")+ loaded = load_doclib_server_config()+ assert loaded.config_file == str(custom)+ assert loaded.config.log.level == "debug"+ assert not config_path.exists()+ raw = yaml.safe_load(custom.read_text())+ assert raw["log"]["level"] == "${DOCLIB_TEST_LOG_LEVEL}"+ assert raw["doclib"]["auth"]["token"] == loaded.config.doclib.auth.token.get_secret_value()diff --git a/tests/unittest/test_doclib_endpoint.py b/tests/unittest/test_doclib_endpoint.pyindex 9d92f91f..738c5a9a 100644--- a/tests/unittest/test_doclib_endpoint.py+++ b/tests/unittest/test_doclib_endpoint.py@@ -1,5 +1,7 @@from __future__ import annotations+from doclib_test_utils import TEST_DOCLIB_TOKEN+import jsonfrom pathlib import Path@@ -155,7 +157,7 @@ def test_doclib_client_explicit_transport_bypasses_discovery(monkeypatch.setattr(client_module, "read_endpoint_file", lambda path: pytest.fail(f"unexpected discovery read: {path}"))monkeypatch.setattr(client_module, "_client_for_transport", _record_transport)- DoclibClient(endpoint_path=tmp_path / "missing.json", **override)+ DoclibClient(token=TEST_DOCLIB_TOKEN, endpoint_path=tmp_path / "missing.json", **override)assert transports == [expected_transport]@@ -188,7 +190,7 @@ def test_doclib_client_discovers_uds_then_tcp(monkeypatch: pytest.MonkeyPatch, tmonkeypatch.setattr(client_module.httpx, "HTTPTransport", _Transport)monkeypatch.setattr(client_module.httpx, "Client", _Client)- client = DoclibClient(endpoint_path=endpoint, timeout=5)+ client = DoclibClient(token=TEST_DOCLIB_TOKEN, endpoint_path=endpoint, timeout=5)client.close()assert calls[0]["base_url"] == DOCLIB_UDS_BASE_URL@@ -219,7 +221,7 @@ def test_doclib_client_does_not_infer_transports_without_valid_endpoint(monkeypatch.setattr(client_module, "_client_for_transport", _reject_inferred_transport)- client = DoclibClient(endpoint_path=endpoint)+ client = DoclibClient(token=TEST_DOCLIB_TOKEN, endpoint_path=endpoint)assert inferred_transports == []with pytest.raises(ServerNotRunningError):@@ -237,7 +239,7 @@ def test_doclib_client_lazily_validates_discovered_server_id(monkeypatch: pytestfake_client = _FakeClient("expected-server", pid=456)monkeypatch.setattr(client_module, "_client_for_transport", lambda transport, timeout: fake_client)- client = DoclibClient(endpoint_path=endpoint)+ client = DoclibClient(token=TEST_DOCLIB_TOKEN, endpoint_path=endpoint)assert fake_client.paths == []status = client.get_server_status()@@ -245,47 +247,31 @@ def test_doclib_client_lazily_validates_discovered_server_id(monkeypatch: pytestassert fake_client.paths == ["/api/v1/server/status", "/api/v1/server/status"]-def test_doclib_client_validates_legacy_endpoint_pid(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- endpoint = tmp_path / "doclib.endpoint.json"- endpoint.write_text(- json.dumps(- {- "version": 1,- "pid": 123,- "transports": [{"type": "tcp", "base_url": "http://127.0.0.1:15980"}],- }- ),- encoding="utf-8",- )- fake_client = _FakeClient("", pid=123)- monkeypatch.setattr(client_module, "_client_for_transport", lambda transport, timeout: fake_client)-- status = DoclibClient(endpoint_path=endpoint).get_server_status()-- assert status.pid == 123- assert fake_client.paths == ["/api/v1/server/status", "/api/v1/server/status"]---def test_doclib_client_rejects_legacy_endpoint_pid_mismatch(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:[email protected]("version", [1, 2])+def test_doclib_client_rejects_unauthenticated_legacy_endpoint(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, version: int+) -> None:+ """旧 endpoint 只保留诊断读取,客户端不得向旧服务发送凭证或匿名请求。"""endpoint = tmp_path / "doclib.endpoint.json"endpoint.write_text(json.dumps({- "version": 1,+ "version": version,"pid": 123,+ "server_id": "legacy-server","transports": [{"type": "tcp", "base_url": "http://127.0.0.1:15980"}],}),encoding="utf-8",)- fake_client = _FakeClient("", pid=456)+ fake_client = _FakeClient("legacy-server", pid=123)monkeypatch.setattr(client_module, "_client_for_transport", lambda transport, timeout: fake_client)with pytest.raises(MineruError) as exc_info:- DoclibClient(endpoint_path=endpoint).get_server_status()+ DoclibClient(token=TEST_DOCLIB_TOKEN, endpoint_path=endpoint).get_server_status()- assert exc_info.value.code == "server_instance_mismatch"- assert fake_client.paths == ["/api/v1/server/status"]+ assert exc_info.value.code == "doclib_upgrade_required"+ assert fake_client.paths == []def test_doclib_client_rejects_discovered_server_id_mismatch(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:@@ -299,7 +285,7 @@ def test_doclib_client_rejects_discovered_server_id_mismatch(monkeypatch: pytestfake_client = _FakeClient("other-server")monkeypatch.setattr(client_module, "_client_for_transport", lambda transport, timeout: fake_client)- client = DoclibClient(endpoint_path=endpoint)+ client = DoclibClient(token=TEST_DOCLIB_TOKEN, endpoint_path=endpoint)with pytest.raises(MineruError) as exc_info:client.get_server_status()@@ -331,7 +317,7 @@ def test_doclib_client_tries_next_transport_after_server_id_mismatch(monkeypatchmonkeypatch.setattr(client_module, "_client_for_transport", _fake_client_for_transport)- status = DoclibClient(endpoint_path=endpoint).get_server_status()+ status = DoclibClient(token=TEST_DOCLIB_TOKEN, endpoint_path=endpoint).get_server_status()assert status.server_id == "expected-server"assert fake_clients[first_url].paths == ["/api/v1/server/status"]diff --git a/tests/unittest/test_doclib_find_pagination.py b/tests/unittest/test_doclib_find_pagination.pyindex 266bc8e3..79b8fc50 100644--- a/tests/unittest/test_doclib_find_pagination.py+++ b/tests/unittest/test_doclib_find_pagination.py@@ -2,7 +2,7 @@from __future__ import annotations-from doclib_test_utils import create_doclib_server+from doclib_test_utils import DOCLIB_AUTH_HEADERS, TEST_DOCLIB_TOKEN, create_doclib_serverfrom mineru.doclib.services.ingest_svc import FileRefreshResult@@ -175,7 +175,9 @@ def test_find_http_exposes_offset_and_validates_pagination(tmp_path: Path) -> Notry:parameters = server.app.openapi()["paths"]["/api/v1/find"]["get"]["parameters"]assert next(item for item in parameters if item["name"] == "offset")["schema"]["default"] == 0- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=server.app), base_url="http://test") as client:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=server.app), base_url="http://test", headers=DOCLIB_AUTH_HEADERS+ ) as client:response = await client.get("/api/v1/find", params={"query": "report", "limit": 2, "offset": 2})assert response.status_code == 200assert response.json()["total"] == 4@@ -201,7 +203,7 @@ def test_find_sdk_transmits_offset(monkeypatch: pytest.MonkeyPatch) -> None:)monkeypatch.setattr(DoclibClient, "_send_request", send_request)- client = DoclibClient(base_url="http://test")+ client = DoclibClient(base_url="http://test", token=TEST_DOCLIB_TOKEN)try:assert client.find("report", ext="pdf", limit=10, offset=200).total == 601assert calls == [{"query": "report", "ext": "pdf", "limit": 10, "offset": 200}]diff --git a/tests/unittest/test_doclib_ingest_service.py b/tests/unittest/test_doclib_ingest_service.pyindex 3ed2c2d3..a0962438 100644--- a/tests/unittest/test_doclib_ingest_service.py+++ b/tests/unittest/test_doclib_ingest_service.py@@ -2,6 +2,8 @@from __future__ import annotations+from doclib_test_utils import DOCLIB_AUTH_HEADERS, authenticated_doclib_config+from mineru.doclib.parse_server_state import ParseServerHealthfrom mineru.doclib.services.parse_queue_svc import ParseQueueService@@ -71,8 +73,12 @@ def test_doclib_instances_share_ingest_only_with_their_own_components(tmp_path:PatchedConfig(doclib={"data_dir": str(tmp_path / name), "sqlite": {"path": str(tmp_path / name / "db.sqlite")}})for name in ("first", "second")]- with TestClient(doclib_app.create_app(configurations[0])) as first:- with TestClient(doclib_app.create_app(configurations[1])) as second:+ with TestClient(+ doclib_app.create_app(authenticated_doclib_config(configurations[0])), headers=DOCLIB_AUTH_HEADERS+ ) as first:+ with TestClient(+ doclib_app.create_app(authenticated_doclib_config(configurations[1])), headers=DOCLIB_AUTH_HEADERS+ ) as second:left, right = first.app.state.doclib_state, second.app.state.doclib_statefor state in (left, right):assert state.ingest_svc is state.parse_queue_svc.ingest_svcdiff --git a/tests/unittest/test_doclib_instance_dependencies.py b/tests/unittest/test_doclib_instance_dependencies.pyindex b859ad08..eeeeec20 100644--- a/tests/unittest/test_doclib_instance_dependencies.py+++ b/tests/unittest/test_doclib_instance_dependencies.py@@ -2,6 +2,8 @@from __future__ import annotations+from doclib_test_utils import DOCLIB_AUTH_HEADERS, authenticated_doclib_config+import asynciofrom pathlib import Pathfrom types import SimpleNamespace@@ -79,13 +81,13 @@ def test_two_apps_keep_rendering_and_health_separate(tmp_path: Path, monkeypatchcfg.render.latex_delimiters.display.right = f"RIGHT-{label}"configs.append(cfg)monkeypatch.setattr(configuration, "get_config", forbidden_default)- monkeypatch.setattr(doclib_app, "get_config", forbidden_default)+ monkeypatch.setattr(doclib_app, "load_doclib_server_config", forbidden_default)monkeypatch.setattr(probes, "get_config", forbidden_default)- first_app, second_app = [doclib_app.create_app(cfg) for cfg in configs]+ first_app, second_app = [doclib_app.create_app(authenticated_doclib_config(cfg)) for cfg in configs]configs[0].render.latex_delimiters.display.left = "changed outside application"sha = "a" * 64- with TestClient(second_app) as second:- with TestClient(first_app) as first:+ with TestClient(second_app, headers=DOCLIB_AUTH_HEADERS) as second:+ with TestClient(first_app, headers=DOCLIB_AUTH_HEADERS) as first:clients = (("A", first), ("B", second))for label, client in clients:state = client.app.state.doclib_statediff --git a/tests/unittest/test_doclib_instance_lock.py b/tests/unittest/test_doclib_instance_lock.pyindex 8849bf3b..4c1a074d 100644--- a/tests/unittest/test_doclib_instance_lock.py+++ b/tests/unittest/test_doclib_instance_lock.py@@ -1,5 +1,7 @@from __future__ import annotations+from doclib_test_utils import authenticated_doclib_config+import osimport subprocessimport sys@@ -80,7 +82,7 @@ def test_doclib_main_exits_before_startup_when_home_lock_is_held(monkeypatch: py"uds": {"path": str(socket_path)},})- monkeypatch.setattr(doclib_app, "get_config", lambda: cfg)+ monkeypatch.setattr(doclib_app, "load_doclib_server_config", lambda: cfg)monkeypatch.setattr(instance_lock, "default_endpoint_path", lambda: str(endpoint_path))with instance_lock.doclib_home_lock():@@ -128,4 +130,4 @@ def test_run_server_writes_owner_endpoint_before_binding_transport(monkeypatch:monkeypatch.setattr(doclib_app, "_bind_tcp_socket", _fail_bind)with pytest.raises(RuntimeError, match="bind failed"):- doclib_app._run_server(cfg)+ doclib_app._run_server(authenticated_doclib_config(cfg))diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.pyindex a2ebb8a5..90d35af0 100644--- a/tests/unittest/test_doclib_interface_contract.py+++ b/tests/unittest/test_doclib_interface_contract.py@@ -1,3 +1,4 @@+from doclib_test_utils import authenticated_doclib_configimport asyncioimport inspectfrom pathlib import Path@@ -193,7 +194,7 @@ def _iter_effective_routes(app: Any) -> Any:def test_interface_app_uses_doclib_server_routes(tmp_path) -> None:cfg = PatchedConfig(doclib={"log": {"dir": str(tmp_path / "logs")}})- app = create_app(cfg)+ app = create_app(authenticated_doclib_config(cfg))route_names = {getattr(route, "name", "") for route in _iter_effective_routes(app)}for method_name in AsyncDoclibInterface.__abstractmethods__:diff --git a/tests/unittest/test_doclib_lifespan.py b/tests/unittest/test_doclib_lifespan.pyindex 34aa5759..ac18b938 100644--- a/tests/unittest/test_doclib_lifespan.py+++ b/tests/unittest/test_doclib_lifespan.py@@ -2,6 +2,8 @@from __future__ import annotations+from doclib_test_utils import authenticated_doclib_config+import asynciofrom pathlib import Pathfrom types import SimpleNamespace@@ -71,7 +73,7 @@ def test_failed_startup_releases_managed_process_and_discovery("""在同一事件循环内检查清理,不依赖测试框架退出时兜底取消。"""cfg = _configuration(tmp_path)await _enable_managed(cfg)- app = doclib_app.create_app(cfg)+ app = doclib_app.create_app(authenticated_doclib_config(cfg))state = app.state.doclib_statestate.discovery_cleanup = lambda: events.append("discovery")with pytest.raises(RuntimeError, match="watch setup failed"):@@ -131,7 +133,7 @@ def test_shutdown_does_not_restart_managed_process_after_inflight_probe(monkeypatch.setattr(probes, "stop_managed_parse_server", stop)monkeypatch.setattr(probes.ParseServerHealthCheck, "_probe", probe)monkeypatch.setattr(doclib_app, "_create_background_task", schedule)- app = doclib_app.create_app(cfg)+ app = doclib_app.create_app(authenticated_doclib_config(cfg))manager = app.router.lifespan_context(app)await manager.__aenter__()state = app.state.doclib_state@@ -168,7 +170,7 @@ def test_component_stop_failure_does_not_skip_remaining_resources(tmp_path: Pathasync def scenario() -> None:"""对实际组件实例注入停止错误,观察后续资源仍被处理。"""- app = doclib_app.create_app(_configuration(tmp_path))+ app = doclib_app.create_app(authenticated_doclib_config(_configuration(tmp_path)))manager = app.router.lifespan_context(app)await manager.__aenter__()state = app.state.doclib_state@@ -208,7 +210,7 @@ def test_teardown_cancellation_waits_for_cleanup(tmp_path: Path, monkeypatch: pyasync def scenario() -> None:"""挂起一个关闭阶段并取消外部等待者,检查数据库最终仍关闭。"""- app = doclib_app.create_app(_configuration(tmp_path))+ app = doclib_app.create_app(authenticated_doclib_config(_configuration(tmp_path)))manager = app.router.lifespan_context(app)await manager.__aenter__()state = app.state.doclib_statediff --git a/tests/unittest/test_doclib_managed_tier_transition.py b/tests/unittest/test_doclib_managed_tier_transition.pyindex 96894042..c456b90e 100644--- a/tests/unittest/test_doclib_managed_tier_transition.py+++ b/tests/unittest/test_doclib_managed_tier_transition.py@@ -1,6 +1,6 @@from __future__ import annotations-from doclib_test_utils import create_doclib_server+from doclib_test_utils import DOCLIB_AUTH_HEADERS, create_doclib_serverfrom doclib_test_utils import create_health_checkfrom mineru.doclib.parse_server_state import ParseServerHealth, ProbeResult, ProbeState@@ -98,7 +98,9 @@ def test_config_api_invalidates_old_tier_before_return(tmp_path: Path, monkeypat"""经 HTTP API 保存配置,然后检查真实状态投影和路由行为。"""cfg, server, parse_svc, health, checker = await _services(tmp_path, monkeypatch)old_remote = health.remote- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=server.app), base_url="http://doclib") as client:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=server.app), base_url="http://doclib", headers=DOCLIB_AUTH_HEADERS+ ) as client:url = "/api/v1/configs/parse_server.local.managed_tier"response = await client.put(url, json={"value": "standard"}) if operation == "set" else await client.delete(url)assert response.status_code == 200diff --git a/tests/unittest/test_doclib_page_selection.py b/tests/unittest/test_doclib_page_selection.pyindex 5a285899..5cea1004 100644--- a/tests/unittest/test_doclib_page_selection.py+++ b/tests/unittest/test_doclib_page_selection.py@@ -2,7 +2,7 @@from __future__ import annotations-from doclib_test_utils import create_doclib_server+from doclib_test_utils import DOCLIB_AUTH_HEADERS, TEST_DOCLIB_TOKEN, create_doclib_serverimport asyncioimport json@@ -357,7 +357,9 @@ def test_range_http_continuation_round_trip(tmp_path: Path) -> None:"""经真实 ASGI 路由执行两页非连续选择的字符续读。"""db, server = await _cached_library(tmp_path, page_count=4)try:- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=server.app), base_url="http://test") as client:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=server.app), base_url="http://test", headers=DOCLIB_AUTH_HEADERS+ ) as client:params: dict[str, Any] = {"locator": f"{_DOC_REF}/page:1,3", "limit": 4, "no_marker": True}chunks: list[str] = []for _ in range(10):@@ -392,7 +394,7 @@ def test_read_sdk_transmits_range_after(monkeypatch: pytest.MonkeyPatch) -> Nonereturn httpx.Response(200, request=httpx.Request(method, f"http://test{path}"), json=response.model_dump(mode="json"))monkeypatch.setattr(DoclibClient, "_send_request", send_request)- client = DoclibClient(base_url="http://test")+ client = DoclibClient(base_url="http://test", token=TEST_DOCLIB_TOKEN)try:client.read_content(locator, after=after)assert captured[0]["locator"] == locatordiff --git a/tests/unittest/test_pdf_page_id.py b/tests/unittest/test_pdf_page_id.pyindex 27c4f61e..442fdf6d 100644--- a/tests/unittest/test_pdf_page_id.py+++ b/tests/unittest/test_pdf_page_id.py@@ -296,7 +296,7 @@ def test_doclib_client_validates_requests_before_transport(monkeypatch: pytest.Mfrom mineru.doclib.client import DoclibClientfrom mineru.doclib.types import DocContentExportRequest, ParseRequest, ParsingRuleRequest- client = DoclibClient(base_url="http://example.test")+ client = DoclibClient(base_url="http://example.test", token="doclib-test-token-with-at-least-32-characters")transport = Mock()monkeypatch.setattr(client, "_request_model", transport)actions = (