Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
fix(backlinks-auth): harden token file writes, including on Windows
Agrici Daniel15a6923e7550
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6bd2d3f..4252a17 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0directory, then `Move-Item -Force` / `os.replace`), and the PowerShellserialisation depth is raised from 10 to 100 so an existing `~/.claude.json`with deeply nested config round-trips intact instead of being flattened.+- `scripts/backlinks_auth.py`'s token file hardening was a no-op on Windows:+ it had no write path at all, and its permission story on POSIX (none) did+ not match `google_auth.py`'s OAuth token handling. It now shares+ `google_auth._chmod_quiet`, gains a `save_config()` that mirrors+ `google_auth.py`'s `os.open`/`os.fchmod` 0o600 write pattern, and both+ `save_config()` and `load_config()` make a best-effort `icacls` call on+ Windows to restrict `~/.config/claude-seo/backlinks-api.json` to the+ current user, since POSIX mode bits do not restrict NTFS ACLs (#290).## [2.2.6] - 2026-09-10diff --git a/SECURITY.md b/SECURITY.mdindex 92e466e..c50adcf 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -57,7 +57,7 @@ claude-seo is a research and audit toolkit that runs on a user's workstation. It- **Playwright + Chromium DNS rebinding.** Chromium does its own DNS resolution inside the renderer process. claude-seo's Python-layer DNS pin (`url_safety._pin_dns`) cannot reach it. The Playwright `route()` handler re-validates every subresource host (`make_safe_playwright_route_handler`), which closes the common case, but a true rebinding attacker can still race Chromium's resolver after our pre-flight returns. Mitigation: do not point `/seo` skills at untrusted sites with high-frequency redirects.- **IPv6-only audit targets.** The strict validator queries `family=AF_INET` for the initial resolution. Hosts with AAAA records only will surface as "DNS resolution failed". This is **fail-closed** by design — we'd rather refuse than connect to an unvalidated IPv6 endpoint. Tracked for a future patch (full dual-stack pinning, similar to the Playwright handler which already uses `AF_UNSPEC`).-- **Windows file permissions.** `os.fchmod(fd, 0o600)` is a no-op on Windows for non-ACL filesystems. Users on Windows should rely on per-user directory ACLs instead of POSIX mode bits.+- **Windows file permissions.** `os.fchmod(fd, 0o600)` is a no-op on Windows for non-ACL filesystems. Users on Windows should rely on per-user directory ACLs instead of POSIX mode bits. `scripts/backlinks_auth.py` additionally makes a best-effort `icacls <path> /inheritance:r /grant:r "%USERNAME%:F"` call after every write to (and load-time remediation of) `~/.config/claude-seo/backlinks-api.json`, restricting it to the current user on NTFS. This is best-effort only: a failure (missing `icacls`, a non-NTFS volume, a restricted shell) is logged as a warning and does not block the credential read or write, so on a failure the file's effective protection on Windows falls back to whatever the containing directory's ACLs already provide.- **RFC 6598 (100.64.0.0/10) is refused.** Cloud providers serve instance metadata in this range, so `url_safety` treats it like RFC 1918. Tailscale also allocates from it: a staging site reached over Tailscale cannot be audited with the default policy. There is no escape hatch yet; an explicit local-target allowlist is planned.diff --git a/scripts/backlinks_auth.py b/scripts/backlinks_auth.pyindex 82df06e..8313c0e 100644--- a/scripts/backlinks_auth.py+++ b/scripts/backlinks_auth.py@@ -17,6 +17,7 @@ Usage:import argparseimport jsonimport os+import subprocessimport sysfrom typing import Optional@@ -37,6 +38,17 @@ except ImportError as _import_exc:"Install with: pip install -r requirements.txt") from _import_exc+try:+ # Reuse google_auth.py's legacy-permission remediation helper instead of+ # duplicating it. It is path/mode-generic (no dependency on google_auth's+ # own TOKEN_PATH), so it is safe to share as-is.+ from google_auth import _chmod_quiet+except ImportError as _import_exc:+ raise RuntimeError(+ "scripts/google_auth.py is required alongside backlinks_auth.py. "+ "Install with: pip install -r requirements.txt"+ ) from _import_exc+CONFIG_PATH = os.path.expanduser("~/.config/claude-seo/backlinks-api.json")CACHE_DIR = os.path.expanduser("~/.cache/claude-seo/commoncrawl")@@ -57,6 +69,76 @@ SERVICE_NAMES = {}+def _restrict_to_current_user_windows(path: str) -> None:+ """Best-effort Windows ACL restriction to the current user (issue #290).++ POSIX mode bits (``chmod``/``fchmod``) are meaningless on Windows: NTFS+ access control is ACL-based, so forcing ``0o600`` there does not actually+ stop other local accounts from reading the file. ``icacls`` is the+ closest equivalent. Failures (missing binary, non-NTFS volume, a+ restricted shell) are swallowed with a logged warning rather than+ aborting the credential write or load — POSIX users never reach this+ function at all, since it is a no-op there.+ """+ if os.name != "nt":+ return+ try:+ subprocess.run(+ [+ "icacls",+ path,+ "/inheritance:r",+ "/grant:r",+ f"{os.environ.get('USERNAME', '')}:F",+ ],+ check=False,+ capture_output=True,+ timeout=10,+ )+ except Exception as exc: # best-effort hardening only; never fatal+ print(+ f"Warning: could not restrict {path} to the current user via icacls: {exc}",+ file=sys.stderr,+ )+++def _write_secure_json(path: str, data: dict) -> None:+ """Write ``data`` to ``path`` as JSON with hardened, non-world-readable permissions.++ Mirrors ``google_auth.py``'s ``_save_oauth_token`` write pattern:+ 1. Pre-chmod any existing file (closes a legacy umask=022 window).+ 2. ``os.open`` with explicit mode 0o600 (applies only to newly+ created files; ignored by the OS when the file already exists).+ 3. ``os.fchmod`` on the open fd to *force* 0o600 even if the file+ pre-existed at step 2 — defeats the os.path.exists()/os.open()+ TOCTOU race where an external writer could install a 0o644 file+ between the two calls.+ 4. On Windows, a best-effort ``icacls`` restriction, since steps 2-3+ are a no-op there (issue #290).++ The file is never world-readable, even briefly.+ """+ os.makedirs(os.path.dirname(path), exist_ok=True)+ if os.path.exists(path):+ _chmod_quiet(path, 0o600)+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC+ fd = os.open(path, flags, 0o600)+ try:+ fchmod = getattr(os, "fchmod", None)+ if fchmod is not None:+ fchmod(fd, 0o600)+ except OSError:+ pass # FS may not support fchmod (e.g. some Windows filesystems)+ with os.fdopen(fd, "w") as f:+ json.dump(data, f, indent=2)+ _restrict_to_current_user_windows(path)+++def save_config(config: dict) -> None:+ """Persist backlink API credentials to CONFIG_PATH with hardened permissions."""+ _write_secure_json(CONFIG_PATH, config)++def load_config() -> dict:"""Load configuration from config file with environment variable fallbacks.@@ -77,6 +159,10 @@ def load_config() -> dict:# Load from config fileif os.path.exists(CONFIG_PATH):+ # Remediate a world-readable legacy file in place (matches+ # google_auth._load_oauth_token), including on Windows (#290).+ _chmod_quiet(CONFIG_PATH, 0o600)+ _restrict_to_current_user_windows(CONFIG_PATH)try:with open(CONFIG_PATH, "r") as f:file_config = json.load(f)diff --git a/tests/test_backlinks_auth_hardening.py b/tests/test_backlinks_auth_hardening.pynew file mode 100644index 0000000..b91d509--- /dev/null+++ b/tests/test_backlinks_auth_hardening.py@@ -0,0 +1,150 @@+"""Token-file hardening regressions for backlinks_auth.py (issue #290).++backlinks_auth.py previously had no write path and no permission handling+at all for ~/.config/claude-seo/backlinks-api.json. It now shares+google_auth._chmod_quiet and mirrors google_auth's os.open + fchmod write+pattern, plus a best-effort Windows icacls restriction: POSIX chmod/fchmod+mode bits are a no-op on Windows (NTFS is ACL-based), so without icacls the+"hardening" does nothing there.+"""++from __future__ import annotations++import json+import os+import stat+import sys++import pytest++_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++import backlinks_auth # noqa: E402+++def _mode(path: str) -> int:+ return stat.S_IMODE(os.stat(path).st_mode)+++ os.name != "posix", reason="asserts 0o600 mode bits, which Windows does not represent"+)+def test_save_config_writes_with_0600_mode_bits(tmp_path, monkeypatch):+ config_path = tmp_path / "backlinks-api.json"+ monkeypatch.setattr(backlinks_auth, "CONFIG_PATH", str(config_path))++ backlinks_auth.save_config({"moz_api_key": "mozscape-xxxx"})++ assert config_path.exists()+ assert _mode(str(config_path)) == 0o600+ assert json.loads(config_path.read_text())["moz_api_key"] == "mozscape-xxxx"+++ os.name != "posix", reason="asserts 0o600 mode bits, which Windows does not represent"+)+def test_save_config_forces_0600_even_if_file_preexisted_world_readable(tmp_path, monkeypatch):+ config_path = tmp_path / "backlinks-api.json"+ config_path.write_text(json.dumps({"moz_api_key": "old"}))+ os.chmod(config_path, 0o644)+ monkeypatch.setattr(backlinks_auth, "CONFIG_PATH", str(config_path))++ backlinks_auth.save_config({"moz_api_key": "new"})++ assert _mode(str(config_path)) == 0o600+++ os.name != "posix", reason="asserts 0o600 mode bits, which Windows does not represent"+)+def test_load_config_remediates_legacy_world_readable_file(tmp_path, monkeypatch):+ config_path = tmp_path / "backlinks-api.json"+ config_path.write_text(json.dumps({"moz_api_key": "legacy"}))+ os.chmod(config_path, 0o644)+ monkeypatch.setattr(backlinks_auth, "CONFIG_PATH", str(config_path))+ monkeypatch.setattr(backlinks_auth, "CACHE_DIR", str(tmp_path / "cache"))++ config = backlinks_auth.load_config()++ assert config["moz_api_key"] == "legacy"+ assert _mode(str(config_path)) == 0o600+++def test_write_secure_json_creates_missing_parent_directory(tmp_path):+ nested_path = tmp_path / "nested" / "dir" / "backlinks-api.json"++ backlinks_auth._write_secure_json(str(nested_path), {"moz_api_key": "x"})++ assert nested_path.exists()+ assert json.loads(nested_path.read_text())["moz_api_key"] == "x"+++def test_restrict_to_current_user_windows_is_a_noop_on_posix(monkeypatch):+ """On the platform this suite normally runs on, the Windows branch must not fire."""+ calls = []+ monkeypatch.setattr(backlinks_auth.subprocess, "run", lambda *a, **kw: calls.append((a, kw)))+ monkeypatch.setattr(backlinks_auth.os, "name", "posix")++ backlinks_auth._restrict_to_current_user_windows("/tmp/whatever.json")++ assert calls == []+++def test_windows_branch_invokes_icacls_with_current_user(monkeypatch):+ calls = []++ def fake_run(cmd, **kwargs):+ calls.append(cmd)++ class _Result:+ returncode = 0++ return _Result()++ monkeypatch.setattr(backlinks_auth.os, "name", "nt")+ monkeypatch.setenv("USERNAME", "test-user")+ monkeypatch.setattr(backlinks_auth.subprocess, "run", fake_run)++ backlinks_auth._restrict_to_current_user_windows(r"C:\Users\test-user\.config\backlinks-api.json")++ assert len(calls) == 1+ cmd = calls[0]+ assert cmd[0] == "icacls"+ assert r"C:\Users\test-user\.config\backlinks-api.json" in cmd+ assert any("test-user:F" in part for part in cmd)+++def test_windows_branch_swallows_subprocess_failure_with_warning(monkeypatch, capsys):+ def raising_run(*args, **kwargs):+ raise FileNotFoundError("icacls not found")++ monkeypatch.setattr(backlinks_auth.os, "name", "nt")+ monkeypatch.setattr(backlinks_auth.subprocess, "run", raising_run)++ # Must not raise: a failed icacls call degrades to a warning, it never+ # aborts the credential write/load.+ backlinks_auth._restrict_to_current_user_windows(r"C:\Users\test-user\.claude-seo.json")++ captured = capsys.readouterr()+ assert "Warning" in captured.err+ assert "icacls" in captured.err+++def test_save_config_calls_windows_restriction_when_os_name_is_nt(tmp_path, monkeypatch):+ """save_config() must reach the Windows hardening step (stubbed) on 'nt'."""+ config_path = tmp_path / "backlinks-api.json"+ monkeypatch.setattr(backlinks_auth, "CONFIG_PATH", str(config_path))+ monkeypatch.setattr(backlinks_auth.os, "name", "nt")++ calls = []+ monkeypatch.setattr(+ backlinks_auth,+ "_restrict_to_current_user_windows",+ lambda path: calls.append(path),+ )++ backlinks_auth.save_config({"moz_api_key": "x"})++ assert calls == [str(config_path)]