AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(xurl): recognize the ~/.xurl/auth.yml directory layout (#1027)
Som Samantray63b27c6d41cd
diff --git a/changelog.d/978.fixed.md b/changelog.d/978.fixed.mdnew file mode 100644index 00000000..76946029--- /dev/null+++ b/changelog.d/978.fixed.md@@ -0,0 +1 @@+`--diagnose` and doctor no longer report xurl as unauthenticated when credentials live in the current `~/.xurl/auth.yml` directory layout; the legacy flat `~/.xurl` file is still recognized.diff --git a/docs/residual-review-findings/fix-xurl-x978.md b/docs/residual-review-findings/fix-xurl-x978.mdnew file mode 100644index 00000000..e33ca0d3--- /dev/null+++ b/docs/residual-review-findings/fix-xurl-x978.md@@ -0,0 +1,28 @@+## Residual Review Findings++Source run: `ce-code-review` on branch `fix/xurl-x978` (issue #978), plan `docs/plans/2026-08-20-fix-xurl-x978-plan.md`. Run dirs: `20260820-220120-767b63a3` (round 1), `20260820-221941-c2d05f7f` (round 2).++### Round 1 findings (P1 fixed, P3s applied)++- **P1 — `stored_auth_status()` masked permission-denied store as AUTH_MISSING** (`skills/last30days/scripts/lib/xurl_x.py`). `pathlib`'s `is_file()`/`is_dir()` swallow `OSError` into `False`, so a chmod-000 `~/.xurl/auth.yml` reported "no token store" instead of the typed `AUTH_ERROR`. Fixed with stat-based probes (`_is_file`/`_is_dir`) that propagate `EACCES`; `FileNotFoundError` stays absent → MISSING. Commits `d1ef34e`, `98795ae`.+- **P3 — legacy flat file precedence** (`xurl_x.py`): candidate order now prefers the live `auth.yml` over a stale flat file when both are physically possible. Covered by `test_canonical_path_preferred_when_both_layouts_exist`.+- **P3 — AUTH_MISSING detail naming** (`xurl_x.py`): `token_store_path()` is re-invoked in the detail string; cosmetic (identical value in scope). Not changed — behavior identical, one redundant `Path.home()` call in a rare error path.+- **P3 — test stub fallback** (`xurl_x.py`): the `except (AttributeError, TypeError)` fallback for path stubs was made explicit and now routes correctly; covered by existing `_UnreadableStore`/`_BrokenFile` tests.++### Round 2 findings (P3, advisory)++- **P3 — dangling-symlink docstring overclaim** (`xurl_x.py:118-138`): `_is_file` returns `False` (MISSING) for a dangling symlink since `stat()` raises `FileNotFoundError` on a missing target. Docstring updated to scope the broken-store claim to permission failures; a dangling target is a missing target and stays MISSING.+- **P3 — stat-PermissionError on candidate scan untested** (testing reviewer): added `test_permission_denied_parent_stat_reports_error_not_missing` (chmod-000 parent dir → AUTH_ERROR) and hardened `test_permission_denied_read_reports_error_not_missing` with a root-euid guard.+- **P3 — "both layouts exist" test naming** (testing reviewer): the two layouts cannot physically coexist (`~/.xurl` is either a file or a directory), so the test pins canonical-path selection rather than a file-vs-dir race. Left as-is with accurate comment.+- **P3 — redundant `token_store_path()` in MISSING detail** (reliability reviewer, advisory): cosmetic; no behavior change.++### Not filed as tracker tickets++All remaining items are P3 advisory/cosmetic with no user-visible impact; the two with real regression value were applied as tests. No GitHub issues filed.++### Verification++- `uv run pytest tests/test_xurl_x.py` → 54 passed+- `uv run pytest tests/test_env_v3.py tests/test_backend_descriptors.py tests/test_diagnose_compat.py` → 132 passed+- `uv run pytest -q --ignore=tests/test_network.py` → full suite passed+- `git diff --check` cleandiff --git a/skills/last30days/scripts/lib/xurl_x.py b/skills/last30days/scripts/lib/xurl_x.pyindex 4b46ca0b..7a48eaa9 100644--- a/skills/last30days/scripts/lib/xurl_x.py+++ b/skills/last30days/scripts/lib/xurl_x.py@@ -14,6 +14,7 @@ Priority: xAI API > Bird/GraphQL > xurl > web-only fallbackimport jsonimport reimport shutil+import statimport subprocessfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple@@ -109,9 +110,54 @@ _TOKEN_STORE_MARKERS = ()+def _is_file(path: Path) -> bool:+ """True when *path* is a regular file; raise on an unreadable stat.++ ``pathlib.Path.is_file()`` swallows ``OSError`` into ``False``, which+ would silently misreport a permission-denied (EACCES) store as absent.+ Probing via ``stat`` keeps the typed ``AUTH_ERROR`` path reachable for+ real stat failures. A missing path (``FileNotFoundError``) returns False —+ absence is a normal state (this also covers a dangling symlink whose+ target is gone). Path stubs without ``stat``/``is_file`` support (test+ doubles) fall back to their own behavior.+ """+ try:+ return stat.S_ISREG(path.stat().st_mode)+ except FileNotFoundError:+ return False+ except (AttributeError, TypeError):+ try:+ return bool(path.is_file())+ except AttributeError:+ return False+++def _is_dir(path: Path) -> bool:+ """True when *path* is a directory; raise on an unreadable stat.++ Same rationale as :func:`_is_file` — pathlib's ``is_dir()`` hides+ ``OSError``, so a permission-denied parent would read as a missing store.+ """+ try:+ return stat.S_ISDIR(path.stat().st_mode)+ except FileNotFoundError:+ return False+ except (AttributeError, TypeError):+ try:+ return bool(path.is_dir())+ except AttributeError:+ return False++def token_store_path() -> Path:- """xurl's on-disk OAuth token store (~/.xurl)."""- return Path.home() / ".xurl"+ """xurl's on-disk OAuth token store (~/.xurl/auth.yml).++ Current xurl (>=1.1) stores credentials in a YAML file at+ ``~/.xurl/auth.yml``; ``~/.xurl`` itself is a directory. Legacy+ releases wrote a flat file at ``~/.xurl``. ``stored_auth_status()``+ resolves both layouts; this returns the canonical current path.+ """+ return Path.home() / ".xurl" / "auth.yml"def stored_auth_status() -> Tuple[str, str]:@@ -123,10 +169,42 @@ def stored_auth_status() -> Tuple[str, str]:AUTH_ERROR (store exists but cannot be read — surfaced as a typederror, not as "unconfigured")."""+ # Resolve the actual credential file across layouts. Current xurl keeps+ # ~/.xurl/auth.yml inside the ~/.xurl directory; legacy installs wrote a+ # flat ~/.xurl file. Honor whatever token_store_path() resolves to and+ # check both shapes so a valid directory layout is never misread as a+ # missing token store. Path stubs that cannot combine (e.g. an unreadable+ # store stub without / support) still reach the typed error path below.path = token_store_path()try:- if not path.is_file():- return AUTH_MISSING, f"no token store at {path}"+ base = path.parent if path.name == "auth.yml" else path+ except (AttributeError, TypeError):+ # A path stub with no parent/name support: treat it as the file itself.+ base = path+ try:+ # Use stat rather than is_file()/is_dir(): pathlib swallows OSError+ # into False, which would silently turn a permission-denied store into+ # "no token store" instead of the typed AUTH_ERROR.+ candidates = [base / "auth.yml", base] if _is_dir(base) else [base, base / "auth.yml"]+ except (TypeError, AttributeError):+ # A path stub that cannot combine (no __truediv__): the path itself is+ # the only candidate.+ candidates = [path]+ except OSError as exc:+ return (+ AUTH_ERROR,+ f"token store {base} unreadable: {type(exc).__name__}: {exc}",+ )+ try:+ path = next(c for c in candidates if _is_file(c))+ except StopIteration:+ return AUTH_MISSING, f"no token store at {token_store_path()}"+ except OSError as exc:+ return (+ AUTH_ERROR,+ f"token store {base} unreadable: {type(exc).__name__}: {exc}",+ )+ try:content = path.read_text(encoding="utf-8", errors="replace")except OSError as exc:return (diff --git a/tests/test_diagnose_compat.py b/tests/test_diagnose_compat.pyindex 09737466..ce9221ab 100644--- a/tests/test_diagnose_compat.py+++ b/tests/test_diagnose_compat.py@@ -30,11 +30,14 @@ otherwise stay frozen; re-record only when a committed baseline legitimatelychanges them."""+import contextlibimport ioimport jsonimport sys+import tempfileimport unittestfrom contextlib import redirect_stderr, redirect_stdout+from pathlib import Pathfrom unittest import mockimport last30days as cli@@ -127,27 +130,46 @@ FAKE_KEYED_CONFIG = {}-def _run_cli(argv: list[str], config: dict) -> tuple[int, str]:- """Run cli.main() in-process with a controlled config; return (rc, stdout)."""- bird_status = {- "installed": False,- "authenticated": False,- "username": None,- "can_install": True,- }- with mock.patch.object(cli.env, "get_config", return_value=dict(config)), \- mock.patch("lib.bird_x.get_bird_status", return_value=bird_status), \- mock.patch("lib.bird_x.is_bird_installed", return_value=False), \- mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None), \- mock.patch(- "lib.xurl_x.is_available",- side_effect=AssertionError(- "--diagnose/--preflight are safe paths and must not run the "- "live `xurl whoami` network check"- ),- ), \- mock.patch("lib.xurl_x.has_stored_auth", return_value=False), \- mock.patch.object(sys, "argv", ["last30days.py"] + argv):+_BIRD_STATUS_KEYLESS = {+ "installed": False,+ "authenticated": False,+ "username": None,+ "can_install": True,+}+++def _run_cli(+ argv: list[str],+ config: dict,+ *,+ extra_patches: tuple = (),+ patch_has_stored_auth: bool = True,+) -> tuple[int, str]:+ """Run cli.main() in-process with a controlled config; return (rc, stdout).++ `extra_patches` are additional `mock.patch(...)` context managers layered+ on top of the common safe-path mock stack (e.g. to fake xurl's on-disk+ token store instead of stubbing `has_stored_auth` directly).+ `patch_has_stored_auth=False` omits the default `has_stored_auth` stub so+ a caller-supplied patch (or the real function) can take its place.+ """+ with contextlib.ExitStack() as stack:+ stack.enter_context(mock.patch.object(cli.env, "get_config", return_value=dict(config)))+ stack.enter_context(mock.patch("lib.bird_x.get_bird_status", return_value=_BIRD_STATUS_KEYLESS))+ stack.enter_context(mock.patch("lib.bird_x.is_bird_installed", return_value=False))+ stack.enter_context(mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None))+ stack.enter_context(mock.patch(+ "lib.xurl_x.is_available",+ side_effect=AssertionError(+ "--diagnose/--preflight are safe paths and must not run the "+ "live `xurl whoami` network check"+ ),+ ))+ if patch_has_stored_auth:+ stack.enter_context(mock.patch("lib.xurl_x.has_stored_auth", return_value=False))+ for patch in extra_patches:+ stack.enter_context(patch)+ stack.enter_context(mock.patch.object(sys, "argv", ["last30days.py"] + argv))stdout = io.StringIO()stderr = io.StringIO()with redirect_stdout(stdout), redirect_stderr(stderr):@@ -219,6 +241,85 @@ class DiagnoseShapeCompat(unittest.TestCase):self.assertIn(free, sources)+class DiagnoseXurlAuthWiring(unittest.TestCase):+ """Regression for #978 / PR #1027: prove `--diagnose`'s `x_backend` and+ `available_sources` reflect xurl_x.stored_auth_status()'s corrected+ directory-layout detection end-to-end through the real CLI entrypoint,+ not just at the `has_stored_auth()` unit level (test_xurl_x.py) or a+ mocked wiring level (test_env_v3.py). Neither of those proves the two+ compose correctly through `pipeline.diagnose()` into the exact+ `available_sources` array SKILL.md reads.++ Scope: this covers the AUTH_OK / AUTH_MISSING distinction only.+ `has_stored_auth()` collapses AUTH_ERROR (permission-denied store) to+ the same `False` as AUTH_MISSING, so a permission-denied store is not+ separately observable through `--diagnose`/`available_sources` -- only+ `doctor`'s `backends._probe_xurl` surfaces the typed AUTH_ERROR. Not+ covered here; that distinction is doctor-only by the current design."""++ def setUp(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.fake_home = Path(self._tmp.name)+ self.store = self.fake_home / ".xurl"+ boom = mock.patch(+ "subprocess.run",+ side_effect=AssertionError(+ "--diagnose is a safe path and must not spawn any subprocess"+ ),+ )+ boom.start()+ self.addCleanup(boom.stop)++ def _diagnose_with_store(self, auth_yml_content: str | None) -> dict:+ """Run `--diagnose` with `Path.home()` pointed at a fake home dir+ holding a real `~/.xurl/auth.yml` (current directory layout);+ `auth_yml_content=None` leaves no store at all. `Path.home()` -- not+ `token_store_path()` -- is what's faked, so this exercises+ `token_store_path()`'s own directory-layout logic instead of+ bypassing it; a pre-fix `token_store_path()` returning the bare+ `~/.xurl` directory would make this fail exactly as it did for #978.++ `Path.home` is a shared class attribute, so this patch also redirects+ any other lib module's `Path.home()` call for the duration of the+ CLI invocation (e.g. `brightdata.gate_status`). That's inert today:+ the paired `shutil.which` patch below makes `brightdata.is_installed()`+ return False, short-circuiting `has_credentials()` before it would+ reach `Path.home()`. If that short-circuit is ever removed, re-check+ whether another module's home-relative lookup needs isolating too."""+ if auth_yml_content is not None:+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text(auth_yml_content, encoding="utf-8")+ rc, out = _run_cli(+ ["--diagnose"],+ FAKE_KEYLESS_CONFIG,+ patch_has_stored_auth=False,+ extra_patches=(+ mock.patch("lib.xurl_x.Path.home", return_value=self.fake_home),+ mock.patch(+ "lib.xurl_x.shutil.which",+ side_effect=lambda name: "/usr/local/bin/xurl" if name == "xurl" else None,+ ),+ ),+ )+ self.assertEqual(0, rc)+ return json.loads(out)++ def test_new_layout_auth_yml_makes_xurl_the_reported_backend(self):+ payload = self._diagnose_with_store("access_token: dummy-not-real\n")+ self.assertEqual("xurl", payload["x_backend"])+ self.assertIn("x", payload["available_sources"])++ def test_no_store_leaves_xurl_unreported(self):+ payload = self._diagnose_with_store(None)+ self.assertNotEqual("xurl", payload["x_backend"])+ self.assertFalse(+ payload["x_pending_browser_auth"],+ "no browser-cookie config in this test, so pending-auth must be False",+ )+ self.assertNotIn("x", payload["available_sources"])++class PreflightShapeCompat(unittest.TestCase):"""Freeze the --preflight JSON shape (snapshot: pre-v3.9.0 baseline)."""diff --git a/tests/test_xurl_x.py b/tests/test_xurl_x.pyindex 931b1201..a86eca55 100644--- a/tests/test_xurl_x.py+++ b/tests/test_xurl_x.py@@ -127,6 +127,179 @@ class TestStoredAuth(unittest.TestCase):self.assertEqual(xurl_x.AUTH_OK, status)self.assertIn(str(self.store), detail)+ def test_directory_layout_auth_yml_with_token_is_ok(self):+ # Current xurl (>=1.1) stores credentials at ~/.xurl/auth.yml inside+ # the ~/.xurl directory. Regression for #978: this was misread as+ # "no token store" because the directory itself fails is_file().+ self.store.mkdir(exist_ok=True)+ auth_yml = self.store / "auth.yml"+ auth_yml.write_text(+ "apps:\n app:\n oauth2_tokens:\n me:\n oauth2:\n"+ " access_token: dummy-not-real\n",+ encoding="utf-8",+ )+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_OK, status)+ self.assertIn("auth.yml", detail)++ def test_directory_layout_empty_auth_yml_is_missing(self):+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text("", encoding="utf-8")+ status, _ = self._status()+ self.assertEqual(xurl_x.AUTH_MISSING, status)++ def test_directory_layout_without_auth_yml_is_missing(self):+ self.store.mkdir(exist_ok=True)+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_MISSING, status)+ self.assertIn("no token store", detail)++ def test_legacy_flat_file_layout_is_ok(self):+ # When token_store_path() returns the canonical ~/.xurl/auth.yml but+ # the legacy flat ~/.xurl file is what exists, still report OK.+ self.store.write_text(+ json.dumps({"bearer_token": {"bearer": "dummy-not-real"}}),+ encoding="utf-8",+ )+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_OK, status)+ self.assertIn(str(self.store), detail)++ def test_directory_layout_unreadable_auth_yml_is_error(self):+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text(+ "access_token: dummy-not-real\n", encoding="utf-8"+ )+ class _BrokenFile:+ def __init__(self, path):+ self._path = path++ def is_file(self):+ return True++ def read_text(self, *args, **kwargs):+ raise PermissionError(13, "Permission denied")++ def __str__(self):+ return str(self._path)++ status, detail = self._status(+ path=_BrokenFile(self.store / "auth.yml")+ )+ self.assertEqual(xurl_x.AUTH_ERROR, status)+ self.assertIn("PermissionError", detail)++ def test_permission_denied_read_reports_error_not_missing(self):+ # Regression: a store that exists but cannot be read must report the+ # typed AUTH_ERROR, not AUTH_MISSING. stat() on a chmod-000 file still+ # succeeds on POSIX; read_text() is what raises PermissionError.+ import os++ if hasattr(os, "geteuid") and os.geteuid() == 0:+ self.skipTest("root bypasses permission checks")+ self.store.mkdir(exist_ok=True)+ auth_yml = self.store / "auth.yml"+ auth_yml.write_text("access_token: dummy-not-real\n", encoding="utf-8")+ auth_yml.chmod(0)+ try:+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_ERROR, status)+ self.assertIn("PermissionError", detail)+ finally:+ auth_yml.chmod(0o600)++ def test_permission_denied_parent_stat_reports_error_not_missing(self):+ # Regression: a store inside a non-searchable directory must report+ # AUTH_ERROR, not AUTH_MISSING. stat() on the candidate inside a+ # chmod-000 parent raises PermissionError, which must not be swallowed+ # into "no token store" the way pathlib's is_file() would.+ import os++ if hasattr(os, "geteuid") and os.geteuid() == 0:+ self.skipTest("root bypasses permission checks")+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text(+ "access_token: dummy-not-real\n", encoding="utf-8"+ )+ self.store.chmod(0)+ try:+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_ERROR, status)+ self.assertIn("PermissionError", detail)+ finally:+ self.store.chmod(0o700)++ def test_permission_denied_grandparent_stat_reports_error_not_missing(self):+ # Regression: distinct from the parent-chmod case above, which denies+ # traversal INTO the store (raising on the per-candidate _is_file scan).+ # Chmod-000 on the store's own PARENT directory instead blocks stat()+ # on the store path itself, raising during the _is_dir(base) call that+ # builds the candidate list -- a separate except-OSError branch that+ # the parent-chmod case never reaches.+ import os++ if hasattr(os, "geteuid") and os.geteuid() == 0:+ self.skipTest("root bypasses permission checks")+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text(+ "access_token: dummy-not-real\n", encoding="utf-8"+ )+ grandparent = self.store.parent+ grandparent.chmod(0)+ try:+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_ERROR, status)+ self.assertIn("PermissionError", detail)+ finally:+ grandparent.chmod(0o700)++ def test_directory_layout_has_stored_auth_with_binary(self):+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text(+ "access_token: dummy-not-real\n", encoding="utf-8"+ )+ with mock.patch("lib.xurl_x.token_store_path", return_value=self.store), \+ mock.patch("lib.xurl_x.shutil.which", return_value="/usr/local/bin/xurl"):+ self.assertTrue(xurl_x.has_stored_auth())++ def test_directory_layout_no_subprocess_spawned(self):+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text(+ "access_token: dummy-not-real\n", encoding="utf-8"+ )+ with mock.patch(+ "subprocess.run",+ side_effect=AssertionError("local auth evidence must not spawn a subprocess"),+ ):+ status, _ = self._status()+ self.assertEqual(xurl_x.AUTH_OK, status)++ def test_walk_up_canonical_path_finds_legacy_flat_file(self):+ # token_store_path() returns the canonical ~/.xurl/auth.yml, but only+ # the legacy flat ~/.xurl file exists. The parent-walk must find it.+ self.store.write_text(+ json.dumps({"bearer_token": {"bearer": "dummy-not-real"}}),+ encoding="utf-8",+ )+ canonical = self.store / "auth.yml"+ with mock.patch("lib.xurl_x.token_store_path", return_value=canonical):+ status, detail = xurl_x.stored_auth_status()+ self.assertEqual(xurl_x.AUTH_OK, status)+ self.assertIn(str(self.store), detail)++ def test_canonical_path_preferred_when_both_layouts_exist(self):+ # A stale legacy flat ~/.xurl must never shadow the live auth.yml.+ self.store.mkdir(exist_ok=True)+ (self.store / "auth.yml").write_text(+ "oauth2_tokens:\n me:\n oauth2:\n access_token: live\n",+ encoding="utf-8",+ )+ canonical = self.store / "auth.yml"+ with mock.patch("lib.xurl_x.token_store_path", return_value=canonical):+ status, detail = xurl_x.stored_auth_status()+ self.assertEqual(xurl_x.AUTH_OK, status)+ self.assertIn("auth.yml", detail)+def test_legacy_json_store_with_bearer_token_is_ok(self):self.store.write_text(json.dumps({"bearer_token": {"bearer": "dummy-not-real"}}),@@ -176,8 +349,8 @@ class TestStoredAuth(unittest.TestCase):mock.patch("lib.xurl_x.shutil.which", return_value="/usr/local/bin/xurl"):self.assertFalse(xurl_x.has_stored_auth())- def test_default_store_path_is_home_dot_xurl(self):- self.assertEqual(Path.home() / ".xurl", xurl_x.token_store_path())+ def test_default_store_path_is_home_dot_xurl_auth_yml(self):+ self.assertEqual(Path.home() / ".xurl" / "auth.yml", xurl_x.token_store_path())# ---------------------------------------------------------------------------# search_x