From 11857d8ab0e90f8add0d9fe6abf7d623f830bf53 Mon Sep 17 00:00:00 2001 From: Lucius Date: Fri, 27 Nov 2026 18:09:57 +0800 Subject: [PATCH 1/2] fix: restrict and atomically replace local caches Adapt the cache-permission portion of public-clis/twitter-cli#102. Also migrate legacy modes on read. --- CHANGELOG.md | 2 ++ tests/test_cache.py | 25 +++++++++++++++++++++++ twitter_cli/cache.py | 46 +++++++++++++++++++++++++++++++++++++------ twitter_cli/client.py | 12 ++++------- 4 files changed, 71 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 564a91a..7968225 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,5 +20,7 @@ This file records user-visible changes maintained on the `stable` branch from ### Fixed +- Restrict local cache files and their directory to the current user on POSIX. + - Resume a timeline from the last returned tweet when X sends an oversized page. - Require curl_cffi 0.15.0 or later for GHSA-qw2m-4pqf-rmpp. diff --git a/tests/test_cache.py b/tests/test_cache.py index 26a2314..164ccac 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -3,6 +3,10 @@ from __future__ import annotations import json +import os +import stat + +import pytest import time @@ -99,3 +103,24 @@ def test_wrong_structure(self, tmp_path, monkeypatch) -> None: tweet_id, size = resolve_cached_tweet(1) assert tweet_id is None assert size == 0 + +@pytest.mark.skipif(os.name != "posix", reason="POSIX mode bits") +def test_migrate_and_replace_private_cache(tmp_path): + from twitter_cli.cache import read_cache_json, write_cache_json + + directory = tmp_path / ".twitter-cli" + directory.mkdir() + directory.chmod(0o755) + path = directory / "transaction_cache.json" + path.write_text('{"generation": 1}') + path.chmod(0o644) + assert read_cache_json(path) == {"generation": 1} + assert stat.S_IMODE(directory.stat().st_mode) == 0o700 + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + with pytest.raises(TypeError): + write_cache_json(path, {"invalid": object()}) + assert read_cache_json(path) == {"generation": 1} + write_cache_json(path, {"generation": 2}) + assert read_cache_json(path) == {"generation": 2} + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert list(directory.iterdir()) == [path] diff --git a/twitter_cli/cache.py b/twitter_cli/cache.py index fb1cad5..c7804c1 100644 --- a/twitter_cli/cache.py +++ b/twitter_cli/cache.py @@ -4,9 +4,12 @@ import json import logging +import os +import stat +import tempfile import time from pathlib import Path -from typing import List, Optional, Tuple +from typing import Any, List, Optional, Tuple from .models import Tweet @@ -17,17 +20,50 @@ _TTL = 3600 # seconds +def _secure_cache_directory(directory: Path) -> None: + if os.name == "posix": + mode = directory.lstat().st_mode + if not stat.S_ISDIR(mode): + raise OSError(f"Expected a cache directory at {directory}") + if stat.S_IMODE(mode) != 0o700: + directory.chmod(0o700) + + +def read_cache_json(path: Path) -> Any: + """Read cached JSON, tightening permissions left by older releases.""" + _secure_cache_directory(path.parent) + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(fd, encoding="utf-8") as stream: + if os.name == "posix" and stat.S_IMODE(os.fstat(fd).st_mode) != 0o600: + os.fchmod(fd, 0o600) + return json.load(stream) + + +def write_cache_json(path: Path, payload: dict) -> None: + """Atomically replace cached JSON with a private file.""" + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + _secure_cache_directory(path.parent) + temporary = tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", dir=path.parent, delete=False, + ) + try: + with temporary as stream: + json.dump(payload, stream, ensure_ascii=False) + os.replace(temporary.name, path) + finally: + Path(temporary.name).unlink(missing_ok=True) + + def save_tweet_cache(tweets: List[Tweet]) -> None: """Persist tweet list so indices can be resolved by `show`.""" try: - _CACHE_DIR.mkdir(parents=True, exist_ok=True) entries = [ {"index": i + 1, "id": t.id, "author": t.author.screen_name, "text": t.text[:80]} for i, t in enumerate(tweets) if t.id ] payload = {"created_at": time.time(), "tweets": entries} - _CACHE_FILE.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") + write_cache_json(_CACHE_FILE, payload) except OSError as exc: logger.debug("Failed to write tweet cache: %s", exc) @@ -35,9 +71,7 @@ def save_tweet_cache(tweets: List[Tweet]) -> None: def _load_cache() -> Optional[List[dict]]: """Load and validate the cache file; return tweet entries or None if stale/missing.""" try: - if not _CACHE_FILE.exists(): - return None - payload = json.loads(_CACHE_FILE.read_text(encoding="utf-8")) + payload = read_cache_json(_CACHE_FILE) if not isinstance(payload, dict): return None if time.time() - payload.get("created_at", 0) > _TTL: diff --git a/twitter_cli/client.py b/twitter_cli/client.py index a3c2a08..13fd457 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -11,6 +11,7 @@ import re import time import urllib.parse +from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, cast import bs4 @@ -18,6 +19,7 @@ from x_client_transaction import ClientTransaction from x_client_transaction.utils import generate_headers as _gen_ct_headers, get_ondemand_file_url +from .cache import read_cache_json, write_cache_json from .constants import ( BEARER_TOKEN, SEC_CH_UA_BITNESS, @@ -1484,10 +1486,7 @@ def _load_ct_cache(self): """Try to load ClientTransaction from cache. Returns True on success.""" try: cache_path = self._ct_cache_path() - if not os.path.exists(cache_path): - return False - with open(cache_path, "r", encoding="utf-8") as f: - cache = json.load(f) + cache = read_cache_json(Path(cache_path)) # Check TTL (1 hour) if time.time() - cache.get("created_at", 0) > 3600: return False @@ -1512,15 +1511,12 @@ def _save_ct_cache(self, home_html, ondemand_text): """Save transaction data to cache file.""" try: cache_path = self._ct_cache_path() - cache_dir = os.path.dirname(cache_path) - os.makedirs(cache_dir, exist_ok=True) cache = { "home_html": home_html, "ondemand_text": ondemand_text, "created_at": time.time(), } - with open(cache_path, "w", encoding="utf-8") as f: - json.dump(cache, f) + write_cache_json(Path(cache_path), cache) logger.debug("Saved CT cache to %s", cache_path) except Exception as exc: logger.debug("Failed to save CT cache: %s", exc) From 4c33049591e81902144b2b3707ba1db82e9baf71 Mon Sep 17 00:00:00 2001 From: Lucius Date: Fri, 27 Nov 2026 18:10:06 +0800 Subject: [PATCH 2/2] fix: honor explicit followers and following limits Adapt the user-list portion of public-clis/twitter-cli#104 to the fork's REST collection (public-clis/twitter-cli#50). --- CHANGELOG.md | 1 + tests/test_client.py | 20 ++++++++++++++++++++ twitter_cli/cli.py | 4 +++- twitter_cli/client.py | 25 ++++++++++++++++++------- 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7968225..cdf15a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ This file records user-visible changes maintained on the `stable` branch from ### Fixed +- Followers and following lists honor an explicit `--max` up to 10,000 users. - Restrict local cache files and their directory to the current user on POSIX. - Resume a timeline from the last returned tweet when X sends an oversized page. diff --git a/tests/test_client.py b/tests/test_client.py index b791ba1..894c2ad 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -883,6 +883,26 @@ def _graphql_get(operation_name, variables, features, field_toggles=None): assert calls[0][1]["listId"] == "list-1" assert calls[0][1]["cursor"] == "cursor-prev" + @pytest.mark.parametrize("method", ["fetch_followers", "fetch_following"]) + def test_explicit_user_count_crosses_500(self, method, monkeypatch): + from urllib.parse import parse_qs, urlsplit + + client = TwitterClient.__new__(TwitterClient) + client._max_count = 3 + client._request_delay = 0 + + def page(url): + params = parse_qs(urlsplit(url).query) + start = max(0, int(params["cursor"][0])) + end = start + int(params["count"][0]) + return {"users": [{"id_str": str(i)} for i in range(start, end)], + "next_cursor_str": str(end)} + + monkeypatch.setattr(client, "_api_get", page) + fetch = getattr(client, method) + assert len(fetch("1")) == 3 + assert [u.id for u in fetch("1", 501)] == [str(i) for i in range(501)] + def test_fetch_rest_user_collection_paginates_until_count(self): client = TwitterClient.__new__(TwitterClient) client._request_delay = 0.0 diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index 89ea450..e77faa2 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -53,7 +53,7 @@ from .auth import get_cookies from .cache import resolve_cached_tweet, save_tweet_cache from .exceptions import TwitterError -from .client import TwitterClient +from .client import TwitterClient, configured_count_limit from .config import load_config from .filter import filter_tweets from .formatter import ( @@ -1384,6 +1384,8 @@ def _fetch_and_display_users( console.print("👤 Fetching @%s's profile..." % screen_name) profile = client.fetch_user(screen_name) fetch_count = _resolve_configured_count(config, max_count) + if max_count is None: + fetch_count = min(fetch_count, configured_count_limit(config.get("rateLimit", {}))) if rich_output: console.print("👥 Fetching %s (%d)...\n" % (label, fetch_count)) start = time.time() diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 13fd457..960677e 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -76,10 +76,17 @@ # Hard ceiling to prevent accidental massive fetches _ABSOLUTE_MAX_COUNT = 500 +_USER_LIST_MAX_COUNT = 10_000 _LIST_COLLECTION_PAGE_SIZE = 100 _LIST_SOURCE_PRIORITY = {"owned": 0, "subscribed": 1, "member": 2} +def configured_count_limit(rate_limit_config): + # type: (dict) -> int + """Return the configured ceiling for ordinary fetches.""" + return min(int(rate_limit_config.get("maxCount", 200)), _ABSOLUTE_MAX_COUNT) + + # ── Session management ─────────────────────────────────────────────────── @@ -210,7 +217,7 @@ def __init__(self, auth_token, ct0, rate_limit_config=None, cookie_string=None): self._request_delay = float(rl.get("requestDelay", 2.5)) self._max_retries = int(rl.get("maxRetries", 3)) self._retry_base_delay = float(rl.get("retryBaseDelay", 5.0)) - self._max_count = min(int(rl.get("maxCount", 200)), _ABSOLUTE_MAX_COUNT) + self._max_count = configured_count_limit(rl) self._client_transaction = None # type: Optional[Any] self._ct_init_attempted = False # Keep startup fast: only reuse a locally cached transaction helper here. @@ -756,13 +763,13 @@ def fetch_lists_for_user(self, user_id): ), ) - def fetch_followers(self, user_id, count=20): - # type: (str, int) -> List[UserProfile] + def fetch_followers(self, user_id, count=None): + # type: (str, Optional[int]) -> List[UserProfile] """Fetch followers of a user.""" return self._fetch_rest_user_collection("followers", user_id, count) - def fetch_following(self, user_id, count=20): - # type: (str, int) -> List[UserProfile] + def fetch_following(self, user_id, count=None): + # type: (str, Optional[int]) -> List[UserProfile] """Fetch users that a user is following.""" return self._fetch_rest_user_collection("friends", user_id, count) @@ -1227,11 +1234,15 @@ def _parse_rest_user_profile(self, data): ) def _fetch_rest_user_collection(self, endpoint, user_id, count): - # type: (str, str, int) -> List[UserProfile] + # type: (str, str, Optional[int]) -> List[UserProfile] """Fetch a paginated REST followers/friends collection for USER_ID.""" + if count is None: + count = min(20, self._max_count) + if count > _USER_LIST_MAX_COUNT: + logger.warning("Requested %d users; limiting to %d", count, _USER_LIST_MAX_COUNT) + count = _USER_LIST_MAX_COUNT if count <= 0: return [] - count = min(count, self._max_count) users = [] # type: List[UserProfile] seen_ids = set() # type: Set[str] cursor = "-1"