Skip to content

Commit 7c549b7

Browse files
SiddarthAAclaude
andcommitted
[failproofai-feat-failproofai-cloud-login] Refuse a claimed token no later request could carry, and send any hostname
`claim_browser_login` saved any non-empty string as the session. A hostile or broken server could hand back a token with a control or non-ASCII character: it was written to cli-auth.json, every later command failed on it, and a non-ASCII one made `fp whoami` a traceback. A hostname that isn't UTF-8 was a traceback at `start`, because Python hands those bytes back as surrogates and JSON can't carry them, and a blank one was a 422 from the server with no fallback to the emailed code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 131d094 commit 7c549b7

2 files changed

Lines changed: 46 additions & 2 deletions

File tree

‎fp-cloud-cli/fp_cli/auth.py‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,25 @@ def verify_otp(
167167
)
168168

169169

170+
#: What a session token can be and still be sent back on every later request. A real one is
171+
#: 64 hex characters; a cookie or a header can't carry a control or a non-ASCII character.
172+
_SESSION_TOKEN = re.compile(r"[A-Za-z0-9._~+/=-]{1,4096}")
173+
174+
170175
def display_text(value: Any, max_chars: int = 200) -> Optional[str]:
171176
"""A server-supplied string made safe to print, or ``None`` if nothing is left."""
172177
if not isinstance(value, str):
173178
return None
174179
return _INVISIBLE.sub("", value).strip()[:max_chars] or None
175180

176181

182+
def _machine_label() -> str:
183+
"""This machine's name, always sendable. Python hands back a hostname's non-UTF-8 bytes
184+
as surrogates, which JSON can't carry, and the server refuses a label with nothing in it."""
185+
name = socket.gethostname().encode("utf-8", "replace").decode("utf-8")
186+
return display_text(name) or "unknown"
187+
188+
177189
def _within(value: Any, low: float, high: float, fallback: float) -> float:
178190
"""A server's number, kept to a range this client can live with."""
179191
if isinstance(value, bool) or not isinstance(value, (int, float)):
@@ -281,7 +293,7 @@ def start_browser_login(
281293
base_url,
282294
"/api/auth/cli/start",
283295
{
284-
"machine_label": socket.gethostname() or "unknown",
296+
"machine_label": _machine_label(),
285297
"machine_os": "macOS" if sys.platform == "darwin" else platform_info.system().lower(),
286298
"cli_version": f"fp {__version__}",
287299
"kind": BROWSER_LOGIN_KIND,
@@ -428,7 +440,13 @@ def claim_browser_login(
428440
user_id, email = display_text(user.get("id")), display_text(user.get("email"))
429441
# No identity is no login: `persist_session` keeps the previous one when a field is
430442
# missing, which would save this session under whoever was signed in before.
431-
if response.status_code != 201 or not isinstance(token, str) or not token or not user_id or not email:
443+
if (
444+
response.status_code != 201
445+
or not isinstance(token, str)
446+
or not _SESSION_TOKEN.fullmatch(token)
447+
or not user_id
448+
or not email
449+
):
432450
raise AuthError(
433451
"That login can't be finished any more.",
434452
hint="run fp login again",

‎fp-cloud-cli/tests/test_browser_login.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,32 @@ def test_a_claim_with_no_identity_is_no_login(user):
254254
auth.claim_browser_login(BASE, "POLL")
255255

256256

257+
@respx.mock
258+
@pytest.mark.parametrize("token", ["☃☃☃", "abc\r\nx-evil: 1", "a b", "\x1b]0;x\x07", "x" * 5000, ""])
259+
def test_a_token_no_later_request_could_carry_is_never_saved(token):
260+
# Saved, every later command fails on it, and a non-ASCII one with a traceback.
261+
respx.post(f"{BASE}/api/auth/cli/claim").mock(
262+
return_value=httpx.Response(201, json={**CLAIMED, "session_token": token})
263+
)
264+
with pytest.raises(AuthError):
265+
auth.claim_browser_login(BASE, "POLL")
266+
267+
268+
@respx.mock
269+
@pytest.mark.parametrize(
270+
"hostname,label",
271+
[("ho\udcffst", "ho?st"), ("\x01\x02", "unknown"), (" ", "unknown"), ("", "unknown"), ("a\x1b]0;x\x07b", "a]0;xb")],
272+
ids=["not-utf8", "controls", "spaces", "empty", "escape"],
273+
)
274+
def test_any_hostname_still_starts_a_login(monkeypatch, hostname, label):
275+
# JSON can't carry a surrogate, which is how Python hands back bytes that aren't UTF-8,
276+
# and the server refuses a label with nothing left in it.
277+
monkeypatch.setattr(auth.socket, "gethostname", lambda: hostname)
278+
route = respx.post(f"{BASE}/api/auth/cli/start").mock(return_value=_start())
279+
assert auth.start_browser_login(BASE) is not None
280+
assert json.loads(route.calls[0].request.content)["machine_label"] == label
281+
282+
257283
@respx.mock
258284
def test_what_the_server_says_about_the_person_cannot_drive_the_terminal():
259285
evil = "me\x1b]0;pwned\x07@te‮st\x1b[2J"

0 commit comments

Comments
 (0)