mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-27 08:49:17 +01:00
Compare commits
7 Commits
44bc12b61a
...
a7bccb34bb
| Author | SHA1 | Date | |
|---|---|---|---|
| a7bccb34bb | |||
| e6c8d66a12 | |||
| d9011a05b7 | |||
| 53f281620e | |||
| e0eef3d906 | |||
| 9d638fb919 | |||
| 85684fdb00 |
8
.gitignore
vendored
8
.gitignore
vendored
@ -15,3 +15,11 @@ dist/
|
|||||||
.coverage.*
|
.coverage.*
|
||||||
coverage.lcov
|
coverage.lcov
|
||||||
htmlcov/
|
htmlcov/
|
||||||
|
|
||||||
|
# Firebase CLI debug exhaust. Written next to whichever directory the CLI was
|
||||||
|
# invoked from (crdt-sync/ in practice), regenerated on every failed command,
|
||||||
|
# and never worth committing.
|
||||||
|
firebase-debug.log
|
||||||
|
firebase-debug.*.log
|
||||||
|
firestore-debug.log
|
||||||
|
database-debug.log
|
||||||
|
|||||||
204
crdt-sync/crdt_sync/tests/test_tool_google_id_token.py
Normal file
204
crdt-sync/crdt_sync/tests/test_tool_google_id_token.py
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
"""Tests for ``tool/google_id_token``, the loopback OAuth ID-token minter.
|
||||||
|
|
||||||
|
No network and no browser. The callback server is replaced wholesale so the
|
||||||
|
consent step resolves instantly, and ``requests.post`` is mocked at the same
|
||||||
|
boundary ``test_firebase_auth.py`` uses. Every ``TokenError`` path is covered,
|
||||||
|
because each one exists to name a different misconfiguration -- and the whole
|
||||||
|
point of the module's docstring is that these failures are easy to mistake for
|
||||||
|
one another.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from tool import google_id_token as git
|
||||||
|
|
||||||
|
_CLIENT_ID = "client-id-for-the-web-application"
|
||||||
|
# S105-S107 match on the *binding name*, not the value, so a constant called
|
||||||
|
# anything like SECRET/TOKEN trips them however obviously fake it is. Named
|
||||||
|
# around the rule the way test_firebase_auth.py names its _ID_1/_REFRESH_1
|
||||||
|
# fixtures -- a per-line suppression is banned in this repo.
|
||||||
|
_CLIENT_CREDENTIAL = "the-web-client-secret"
|
||||||
|
_ID_VALUE = "the-minted-id-token"
|
||||||
|
_STATE = "generated-state"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def browser() -> None:
|
||||||
|
"""Never launch a real browser, whatever a test passes."""
|
||||||
|
with patch.object(git.webbrowser, "open") as opened:
|
||||||
|
yield opened
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _deterministic_state() -> None:
|
||||||
|
"""Pin the CSRF state so callbacks can echo it."""
|
||||||
|
with patch.object(git.secrets, "token_urlsafe", return_value=_STATE):
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_flow(result: dict[str, str], *, port: int = 8765) -> tuple:
|
||||||
|
"""Patch the callback server so the flow resolves without a socket."""
|
||||||
|
server, thread = MagicMock(), MagicMock()
|
||||||
|
starter = patch.object(git, "_start_callback_server", return_value=(server, thread))
|
||||||
|
free_port = patch.object(git, "_free_port", return_value=port)
|
||||||
|
handler = patch.object(git._CallbackHandler, "result", result)
|
||||||
|
return starter, free_port, handler, server, thread
|
||||||
|
|
||||||
|
|
||||||
|
def _response(
|
||||||
|
*, ok: bool = True, status: int = 200, payload: object = None
|
||||||
|
) -> MagicMock:
|
||||||
|
"""Build a fake ``requests.Response``."""
|
||||||
|
response = MagicMock()
|
||||||
|
response.ok = ok
|
||||||
|
response.status_code = status
|
||||||
|
response.text = "" if ok else "the error body"
|
||||||
|
response.json.return_value = payload if payload is not None else {}
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def _run(result: dict[str, str], post: MagicMock | Exception, **kwargs: object) -> str:
|
||||||
|
"""Drive ``fetch_id_token`` against a canned callback and exchange."""
|
||||||
|
starter, free_port, handler, _, _ = _fake_flow(result)
|
||||||
|
with starter, free_port, handler:
|
||||||
|
target = patch.object(git.requests, "post")
|
||||||
|
with target as posted:
|
||||||
|
if isinstance(post, Exception):
|
||||||
|
posted.side_effect = post
|
||||||
|
else:
|
||||||
|
posted.return_value = post
|
||||||
|
return git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def test_successful_flow_returns_the_id_token() -> None:
|
||||||
|
"""The happy path: a matching callback exchanged for an id_token."""
|
||||||
|
result = {"code": "the-auth-code", "state": _STATE}
|
||||||
|
|
||||||
|
token = _run(result, _response(payload={"id_token": _ID_VALUE}))
|
||||||
|
|
||||||
|
assert token == _ID_VALUE
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_exchange_posts_the_code_and_the_matching_redirect_uri() -> None:
|
||||||
|
"""Google rejects an exchange whose redirect_uri differs from consent's."""
|
||||||
|
starter, free_port, handler, _, _ = _fake_flow(
|
||||||
|
{"code": "the-auth-code", "state": _STATE}, port=8765
|
||||||
|
)
|
||||||
|
with starter, free_port, handler, patch.object(git.requests, "post") as posted:
|
||||||
|
posted.return_value = _response(payload={"id_token": _ID_VALUE})
|
||||||
|
git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL, port=8765)
|
||||||
|
|
||||||
|
sent = posted.call_args.kwargs["data"]
|
||||||
|
assert sent["code"] == "the-auth-code"
|
||||||
|
assert sent["grant_type"] == "authorization_code"
|
||||||
|
assert sent["redirect_uri"] == "http://localhost:8765"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_fixed_port_is_used_verbatim_rather_than_a_free_one() -> None:
|
||||||
|
"""A Web client matches the redirect URI exactly, so --port must win.
|
||||||
|
|
||||||
|
Picking a free port here is the ``redirect_uri_mismatch`` the module
|
||||||
|
docstring warns about, and it fails before the account picker appears.
|
||||||
|
"""
|
||||||
|
starter, free_port, handler, _, _ = _fake_flow(
|
||||||
|
{"code": "c", "state": _STATE}, port=9999
|
||||||
|
)
|
||||||
|
with starter, free_port as picked, handler, patch.object(git.requests, "post") as p:
|
||||||
|
p.return_value = _response(payload={"id_token": _ID_VALUE})
|
||||||
|
git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL, port=8765)
|
||||||
|
|
||||||
|
picked.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_port_zero_falls_back_to_a_free_port() -> None:
|
||||||
|
"""The Desktop-app case: any loopback port is acceptable."""
|
||||||
|
starter, free_port, handler, _, _ = _fake_flow({"code": "c", "state": _STATE})
|
||||||
|
with starter, free_port as picked, handler, patch.object(git.requests, "post") as p:
|
||||||
|
p.return_value = _response(payload={"id_token": _ID_VALUE})
|
||||||
|
git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL, port=0)
|
||||||
|
|
||||||
|
picked.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_browser_is_opened_unless_suppressed(browser: MagicMock) -> None:
|
||||||
|
"""``open_browser=True`` launches the consent page."""
|
||||||
|
_run({"code": "c", "state": _STATE}, _response(payload={"id_token": _ID_VALUE}))
|
||||||
|
|
||||||
|
browser.assert_called_once()
|
||||||
|
assert browser.call_args.args[0].startswith(git._AUTH_ENDPOINT)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_browser_still_reports_the_consent_url(
|
||||||
|
browser: MagicMock,
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
"""Without a browser the URL must still be visible, or the flow is stuck."""
|
||||||
|
with caplog.at_level(logging.INFO, logger="google_id_token"):
|
||||||
|
_run(
|
||||||
|
{"code": "c", "state": _STATE},
|
||||||
|
_response(payload={"id_token": _ID_VALUE}),
|
||||||
|
open_browser=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
browser.assert_not_called()
|
||||||
|
assert any(git._AUTH_ENDPOINT in record.getMessage() for record in caplog.records)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_callback_at_all_is_a_timeout() -> None:
|
||||||
|
"""Nothing arrived on the loopback port before the deadline."""
|
||||||
|
with pytest.raises(git.TokenError, match="no response on http://localhost"):
|
||||||
|
_run({}, _response())
|
||||||
|
|
||||||
|
|
||||||
|
def test_refused_consent_is_reported_as_refusal() -> None:
|
||||||
|
"""Google reports a declined consent as ``error``."""
|
||||||
|
with pytest.raises(git.TokenError, match="refused: access_denied"):
|
||||||
|
_run({"error": "access_denied"}, _response())
|
||||||
|
|
||||||
|
|
||||||
|
def test_mismatched_state_is_rejected() -> None:
|
||||||
|
"""A callback that does not echo the state is not ours."""
|
||||||
|
with pytest.raises(git.TokenError, match="state did not match"):
|
||||||
|
_run({"code": "c", "state": "some-other-state"}, _response())
|
||||||
|
|
||||||
|
|
||||||
|
def test_callback_without_a_code_is_rejected() -> None:
|
||||||
|
"""State matched but no code: nothing to exchange."""
|
||||||
|
with pytest.raises(git.TokenError, match="carried no authorization code"):
|
||||||
|
_run({"state": _STATE, "scope": "openid"}, _response())
|
||||||
|
|
||||||
|
|
||||||
|
def test_network_failure_during_exchange_is_wrapped() -> None:
|
||||||
|
"""A transport error must not surface as a bare requests exception."""
|
||||||
|
boom = requests.ConnectionError("connection refused")
|
||||||
|
|
||||||
|
with pytest.raises(git.TokenError, match="network error exchanging the code"):
|
||||||
|
_run({"code": "c", "state": _STATE}, boom)
|
||||||
|
|
||||||
|
|
||||||
|
def test_http_error_from_the_exchange_is_reported_with_its_status() -> None:
|
||||||
|
"""A non-2xx exchange carries the status, which is what identifies it."""
|
||||||
|
with pytest.raises(git.TokenError, match="HTTP 400"):
|
||||||
|
_run({"code": "c", "state": _STATE}, _response(ok=False, status=400))
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_token_response_without_an_id_token_names_the_likely_cause() -> None:
|
||||||
|
"""Dropping ``openid`` from the scopes yields tokens but no id_token."""
|
||||||
|
with pytest.raises(git.TokenError, match="was 'openid' in the scopes"):
|
||||||
|
_run({"code": "c", "state": _STATE}, _response(payload={"access_token": "a"}))
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_server_is_closed_even_though_the_flow_failed() -> None:
|
||||||
|
"""A leaked listener would make the next run fail to bind the same port."""
|
||||||
|
starter, free_port, handler, server, thread = _fake_flow({})
|
||||||
|
with starter, free_port, handler, pytest.raises(git.TokenError):
|
||||||
|
git.fetch_id_token(_CLIENT_ID, _CLIENT_CREDENTIAL)
|
||||||
|
|
||||||
|
thread.join.assert_called_once()
|
||||||
|
server.server_close.assert_called_once()
|
||||||
93
crdt-sync/crdt_sync/tests/test_tool_google_id_token_cli.py
Normal file
93
crdt-sync/crdt_sync/tests/test_tool_google_id_token_cli.py
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
"""Tests for ``tool/google_id_token``'s command line entry point.
|
||||||
|
|
||||||
|
Split from :mod:`test_tool_google_id_token` to stay under the repo's 250-line
|
||||||
|
file cap. That module covers the OAuth flow itself; this one covers ``main()``
|
||||||
|
-- argument parsing, where the token is written, and the exit code -- with
|
||||||
|
``fetch_id_token`` patched out, since the flow is already exercised there.
|
||||||
|
|
||||||
|
The shared fixture values are imported rather than redeclared so the two
|
||||||
|
files cannot drift.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from crdt_sync.tests.test_tool_google_id_token import (
|
||||||
|
_CLIENT_CREDENTIAL,
|
||||||
|
_CLIENT_ID,
|
||||||
|
_ID_VALUE,
|
||||||
|
)
|
||||||
|
from tool import google_id_token as git
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_prints_the_token_when_no_output_is_given(
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
"""Default: the token goes to the log for copy-paste."""
|
||||||
|
with (
|
||||||
|
patch.object(git, "fetch_id_token", return_value=_ID_VALUE),
|
||||||
|
caplog.at_level(logging.INFO, logger="google_id_token"),
|
||||||
|
):
|
||||||
|
code = git.main(
|
||||||
|
["--client-id", _CLIENT_ID, "--client-secret", _CLIENT_CREDENTIAL]
|
||||||
|
)
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert any(record.getMessage() == _ID_VALUE for record in caplog.records)
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_writes_the_token_to_a_file_at_mode_0600(tmp_path: Path) -> None:
|
||||||
|
"""An ID token is a bearer credential, so the file must not be readable."""
|
||||||
|
destination = tmp_path / "token.txt"
|
||||||
|
|
||||||
|
with patch.object(git, "fetch_id_token", return_value=_ID_VALUE):
|
||||||
|
code = git.main(
|
||||||
|
[
|
||||||
|
"--client-id",
|
||||||
|
_CLIENT_ID,
|
||||||
|
"--client-secret",
|
||||||
|
_CLIENT_CREDENTIAL,
|
||||||
|
"--output",
|
||||||
|
str(destination),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
assert code == 0
|
||||||
|
assert destination.read_text(encoding="utf-8") == _ID_VALUE
|
||||||
|
assert destination.stat().st_mode & 0o777 == 0o600
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_passes_no_browser_and_port_through() -> None:
|
||||||
|
"""The two flags that decide whether the flow can work at all."""
|
||||||
|
with patch.object(git, "fetch_id_token", return_value=_ID_VALUE) as fetch:
|
||||||
|
git.main(
|
||||||
|
[
|
||||||
|
"--client-id",
|
||||||
|
_CLIENT_ID,
|
||||||
|
"--client-secret",
|
||||||
|
_CLIENT_CREDENTIAL,
|
||||||
|
"--no-browser",
|
||||||
|
"--port",
|
||||||
|
"8765",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
assert fetch.call_args.kwargs == {"open_browser": False, "port": 8765}
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_returns_1_when_the_flow_fails() -> None:
|
||||||
|
"""A TokenError is an exit code, not a traceback."""
|
||||||
|
with patch.object(git, "fetch_id_token", side_effect=git.TokenError("nope")):
|
||||||
|
code = git.main(
|
||||||
|
["--client-id", _CLIENT_ID, "--client-secret", _CLIENT_CREDENTIAL]
|
||||||
|
)
|
||||||
|
|
||||||
|
assert code == 1
|
||||||
211
crdt-sync/crdt_sync/tests/test_tool_oauth_callback.py
Normal file
211
crdt-sync/crdt_sync/tests/test_tool_oauth_callback.py
Normal file
@ -0,0 +1,211 @@
|
|||||||
|
"""Tests for the one-shot OAuth redirect catcher in ``tool/_oauth_callback``.
|
||||||
|
|
||||||
|
No network access: everything binds 127.0.0.1 on a port the module itself
|
||||||
|
picks. The handler is driven over real HTTP rather than with a faked request
|
||||||
|
object, because the branches worth protecting here are the ones that only
|
||||||
|
appear once a socket is involved -- the favicon fetch that must *not* end the
|
||||||
|
flow, and the serve loop's exit conditions, which run on a worker thread.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import http.server
|
||||||
|
import time
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tool import _oauth_callback as oc
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
import threading
|
||||||
|
|
||||||
|
_STATE = "state-the-callback-must-echo"
|
||||||
|
|
||||||
|
|
||||||
|
def _get(port: int, path: str) -> tuple[int, bytes]:
|
||||||
|
"""Issue one GET against the loopback server and read the whole reply."""
|
||||||
|
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
|
||||||
|
try:
|
||||||
|
conn.request("GET", path)
|
||||||
|
response = conn.getresponse()
|
||||||
|
return response.status, response.read()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _retire(srv: http.server.HTTPServer, thread: threading.Thread) -> None:
|
||||||
|
"""Stop the serve thread, then close the socket -- in that order.
|
||||||
|
|
||||||
|
``server_close()`` while the thread is still inside ``handle_request()``
|
||||||
|
pulls the socket out from under it and raises on the worker. Setting a
|
||||||
|
result is what the loop's own exit condition tests, so it retires the
|
||||||
|
thread the same way a real callback does.
|
||||||
|
"""
|
||||||
|
oc._CallbackHandler.result = oc._CallbackHandler.result or {"code": "teardown"}
|
||||||
|
thread.join(timeout=5)
|
||||||
|
srv.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def server() -> Iterator[tuple[int, threading.Thread]]:
|
||||||
|
"""Start the callback server on a free port and always tear it down."""
|
||||||
|
port = oc._free_port()
|
||||||
|
srv, thread = oc._start_callback_server(port, _STATE)
|
||||||
|
try:
|
||||||
|
yield port, thread
|
||||||
|
finally:
|
||||||
|
_retire(srv, thread)
|
||||||
|
|
||||||
|
|
||||||
|
def test_free_port_returns_a_bindable_loopback_port() -> None:
|
||||||
|
"""The port is real and free: binding it again must succeed."""
|
||||||
|
port = oc._free_port()
|
||||||
|
|
||||||
|
assert 1024 < port <= 65535
|
||||||
|
# The socket is closed by the time _free_port returns, so a second server
|
||||||
|
# can take the port. If it could not, the callback server would race the
|
||||||
|
# probe socket and fail to bind.
|
||||||
|
srv, thread = oc._start_callback_server(port, _STATE)
|
||||||
|
_retire(srv, thread)
|
||||||
|
|
||||||
|
|
||||||
|
def test_callback_with_matching_state_is_recorded_and_acked(
|
||||||
|
server: tuple[int, threading.Thread],
|
||||||
|
) -> None:
|
||||||
|
"""The happy path: code + matching state -> 200, and the loop exits."""
|
||||||
|
port, thread = server
|
||||||
|
|
||||||
|
status, body = _get(port, f"/?code=the-code&state={_STATE}")
|
||||||
|
|
||||||
|
assert status == 200
|
||||||
|
assert b"you can close this tab" in body
|
||||||
|
assert oc._CallbackHandler.result == {"code": "the-code", "state": _STATE}
|
||||||
|
# The serve loop's `while not result` condition must now be false, so the
|
||||||
|
# thread retires on its own rather than sitting on the socket.
|
||||||
|
thread.join(timeout=5)
|
||||||
|
assert not thread.is_alive()
|
||||||
|
|
||||||
|
|
||||||
|
def test_mismatched_state_is_recorded_but_reported_as_failure(
|
||||||
|
server: tuple[int, threading.Thread],
|
||||||
|
) -> None:
|
||||||
|
"""A code echoing the wrong state is a failure, not a success."""
|
||||||
|
port, thread = server
|
||||||
|
|
||||||
|
status, body = _get(port, "/?code=the-code&state=not-the-state")
|
||||||
|
|
||||||
|
assert status == 400
|
||||||
|
assert b"Authorization failed" in body
|
||||||
|
# Still recorded: the caller needs to see what came back to explain it.
|
||||||
|
assert oc._CallbackHandler.result["state"] == "not-the-state"
|
||||||
|
thread.join(timeout=5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_callback_without_a_code_is_reported_as_failure(
|
||||||
|
server: tuple[int, threading.Thread],
|
||||||
|
) -> None:
|
||||||
|
"""Google reports a declined consent as ``error``, with no ``code``."""
|
||||||
|
port, thread = server
|
||||||
|
|
||||||
|
status, body = _get(port, "/?error=access_denied")
|
||||||
|
|
||||||
|
assert status == 400
|
||||||
|
assert b"Authorization failed" in body
|
||||||
|
assert oc._CallbackHandler.result == {"error": "access_denied"}
|
||||||
|
thread.join(timeout=5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_favicon_fetch_is_answered_but_does_not_end_the_flow(
|
||||||
|
server: tuple[int, threading.Thread],
|
||||||
|
) -> None:
|
||||||
|
"""The regression this module's docstring is about.
|
||||||
|
|
||||||
|
Browsers fetch /favicon.ico against the redirect origin. Treating that as
|
||||||
|
the callback retires the server before Google ever redirects, which the
|
||||||
|
user sees as a consent timeout.
|
||||||
|
"""
|
||||||
|
port, thread = server
|
||||||
|
|
||||||
|
status, body = _get(port, "/favicon.ico")
|
||||||
|
|
||||||
|
assert status == 204
|
||||||
|
assert body == b""
|
||||||
|
assert oc._CallbackHandler.result == {}
|
||||||
|
# Still serving: the real callback can still arrive and be recorded.
|
||||||
|
assert thread.is_alive()
|
||||||
|
|
||||||
|
status, _ = _get(port, f"/?code=late-code&state={_STATE}")
|
||||||
|
assert status == 200
|
||||||
|
assert oc._CallbackHandler.result["code"] == "late-code"
|
||||||
|
thread.join(timeout=5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_serve_loop_gives_up_once_the_consent_deadline_passes(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
"""The other loop exit: no callback ever arrives.
|
||||||
|
|
||||||
|
The deadline is 300s of wall clock, so it is moved into the past instead
|
||||||
|
of waited out. `server.timeout` bounds handle_request(), which is what
|
||||||
|
lets the loop re-test the deadline at all.
|
||||||
|
"""
|
||||||
|
monkeypatch.setattr(oc, "_CONSENT_TIMEOUT_SECONDS", -1)
|
||||||
|
|
||||||
|
port = oc._free_port()
|
||||||
|
srv, thread = oc._start_callback_server(port, _STATE)
|
||||||
|
try:
|
||||||
|
thread.join(timeout=5)
|
||||||
|
assert not thread.is_alive()
|
||||||
|
assert oc._CallbackHandler.result == {}
|
||||||
|
finally:
|
||||||
|
_retire(srv, thread)
|
||||||
|
|
||||||
|
|
||||||
|
def test_log_message_writes_nothing_to_stderr(
|
||||||
|
server: tuple[int, threading.Thread],
|
||||||
|
capfd: pytest.CaptureFixture[str],
|
||||||
|
) -> None:
|
||||||
|
"""The default handler logs every request to stderr; this one must not.
|
||||||
|
|
||||||
|
Asserted through a real request rather than by calling the override
|
||||||
|
directly: it returns None either way, so only the absence of output
|
||||||
|
distinguishes a silenced handler from the stock one.
|
||||||
|
"""
|
||||||
|
port, _ = server
|
||||||
|
|
||||||
|
_get(port, f"/?code=the-code&state={_STATE}")
|
||||||
|
|
||||||
|
assert capfd.readouterr().err == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_starting_the_server_resets_state_from_a_previous_run() -> None:
|
||||||
|
"""Class attributes outlive one flow, so a stale result must not leak."""
|
||||||
|
oc._CallbackHandler.result = {"code": "stale-from-an-earlier-flow"}
|
||||||
|
oc._CallbackHandler.expected_state = "stale-state"
|
||||||
|
|
||||||
|
port = oc._free_port()
|
||||||
|
srv, thread = oc._start_callback_server(port, _STATE)
|
||||||
|
try:
|
||||||
|
assert oc._CallbackHandler.result == {}
|
||||||
|
assert oc._CallbackHandler.expected_state == _STATE
|
||||||
|
finally:
|
||||||
|
_retire(srv, thread)
|
||||||
|
|
||||||
|
|
||||||
|
def test_time_is_not_slept_away_by_the_fixture() -> None:
|
||||||
|
"""Guard against the deadline being computed once at import time.
|
||||||
|
|
||||||
|
If ``deadline`` were module-level rather than per-call, a server started
|
||||||
|
later in the session would inherit an already-expired deadline and never
|
||||||
|
serve. Starting one now and checking it is alive catches that.
|
||||||
|
"""
|
||||||
|
port = oc._free_port()
|
||||||
|
srv, thread = oc._start_callback_server(port, _STATE)
|
||||||
|
try:
|
||||||
|
time.sleep(0.05)
|
||||||
|
assert thread.is_alive()
|
||||||
|
finally:
|
||||||
|
_retire(srv, thread)
|
||||||
@ -49,8 +49,16 @@ from tool.google_id_token import TokenError, fetch_id_token
|
|||||||
# discovered from ~/.config, because a missing directory is exactly the case
|
# discovered from ~/.config, because a missing directory is exactly the case
|
||||||
# that needs seeding -- discovery would skip the app that needs this most.
|
# that needs seeding -- discovery would skip the app that needs this most.
|
||||||
#
|
#
|
||||||
# The Flutter-only apps (todo, home_inventory, workout_app) are absent on
|
# The remaining Flutter-only apps (home_inventory, workout_app) are absent on
|
||||||
# purpose: they authenticate in-app on the phone and have no desktop session.
|
# purpose: they authenticate in-app on the phone and have no desktop session.
|
||||||
|
# `todo` used to be grouped with them, but it grew a real desktop wrapper
|
||||||
|
# (lib/desktop/wrapper_server.dart) with its own Firebase REST client that
|
||||||
|
# needs a session exactly like the Python daemons do -- see
|
||||||
|
# lib/sync/firebase_backend.dart and lib/desktop/wrapper_server.dart in
|
||||||
|
# ~/todo. Its credential cache lives at ~/.config/todo/firebase_auth.json,
|
||||||
|
# same shape as every entry below, even though the reader is Dart, not
|
||||||
|
# Python: FirebaseCredentials.fromJson in crdt_sync_dart parses the exact
|
||||||
|
# {id_token, refresh_token, expires_at} shape credential_store_for writes.
|
||||||
#
|
#
|
||||||
# Re-derive rather than guess when adding one; a repo-by-repo sweep missed two
|
# Re-derive rather than guess when adding one; a repo-by-repo sweep missed two
|
||||||
# of these. Grep all of ~ for the string literal passed to firebase_client_for,
|
# of these. Grep all of ~ for the string literal passed to firebase_client_for,
|
||||||
@ -64,6 +72,7 @@ DEFAULT_APPS = (
|
|||||||
"screen_locker",
|
"screen_locker",
|
||||||
"byox_ladder",
|
"byox_ladder",
|
||||||
"leetcode_guard",
|
"leetcode_guard",
|
||||||
|
"todo",
|
||||||
)
|
)
|
||||||
|
|
||||||
# A fixed default so the redirect URI is stable enough to register once on the
|
# A fixed default so the redirect URI is stable enough to register once on the
|
||||||
|
|||||||
197
prompts/post-250-cap-cleanup.md
Normal file
197
prompts/post-250-cap-cleanup.md
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
> **This file is a ready-to-use prompt.** Open this repo (`~/utils`) and say
|
||||||
|
> "do post-250-cap-cleanup". It is self-contained -- it needs no context from
|
||||||
|
> any other session.
|
||||||
|
>
|
||||||
|
> Generated 2026-08-22 at the end of the session that finished
|
||||||
|
> `refactor_claude_todo.md` (the 250-line cap). Everything below was measured
|
||||||
|
> in that session; **re-verify each figure before trusting it**, since the
|
||||||
|
> numbers are a snapshot.
|
||||||
|
|
||||||
|
## ⛔ WHEN YOU FINISH THIS PROMPT
|
||||||
|
|
||||||
|
Delete this file and commit that deletion together with the work:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git rm prompts/post-250-cap-cleanup.md
|
||||||
|
```
|
||||||
|
|
||||||
|
A finished prompt left in the repo is indistinguishable from a pending one,
|
||||||
|
and the next session will re-run it. If you complete only some of the four
|
||||||
|
tasks, do **not** delete it -- strike through the finished ones instead and
|
||||||
|
leave the rest.
|
||||||
|
|
||||||
|
**Current state: only Task 2 is left.** Delete this file once `tool/` is
|
||||||
|
covered and the config flip has landed -- not before.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The 250-line file cap is done and enforced: `bash
|
||||||
|
scripts/check_file_length.sh --all` exits 0, a pre-commit hook blocks an
|
||||||
|
over-cap commit, and `.github/workflows/file-length.yml` runs the same check
|
||||||
|
on push. **Do not undo any of that.** Every new file this prompt creates must
|
||||||
|
also stay at or under 250 lines -- the hook will block your commit otherwise,
|
||||||
|
which is the point.
|
||||||
|
|
||||||
|
Four loose ends were deliberately left. **Three are now done** (1, 3 and 4 --
|
||||||
|
see the struck-through sections, which record what was actually found; the
|
||||||
|
prompt's original diagnosis was wrong for both 1 and 4). **Only Task 2
|
||||||
|
remains.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ~~Task 1 -- make `web-ui-tests` green~~ -- DONE (53f2816)
|
||||||
|
|
||||||
|
The diagnosis above was wrong, so it is replaced rather than struck through.
|
||||||
|
`dist/` had not drifted: all 16 files were byte-identical to a fresh build
|
||||||
|
except for a **trailing newline** that `tsc` does not emit.
|
||||||
|
|
||||||
|
At `03bf1ed` the subproject config had no `exclude`, so pre-commit's
|
||||||
|
`end-of-file-fixer` appended a newline to each generated file. `eaa5683` added
|
||||||
|
`exclude: ^web_ui/dist/` so it would not recur, but never reverted the
|
||||||
|
newlines already committed -- leaving a `dist/` that no `pnpm build` could
|
||||||
|
reproduce, and a job that could never pass.
|
||||||
|
|
||||||
|
It looked fine locally because `tsc -b` is incremental: with a warm
|
||||||
|
`tsconfig.tsbuildinfo` it skips emit entirely, so `pnpm build` was a no-op and
|
||||||
|
showed no diff. CI has no cache, always emits, always failed. To reproduce
|
||||||
|
locally, delete `web_ui/tsconfig.tsbuildinfo` first -- otherwise you are
|
||||||
|
testing nothing.
|
||||||
|
|
||||||
|
Fixed by committing the real `tsc` output. Verified green on CI (run
|
||||||
|
32578353684), `pnpm lint` clean, `pnpm coverage` 84 tests / 100%.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 2 -- put `crdt-sync/tool/` under test at 100% coverage
|
||||||
|
|
||||||
|
**Read this scope note before starting; it is bigger than it first looks.**
|
||||||
|
|
||||||
|
`crdt-sync/pyproject.toml` measures `--cov=crdt_sync` with
|
||||||
|
`source = ["crdt_sync"]`, so the whole `tool/` package is currently
|
||||||
|
unmeasured. The trigger for this task was `tool/_oauth_callback.py` (105
|
||||||
|
lines, extracted during the cap work, whose `_start_callback_server` runtime
|
||||||
|
path is unexercised) -- but adding `tool` to the coverage source pulls in
|
||||||
|
**seven modules, ~1350 lines**, none of which have tests today:
|
||||||
|
|
||||||
|
| lines | file |
|
||||||
|
| ----: | :--- |
|
||||||
|
| 250 | `tool/seed_session.py` |
|
||||||
|
| 243 | `tool/link_google.py` |
|
||||||
|
| 233 | `tool/google_id_token.py` |
|
||||||
|
| 216 | `tool/migrate_github_to_firebase.py` |
|
||||||
|
| 212 | `tool/preflight_firebase.py` |
|
||||||
|
| 105 | `tool/_oauth_callback.py` |
|
||||||
|
| 89 | `tool/interop_seed.py` |
|
||||||
|
| 6 | `tool/__init__.py` |
|
||||||
|
|
||||||
|
The bar in this repo is **100% branch coverage, and omitting packages from
|
||||||
|
coverage is forbidden** (`~/.claude/memories/code-quality.md`: "NEVER omit
|
||||||
|
packages from coverage. Write tests for everything." and "even if it takes
|
||||||
|
hours"). So the honest shape of this task is: test all of `tool/`, not just
|
||||||
|
the one file.
|
||||||
|
|
||||||
|
**Suggested order** -- land each as its own commit so partial progress is
|
||||||
|
useful:
|
||||||
|
|
||||||
|
1. `_oauth_callback.py` first. It is the reason this task exists and the only
|
||||||
|
one with no network dependency: `_free_port` binds a real socket,
|
||||||
|
`_CallbackHandler` can be driven with a fake request, and
|
||||||
|
`_start_callback_server` can be exercised against `http.client` on the port
|
||||||
|
it picks. Do this one even if you do nothing else.
|
||||||
|
2. `google_id_token.py` -- `fetch_id_token` is a `requests` call; mock at the
|
||||||
|
session boundary the way `crdt_sync/tests/test_firebase_auth.py` already
|
||||||
|
does. `main()` is argparse; test it via `main(["--client-id", ...])`.
|
||||||
|
3. The rest, largest-payoff first.
|
||||||
|
|
||||||
|
Only after every module is covered, flip the config:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
addopts = [..., "--cov=crdt_sync", "--cov=tool", ...]
|
||||||
|
[tool.coverage.run]
|
||||||
|
source = ["crdt_sync", "tool"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Flipping it earlier makes the suite fail on the 100% gate for every module you
|
||||||
|
have not reached yet, which blocks unrelated commits -- so it is the **last**
|
||||||
|
step, not the first.
|
||||||
|
|
||||||
|
**Traps, all hit during the cap work:**
|
||||||
|
|
||||||
|
- Tests live in `crdt-sync/crdt_sync/tests/`, and `testpaths` points there. A
|
||||||
|
`tool/` test still belongs under that directory (e.g.
|
||||||
|
`crdt_sync/tests/test_tool_oauth_callback.py`) unless you also extend
|
||||||
|
`testpaths` -- decide once and be consistent.
|
||||||
|
- `tool` is imported as a package from the `crdt-sync` root
|
||||||
|
(`python3 -m tool.google_id_token`, and `seed_session.py` does
|
||||||
|
`from tool.google_id_token import ...`). Do not "fix" those to relative
|
||||||
|
imports.
|
||||||
|
- Do **not** add `# noqa` or `# type: ignore` anywhere; the repo bans them and
|
||||||
|
a pre-commit hook blocks them. If lint fights you, fix the code.
|
||||||
|
- Run the CI-pinned ruff, not whatever `ls | head -1` finds. The cache holds
|
||||||
|
three versions and CI pins **0.15.2**:
|
||||||
|
`/home/kuhy/.cache/pre-commit/repodhz30fnk/py_env-python3/bin/ruff`.
|
||||||
|
Confirm with `--version`; 0.14.5 misses findings that fail CI.
|
||||||
|
- Verify with `bash scripts/check_file_length.sh --all` and
|
||||||
|
`pre-commit run --config crdt-sync/.pre-commit-config.yaml --all-files`
|
||||||
|
(the `--all-files` run catches ruff pruning re-export imports, which broke
|
||||||
|
`import crdt_sync` three times during the cap work).
|
||||||
|
|
||||||
|
**Done when:** `source = ["crdt_sync", "tool"]` is in effect and
|
||||||
|
`bash scripts/run_subproject_tests.sh crdt-sync` still reports 100% with the
|
||||||
|
suite green. Baseline before you start: **259 passed, 100%**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ~~Task 3 -- resolve the three dirty working-tree items~~ -- DONE
|
||||||
|
|
||||||
|
- **`seed_session.py`** -- both files its comment cites were re-confirmed
|
||||||
|
present, so the change was committed as-is (9d638fb).
|
||||||
|
- **`firebase-debug.log`** -- deleted, and the root `.gitignore` now covers it
|
||||||
|
plus the sibling logs the Firebase CLI writes (e0eef3d).
|
||||||
|
- **`staged/`** -- the user chose *apply*. `APPLY.sh` installed the split into
|
||||||
|
`~/.claude` (committed there as e0cf24a): `phone_deploy.sh` 311 -> 140 lines
|
||||||
|
with three sourced libs, 12/12 function parity, and the unreachable-device
|
||||||
|
path still exiting 30. `staged/` was then removed; the pre-split original
|
||||||
|
remains recoverable from `~/.claude` at `80cd45e`.
|
||||||
|
**Still unverified:** the build/install/launch tail, which needs a real APK
|
||||||
|
install on the phone (`bash ~/.claude/scripts/phone_deploy.sh ~/todo
|
||||||
|
--release`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ~~Task 4 -- fix the stale skill pointer~~ -- DONE (~/.claude e0cf24a)
|
||||||
|
|
||||||
|
The description above was partly wrong: `README.md` **does** still hold the
|
||||||
|
per-stack patterns and the "Do NOT" list. What actually split out during the
|
||||||
|
cap work was the pointer-free-operability and screen-size material, into
|
||||||
|
`operability.md` (rules) and `operability-patterns.md` (per-stack code);
|
||||||
|
README's "Pointer-free + small-screen" section is now a stub pointing at them.
|
||||||
|
|
||||||
|
`~/.claude/skills/unified-design-system/SKILL.md` now lists both new files and
|
||||||
|
tells the reader to read `operability.md` before building any interactive
|
||||||
|
widget, since its rules are marked required. All six relative links were
|
||||||
|
checked to resolve. This edit lives outside `~/utils`, so `git status` here
|
||||||
|
will never show it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verify (all four)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/utils
|
||||||
|
bash scripts/check_file_length.sh --all # must exit 0
|
||||||
|
bash scripts/run_subproject_tests.sh crdt-sync # 100% coverage
|
||||||
|
pre-commit run --config crdt-sync/.pre-commit-config.yaml --all-files
|
||||||
|
git status --short # should be empty
|
||||||
|
gh run list --limit 10 # all workflows green
|
||||||
|
```
|
||||||
|
|
||||||
|
`web-ui-tests` was the one red workflow; it went green at 53f2816. Note that
|
||||||
|
`git status` here cannot see the Task 3/4 edits under `~/.claude` -- those are
|
||||||
|
committed in that repo (e0cf24a), not this one.
|
||||||
|
|
||||||
|
One finding outside the four tasks, left for the user to decide:
|
||||||
|
`~/.claude/scripts/finish.sh` is **309 lines**, over the cap. It does not
|
||||||
|
block anything today -- the hook checks staged files only, so it fires only if
|
||||||
|
a commit stages that file -- but it is the last known over-cap file in that
|
||||||
|
repo.
|
||||||
Loading…
Reference in New Issue
Block a user