fix(login): atomic credential write and respect server poll_interval

Write credentials via a 0600 temp file + os.replace() so the token file
never appears at its final path with world-readable permissions, even if
the process is interrupted between write and chmod.

Parse poll_interval from the authorization response (clamped to 1–60 s,
falling back to _POLL_SLEEP) so aggressive polling can't trigger console
rate limits.

Tests: add atomicity spy asserting the temp file is 0600 before replace;
patch time.sleep instead of _POLL_SLEEP; add explicit interval-passthrough
assertion.
This commit is contained in:
2026-07-21 03:57:07 +00:00
committed by didericis
parent 4998a5ec6a
commit d4e2bc5f93
2 changed files with 72 additions and 8 deletions
+17 -3
View File
@@ -18,6 +18,7 @@ import json
import os
import socket
import sys
import tempfile
import time
import urllib.error
import urllib.request
@@ -71,7 +72,7 @@ def _save_credentials(
) -> Path:
path = bot_bottle_root() / "console.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
content = (
json.dumps(
{
"url": console_url,
@@ -83,7 +84,19 @@ def _save_credentials(
)
+ "\n"
)
path.chmod(0o600)
fd, tmp_path_str = tempfile.mkstemp(dir=path.parent, prefix=".console-")
tmp = Path(tmp_path_str)
try:
tmp.chmod(0o600)
with os.fdopen(fd, "w") as f:
f.write(content)
os.replace(tmp, path)
except Exception:
try:
tmp.unlink()
except OSError:
pass
raise
return path
@@ -111,6 +124,7 @@ def cmd_login(argv: list[str]) -> int:
device_code = resp["device_code"]
user_code = resp["user_code"]
expires_in = resp.get("expires_in", 300)
poll_sleep = max(1, min(int(resp.get("poll_interval", _POLL_SLEEP)), 60))
sys.stderr.write(
f"\nOpen this URL in your browser to authorize this host:\n\n"
@@ -122,7 +136,7 @@ def cmd_login(argv: list[str]) -> int:
while time.monotonic() < deadline:
sys.stderr.write(".")
sys.stderr.flush()
time.sleep(_POLL_SLEEP)
time.sleep(poll_sleep)
try:
code, result = _get(