Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/system-specs/modules/kas-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
74 changes: 74 additions & 0 deletions src/kiro_crew/acp/proxy_refusal.py
Original file line number Diff line number Diff line change
@@ -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))
19 changes: 18 additions & 1 deletion src/kiro_crew/acp/transport_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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, "
Expand Down
11 changes: 7 additions & 4 deletions src/kiro_crew/auth/login/builder_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion src/kiro_crew/auth/login/control_plane.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions src/kiro_crew/auth/login/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion src/kiro_crew/auth/login/external_idp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion src/kiro_crew/auth/login/portal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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}")
Expand Down
4 changes: 2 additions & 2 deletions src/kiro_crew/auth/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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:
Expand Down
24 changes: 21 additions & 3 deletions src/kiro_crew/auth/refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading