Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,8 @@ 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.
- Require curl_cffi 0.15.0 or later for GHSA-qw2m-4pqf-rmpp.
25 changes: 25 additions & 0 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
from __future__ import annotations

import json
import os
import stat

import pytest
import time


Expand Down Expand Up @@ -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]
20 changes: 20 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 40 additions & 6 deletions twitter_cli/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -17,27 +20,58 @@
_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)


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:
Expand Down
4 changes: 3 additions & 1 deletion twitter_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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()
Expand Down
37 changes: 22 additions & 15 deletions twitter_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@
import re
import time
import urllib.parse
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, cast

import bs4
from curl_cffi import requests as _cffi_requests
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,
Expand Down Expand Up @@ -74,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 ───────────────────────────────────────────────────


Expand Down Expand Up @@ -208,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.
Expand Down Expand Up @@ -754,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)

Expand Down Expand Up @@ -1225,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"
Expand Down Expand Up @@ -1484,10 +1497,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
Expand All @@ -1512,15 +1522,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)
Expand Down