Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix(doclib): accept Windows owner-rights directory ACLs

myhloli8c2148dcb5f4
diff --git a/mineru/utils/private_file.py b/mineru/utils/private_file.py
index 51369446..2847ad02 100644
--- a/mineru/utils/private_file.py
+++ b/mineru/utils/private_file.py
@@ -186,6 +186,9 @@ def _protect_windows_file(path: Path, *, create: bool = False) -> int | None:
raise ctypes.WinError(ctypes.get_last_error())
if sid_string(owner.value) not in trusted:
raise PermissionError("Credential configuration must have a trusted owner.")
+ # OWNER RIGHTS 代表已验证可信的目录所有者;Python 的 mkdir(mode=0o700) 会使用该 SID。
+ # 仅将它用于目录 ACE 校验,不把它本身当作可信的文件或目录所有者。
+ trusted_writers = trusted | {"S-1-3-4"}
parent_dacl = dacl_pointer(parent)
count = ctypes.c_ushort.from_address(parent_dacl + 4).value
ace = parent_dacl + 8
@@ -196,7 +199,7 @@ def _protect_windows_file(path: Path, *, create: bool = False) -> int | None:
# 忽略仅继承的 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):
+ if mask & 0x500D0156 and (ace_type != 0 or sid_string(ace + 8) not in trusted_writers):
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)"
diff --git a/tests/unittest/test_doclib_auth.py b/tests/unittest/test_doclib_auth.py
index 20cacbdd..44c277a4 100644
--- a/tests/unittest/test_doclib_auth.py
+++ b/tests/unittest/test_doclib_auth.py
@@ -127,6 +127,21 @@ def test_concurrent_initialization_uses_one_persisted_token(config_path: Path) -
assert yaml.safe_load(config_path.read_text())["doclib"]["auth"]["token"] in tokens
+def test_first_start_creates_private_home_and_persistent_token(config_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """全新 home 的 0700 目录在 Windows 使用 OWNER RIGHTS,也必须正常生成凭证。"""
+ home = config_path.parent / "new-home"
+ monkeypatch.setenv("MINERU_HOME", str(home))
+ assert not home.exists()
+ first = load_doclib_server_config()
+ path = home / "config.yaml"
+ assert path.is_file()
+ token = first.config.doclib.auth.token.get_secret_value()
+ assert len(token) >= 32
+ assert yaml.safe_load(path.read_text(encoding="utf-8"))["doclib"]["auth"]["token"] == token
+ assert load_doclib_server_config().config.doclib.auth.token.get_secret_value() == token
+ assert not list(home.glob(".config.*.tmp"))
+
+
def test_configuration_reads_do_not_generate_credentials(config_path: Path) -> None:
"""普通 SDK 和配置读取没有生成凭证或配置文件的副作用。"""
assert load_config().config.doclib.auth.token is None
diff --git a/tests/unittest/test_private_file_windows.py b/tests/unittest/test_private_file_windows.py
new file mode 100644
index 00000000..3ac9f12f
--- /dev/null
+++ b/tests/unittest/test_private_file_windows.py
@@ -0,0 +1,125 @@
+"""在真实 Windows 文件系统上验证 OWNER RIGHTS 目录和凭证文件 DACL。"""
+
+from __future__ import annotations
+
+import ctypes
+import os
+from ctypes import wintypes
+from pathlib import Path
+
+import pytest
+
+from mineru.utils.private_file import create_private_tempfile, protect_private_file
+
+pytestmark = pytest.mark.skipif(os.name != "nt", reason="Requires Windows DACL support")
+
+
+def _set_owner_rights_directory(path: Path, extra_ace: str = "") -> None:
+ """显式构造 Python mkdir(mode=0o700) 的 DACL,兼容不同 Python 版本。"""
+ security = ctypes.WinDLL("advapi32", use_last_error=True)
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ security.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
+ wintypes.LPCWSTR,
+ wintypes.DWORD,
+ ctypes.POINTER(ctypes.c_void_p),
+ ctypes.c_void_p,
+ ]
+ security.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL
+ security.SetFileSecurityW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.c_void_p]
+ security.SetFileSecurityW.restype = wintypes.BOOL
+ kernel.LocalFree.argtypes = [ctypes.c_void_p]
+ kernel.LocalFree.restype = ctypes.c_void_p
+ descriptor = ctypes.c_void_p()
+ sddl = "D:P(A;OICI;FA;;;OW)(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)" + extra_ace
+ if not security.ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, 1, ctypes.byref(descriptor), None):
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ if not security.SetFileSecurityW(str(path), 0x80000004, descriptor):
+ raise ctypes.WinError(ctypes.get_last_error())
+ finally:
+ kernel.LocalFree(descriptor)
+
+
+def _read_dacl(path: Path) -> str:
+ """通过独立的 Windows SDDL 转换读回磁盘权限。"""
+ security = ctypes.WinDLL("advapi32", use_last_error=True)
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ security.GetFileSecurityW.argtypes = [
+ wintypes.LPCWSTR,
+ wintypes.DWORD,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD),
+ ]
+ security.GetFileSecurityW.restype = wintypes.BOOL
+ security.ConvertSecurityDescriptorToStringSecurityDescriptorW.argtypes = [
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.LPWSTR),
+ ctypes.c_void_p,
+ ]
+ security.ConvertSecurityDescriptorToStringSecurityDescriptorW.restype = wintypes.BOOL
+ kernel.LocalFree.argtypes = [ctypes.c_void_p]
+ kernel.LocalFree.restype = ctypes.c_void_p
+ size = wintypes.DWORD()
+ security.GetFileSecurityW(str(path), 4, None, 0, ctypes.byref(size))
+ if not size.value:
+ raise ctypes.WinError(ctypes.get_last_error())
+ descriptor = ctypes.create_string_buffer(size.value)
+ if not security.GetFileSecurityW(str(path), 4, descriptor, size, ctypes.byref(size)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ sddl = wintypes.LPWSTR()
+ if not security.ConvertSecurityDescriptorToStringSecurityDescriptorW(descriptor, 1, 4, ctypes.byref(sddl), None):
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ return sddl.value
+ finally:
+ kernel.LocalFree(ctypes.cast(sddl, ctypes.c_void_p))
+
+
[email protected]("create", [False, True], ids=["existing-file", "new-tempfile"])
+def test_owner_rights_directory_allows_private_files(tmp_path: Path, create: bool) -> None:
+ """安全目录使用 OW 时应成功,文件仍使用显式用户 SID 且不继承目录权限。"""
+ _set_owner_rights_directory(tmp_path)
+ parent_dacl = _read_dacl(tmp_path)
+ assert "(A;OICI;FA;;;OW)" in parent_dacl
+ if create:
+ fd, filename = create_private_tempfile(str(tmp_path))
+ path = Path(filename)
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
+ assert path.read_bytes() == b""
+ protected_dacl = _read_dacl(path)
+ stream.write("private test content")
+ else:
+ path = tmp_path / "config.yaml"
+ path.write_text("private test content", encoding="utf-8")
+ protect_private_file(path)
+ protected_dacl = _read_dacl(path)
+ assert path.read_text(encoding="utf-8") == "private test content"
+ assert protected_dacl.startswith("D:P(A;;FA;;;S-1-")
+ assert protected_dacl.endswith("(A;;FA;;;SY)")
+ assert protected_dacl.count("(") == 2
+ protect_private_file(path)
+ assert _read_dacl(path) == protected_dacl
+ assert _read_dacl(tmp_path) == parent_dacl
+
+
[email protected]("create", [False, True], ids=["existing-file", "new-tempfile"])
[email protected]("trustee", ["WD", "AU", "BU"], ids=["everyone", "authenticated-users", "users"])
+def test_owner_rights_does_not_allow_other_directory_writers(tmp_path: Path, create: bool, trustee: str) -> None:
+ """即使存在 OW,其他普通账户可写的父目录仍必须拒绝。"""
+ _set_owner_rights_directory(tmp_path, f"(A;OICI;FA;;;{trustee})")
+ path = tmp_path / "config.yaml"
+ path.write_text("private test content", encoding="utf-8")
+ original_dacl = _read_dacl(path)
+ with pytest.raises(PermissionError, match="directory must not be writable by other users"):
+ if create:
+ fd, filename = create_private_tempfile(str(tmp_path))
+ os.close(fd)
+ Path(filename).unlink()
+ else:
+ protect_private_file(path)
+ assert _read_dacl(path) == original_dacl
+ assert path.read_text(encoding="utf-8") == "private test content"
+ assert not list(tmp_path.glob(".config.*.tmp"))