Skip to content
Open
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
42 changes: 37 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,37 +1,69 @@
name: CI

# Pull requests from first-time contributors need a maintainer to approve the
# workflow run ("action_required"), otherwise no checks are reported and the PR
# looks untested. Repository admins can switch this off under
# Settings -> Actions -> General -> "Fork pull request workflows from outside
# collaborators" (require approval for first-time contributors).

on:
push:
branches: ["**"]
pull_request:
workflow_call:

permissions:
contents: read

concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
test:
runs-on: ubuntu-latest
# Pin the runner image: "ubuntu-latest" is a moving target (it migrates to
# Ubuntu 26 in Oct 2026), which makes a failure hard to attribute.
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
# Lower bound follows requires-python (>=3.10) from upstream; the 3.13
# entry is restored from the fork's earlier CI work and verified green.
python-version: ["3.10", "3.11", "3.12", "3.13"]
# A job with no timeout inherits GitHub's 30-day ceiling: a hung dependency
# install or a stalled test keeps the whole PR in "expected" state until
# then. Bound it so a stall fails fast and visibly instead.
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
persist-credentials: false

- name: Setup uv
uses: astral-sh/setup-uv@v6
# setup-uv publishes no floating v10 major tag, so pin the release.
uses: astral-sh/setup-uv@v10.3.3
with:
enable-cache: true

- name: Setup Python
uses: actions/setup-python@v5
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: uv sync --extra dev
timeout-minutes: 10

# Fail fast on the cheap static checks, then run the suite.
- name: Lint
run: uv run ruff check .
timeout-minutes: 5

- name: Type check
run: uv run mypy twitter_cli
timeout-minutes: 5

