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
65 changes: 64 additions & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1356,7 +1356,9 @@ def _make_client(self):
client._max_retries = 3
client._retry_base_delay = 5.0
client._max_count = 200
client._client_transaction = None
# media upload is a POST: it needs a transaction id like any other write
client._client_transaction = MagicMock()
client._client_transaction.generate_transaction_id.return_value = "tid-media"
client._ct_init_attempted = True
return client

Expand Down Expand Up @@ -1545,3 +1547,64 @@ def mock_post(operation_name, variables, features=None):

assert captured.get("product") == "Latest"
assert captured.get("querySource") == "typed_query"


# ── Fail-closed guard for unsigned writes ────────────────────────────────


class TestUnsignedWriteGuard:
"""X gates GraphQL writes on `x-client-transaction-id`.

A POST sent without that header is treated as automation by X: it either
fails with a misleading `344 "daily limit"` on accounts that never posted,
or it goes through and the account is suspended shortly after. When the
ClientTransaction bootstrap fails we must refuse the write instead of
sending it unsigned.
"""

@staticmethod
def _client():
client = TwitterClient.__new__(TwitterClient)
client._auth_token = "test_token"
client._ct0 = "test_ct0"
client._cookie_string = None
client._client_transaction = None
client._ct_init_attempted = True
return client

def test_post_without_transaction_id_is_refused(self):
client = self._client()
with pytest.raises(TwitterAPIError) as exc:
client._build_headers("https://x.com/i/api/graphql/qid/CreateTweet", "POST")
assert "REFUSING unsigned write" in str(exc.value)

def test_override_env_allows_unsigned_post(self, monkeypatch):
monkeypatch.setenv("TWITTER_ALLOW_UNSIGNED", "1")
client = self._client()
headers = client._build_headers(
"https://x.com/i/api/graphql/qid/CreateTweet", "POST")
assert "X-Client-Transaction-Id" not in headers

def test_get_without_transaction_id_is_allowed(self):
client = self._client()
headers = client._build_headers(
"https://x.com/i/api/graphql/qid/HomeTimeline", "GET")
assert "X-Client-Transaction-Id" not in headers
assert "Authorization" in headers

def test_post_with_transaction_id_sets_header(self):
client = self._client()
transaction = MagicMock()
transaction.generate_transaction_id.return_value = "tid-123"
client._client_transaction = transaction
headers = client._build_headers(
"https://x.com/i/api/graphql/qid/CreateTweet", "POST")
assert headers["X-Client-Transaction-Id"] == "tid-123"

def test_failing_generator_also_refuses(self):
client = self._client()
transaction = MagicMock()
transaction.generate_transaction_id.side_effect = RuntimeError("boom")
client._client_transaction = transaction
with pytest.raises(TwitterAPIError):
client._build_headers("https://x.com/i/api/graphql/qid/CreateTweet", "POST")
29 changes: 26 additions & 3 deletions twitter_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1125,7 +1125,13 @@ def _ensure_client_transaction(self):
# Save to cache for future use
self._save_ct_cache(home_page.text, ondemand_file.text)
except Exception as exc:
logger.warning("Failed to init ClientTransaction: %s", exc)
logger.warning(
"Failed to init ClientTransaction: %s — x-client-transaction-id is "
"UNAVAILABLE. Write requests will be REFUSED (unsigned POSTs get "
"accounts suspended). Fix the bootstrap, or set "
"TWITTER_ALLOW_UNSIGNED=1 to override.",
exc,
)

def _build_headers(self, url="", method="GET"):
# type: (str, str) -> Dict[str, str]
Expand Down Expand Up @@ -1159,14 +1165,31 @@ def _build_headers(self, url="", method="GET"):
headers["Content-Type"] = "application/json"
headers["Referer"] = "https://x.com/compose/post"
headers["Priority"] = "u=1, i"
# Generate x-client-transaction-id if available
# Generate x-client-transaction-id. X gates GraphQL writes on this header:
# a POST without it is treated as automation (silent fake `344 daily
# limit`, or a suspension within ~24-48h). Fail CLOSED instead of
# sending an unsigned write.
tid = None
if self._client_transaction and url:
try:
path = urllib.parse.urlparse(url).path
tid = self._client_transaction.generate_transaction_id(
method=method, path=path,
)
headers["X-Client-Transaction-Id"] = tid
except Exception as exc:
logger.debug("Failed to generate transaction id: %s", exc)
if tid:
headers["X-Client-Transaction-Id"] = tid
elif method == "POST":
msg = (
"REFUSING unsigned write: x-client-transaction-id is not available "
"(ClientTransaction failed to init). X treats unsigned writes as "
"automation and can suspend the account. Fix the ClientTransaction "
"bootstrap, or set TWITTER_ALLOW_UNSIGNED=1 to override at your own risk."
)
if os.environ.get("TWITTER_ALLOW_UNSIGNED") == "1":
logger.warning("%s [overridden by TWITTER_ALLOW_UNSIGNED=1]", msg)
else:
logger.error("%s", msg)
raise TwitterAPIError(0, msg)
return headers