Skip to content

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

fix: restrict Windows config.toml ACL to the current user

Frankie-Xuf501d5366be2
diff --git a/hyperextract/cli/config.py b/hyperextract/cli/config.py
index 3cfdff6..b4a1ce7 100644
--- a/hyperextract/cli/config.py
+++ b/hyperextract/cli/config.py
@@ -3,6 +3,7 @@
import json
import logging
import os
+import subprocess
import tomllib
from dataclasses import dataclass
from pathlib import Path
@@ -76,16 +77,86 @@ def _env_api_key(provider: str) -> str:
def _restrict_config_permissions(path: Path) -> None:
- """Set *path* to owner read/write only (0600). Best-effort on Windows."""
+ """Set *path* to owner read/write only. POSIX 0600; Windows owner DACL."""
+ if os.name == "nt":
+ _restrict_windows_acl(path)
+ return
try:
os.chmod(path, _CONFIG_FILE_MODE)
except OSError:
pass
+def _icacls(*args: str) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ ["icacls", *args],
+ capture_output=True,
+ check=False,
+ )
+
+
+def _icacls_text(result: subprocess.CompletedProcess) -> str:
+ """Decode icacls output; Windows uses the ANSI code page, not UTF-8."""
+
+ def _decode(data: bytes | None) -> str:
+ if not data:
+ return ""
+ if os.name == "nt":
+ return data.decode("mbcs", errors="replace")
+ return data.decode("utf-8", errors="replace")
+
+ return f"{_decode(result.stdout)}\n{_decode(result.stderr)}"
+
+
+def _windows_account() -> str:
+ user = os.environ.get("USERNAME", "").strip()
+ domain = os.environ.get("USERDOMAIN", "").strip()
+ if user and domain and domain.upper() != user.upper():
+ return f"{domain}\\{user}"
+ return user
+
+
+def _restrict_windows_acl(path: Path) -> None:
+ """Grant the current user FullControl; drop Everyone/Users inherited read."""
+ account = _windows_account()
+ if not account:
+ return
+ target = str(path)
+ # Grant first so stripping inheritance cannot lock the file out.
+ _icacls(target, "/grant:r", f"{account}:(F)")
+ _icacls(target, "/inheritance:r")
+ for principal in (
+ "Everyone",
+ "*S-1-1-0",
+ "Users",
+ "BUILTIN\\Users",
+ "Authenticated Users",
+ ):
+ _icacls(target, "/remove:g", principal)
+
+
+def _windows_acl_everyone_readable(path: Path) -> bool:
+ """True when icacls reports Everyone with a read-class right."""
+ text = _icacls_text(_icacls(str(path)))
+ for line in text.splitlines():
+ stripped = line.strip()
+ if "Everyone:" not in stripped and "S-1-1-0" not in stripped:
+ continue
+ if ":(" in stripped:
+ return True
+ return False
+
+
def _warn_if_insecure_permissions(path: Path) -> None:
- """Warn when group or others can read the config file. Unix-only."""
+ """Warn when group, others, or Everyone can read the config file."""
if os.name == "nt":
+ if _windows_acl_everyone_readable(path):
+ logger.warning(
+ "Config file %s is readable by Everyone. "
+ "The next `he config` save will restrict the ACL to the "
+ "current user.",
+ path,
+ )
return
try:
mode = path.stat().st_mode
diff --git a/tests/cli/test_config.py b/tests/cli/test_config.py
index c8df0d4..3690cfe 100644
--- a/tests/cli/test_config.py
+++ b/tests/cli/test_config.py
@@ -2,10 +2,11 @@
import logging
import os
+import subprocess
import pytest
-from hyperextract.cli.config import ConfigManager
+from hyperextract.cli.config import ConfigManager, _icacls, _icacls_text
# Fixture-only dummy; never a real key from the environment.
_FAKE_API_KEY = "sk-test"
@@ -14,6 +15,10 @@ _POSIX_ONLY = pytest.mark.skipif(
os.name == "nt",
reason="POSIX file modes are not enforced on Windows",
)
+_WINDOWS_ONLY = pytest.mark.skipif(
+ os.name != "nt",
+ reason="Windows ACL checks use icacls",
+)
def test_save_creates_custom_parent_dir(tmp_path):
@@ -72,3 +77,63 @@ def test_load_warns_when_config_is_group_or_world_readable(tmp_path, caplog):
assert caplog.records
assert any("0600" in record.getMessage() for record in caplog.records)
assert _FAKE_API_KEY not in caplog.text
+
+
+def _acl_text(path) -> str:
+ return _icacls_text(_icacls(str(path)))
+
+
+@_WINDOWS_ONLY
+def test_save_sets_owner_only_acl(tmp_path):
+ cfg_path = tmp_path / "config.toml"
+ mgr = ConfigManager(cfg_path)
+ mgr.set_llm(provider="openai", model="gpt-4o-mini", api_key=_FAKE_API_KEY)
+
+ text = _acl_text(cfg_path)
+ assert "Everyone:(R)" not in text
+ assert "Everyone:" not in text
+
+
+@_WINDOWS_ONLY
+def test_save_removes_everyone_read(tmp_path):
+ cfg_path = tmp_path / "config.toml"
+ cfg_path.write_text(
+ '[llm]\nprovider = "openai"\nmodel = "gpt-4o-mini"\n'
+ f'api_key = "{_FAKE_API_KEY}"\nbase_url = ""\n',
+ encoding="utf-8",
+ )
+ subprocess.run(
+ ["icacls", str(cfg_path), "/grant", "Everyone:(R)"],
+ check=True,
+ capture_output=True,
+ )
+ assert "Everyone:" in _acl_text(cfg_path)
+
+ mgr = ConfigManager(cfg_path)
+ mgr.set_llm(provider="openai", api_key=_FAKE_API_KEY)
+
+ text = _acl_text(cfg_path)
+ assert "Everyone:(R)" not in text
+ assert "Everyone:" not in text
+
+
+@_WINDOWS_ONLY
+def test_load_warns_when_everyone_can_read(tmp_path, caplog):
+ cfg_path = tmp_path / "config.toml"
+ cfg_path.write_text(
+ '[llm]\nprovider = "openai"\nmodel = "gpt-4o-mini"\n'
+ f'api_key = "{_FAKE_API_KEY}"\nbase_url = ""\n',
+ encoding="utf-8",
+ )
+ subprocess.run(
+ ["icacls", str(cfg_path), "/grant", "Everyone:(R)"],
+ check=True,
+ capture_output=True,
+ )
+
+ with caplog.at_level(logging.WARNING, logger="hyperextract.cli.config"):
+ ConfigManager(cfg_path)
+
+ assert caplog.records
+ assert any("Everyone" in record.getMessage() for record in caplog.records)
+ assert _FAKE_API_KEY not in caplog.text