Skip to content

Commit cfa9e57

Browse files
SiddarthAAclaude
andcommitted
[failproofai-feat-failproofai-cloud-login] Don't let a key pressed during the last poll answer the next screen
Pending keys were only read when that poll came back approved. On a poll that came back denied or expired, a queued Enter went straight to `link_ended`, so a new link started with "not authorized" on screen for no time at all, and a queued Esc went back to the menu when the screen had promised to cancel. Pending keys are now read whatever the poll said. Ctrl-C while asking for a link or finishing sign-in also wasn't the calm cancel the PR promises: it left the box with exit 130 and no message. It now covers every request of the browser flow. The email path is deliberately left as it is on main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7c549b7 commit cfa9e57

3 files changed

Lines changed: 98 additions & 20 deletions

File tree

‎__tests__/e2e/layout/fp-login.sh‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,10 @@ has "…calmly" "$T" "cancelled"
342342

343343
# A person who presses esc while a poll is in flight has said no, even if that poll comes
344344
# back approved. Only a stand-in can hold a poll open, so this one records every claim.
345-
python3 - "$OUT/held.port" "$OUT/held.claims" <<'PY' &
346-
import http.server, json, sys, time
345+
python3 - "$OUT/held.port" "$OUT/held.claims" "$OUT/held.mode" "$OUT/held.starts" <<'PY' &
346+
import http.server, json, os, sys, time
347+
def mode():
348+
return open(sys.argv[3]).read().strip() if os.path.exists(sys.argv[3]) else ""
347349
class H(http.server.BaseHTTPRequestHandler):
348350
def reply(self, code, body):
349351
data = json.dumps(body).encode()
@@ -357,13 +359,19 @@ class H(http.server.BaseHTTPRequestHandler):
357359
def do_POST(self):
358360
self.rfile.read(int(self.headers.get("content-length", 0)))
359361
if self.path.endswith("/start"):
362+
open(sys.argv[4], "a").write("start\n")
363+
if mode() == "slow-start":
364+
time.sleep(8)
360365
self.reply(201, {"verification_url": f"http://{self.headers['host']}/cli/authorize?r=" + "a" * 64,
361366
"poll_secret": "p", "expires_in": 600, "interval": 1, "kind": "session"})
362367
elif self.path.endswith("/poll"):
363-
time.sleep(4)
364-
self.reply(200, {"status": "approved"})
368+
if mode() != "slow-claim":
369+
time.sleep(4)
370+
self.reply(200, {"status": "denied" if mode() == "denied" else "approved"})
365371
elif self.path.endswith("/claim"):
366372
open(sys.argv[2], "a").write("claim\n")
373+
if mode() == "slow-claim":
374+
time.sleep(8)
367375
self.reply(201, {"session_token": "HELD-TOKEN", "expires_in_secs": 3600,
368376
"user": {"id": "u1", "email": "held@example.test"}})
369377
def log_message(self, *a): pass
@@ -394,6 +402,42 @@ run_fp notheld "$MENU,key:enter,url" "$HELD" -- login
394402
wait_url notheld >/dev/null
395403
T=$(wait_done notheld)
396404
eq "the same poll with no key pressed does claim, so the stand-in is a fair test" "$(cat "$OUT/held.claims" 2>/dev/null | wc -l)" "1"
405+
406+
# Enter pressed during a poll that comes back denied was pressed at a screen that's gone.
407+
reset_fp
408+
echo denied > "$OUT/held.mode"
409+
rm -f "$OUT/held.starts"
410+
run_fp heldenter "$MENU,key:enter,url,wait:waiting for you,sleep:1,key:enter,wait:not authorized,sleep:2,key:esc,$MENU,key:esc" "$HELD" -- login
411+
wait_url heldenter >/dev/null
412+
T=$(wait_done heldenter)
413+
eq "enter during a poll that comes back denied doesn't take a new link" "$(wc -l < "$OUT/held.starts")" "1"
414+
has "…the denial stays on screen until it's answered" "$T" "new link"
415+
eq "…and the person can still leave" "$(cat "$OUT/heldenter.rc")" "0"
416+
reset_fp
417+
rm -f "$OUT/held.starts"
418+
run_fp heldescdeny "$MENU,key:enter,url,wait:waiting for you,sleep:1,key:esc" "$HELD" -- login
419+
wait_url heldescdeny >/dev/null
420+
T=$(wait_done heldescdeny)
421+
eq "esc during a poll that comes back denied exits 0" "$(cat "$OUT/heldescdeny.rc")" "0"
422+
has "…calmly, as the screen promised" "$T" "cancelled"
423+
eq "…with one link" "$(wc -l < "$OUT/held.starts")" "1"
424+
425+
# Ctrl-C at any request, not only during a poll.
426+
reset_fp
427+
echo slow-start > "$OUT/held.mode"
428+
run_fp heldstart "$MENU,key:enter,wait:asking for a link,sleep:1,key:ctrl-c" "$HELD" -- login
429+
T=$(wait_done heldstart)
430+
eq "ctrl-c while asking for a link exits 0" "$(cat "$OUT/heldstart.rc")" "0"
431+
has "…calmly" "$T" "cancelled"
432+
reset_fp
433+
echo slow-claim > "$OUT/held.mode"
434+
rm -f "$OUT/held.claims"
435+
run_fp heldclaim "$MENU,key:enter,url,wait:finishing sign-in,sleep:1,key:ctrl-c" "$HELD" -- login
436+
wait_url heldclaim >/dev/null
437+
T=$(wait_done heldclaim)
438+
eq "ctrl-c while finishing exits 0" "$(cat "$OUT/heldclaim.rc")" "0"
439+
has "…calmly" "$T" "cancelled"
440+
eq "…and saves nothing" "$(saved session_token)" ""
397441
kill "$HELD_PID" 2>/dev/null
398442

