diff --git a/docs/system-specs/modules/kas-auth.md b/docs/system-specs/modules/kas-auth.md index 91cbcbb4c885..ff2eb39634ca 100644 --- a/docs/system-specs/modules/kas-auth.md +++ b/docs/system-specs/modules/kas-auth.md @@ -335,6 +335,24 @@ shutdown budget) for an in-flight renewal to finish (`drain_sign_in_refresher`), so a rotated refresh token is persisted rather than consumed at the issuer and lost to the hard exit. +### Proxy + +Every request this module sends to the sign-in service (device authorization and +its polls, the portal and external IdP code exchanges, SSO-OIDC registration, +device authorization and token polls, the control-plane profile lookup, and all +three refresh paths) passes `proxy=resolve_proxy(url)` from `kiro_crew.http_proxy`. +So `HTTPS_PROXY` / `HTTP_PROXY` and `NO_PROXY` apply as they do for kiro-cli, while +the sessions keep aiohttp's `trust_env` off and never pick up `~/.netrc` +credentials. Every session that sends them is bounded by `refresh.HTTP_TIMEOUT` +(30s total, 10s connect): the login service's shared session, the temporary +session `KasAuthProvider` opens for an engine callback, and the gateway tick's +own 8s cap. A proxy's own refusal on the engine's side (a line naming the proxy, +its tunnel or the `CONNECT` request, with a 401/403/407 or a tunnel failure) is a +network error, not a sign-out: `acp/transport_errors._is_proxy_refusal` keeps it +out of the signed-out latch and the chat says the proxy blocked the request. A +bare `status code 403` cannot be told from Kiro's own rejection and still reads as +signed out. + ## Storage Context: kiro-cli does **not** encrypt its tokens — they live plaintext in a SQLite diff --git a/src/kiro_crew/acp/proxy_refusal.py b/src/kiro_crew/acp/proxy_refusal.py new file mode 100644 index 000000000000..9782b87a50cd --- /dev/null +++ b/src/kiro_crew/acp/proxy_refusal.py @@ -0,0 +1,74 @@ +"""Telling an HTTP proxy's own refusal apart from the service refusing a credential. + +The status and "authentication required" wording that marks a rejected sign-in +also fires on a proxy's own 403/407, which then read as "not signed in" and point +at the sign-in card while the fix is the network's proxy. These helpers match per +LINE and only on a line that names the proxy (or the tunnel or CONNECT request it +runs), because a bare "status code 403" cannot be told apart from Kiro's own +rejection and must keep its sign-in verdict. A named service exception is never a +proxy's answer and is not affected. + +Wording covered: reqwest/hyper's "407 Proxy Authentication Required" status +display and "tunnel error: ...", curl's "Received HTTP code 403 from proxy after +CONNECT" and "CONNECT tunnel failed", undici's "Proxy response (403) !== 200 when +HTTP Tunneling", and the "tunneling socket could not be established" of Node's +tunnel agents. + +``kiro_crew.acp.transport_errors`` re-exports every name defined here. +""" + +from __future__ import annotations + +from collections.abc import Callable + +_PROXY_WORDS = frozenset({"proxy", "tunnel", "tunneling"}) +_REFUSAL_CODES = frozenset({"401", "403", "407"}) +_REFUSAL_PHRASES = ( + "authentication required", + "authorization required", + "tunnel error", + "tunnel failed", + "tunneling failed", + "could not be established", + "!== 200", +) + + +def _split_on(line: str, keep: Callable[[str], bool]) -> list[str]: + """*line* split into runs of the characters *keep* accepts.""" + return "".join(c if keep(c) else " " for c in line).split() + + +def _names_proxy(line: str) -> bool: + if "CONNECT" in _split_on(line, str.isalpha): + return True + return not _PROXY_WORDS.isdisjoint(_split_on(line.lower(), str.isalpha)) + + +def _refuses(line: str) -> bool: + if not _REFUSAL_CODES.isdisjoint(_split_on(line, str.isalnum)): + return True + lower = line.lower() + return any(phrase in lower for phrase in _REFUSAL_PHRASES) + + +#: The chat text for a request a proxy refused. Signing in again cannot help. +PROXY_REFUSAL_TEXT = ( + "A network proxy blocked the request to the model backend. Check the " + "proxy settings on this computer (HTTPS_PROXY, NO_PROXY) or ask your " + "network administrator to allow the Kiro service." +) + + +def _proxy_refusal_line(line: str) -> bool: + return _names_proxy(line) and _refuses(line) + + +def _is_proxy_refusal(haystack: str) -> bool: + """True when a line of *haystack* is an HTTP proxy refusing the request.""" + return any(_proxy_refusal_line(line) for line in haystack.splitlines()) + + +def drop_proxy_refusal_lines(haystack: str) -> str: + """*haystack* without the lines :func:`_is_proxy_refusal` claims.""" + return "\n".join(line for line in haystack.splitlines() if not _proxy_refusal_line(line)) diff --git a/src/kiro_crew/acp/transport_errors.py b/src/kiro_crew/acp/transport_errors.py index d163b05f0119..505b7151c9fd 100644 --- a/src/kiro_crew/acp/transport_errors.py +++ b/src/kiro_crew/acp/transport_errors.py @@ -50,6 +50,12 @@ _RE_OVERSIZED_REQUEST, _is_request_size_exceeded, ) +from kiro_crew.acp.proxy_refusal import ( # noqa: F401 - re-exported + PROXY_REFUSAL_TEXT, + _is_proxy_refusal, + _proxy_refusal_line, + drop_proxy_refusal_lines, +) from kiro_crew.acp.runtime_models import ( DEFAULT_MODEL, advertised_model_ids, @@ -714,7 +720,12 @@ def _is_session_expired(haystack: str) -> bool: All three signals are terminal: retrying can neither refresh a login nor revive a credential the upstream has rejected. Checked before the 5xx family so an aborted request's transport error does not shadow the real cause. + + A line that :func:`_is_proxy_refusal` claims is left out first: a proxy's 403 + or 407 is the network refusing the request, not Kiro refusing the credential. """ + if _is_proxy_refusal(haystack): + haystack = drop_proxy_refusal_lines(haystack) return bool( _RE_AUTH_STATUS.search(haystack) or _RE_SESSION_EXPIRED.search(haystack) @@ -1255,7 +1266,7 @@ def _is_transient_raw_error(error: object, available_models: Sequence[str] | Non if _is_session_expired(haystack): # Session expiry is terminal — retrying can't refresh an expired login. return False - if _RE_CONNECTION.search(haystack): + if _RE_CONNECTION.search(haystack) or _is_proxy_refusal(haystack): # A temporary endpoint failure is safe for the bounded retry ladder. return True return bool( @@ -1339,6 +1350,8 @@ def classify_provider_error(haystack: str, *, data: str | None = None) -> Provid match = _RE_CONNECTION.search(text) or _RE_CONNECTOR_FAILURE.search(text) if match: return ProviderErrorClass(PROVIDER_ERROR_CONNECTION, True, match.group(0)) + if _is_proxy_refusal(text): + return ProviderErrorClass(PROVIDER_ERROR_CONNECTION, True, "proxy refusal") match = ( _RE_5XX_NAMED.search(text) or _RE_5XX_STATUS.search(text) @@ -1640,6 +1653,10 @@ def _format_acp_error_worded( ) elif is_model_registry_unavailable(error.get("data")): formatted = MODEL_REGISTRY_UNAVAILABLE_TEXT + req_id_suffix + elif _is_proxy_refusal(haystack): + # A proxy between this computer and the backend refused the request. + # Signing in again cannot help, so this does not take the sign-in arm. + formatted = PROXY_REFUSAL_TEXT + req_id_suffix elif _RE_CONNECTION.search(haystack) or _RE_CONNECTOR_FAILURE.search(haystack): formatted = ( "Could not reach the model backend (connection refused, reset, " diff --git a/src/kiro_crew/auth/login/builder_id.py b/src/kiro_crew/auth/login/builder_id.py index ab79238430db..5f5843c7741e 100644 --- a/src/kiro_crew/auth/login/builder_id.py +++ b/src/kiro_crew/auth/login/builder_id.py @@ -38,6 +38,7 @@ oidc_url, ) from kiro_crew.auth.store import KasToken +from kiro_crew.http_proxy import resolve_proxy logger = logging.getLogger(__name__) @@ -161,7 +162,7 @@ async def register_client( "clientType": "public", "scopes": list(scopes), } - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post(url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url)) as resp: if resp.status not in (200, 201): body = await resp.text() raise BuilderIdAuthError(f"RegisterClient failed: HTTP {resp.status} {body}") @@ -210,7 +211,7 @@ async def start_device_authorization( "clientSecret": client.client_secret, "startUrl": start_url, } - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post(url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url)) as resp: if resp.status != 200: body = await resp.text() if resp.status == 400 and start_url != BUILDER_ID_START_URL: @@ -259,7 +260,7 @@ async def poll_token_once( "grantType": _DEVICE_GRANT, "deviceCode": auth.device_code, } - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post(url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url)) as resp: try: data = await resp.json(content_type=None) except (aiohttp.ClientError, ValueError, asyncio.TimeoutError): @@ -298,7 +299,9 @@ async def poll_token( "deviceCode": auth.device_code, } while datetime.now(timezone.utc) < auth.expires_at: - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post( + url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url) + ) as resp: data = await resp.json() if resp.status == 200: return _token_from_create(data, client, region, identity, provider) diff --git a/src/kiro_crew/auth/login/control_plane.py b/src/kiro_crew/auth/login/control_plane.py index bab09546b645..010ab1b5a3bb 100644 --- a/src/kiro_crew/auth/login/control_plane.py +++ b/src/kiro_crew/auth/login/control_plane.py @@ -34,6 +34,7 @@ import aiohttp from kiro_crew.auth.login.endpoints import USER_AGENT +from kiro_crew.http_proxy import resolve_proxy logger = logging.getLogger(__name__) @@ -137,7 +138,7 @@ async def _profiles_page( a non-200, an undecodable or malformed body, or a ``nextToken`` that is not a string. """ - async with session.post(url, json=body, headers=headers) as resp: + async with session.post(url, json=body, headers=headers, proxy=resolve_proxy(url)) as resp: if resp.status != 200: # The body is only log material. A mislabelled or unknown charset makes # decoding raise, and that must still end as ControlPlaneError so the diff --git a/src/kiro_crew/auth/login/device.py b/src/kiro_crew/auth/login/device.py index bb5f6772271d..1fc426aa257a 100644 --- a/src/kiro_crew/auth/login/device.py +++ b/src/kiro_crew/auth/login/device.py @@ -31,6 +31,7 @@ social_service_url, ) from kiro_crew.auth.store import KasToken, SocialProvider +from kiro_crew.http_proxy import resolve_proxy logger = logging.getLogger(__name__) @@ -61,7 +62,7 @@ async def initiate_device_authorization( """Step 1 — request a device code the user will approve in a browser.""" url = f"{social_service_url()}/oauth/device/authorization" payload = {"clientId": USER_AGENT, "loginProvider": provider.value} - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post(url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url)) as resp: if resp.status != 200: body = await resp.text() raise DeviceAuthError(f"device authorization failed: HTTP {resp.status} {body}") @@ -100,7 +101,9 @@ async def poll_device_token( payload = {"deviceCode": auth.device_code, "clientId": USER_AGENT} while datetime.now(timezone.utc) < auth.expires_at: - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post( + url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url) + ) as resp: if resp.status != 200: body = await resp.text() logger.warning("device poll HTTP %s: %s", resp.status, body) diff --git a/src/kiro_crew/auth/login/external_idp.py b/src/kiro_crew/auth/login/external_idp.py index 5ead241aaf6e..0cb3dd8b8c5c 100644 --- a/src/kiro_crew/auth/login/external_idp.py +++ b/src/kiro_crew/auth/login/external_idp.py @@ -20,6 +20,7 @@ from kiro_crew.auth.login.endpoints import DEFAULT_TOKEN_TTL_SECS, USER_AGENT from kiro_crew.auth.store import KasToken +from kiro_crew.http_proxy import resolve_proxy logger = logging.getLogger(__name__) @@ -89,7 +90,10 @@ async def exchange_code( "code_verifier": code_verifier, } async with session.post( - meta.token_endpoint, data=form, headers={"User-Agent": USER_AGENT} + meta.token_endpoint, + data=form, + headers={"User-Agent": USER_AGENT}, + proxy=resolve_proxy(meta.token_endpoint), ) as resp: if resp.status != 200: body = await resp.text() diff --git a/src/kiro_crew/auth/login/portal.py b/src/kiro_crew/auth/login/portal.py index 81ce4fcfc854..aa8a2389ffbc 100644 --- a/src/kiro_crew/auth/login/portal.py +++ b/src/kiro_crew/auth/login/portal.py @@ -39,6 +39,7 @@ social_service_url, ) from kiro_crew.auth.store import KasToken, SocialProvider +from kiro_crew.http_proxy import resolve_proxy logger = logging.getLogger(__name__) @@ -128,7 +129,7 @@ async def exchange_code( """Exchange the authorization code for a token at {service}/oauth/token.""" url = f"{social_service_url()}/oauth/token" payload = {"code": code, "code_verifier": code_verifier, "redirect_uri": redirect_uri} - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post(url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url)) as resp: if resp.status != 200: body = await resp.text() raise PortalAuthError(f"token exchange failed: HTTP {resp.status} {body}") diff --git a/src/kiro_crew/auth/provider.py b/src/kiro_crew/auth/provider.py index 6ced6be4c9cb..2a6081189aa3 100644 --- a/src/kiro_crew/auth/provider.py +++ b/src/kiro_crew/auth/provider.py @@ -19,7 +19,7 @@ import aiohttp -from kiro_crew.auth.refresh import IdentitySignedOut, ensure_fresh +from kiro_crew.auth.refresh import HTTP_TIMEOUT, IdentitySignedOut, ensure_fresh from kiro_crew.auth.store import KasToken, TokenStore logger = logging.getLogger(__name__) @@ -87,7 +87,7 @@ def __init__( async def _session_or_temp(self): if self._session is not None: return self._session, False - return aiohttp.ClientSession(), True + return aiohttp.ClientSession(timeout=HTTP_TIMEOUT), True def _env_api_key(self) -> str | None: if not self._allow_env_api_key: diff --git a/src/kiro_crew/auth/refresh.py b/src/kiro_crew/auth/refresh.py index e2ef2a3ea8ed..ddbc3499d85f 100644 --- a/src/kiro_crew/auth/refresh.py +++ b/src/kiro_crew/auth/refresh.py @@ -28,11 +28,19 @@ social_service_url, ) from kiro_crew.auth.store import KasToken, TokenStore +from kiro_crew.http_proxy import resolve_proxy from kiro_crew.loop_lock import LoopBoundLock from kiro_crew.platform_compat import acquire_lock, release_lock logger = logging.getLogger(__name__) +# Every request to the sign-in service is bounded. aiohttp's own default is five +# minutes, which on a black-holed route leaves a poll or a renewal hanging many +# times longer than the dashboard's poll cadence or the engine's wait for a token; +# 30s is longer than any healthy auth call and short enough that a dead route is +# visible inside one login. +HTTP_TIMEOUT = aiohttp.ClientTimeout(total=30, connect=10) + # Per-identity in-process locks, so concurrent coroutines in THIS process serialize # on the asyncio lock (cooperative, no event-loop block) before contending the # cross-process flock. LoopBoundLock (not a bare module-global asyncio.Lock, which @@ -226,7 +234,10 @@ async def _refresh(token: KasToken, *, session: aiohttp.ClientSession) -> KasTok async def _refresh_social(token: KasToken, *, session: aiohttp.ClientSession) -> KasToken: url = f"{social_service_url()}/refreshToken" async with session.post( - url, json={"refreshToken": token.refresh_token}, headers=_JSON_HEADERS + url, + json={"refreshToken": token.refresh_token}, + headers=_JSON_HEADERS, + proxy=resolve_proxy(url), ) as resp: if resp.status != 200: body = await resp.text() @@ -256,7 +267,9 @@ async def _refresh_sso_oidc(token: KasToken, *, session: aiohttp.ClientSession) "grantType": "refresh_token", "refreshToken": token.refresh_token, } - async with session.post(url, json=payload, headers=_AMZ_HEADERS) as resp: + async with session.post( + url, json=payload, headers=_AMZ_HEADERS, proxy=resolve_proxy(url) + ) as resp: if resp.status != 200: body = await resp.text() raise _http_failure("SSO-OIDC", resp.status, body) @@ -287,7 +300,12 @@ async def _refresh_external_idp(token: KasToken, *, session: aiohttp.ClientSessi } if token.client_id: form["client_id"] = token.client_id - async with session.post(endpoint, data=form, headers={"User-Agent": USER_AGENT}) as resp: + async with session.post( + endpoint, + data=form, + headers={"User-Agent": USER_AGENT}, + proxy=resolve_proxy(endpoint), + ) as resp: if resp.status != 200: body = await resp.text() raise _http_failure("external IdP", resp.status, body) diff --git a/src/kiro_crew/auth/service.py b/src/kiro_crew/auth/service.py index 6a1e7074f4e5..ae2b4d66a7ec 100644 --- a/src/kiro_crew/auth/service.py +++ b/src/kiro_crew/auth/service.py @@ -32,6 +32,7 @@ oidc_scopes, social_service_url, ) +from kiro_crew.auth.refresh import HTTP_TIMEOUT from kiro_crew.auth.shape import Transport, select_transport from kiro_crew.auth.store import ( KNOWN_IDENTITIES, @@ -41,17 +42,12 @@ TokenStoreError, ) from kiro_crew.auth.whoami import START_URL_EXTRA_KEY +from kiro_crew.http_proxy import resolve_proxy logger = logging.getLogger(__name__) _HEADERS = {"Content-Type": "application/json", "User-Agent": USER_AGENT} -# Every auth request on the shared session is bounded. aiohttp's own default is five -# minutes, which on a black-holed route leaves a poll hanging many times longer than -# the dashboard's poll cadence; 30s is longer than any healthy auth call and short -# enough that a dead route is visible inside one login. -_HTTP_TIMEOUT = aiohttp.ClientTimeout(total=30, connect=10) - # How many CONSECUTIVE connection-level poll failures one pending login absorbs before # a poll reports the auth service unreachable. The poll is the longest-lived request in # a login -- one every few seconds for as long as the user takes to approve in their @@ -349,7 +345,7 @@ async def _http(self) -> aiohttp.ClientSession: # Lazy: constructing the session at gateway boot would bind it to a loop the # service may never run on; first use always happens on the serving loop. if self._session is None or self._session.closed: - self._session = aiohttp.ClientSession(timeout=_HTTP_TIMEOUT) + self._session = aiohttp.ClientSession(timeout=HTTP_TIMEOUT) return self._session async def close(self) -> None: @@ -592,7 +588,9 @@ async def poll_device(self, login_id: str) -> dict[str, Any]: payload = {"deviceCode": pending.auth.device_code, "clientId": USER_AGENT} answered = False try: - async with session.post(url, json=payload, headers=_HEADERS) as resp: + async with session.post( + url, json=payload, headers=_HEADERS, proxy=resolve_proxy(url) + ) as resp: # The issuer answered, so whatever went wrong on earlier polls of this # login was transient: the budget starts over. answered = True diff --git a/test/test_acp_auth_failure_on_stderr.py b/test/test_acp_auth_failure_on_stderr.py index ddf2e5e2f239..762d4b6518b4 100644 --- a/test/test_acp_auth_failure_on_stderr.py +++ b/test/test_acp_auth_failure_on_stderr.py @@ -189,3 +189,55 @@ def test_noise_lines_are_not_flagged_individually(): for line in HEALTHY_STDERR: assert is_auth_failure_output(line) is False, f"false positive on {line!r}" + + +# A proxy's own refusal, worded the way the HTTP stacks in front of the engine word +# it. The 407 line is reqwest's status display with the http crate's reason phrase +# ("Proxy Authentication Required" ships in the kiro-cli binary); the CONNECT line is +# curl's. Each names the proxy, so it says nothing about the Kiro sign-in. +PROXY_REFUSAL_LINES = [ + "HTTP status client error (407 Proxy Authentication Required) for url (https://q.example/)", + "Received HTTP code 403 from proxy after CONNECT", + "proxy returned HTTP 403 Forbidden", +] + + +@pytest.mark.parametrize("line", PROXY_REFUSAL_LINES) +def test_a_proxy_refusal_is_a_network_error_not_a_sign_in_failure(line): + from kiro_crew.acp.transport_errors import ( + PROVIDER_ERROR_CONNECTION, + classify_provider_error, + is_auth_failure_output, + ) + + assert is_auth_failure_output(line) is False + assert classify_provider_error(line).kind == PROVIDER_ERROR_CONNECTION + + +@pytest.mark.asyncio +async def test_a_proxy_refusal_does_not_set_the_signed_out_latch(): + runtime = _runtime(PROXY_REFUSAL_LINES) + await runtime._drain_stderr() + assert runtime.saw_not_logged_in() is False + + +def test_a_kiro_refusal_still_reads_as_signed_out(): + """Only lines that name the proxy move; a Kiro 403 keeps its sign-in verdict.""" + from kiro_crew.acp.transport_errors import is_auth_failure_output + + # Without a proxy word the line cannot be told from Kiro's own 403. + assert is_auth_failure_output("Request failed with status code 403") is True + # A named service exception is Kiro's answer even when the line mentions a proxy. + assert is_auth_failure_output("AccessDeniedException: Invalid token (via proxy)") is True + # A real sign-in line beside a proxy line still counts. + assert is_auth_failure_output(f"{PROXY_REFUSAL_LINES[1]}\nnot logged in") is True + + +def test_a_proxy_refusal_frame_names_the_proxy_not_the_sign_in(): + from kiro_crew.acp.transport_errors import _format_acp_error_worded + + err = {"code": -32603, "message": "Internal error", "data": PROXY_REFUSAL_LINES[0]} + text, worded = _format_acp_error_worded(err, backend="kas") + assert worded + assert "proxy" in text.lower() + assert "signed in" not in text.lower() and "sign in" not in text.lower() diff --git a/test/test_kas_auth_device.py b/test/test_kas_auth_device.py index 388ab60c390b..afe161822c45 100644 --- a/test/test_kas_auth_device.py +++ b/test/test_kas_auth_device.py @@ -46,7 +46,7 @@ def __init__(self, responses: list[_FakeResp]): self._responses = responses self.calls: list[tuple[str, dict]] = [] - def post(self, url, *, json=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, headers=None, proxy=None): # noqa: A002 self.calls.append((url, json or {})) return self._responses.pop(0) diff --git a/test/test_kas_auth_flows.py b/test/test_kas_auth_flows.py index ed99e7205ad9..fc06cce0053a 100644 --- a/test/test_kas_auth_flows.py +++ b/test/test_kas_auth_flows.py @@ -58,7 +58,7 @@ def __init__(self, responses): self._responses = list(responses) self.calls: list[tuple[str, dict]] = [] - def post(self, url, *, json=None, data=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, data=None, headers=None, proxy=None): # noqa: A002 self.calls.append((url, json if json is not None else (data or {}))) return self._responses.pop(0) @@ -521,7 +521,7 @@ class _CountingResp(_FakeResp): pass class _CountingSession: - def post(self, url, *, json=None, data=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, data=None, headers=None, proxy=None): # noqa: A002 calls["n"] += 1 return _CountingResp( 200, diff --git a/test/test_kas_auth_proxy.py b/test/test_kas_auth_proxy.py new file mode 100644 index 000000000000..4c90118e21f2 --- /dev/null +++ b/test/test_kas_auth_proxy.py @@ -0,0 +1,232 @@ +"""Kiro sign-in and token renewal requests go through the proxy the environment names. + +Every request ``kiro_crew.auth`` sends to the sign-in service passes an explicit +``proxy=`` chosen by :func:`kiro_crew.http_proxy.resolve_proxy`, so ``HTTPS_PROXY`` / +``HTTP_PROXY`` / ``NO_PROXY`` apply while the session keeps ``trust_env`` off (no +``~/.netrc`` credentials). The fake session records each request's keyword arguments +and then fails the connection, so no test touches the network. +""" + +from __future__ import annotations + +import urllib.request +from datetime import datetime, timedelta, timezone + +import aiohttp +import pytest + +from kiro_crew import http_proxy +from kiro_crew.auth import refresh +from kiro_crew.auth.login import builder_id, control_plane, device, external_idp, portal +from kiro_crew.auth.login.builder_id import DeviceAuthorization as OidcDeviceAuthorization +from kiro_crew.auth.login.builder_id import RegisteredClient +from kiro_crew.auth.login.device import DeviceAuthorization +from kiro_crew.auth.login.external_idp import ExternalIdpMetadata +from kiro_crew.auth.provider import KasAuthProvider +from kiro_crew.auth.service import KasLoginService +from kiro_crew.auth.store import KasToken, SocialProvider, TokenStore + +pytestmark = pytest.mark.asyncio + +_PROXY = "http://proxy.example:3128" +_SOCIAL = "https://auth.issuer.example" +_IDP_TOKEN = "https://idp.example/oauth2/token" + + +class _Refused: + """A request whose connection fails, which every auth caller handles or raises.""" + + async def __aenter__(self): + raise aiohttp.ClientConnectionError("test double: no network") + + async def __aexit__(self, *a): + return False + + +class _RecordingSession: + closed = False + + def __init__(self): + self.requests: list[tuple[str, dict]] = [] + + def post(self, url, **kwargs): + self.requests.append((url, kwargs)) + return _Refused() + + async def close(self): + return None + + +@pytest.fixture +def proxy_env(monkeypatch): + # Pin the readers to environment-only variants on every OS, as test_http_proxy does. + for name in ("http_proxy", "https_proxy", "no_proxy", "all_proxy"): + monkeypatch.delenv(name, raising=False) + monkeypatch.delenv(name.upper(), raising=False) + monkeypatch.setenv("HTTPS_PROXY", _PROXY) + monkeypatch.setenv("KIRO_AUTH_SERVICE_URL", _SOCIAL) + monkeypatch.setattr( + http_proxy.urllib.request, "getproxies", urllib.request.getproxies_environment + ) + monkeypatch.setattr( + http_proxy.urllib.request, "proxy_bypass", urllib.request.proxy_bypass_environment + ) + return monkeypatch + + +def _later(secs: int = 300) -> datetime: + return datetime.now(timezone.utc) + timedelta(seconds=secs) + + +def _social_auth() -> DeviceAuthorization: + return DeviceAuthorization( + device_code="dc", + user_code="UC", + verification_uri="https://app.example/device", + verification_uri_complete="https://app.example/device?c=UC", + expires_at=_later(), + interval_secs=0.0, + ) + + +def _oidc_auth() -> OidcDeviceAuthorization: + return OidcDeviceAuthorization( + device_code="dc", + user_code="UC", + verification_uri="https://device.example", + verification_uri_complete="https://device.example?c=UC", + expires_at=_later(), + interval_secs=0.0, + ) + + +_CLIENT = RegisteredClient(client_id="cid", client_secret="cs") + + +def _token(identity: str, **kw) -> KasToken: + return KasToken( + access_token="at", + expires_at=_later(-60), + provider="p", + identity=identity, + refresh_token="rt", + profile_arn="arn:x", + region="us-east-1", + **kw, + ) + + +_IDP = ExternalIdpMetadata( + issuer_url="https://idp.example", + client_id="cid", + scopes="openid", + authorization_endpoint="https://idp.example/authorize", + token_endpoint=_IDP_TOKEN, +) + +# One entry per request site in kiro_crew.auth: (label, coroutine factory). +_SITES = [ + ( + "social device authorization", + lambda s: device.initiate_device_authorization(SocialProvider.GOOGLE, session=s), + ), + ( + "social device poll", + lambda s: device.poll_device_token(_social_auth(), SocialProvider.GOOGLE, session=s), + ), + ( + "portal code exchange", + lambda s: portal.exchange_code( + SocialProvider.GOOGLE, "code", "verifier", "http://127.0.0.1:3128", session=s + ), + ), + ("OIDC register client", lambda s: builder_id.register_client("us-east-1", session=s)), + ( + "OIDC device authorization", + lambda s: builder_id.start_device_authorization(_CLIENT, region="us-east-1", session=s), + ), + ( + "OIDC poll once", + lambda s: builder_id.poll_token_once(_CLIENT, _oidc_auth(), region="us-east-1", session=s), + ), + ( + "OIDC poll loop", + lambda s: builder_id.poll_token(_CLIENT, _oidc_auth(), region="us-east-1", session=s), + ), + ( + "external IdP code exchange", + lambda s: external_idp.exchange_code( + _IDP, code="c", code_verifier="v", redirect_uri="http://127.0.0.1:3128", session=s + ), + ), + ( + "control-plane profile page", + lambda s: control_plane._profiles_page( + "https://cps.issuer.example/", {}, {}, s # noqa: SLF001 + ), + ), + ("social refresh", lambda s: refresh._refresh(_token("social"), session=s)), # noqa: SLF001 + ( + "SSO-OIDC refresh", + lambda s: refresh._refresh( # noqa: SLF001 + _token("identity_center", client_id="cid", client_secret="cs"), session=s + ), + ), + ( + "external IdP refresh", + lambda s: refresh._refresh( # noqa: SLF001 + _token("external_idp", token_endpoint=_IDP_TOKEN), session=s + ), + ), +] + + +async def _drive(factory) -> _RecordingSession: + session = _RecordingSession() + try: + await factory(session) + except Exception: # noqa: BLE001 - the double refuses every connection + pass + assert session.requests, "the site sent no request" + return session + + +@pytest.mark.parametrize(("label", "factory"), _SITES, ids=[s[0] for s in _SITES]) +async def test_every_auth_request_goes_through_the_env_proxy(proxy_env, label, factory): + session = await _drive(factory) + for url, kwargs in session.requests: + assert kwargs.get("proxy") == _PROXY, f"{label}: {url} sent without the proxy" + + +@pytest.mark.parametrize(("label", "factory"), _SITES, ids=[s[0] for s in _SITES]) +async def test_no_proxy_host_is_sent_direct(proxy_env, label, factory): + proxy_env.setenv("NO_PROXY", ".example,.amazonaws.com") + session = await _drive(factory) + for url, kwargs in session.requests: + assert "proxy" in kwargs, f"{label}: {url} never chose a proxy" + assert kwargs["proxy"] is None, f"{label}: {url} used a proxy for a NO_PROXY host" + + +async def test_login_service_poll_goes_through_the_env_proxy(proxy_env, tmp_path): + session = _RecordingSession() + service = KasLoginService(TokenStore(tmp_path), session=session) # type: ignore[arg-type] + + async def _fake_initiate(provider, *, session): + return _social_auth() + + proxy_env.setattr(device, "initiate_device_authorization", _fake_initiate) + login_id = (await service.begin_device("google"))["login_id"] + await service.poll_device(login_id) + assert [kw.get("proxy") for _, kw in session.requests] == [_PROXY] + + +async def test_renewal_session_is_bounded_and_ignores_env_credentials(tmp_path): + provider = KasAuthProvider(TokenStore(tmp_path)) + session, temp = await provider._session_or_temp() # noqa: SLF001 + try: + assert temp + # aiohttp's own default is five minutes, far past the engine's patience. + assert session.timeout.total is not None and session.timeout.total <= 30 + assert session.trust_env is False + finally: + await session.close() diff --git a/test/test_kas_auth_shape_idp.py b/test/test_kas_auth_shape_idp.py index 14320ee30608..8476ecbcde89 100644 --- a/test/test_kas_auth_shape_idp.py +++ b/test/test_kas_auth_shape_idp.py @@ -127,7 +127,7 @@ class _FakeSession: def __init__(self, responses): self._responses = list(responses) - def post(self, url, *, json=None, data=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, data=None, headers=None, proxy=None): # noqa: A002 return self._responses.pop(0) diff --git a/test/test_kas_login_loopback.py b/test/test_kas_login_loopback.py index 878582b15dea..0cd624523c0f 100644 --- a/test/test_kas_login_loopback.py +++ b/test/test_kas_login_loopback.py @@ -58,7 +58,7 @@ def __init__(self, responses=None): self.calls: list[tuple[str, dict]] = [] self.closed = False - def post(self, url, *, json=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, headers=None, proxy=None): # noqa: A002 self.calls.append((url, json or {})) return self._responses.pop(0) diff --git a/test/test_kas_login_service.py b/test/test_kas_login_service.py index 3610c79ddd71..43ecc6f50587 100644 --- a/test/test_kas_login_service.py +++ b/test/test_kas_login_service.py @@ -54,7 +54,7 @@ def __init__(self, responses: list[_FakeResp] | None = None): self.calls_with_headers: list[tuple[str, dict, dict]] = [] self.closed = False - def post(self, url, *, json=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, headers=None, proxy=None): # noqa: A002 self.calls.append((url, json or {})) self.calls_with_headers.append((url, json or {}, dict(headers or {}))) return self._responses.pop(0) diff --git a/test/test_kas_login_signout_generation.py b/test/test_kas_login_signout_generation.py index efa938cc677b..05b5c797e65d 100644 --- a/test/test_kas_login_signout_generation.py +++ b/test/test_kas_login_signout_generation.py @@ -44,7 +44,7 @@ class _FakeSession: def __init__(self, responses): self._responses = list(responses) - def post(self, url, *, json=None, data=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, data=None, headers=None, proxy=None): # noqa: A002 return self._responses.pop(0) @property diff --git a/test/test_sign_in_refresher.py b/test/test_sign_in_refresher.py index 1bca5de0fbd5..49d9e7bb46c9 100644 --- a/test/test_sign_in_refresher.py +++ b/test/test_sign_in_refresher.py @@ -52,7 +52,7 @@ async def __aenter__(self): async def __aexit__(self, *a): return False - def post(self, url, *, json=None, data=None, headers=None): # noqa: A002 + def post(self, url, *, json=None, data=None, headers=None, proxy=None): # noqa: A002 self.calls.append(url) assert self._responses, f"unexpected refresh request to {url}" return self._responses.pop(0)