- name: Test
run: uv run pytest -q
timeout-minutes: 10
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[![CI](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml)
[![PyPI version](https://badge.fury.io/py/twitter-cli.svg)](https://pypi.org/project/twitter-cli/)
[![Python](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)](https://pypi.org/project/twitter-cli/)
[![Python versions](https://img.shields.io/pypi/pyversions/twitter-cli.svg)](https://pypi.org/project/twitter-cli/)

A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles without API keys.

Expand Down
46 changes: 29 additions & 17 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,25 @@
from twitter_cli import auth


def _patch_home(monkeypatch, tmp_path) -> None:
"""Point ``os.path.expanduser("~")`` at ``tmp_path`` on every platform.

POSIX honours ``HOME``; Windows ``ntpath.expanduser`` instead reads
``USERPROFILE`` (falling back to ``HOMEDRIVE``/``HOMEPATH``). Tests that
build a fake browser profile under ``tmp_path`` must set both.

Note: several tests monkeypatch ``auth.sys.platform`` to exercise POSIX
branches, which mutates the real ``sys`` module. ``expanduser`` is still
resolved by the *running* path module, so the platform check here must not
consult ``sys.platform`` — and not ``platform.system()`` either, which
derives from ``sys.platform`` and would also report the patched value.
``os.name`` is fixed at interpreter start and is immune to that patch.
"""
monkeypatch.setenv("HOME", str(tmp_path))
if os.name == "nt":
monkeypatch.setenv("USERPROFILE", str(tmp_path))


def test_get_cookies_prefers_env(monkeypatch) -> None:
monkeypatch.setattr(auth, "load_from_env", lambda: {"auth_token": "env-token", "ct0": "env-csrf"})
monkeypatch.setattr(auth, "extract_from_browser", lambda: pytest.fail("should not extract from browser"))
Expand Down Expand Up @@ -192,13 +211,10 @@ def get(self, url, headers=None, timeout=5):

def test_iter_chrome_cookie_files_default_first(monkeypatch, tmp_path) -> None:
"""Default profile should be yielded first, then Profile N sorted."""
# Create the correct platform-specific directory structure
if sys.platform == "darwin":
chrome_dir = tmp_path / "Library" / "Application Support" / "Google" / "Chrome"
elif sys.platform == "win32":
chrome_dir = tmp_path / "Google" / "Chrome" / "User Data"
else:
chrome_dir = tmp_path / ".config" / "Google" / "Chrome"
# Pin the POSIX layout so this test is deterministic on every host
# (Windows would otherwise resolve a 'User Data' tree instead).
monkeypatch.setattr(auth.sys, "platform", "linux")
chrome_dir = tmp_path / ".config" / "Google" / "Chrome"

(chrome_dir / "Default").mkdir(parents=True)
(chrome_dir / "Default" / "Cookies").touch()
Expand All @@ -208,9 +224,7 @@ def test_iter_chrome_cookie_files_default_first(monkeypatch, tmp_path) -> None:
(chrome_dir / "Profile 1" / "Cookies").touch()

monkeypatch.delenv("TWITTER_CHROME_PROFILE", raising=False)
monkeypatch.setenv("HOME", str(tmp_path))
if sys.platform == "win32":
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
_patch_home(monkeypatch, tmp_path)

paths = auth._iter_chrome_cookie_files("chrome")

Expand All @@ -224,17 +238,15 @@ def test_iter_chrome_cookie_files_default_first(monkeypatch, tmp_path) -> None:

def test_iter_chrome_cookie_files_env_override(monkeypatch, tmp_path) -> None:
"""TWITTER_CHROME_PROFILE should restrict to that single profile."""
if sys.platform == "darwin":
chrome_dir = tmp_path / "Library" / "Application Support" / "Google" / "Chrome"
else:
chrome_dir = tmp_path / ".config" / "Google" / "Chrome"
monkeypatch.setattr(auth.sys, "platform", "linux")
chrome_dir = tmp_path / ".config" / "Google" / "Chrome"

(chrome_dir / "Default").mkdir(parents=True)
(chrome_dir / "Default" / "Cookies").touch()
(chrome_dir / "Profile 5").mkdir()
(chrome_dir / "Profile 5" / "Cookies").touch()

monkeypatch.setenv("HOME", str(tmp_path))
_patch_home(monkeypatch, tmp_path)
monkeypatch.setenv("TWITTER_CHROME_PROFILE", "Profile 5")

paths = auth._iter_chrome_cookie_files("chrome")
Expand All @@ -249,13 +261,13 @@ def test_iter_chrome_cookie_files_edge_linux_uses_microsoft_edge_path(monkeypatc
(edge_dir / "Default").mkdir(parents=True)
(edge_dir / "Default" / "Cookies").touch()

monkeypatch.setenv("HOME", str(tmp_path))
_patch_home(monkeypatch, tmp_path)
monkeypatch.delenv("TWITTER_CHROME_PROFILE", raising=False)

paths = auth._iter_chrome_cookie_files("edge")

assert len(paths) == 1
assert paths[0].endswith(".config/microsoft-edge/Default/Cookies")
assert paths[0] == os.path.join(str(tmp_path), ".config", "microsoft-edge", "Default", "Cookies")


def test_iter_chrome_cookie_files_edge_windows_uses_user_data(monkeypatch, tmp_path) -> None:
Expand Down
107 changes: 107 additions & 0 deletions tests/test_cache_permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Owner-only permissions for cache artefacts.

The ClientTransaction cache stores the full ``x.com/home`` HTML, which embeds the
session's live ``auth_token``/``ct0``; the index cache stores tweet text the user
has read. Both used to be written with the process umask default (typically
``0644``), so any other local user could read a session off disk.

These assertions are POSIX-only: Windows has no POSIX permission bits and
``os.chmod`` there only toggles the read-only flag, so ``stat.S_IMODE`` returns
``0o666`` regardless.
"""

from __future__ import annotations

import json
import os
import stat

import pytest

from twitter_cli import cache

posix_only = pytest.mark.skipif(
os.name != "posix", reason="POSIX permission bits are not enforced on this OS"
)


def _make_tweet(tweet_factory, tweet_id: str = "100"):
return tweet_factory(tweet_id=tweet_id, text="cache me")


@posix_only
def test_save_writes_owner_only(tmp_path, monkeypatch, tweet_factory) -> None:
cache_file = tmp_path / ".twitter-cli" / "last_results.json"
monkeypatch.setattr(cache, "_CACHE_DIR", cache_file.parent)
monkeypatch.setattr(cache, "_CACHE_FILE", cache_file)

cache.save_tweet_cache([_make_tweet(tweet_factory)])

assert cache_file.exists()
assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600
assert stat.S_IMODE(cache_file.parent.stat().st_mode) == 0o700
# Still valid JSON that round-trips.
assert json.loads(cache_file.read_text(encoding="utf-8"))["tweets"][0]["id"] == "100"


@posix_only
def test_save_tightens_preexisting_world_readable_file(tmp_path, monkeypatch, tweet_factory) -> None:
cache_file = tmp_path / ".twitter-cli" / "last_results.json"
cache_file.parent.mkdir(parents=True)
cache_file.write_text("{}", encoding="utf-8")
cache_file.chmod(0o644) # simulate a file left behind by an older build
assert stat.S_IMODE(cache_file.stat().st_mode) == 0o644

monkeypatch.setattr(cache, "_CACHE_DIR", cache_file.parent)
monkeypatch.setattr(cache, "_CACHE_FILE", cache_file)

cache.save_tweet_cache([_make_tweet(tweet_factory)])

assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600


def test_save_never_raises_on_unwritable_dir(tmp_path, monkeypatch, tweet_factory) -> None:
"""A cache write must never break the command that triggered it."""
cache_file = tmp_path / "missing" / "last_results.json"
monkeypatch.setattr(cache, "_CACHE_DIR", cache_file.parent)
monkeypatch.setattr(cache, "_CACHE_FILE", cache_file)
# Parent creation will fail because we point at a file, not a directory.
blocker = tmp_path / "missing"
blocker.write_text("not a directory", encoding="utf-8")

cache.save_tweet_cache([_make_tweet(tweet_factory)]) # must not raise

assert not cache_file.exists()


def test_client_transaction_cache_is_owner_only(tmp_path, monkeypatch) -> None:
"""The CT cache embeds auth_token/ct0 and must be created owner-only."""
from twitter_cli.client import TwitterClient

ct_cache = tmp_path / ".twitter-cli" / "transaction_cache.json"
monkeypatch.setattr(
TwitterClient, "_ct_cache_path", staticmethod(lambda: str(ct_cache))
)

client = TwitterClient.__new__(TwitterClient)
client._save_ct_cache("<html>home</html>", "ondemand")

assert ct_cache.exists()
payload = json.loads(ct_cache.read_text(encoding="utf-8"))
assert payload["home_html"] == "<html>home</html>"
if os.name == "posix":
assert stat.S_IMODE(ct_cache.stat().st_mode) == 0o600
assert stat.S_IMODE(ct_cache.parent.stat().st_mode) == 0o700


def test_open_owner_only_uses_restrictive_mode(tmp_path) -> None:
"""The create mode itself is narrow, not just a post-hoc chmod."""
target = tmp_path / "secret.json"
with cache._open_owner_only(target) as handle:
handle.write('{"ok": true}')

assert target.read_text(encoding="utf-8") == '{"ok": true}'
if os.name == "posix":
assert stat.S_IMODE(target.stat().st_mode) == 0o600


50 changes: 48 additions & 2 deletions twitter_cli/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

import json
import logging
import os
import time
from pathlib import Path
from typing import List, Optional, Tuple
from typing import IO, List, Optional, Tuple

from .models import Tweet

Expand All @@ -16,22 +17,67 @@
_CACHE_FILE = _CACHE_DIR / "last_results.json"
_TTL = 3600 # seconds

# Owner-only permissions for cache artefacts.
#
# The ClientTransaction cache stores the full x.com/home HTML, which embeds the
# live auth_token / ct0 for the session, and the index cache stores tweet text
# the user has read. Neither should be world- or group-readable on a host with
# other local users.
_OWNER_ONLY_FILE = 0o600
_OWNER_ONLY_DIR = 0o700


def _open_owner_only(path: Path) -> IO[str]:
"""Open ``path`` for writing with owner-only permissions.

Uses ``O_CREAT`` with an explicit mode so a newly created file is never
briefly world-readable (a plain ``open()`` would honour the umask first and
only narrow afterwards). An existing file with looser permissions is
tightened on every write. Permission changes are best-effort: on Windows
``chmod`` only toggles the read-only bit, and a cache write must never fail
the command that triggered it.
"""
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0)
fd = os.open(str(path), flags, _OWNER_ONLY_FILE)
try:
# Resolved via getattr: fchmod is absent from typeshed on some platforms,
# so a direct call needs a version-dependent type: ignore, while being
# genuinely available at runtime on every POSIX host.
fchmod = getattr(os, "fchmod", None)
if fchmod is not None:
fchmod(fd, _OWNER_ONLY_FILE)
else: # pragma: no cover - non-POSIX
os.chmod(str(path), _OWNER_ONLY_FILE)
except OSError: # pragma: no cover - permission change is best-effort
pass
return os.fdopen(fd, "w", encoding="utf-8")


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)
_tighten_dir(_CACHE_DIR)
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")
with _open_owner_only(_CACHE_FILE) as f:
f.write(json.dumps(payload, ensure_ascii=False, indent=2))
except OSError as exc:
logger.debug("Failed to write tweet cache: %s", exc)


def _tighten_dir(directory: Path) -> None:
"""Best-effort owner-only permission on a cache directory."""
try:
os.chmod(str(directory), _OWNER_ONLY_DIR)
except OSError:
pass


def _load_cache() -> Optional[List[dict]]:
"""Load and validate the cache file; return tweet entries or None if stale/missing."""
try:
Expand Down
Loading