399443
# ═════════════════════════════════════════════════════════════════════════════

‎fp-cloud-cli/fp_cli/commands/auth_cmds.py‎

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -145,28 +145,30 @@ def tick(left: float, offline: bool) -> None:
145145
box.waiting(f"{next(frames)} {doing} · {minutes}:{seconds:02d} · esc to cancel")
146146
box.wait_key(0.1)
147147

148-
while True:
149-
box.working("asking for a link…")
150-
login = auth.start_browser_login(base, **options)
151-
if login is None:
152-
return None
153-
_offer_link(login.verification_url)
154-
try:
148+
try:
149+
while True:
150+
box.working("asking for a link…")
151+
login = auth.start_browser_login(base, **options)
152+
if login is None:
153+
return None
154+
_offer_link(login.verification_url)
155155
# ponytail: Esc during a stalled poll waits out its 10s timeout (Ctrl-C doesn't);
156156
# polling on a thread would fix that if it ever matters.
157157
outcome = auth.await_browser_approval(base, login, tick=tick, **options)
158-
except KeyboardInterrupt: # Ctrl-C during a poll, outside `wait_key`
159-
raise selectmod.LoginCancelled()
160-
if outcome == "approved":
161-
# A key pressed during the last poll is still waiting to be read, and Esc means no
162-
# session. This is the last moment that can be honoured: the claim creates it.
158+
# A key pressed during the last poll is still waiting to be read. Esc means no
159+
# session, and this is the last moment that can be honoured: the claim creates it.
160+
# Anything else was pressed at a screen that's gone, and must not answer the next
161+
# one: Enter would take a new link with "not authorized" on screen for no time.
163162
# `is not None`: the first byte of a non-ASCII character reads as "".
164163
while box.wait_key(0) is not None:
165164
pass
166-
box.working("finishing sign-in…")
167-
return auth.claim_browser_login(base, login.poll_secret, **options)
168-
if not box.link_ended(_LINK_ENDED.get(outcome, "that link can't be used any more")):
169-
return _BACK_TO_MENU
165+
if outcome == "approved":
166+
box.working("finishing sign-in…")
167+
return auth.claim_browser_login(base, login.poll_secret, **options)
168+
if not box.link_ended(_LINK_ENDED.get(outcome, "that link can't be used any more")):
169+
return _BACK_TO_MENU
170+
except KeyboardInterrupt: # Ctrl-C during a request, outside `wait_key`
171+
raise selectmod.LoginCancelled()
170172

171173

172174
def _browser_login_plain(state: AppState, base: str):

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,10 +340,15 @@ class _Box:
340340

341341
def __init__(self, *keys):
342342
self.keys = list(keys)
343+
self.ended = []
343344

344345
def working(self, _text):
345346
pass
346347

348+
def link_ended(self, message):
349+
self.ended.append((message, list(self.keys)))
350+
return False
351+
347352
def wait_key(self, _seconds):
348353
key = self.keys.pop(0) if self.keys else None
349354
if key == "ESC":
@@ -384,6 +389,33 @@ def test_any_other_key_pressed_during_the_last_poll_changes_nothing(approved_lin
384389
assert approved_link == [1]
385390

386391

392+
@pytest.mark.parametrize("final", ["denied", "expired"])
393+
def test_enter_pressed_during_the_last_poll_cannot_answer_a_screen_nobody_saw(approved_link, monkeypatch, final):
394+
# It would take the next link straight away, with the denial on screen for no time at all.
395+
monkeypatch.setattr(auth, "await_browser_approval", lambda *_a, **_k: final)
396+
box = _Box("ENTER", "")
397+
assert auth_cmds._browser_login_in_box(_state(), BASE, box) is auth_cmds._BACK_TO_MENU
398+
assert [keys for _message, keys in box.ended] == [[]]
399+
400+
401+
def test_esc_pressed_during_the_last_poll_of_a_denied_link_still_cancels(approved_link, monkeypatch):
402+
monkeypatch.setattr(auth, "await_browser_approval", lambda *_a, **_k: "denied")
403+
box = _Box("ESC")
404+
with pytest.raises(selectmod.LoginCancelled):
405+
auth_cmds._browser_login_in_box(_state(), BASE, box)
406+
assert box.ended == []
407+
408+
409+
@pytest.mark.parametrize("step", ["start_browser_login", "claim_browser_login"])
410+
def test_ctrl_c_during_any_request_of_a_browser_login_cancels_calmly(approved_link, monkeypatch, step):
411+
def interrupted(*_a, **_k):
412+
raise KeyboardInterrupt()
413+
414+
monkeypatch.setattr(auth, step, interrupted)
415+
with pytest.raises(selectmod.LoginCancelled):
416+
auth_cmds._browser_login_in_box(_state(), BASE, _Box())
417+
418+
387419
# --- the command, on a terminal with no raw mode ----------------------------
388420
#
389421
# The box needs termios and a real pty, so this is the path CliRunner can reach:

0 commit comments

Comments
 (0)