草稿
[WIP]feat(gateway): centralize accounts and issue worker credential leases #487
yutaoJustinBieber1223创建于 2 天前
[WIP]feat(gateway): centralize accounts and issue worker credential leases #487
草稿
共 60 个文件变更+11531-91
| @@ -13,7 +13,7 @@ from typing import AbstractSet, Any, TYPE_CHECKING | |||
| 13 | if TYPE_CHECKING: | 13 | if TYPE_CHECKING: |
| 14 | from agent_gateway.auth.credential_access import CredentialAccess | 14 | from agent_gateway.auth.credential_access import CredentialAccess |
| 15 | 15 | ||
| 16 | -from agent_gateway.auth.credential_access import LOGIN_REFRESH_WAIT_S | 16 | +from agent_gateway.auth.credential_access import CredentialAccessError, LOGIN_REFRESH_WAIT_S |
| 17 | from e2a.message import Message | 17 | from e2a.message import Message |
| 18 | from agent_gateway.channel_manager.web.req_method_routing import ( | 18 | from agent_gateway.channel_manager.web.req_method_routing import ( |
| 19 | ROUTE_DENIED, | 19 | ROUTE_DENIED, |
| @@ -181,8 +181,9 @@ def _inject_session_work_mode(msg: Message) -> None: | |||
| 181 | class InboundQueue: | 181 | class InboundQueue: |
| 182 | """Gateway internal inbound service for forwarding channel messages to MessageHandler.""" | 182 | """Gateway internal inbound service for forwarding channel messages to MessageHandler.""" |
| 183 | 183 | ||
| 184 | - def __init__(self, inbound_handler): | 184 | + def __init__(self, inbound_handler, *, error_callback=None): |
| 185 | self._inbound_handler = inbound_handler | 185 | self._inbound_handler = inbound_handler |
| 186 | + self._error_callback = error_callback | ||
| 186 | self._queue: asyncio.Queue = asyncio.Queue() | 187 | self._queue: asyncio.Queue = asyncio.Queue() |
| 187 | self._task: asyncio.Task | None = None | 188 | self._task: asyncio.Task | None = None |
| 188 | self._running = False | 189 | self._running = False |
| @@ -218,6 +219,14 @@ class InboundQueue: | |||
| 218 | handled = self._inbound_handler(msg) | 219 | handled = self._inbound_handler(msg) |
| 219 | if asyncio.iscoroutine(handled): | 220 | if asyncio.iscoroutine(handled): |
| 220 | await handled | 221 | await handled |
| 222 | + except CredentialAccessError as error: | ||
| 223 | + if self._error_callback is None: | ||
| 224 | + logger.warning("[App] Gateway credential access failed: id=%s", getattr(msg, "id", None)) | ||
| 225 | + else: | ||
| 226 | + try: | ||
| 227 | + await self._error_callback(msg, error) | ||
| 228 | + except Exception: | ||
| 229 | + logger.exception("[App] Gateway credential failure response could not be delivered") | ||
| 221 | except Exception: # noqa: BLE001 | 230 | except Exception: # noqa: BLE001 |
| 222 | logger.exception("[App] Gateway inbound handling failed: id=%s", getattr(msg, "id", None)) | 231 | logger.exception("[App] Gateway inbound handling failed: id=%s", getattr(msg, "id", None)) |
| 223 | 232 | ||
| @@ -260,6 +269,8 @@ class MessagePreprocessor: | |||
| 260 | with trace_stage("preprocess.credentials"): | 269 | with trace_stage("preprocess.credentials"): |
| 261 | try: | 270 | try: |
| 262 | auth = await self.credential_access.request_model_auth(_auth_session_id(msg), model_name) | 271 | auth = await self.credential_access.request_model_auth(_auth_session_id(msg), model_name) |
| 272 | + except CredentialAccessError: | ||
| 273 | + raise | ||
| 263 | except Exception: # Login availability must not break request forwarding. | 274 | except Exception: # Login availability must not break request forwarding. |
| 264 | logger.debug('[App] Credential lookup failed; forwarding without login credentials', exc_info=True) | 275 | logger.debug('[App] Credential lookup failed; forwarding without login credentials', exc_info=True) |
| 265 | auth = None | 276 | auth = None |
| @@ -269,13 +280,22 @@ class MessagePreprocessor: | |||
| 269 | 280 | ||
| 270 | async def forward(self, msg: Any, channel_manager: Any) -> bool: | 281 | async def forward(self, msg: Any, channel_manager: Any) -> bool: |
| 271 | normalized = await self._prepare(msg) | 282 | normalized = await self._prepare(msg) |
| 272 | - method = request_method_name(getattr(msg, "req_method", None)) | 283 | + await self._deliver(normalized, msg, channel_manager) |
| 273 | - if method == "session.create": | ||
| 274 | - self.inject_work_mode(normalized) | ||
| 275 | - await channel_manager.deliver_to_message_handler(normalized) | ||
| 276 | logger.info("[App] Gateway inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id) | 284 | logger.info("[App] Gateway inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id) |
| 277 | return False | 285 | return False |
| 278 | 286 | ||
| 287 | + async def _deliver(self, normalized: Any, msg: Any, channel_manager: Any) -> None: | ||
| 288 | + accepted = False | ||
| 289 | + try: | ||
| 290 | + if request_method_name(getattr(msg, "req_method", None)) == "session.create": | ||
| 291 | + self.inject_work_mode(normalized) | ||
| 292 | + accepted = await channel_manager.deliver_to_message_handler(normalized) is not False | ||
| 293 | + finally: | ||
| 294 | + if not accepted: | ||
| 295 | + release = getattr(self.credential_access, "release_request", None) | ||
| 296 | + if release is not None: | ||
| 297 | + release(normalized) | ||
| 298 | + | ||
| 279 | def for_channel( | 299 | def for_channel( |
| 280 | self, | 300 | self, |
| 281 | channel_manager: Any, | 301 | channel_manager: Any, |
| @@ -297,9 +317,7 @@ class MessagePreprocessor: | |||
| 297 | if route in (ROUTE_LOCAL, ROUTE_DENIED): | 317 | if route in (ROUTE_LOCAL, ROUTE_DENIED): |
| 298 | return False | 318 | return False |
| 299 | normalized = await self._prepare(msg) | 319 | normalized = await self._prepare(msg) |
| 300 | - if method == "session.create": | 320 | + await self._deliver(normalized, msg, channel_manager) |
| 301 | - self.inject_work_mode(normalized) | ||
| 302 | - await channel_manager.deliver_to_message_handler(normalized) | ||
| 303 | logger.debug("[App] %s 入站 -> MessageHandler: id=%s channel_id=%s", source_label, msg.id, msg.channel_id) | 321 | logger.debug("[App] %s 入站 -> MessageHandler: id=%s channel_id=%s", source_label, msg.id, msg.channel_id) |
| 304 | return route == ROUTE_FORWARD_UNKNOWN or method in no_local_methods | 322 | return route == ROUTE_FORWARD_UNKNOWN or method in no_local_methods |
| 305 | 323 | ||
| @@ -7,8 +7,11 @@ from __future__ import annotations | |||
| 7 | from collections.abc import Callable | 7 | from collections.abc import Callable |
| 8 | from dataclasses import dataclass | 8 | from dataclasses import dataclass |
| 9 | import os | 9 | import os |
| 10 | +import time | ||
| 10 | from typing import Any | 11 | from typing import Any |
| 11 | 12 | ||
| 13 | +from e2a.message import EventType, Message | ||
| 14 | + | ||
| 12 | from agent_gateway.application.inbound import InboundQueue, MessagePreprocessor | 15 | from agent_gateway.application.inbound import InboundQueue, MessagePreprocessor |
| 13 | from agent_gateway.routing.protocol_runtime import ProtocolRuntime, ProtocolRuntimeConfig, RouteConfig | 16 | from agent_gateway.routing.protocol_runtime import ProtocolRuntime, ProtocolRuntimeConfig, RouteConfig |
| 14 | from agent_gateway.routing.route_binding import GatewayRouteBinding | 17 | from agent_gateway.routing.route_binding import GatewayRouteBinding |
| @@ -101,10 +104,20 @@ async def assemble_tui_acp( | |||
| 101 | if callable(subscribe_fn): | 104 | if callable(subscribe_fn): |
| 102 | subscribe_fn(channel_manager) | 105 | subscribe_fn(channel_manager) |
| 103 | 106 | ||
| 107 | + async def publish_credential_error(message, error): | ||
| 108 | + acp = message.channel_id == "acp" | ||
| 109 | + payload = {"error": str(error), "code": "CREDENTIAL_SERVICE_FAILED"} | ||
| 110 | + await protocol_runtime.send(Message( | ||
| 111 | + id=message.id, type="event" if acp else "res", channel_id=message.channel_id, | ||
| 112 | + session_id=message.session_id, params={}, timestamp=time.time(), ok=False, | ||
| 113 | + user_id=message.user_id, agent_ref=message.agent_ref, metadata=message.metadata, | ||
| 114 | + event_type=EventType.CHAT_ERROR if acp else None, payload=payload, | ||
| 115 | + )) | ||
| 116 | + | ||
| 104 | acp_inbound_server = InboundQueue( | 117 | acp_inbound_server = InboundQueue( |
| 105 | - lambda msg: preprocessor.forward(msg, channel_manager) | 118 | + lambda msg: preprocessor.forward(msg, channel_manager), |
| 119 | + error_callback=publish_credential_error, | ||
| 106 | ) | 120 | ) |
| 107 | - await acp_inbound_server.start() | ||
| 108 | 121 | ||
| 109 | route_bindings = [ | 122 | route_bindings = [ |
| 110 | _build_acp_route_binding( | 123 | _build_acp_route_binding( |
| @@ -148,5 +161,6 @@ async def assemble_tui_acp( | |||
| 148 | if binding.install is not None: | 161 | if binding.install is not None: |
| 149 | binding.install(protocol_runtime) | 162 | binding.install(protocol_runtime) |
| 150 | protocol_runtime.on_message(acp_inbound_server.handle_message) | 163 | protocol_runtime.on_message(acp_inbound_server.handle_message) |
| 164 | + await acp_inbound_server.start() | ||
| 151 | log_stage("gateway_routes_registered") | 165 | log_stage("gateway_routes_registered") |
| 152 | return TuiAcpAssembly(tui_channel, acp_inbound_server, protocol_runtime) | 166 | return TuiAcpAssembly(tui_channel, acp_inbound_server, protocol_runtime) |
| @@ -0,0 +1,150 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Bound actual Control blocking work, including work outliving its caller.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +from collections.abc import Callable | ||
| 8 | +from concurrent.futures import Future, ThreadPoolExecutor | ||
| 9 | +import math | ||
| 10 | +import threading | ||
| 11 | +from typing import Any, TypeVar | ||
| 12 | + | ||
| 13 | +from agent_gateway.processes.control_service import ControlServiceBusy, ControlServiceError | ||
| 14 | + | ||
| 15 | +_Result = TypeVar('_Result') | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def _consume_result(future: asyncio.Future[Any]) -> None: | ||
| 19 | + """Retrieve abandoned exceptions without logging their possibly secret text.""" | ||
| 20 | + if not future.cancelled(): | ||
| 21 | + future.exception() | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class ControlBlockingWork: | ||
| 25 | + """Same-loop submissions to a private pool with no admission waiting queue. | ||
| 26 | + | ||
| 27 | + Caller cancellation never returns an occupied slot. Only completion of the | ||
| 28 | + concurrent future does so. Construction starts no threads; the owner must | ||
| 29 | + call ``stop`` before closing its event loop. A timed-out stop leaves actual | ||
| 30 | + work observable through ``pending_count`` and does not claim to kill it. | ||
| 31 | + """ | ||
| 32 | + | ||
| 33 | + def __init__(self, limit: int = 4) -> None: | ||
| 34 | + if type(limit) is not int or limit <= 0: | ||
| 35 | + raise ValueError('limit must be a positive integer') | ||
| 36 | + self._limit = limit | ||
| 37 | + self._executor = ThreadPoolExecutor(max_workers=limit, thread_name_prefix='control-blocking') | ||
| 38 | + self._lock = threading.Lock() | ||
| 39 | + self._pending: set[Future[Any]] = set() | ||
| 40 | + self._count = 0 | ||
| 41 | + self._loop: asyncio.AbstractEventLoop | None = None | ||
| 42 | + self._idle = asyncio.Event() | ||
| 43 | + self._idle.set() | ||
| 44 | + self._closed = False | ||
| 45 | + self._stop_task: asyncio.Task[None] | None = None | ||
| 46 | + | ||
| 47 | + @property | ||
| 48 | + def pending_count(self) -> int: | ||
| 49 | + """Number of actual occupied slots, even after a caller or loop exits.""" | ||
| 50 | + with self._lock: | ||
| 51 | + return self._count | ||
| 52 | + | ||
| 53 | + def _owner_loop(self) -> asyncio.AbstractEventLoop: | ||
| 54 | + try: | ||
| 55 | + loop = asyncio.get_running_loop() | ||
| 56 | + except RuntimeError: | ||
| 57 | + raise ControlServiceError() from None | ||
| 58 | + if self._loop is None: | ||
| 59 | + self._loop = loop | ||
| 60 | + elif self._loop is not loop: | ||
| 61 | + raise ControlServiceError() | ||
| 62 | + return loop | ||
| 63 | + | ||
| 64 | + def submit(self, fn: Callable[..., _Result], *args: Any) -> Future[_Result]: | ||
| 65 | + """Reserve a real slot synchronously or fail immediately without queuing.""" | ||
| 66 | + self._owner_loop() | ||
| 67 | + if self._closed: | ||
| 68 | + raise ControlServiceError() | ||
| 69 | + with self._lock: | ||
| 70 | + if self._count >= self._limit: | ||
| 71 | + raise ControlServiceBusy() | ||
| 72 | + self._count += 1 | ||
| 73 | + self._idle.clear() | ||
| 74 | + try: | ||
| 75 | + future = self._executor.submit(fn, *args) | ||
| 76 | + except Exception: | ||
| 77 | + with self._lock: | ||
| 78 | + self._count -= 1 | ||
| 79 | + self._notify_completion() | ||
| 80 | + raise ControlServiceError() from None | ||
| 81 | + with self._lock: | ||
| 82 | + self._pending.add(future) | ||
| 83 | + # Register outside the lock: add_done_callback may execute immediately. | ||
| 84 | + future.add_done_callback(self._work_finished) | ||
| 85 | + return future | ||
| 86 | + | ||
| 87 | + async def run(self, fn: Callable[..., _Result], *args: Any) -> _Result: | ||
| 88 | + """Await a submitted call without cancelling its actual work on timeout.""" | ||
| 89 | + future = asyncio.wrap_future(self.submit(fn, *args)) | ||
| 90 | + future.add_done_callback(_consume_result) | ||
| 91 | + return await asyncio.shield(future) | ||
| 92 | + | ||
| 93 | + def _work_finished(self, future: Future[Any]) -> None: | ||
| 94 | + # This can run on a pool thread, including after the owner loop closes. | ||
| 95 | + with self._lock: | ||
| 96 | + self._pending.remove(future) | ||
| 97 | + self._count -= 1 | ||
| 98 | + loop = self._loop | ||
| 99 | + if loop is not None: | ||
| 100 | + try: | ||
| 101 | + loop.call_soon_threadsafe(self._notify_completion) | ||
| 102 | + except RuntimeError: | ||
| 103 | + # A closed loop cannot be notified; actual-work tracking is done. | ||
| 104 | + pass | ||
| 105 | + | ||
| 106 | + def _notify_completion(self) -> None: | ||
| 107 | + if self.pending_count == 0: | ||
| 108 | + self._idle.set() | ||
| 109 | + | ||
| 110 | + async def _wait_for_work(self, timeout: float) -> None: | ||
| 111 | + try: | ||
| 112 | + async with asyncio.timeout(timeout): | ||
| 113 | + while self.pending_count: | ||
| 114 | + await self._idle.wait() | ||
| 115 | + except TimeoutError: | ||
| 116 | + if self.pending_count: | ||
| 117 | + raise ControlServiceError() from None | ||
| 118 | + | ||
| 119 | + async def stop(self, timeout: float = 1.0) -> None: | ||
| 120 | + """Reject new calls and finish owned, bounded cleanup despite cancellation. | ||
| 121 | + | ||
| 122 | + Concurrent stop callers share the current cleanup deadline. After a | ||
| 123 | + timeout a later stop can wait again, but submissions remain closed. | ||
| 124 | + Residual work raises only a fixed error and remains counted until done. | ||
| 125 | + """ | ||
| 126 | + if type(timeout) not in {int, float} or not math.isfinite(timeout) or timeout < 0: | ||
| 127 | + raise ValueError('timeout must be a non-negative finite number') | ||
| 128 | + loop = self._owner_loop() | ||
| 129 | + if not self._closed: | ||
| 130 | + self._closed = True | ||
| 131 | + self._executor.shutdown(wait=False, cancel_futures=False) | ||
| 132 | + if self._stop_task is None or self._stop_task.done(): | ||
| 133 | + self._stop_task = loop.create_task(self._wait_for_work(float(timeout))) | ||
| 134 | + self._stop_task.add_done_callback(_consume_result) | ||
| 135 | + task = self._stop_task | ||
| 136 | + cancelled = False | ||
| 137 | + while True: | ||
| 138 | + try: | ||
| 139 | + await asyncio.shield(task) | ||
| 140 | + break | ||
| 141 | + except asyncio.CancelledError: | ||
| 142 | + if task.cancelled(): | ||
| 143 | + raise | ||
| 144 | + cancelled = True | ||
| 145 | + except ControlServiceError: | ||
| 146 | + if cancelled: | ||
| 147 | + raise asyncio.CancelledError from None | ||
| 148 | + raise | ||
| 149 | + if cancelled: | ||
| 150 | + raise asyncio.CancelledError | ||
| @@ -0,0 +1,540 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Explicit Control-owned credential handlers; not a production account switch.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +from collections.abc import Callable, Mapping | ||
| 8 | +from concurrent.futures import Future | ||
| 9 | +from dataclasses import dataclass | ||
| 10 | +from functools import partial | ||
| 11 | +import hashlib | ||
| 12 | +import hmac | ||
| 13 | +import secrets | ||
| 14 | +from types import MappingProxyType | ||
| 15 | +from typing import Any, TYPE_CHECKING | ||
| 16 | + | ||
| 17 | +from agent_gateway.auth.credential_access import ModelCredential | ||
| 18 | +from agent_gateway.auth.control_blocking_work import ControlBlockingWork | ||
| 19 | +from agent_gateway.auth.credential_issuance import CredentialIssuanceRegistry, CredentialTarget | ||
| 20 | +from agent_gateway.auth.local_credential_access import ( | ||
| 21 | + LocalCredentialAccess, | ||
| 22 | + LocalCredentialResult, | ||
| 23 | + LocalCredentialSnapshot, | ||
| 24 | +) | ||
| 25 | +from agent_gateway.auth.session_login_bindings import LocalSessionLoginBindings | ||
| 26 | +from agent_gateway.processes.control_service import ControlServiceBusy, ControlServiceIdentity, Handler | ||
| 27 | + | ||
| 28 | +if TYPE_CHECKING: | ||
| 29 | + from agent_gateway.auth.service import AuthService | ||
| 30 | + from agent_gateway.auth.session_store import AuthSessionStore | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def _fields(value: object, names: set[str]) -> dict[str, Any]: | ||
| 34 | + if not isinstance(value, dict) or set(value) != names: | ||
| 35 | + raise ValueError('invalid credential service value') | ||
| 36 | + return value | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def _text(value: object, limit: int, *, empty: bool = False) -> str: | ||
| 40 | + if not isinstance(value, str) or len(value) > limit or (not empty and not value.strip()): | ||
| 41 | + raise ValueError('invalid credential service value') | ||
| 42 | + return value | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def _ref(value: object) -> str: | ||
| 46 | + from agent_gateway.auth.login_credentials import is_credential_ref | ||
| 47 | + | ||
| 48 | + result = _text(value, 32) | ||
| 49 | + if not is_credential_ref(result): | ||
| 50 | + raise ValueError('invalid credential service value') | ||
| 51 | + return result | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def _credential(value: ModelCredential | None) -> dict[str, Any]: | ||
| 55 | + if value is None: | ||
| 56 | + return {'status': 'invalid'} | ||
| 57 | + return {'status': 'ok', 'credential': { | ||
| 58 | + 'api_base': _text(value.api_base, 2048), | ||
| 59 | + 'api_key': _text(value.api_key, 4096), | ||
| 60 | + 'credential_ref': _ref(value.credential_ref), | ||
| 61 | + }} | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +@dataclass(frozen=True) | ||
| 65 | +class _SessionSnapshot: | ||
| 66 | + """Immutable identity facts captured by a bounded store read.""" | ||
| 67 | + | ||
| 68 | + store: AuthSessionStore | ||
| 69 | + session_id: str | ||
| 70 | + user_id: str | ||
| 71 | + created_at: float | ||
| 72 | + credential_ref: str | ||
| 73 | + epoch: str | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +@dataclass(frozen=True) | ||
| 77 | +class _CredentialRead: | ||
| 78 | + """Immutable credential facts captured by a bounded store read.""" | ||
| 79 | + | ||
| 80 | + id_token: str | ||
| 81 | + expired: bool | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +@dataclass(frozen=True) | ||
| 85 | +class _SessionRead: | ||
| 86 | + """A mutable session object plus the immutable commit identity.""" | ||
| 87 | + | ||
| 88 | + snapshot: _SessionSnapshot | ||
| 89 | + session: Any | ||
| 90 | + credential: _CredentialRead | ||
| 91 | + | ||
| 92 | + | ||
| 93 | +@dataclass(frozen=True) | ||
| 94 | +class _RefreshWork: | ||
| 95 | + """A shared explicit refresh submitted to the real bounded pool.""" | ||
| 96 | + | ||
| 97 | + future: Future | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +class ControlCredentialServices: | ||
| @@ -0,0 +1,217 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Opt-in public discovery using Control's existing blocking-work budget.""" | ||
| 3 | + | ||
| 4 | +from __future__ import annotations | ||
| 5 | + | ||
| 6 | +import asyncio | ||
| 7 | +from collections.abc import Callable | ||
| 8 | +from concurrent.futures import Future | ||
| 9 | +from dataclasses import dataclass | ||
| 10 | +import threading | ||
| 11 | +from typing import Any, TYPE_CHECKING | ||
| 12 | + | ||
| 13 | +from agent_gateway.auth.control_blocking_work import ControlBlockingWork | ||
| 14 | +from agent_gateway.processes.control_service import ControlServiceBusy | ||
| 15 | + | ||
| 16 | +if TYPE_CHECKING: | ||
| 17 | + from agent_gateway.auth.service import AuthService | ||
| 18 | + from agent_gateway.auth.session_store import AuthSessionStore | ||
| 19 | + | ||
| 20 | +_HANDLER_TIMEOUT_S = 15.0 | ||
| 21 | +_SNAPSHOT_HANDLER_TIMEOUT_S = 8.0 | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +@dataclass(frozen=True) | ||
| 25 | +class _CatalogCommit: | ||
| 26 | + result: dict[str, Any] | ||
| 27 | + store: AuthSessionStore | ||
| 28 | + session_id: str | ||
| 29 | + user_id: str | ||
| 30 | + created_at: float | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def _consume_result(future: asyncio.Future[Any]) -> None: | ||
| 34 | + if not future.cancelled(): | ||
| 35 | + future.exception() | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class ControlPublicModelCatalog: | ||
| 39 | + """Validate one explicit session and publish only bounded public metadata. | ||
| 40 | + | ||
| 41 | + The existing discovery cache is shared. This port validates who is asking; | ||
| 42 | + it does not turn that cache into an account-specific entitlement list. | ||
| 43 | + """ | ||
| 44 | + | ||
| 45 | + def __init__( | ||
| 46 | + self, provider: Callable[[], AuthService], *, blocking_work: ControlBlockingWork, | ||
| 47 | + ) -> None: | ||
| 48 | + self._provider = provider | ||
| 49 | + self._blocking_work = blocking_work | ||
| 50 | + self._lock = threading.Lock() | ||
| 51 | + self._pending = False | ||
| 52 | + | ||
| 53 | + def _finished(self, future: Future[Any]) -> None: | ||
| 54 | + # Release on actual thread completion, never on caller cancellation. | ||
| 55 | + with self._lock: | ||
| 56 | + self._pending = False | ||
| 57 | + | ||
| 58 | + def _unauthenticated_snapshot(self) -> dict[str, Any]: | ||
| 59 | + return {'version': 1, 'status': 'unauthenticated', 'api_base': '', 'models': []} | ||
| 60 | + | ||
| 61 | + def _unavailable_snapshot(self) -> dict[str, Any]: | ||
| 62 | + return {'version': 1, 'status': 'unavailable', 'api_base': '', 'models': []} | ||
| 63 | + | ||
| 64 | + async def list_login_models(self, arguments: dict[str, Any]) -> dict[str, Any]: | ||
| 65 | + from agent_gateway.auth.public_model_catalog import validate_auth_session | ||
| 66 | + | ||
| 67 | + if not isinstance(arguments, dict) or set(arguments) != {'auth_session'}: | ||
| 68 | + raise ValueError('invalid catalog service value') | ||
| 69 | + try: | ||
| 70 | + session_id = validate_auth_session(arguments['auth_session']) | ||
| 71 | + except ValueError: | ||
| 72 | + raise ValueError('invalid catalog service value') from None | ||
| 73 | + if session_id is None: | ||
| 74 | + return {'status': 'unauthenticated', 'models': []} | ||
| 75 | + with self._lock: | ||
| 76 | + if self._pending: | ||
| 77 | + raise ControlServiceBusy() | ||
| 78 | + self._pending = True | ||
| 79 | + try: | ||
| 80 | + future = self._blocking_work.submit(self._load, session_id) | ||
| 81 | + except BaseException: | ||
| 82 | + with self._lock: | ||
| 83 | + self._pending = False | ||
| 84 | + raise | ||
| 85 | + future.add_done_callback(self._finished) | ||
| 86 | + waiter = asyncio.wrap_future(future) | ||
| 87 | + waiter.add_done_callback(_consume_result) | ||
| 88 | + try: | ||
| 89 | + async with asyncio.timeout(_HANDLER_TIMEOUT_S): | ||
| 90 | + result = await asyncio.shield(waiter) | ||
| 91 | + if isinstance(result, _CatalogCommit): | ||
| 92 | + current = result.store.matches_live_memory( | ||
| 93 | + result.session_id, result.user_id, result.created_at, | ||
| 94 | + ) | ||
| 95 | + if current is None: | ||
| 96 | + return {'status': 'unavailable', 'models': []} | ||
| 97 | + if not current: | ||
| 98 | + return {'status': 'unauthenticated', 'models': []} | ||
| 99 | + return result.result | ||
| 100 | + return result | ||
| 101 | + except TimeoutError: | ||
| 102 | + return {'status': 'unavailable', 'models': []} | ||
| 103 | + | ||
| 104 | + async def get_login_model_snapshot(self, arguments: dict[str, Any]) -> dict[str, Any]: | ||
| 105 | + from agent_gateway.auth.public_model_catalog import validate_auth_session | ||
| 106 | + | ||
| 107 | + if not isinstance(arguments, dict) or set(arguments) != {'auth_session'}: | ||
| 108 | + raise ValueError('invalid catalog service value') | ||
| 109 | + try: | ||
| 110 | + session_id = validate_auth_session(arguments['auth_session']) | ||
| 111 | + except ValueError: | ||
| 112 | + raise ValueError('invalid catalog service value') from None | ||
| 113 | + if session_id is None: | ||
| 114 | + return self._unauthenticated_snapshot() | ||
| 115 | + with self._lock: | ||
| 116 | + if self._pending: | ||
| 117 | + raise ControlServiceBusy() | ||
| 118 | + self._pending = True | ||
| 119 | + try: | ||
| 120 | + future = self._blocking_work.submit(self._load_snapshot, session_id) | ||
| 121 | + except BaseException: | ||
| 122 | + with self._lock: | ||
| 123 | + self._pending = False | ||
| 124 | + raise | ||
| 125 | + future.add_done_callback(self._finished) | ||
| 126 | + waiter = asyncio.wrap_future(future) | ||
| 127 | + waiter.add_done_callback(_consume_result) | ||
| 128 | + try: | ||
| 129 | + async with asyncio.timeout(_SNAPSHOT_HANDLER_TIMEOUT_S): | ||
| 130 | + result = await asyncio.shield(waiter) | ||
| 131 | + if isinstance(result, _CatalogCommit): | ||
| 132 | + current = result.store.matches_live_memory( | ||
| 133 | + result.session_id, result.user_id, result.created_at, | ||
| 134 | + ) | ||
| 135 | + if current is None: | ||
| 136 | + return self._unavailable_snapshot() | ||
| 137 | + if not current: | ||
| 138 | + return self._unauthenticated_snapshot() | ||
| 139 | + return result.result | ||
| 140 | + return result | ||
| 141 | + except TimeoutError: | ||
| 142 | + return self._unavailable_snapshot() | ||
| 143 | + | ||
| 144 | + def _load(self, session_id: str) -> _CatalogCommit | dict[str, Any]: | ||
| 145 | + from agent_gateway.auth.model_catalog import get_models | ||
| 146 | + from agent_gateway.auth.public_model_catalog import CatalogError, validate_catalog_response | ||
| 147 | + from agent_gateway.auth.service import ModelAuthRequired, live_session | ||
| 148 | + | ||
| 149 | + try: | ||
| 150 | + service = self._provider() | ||
| 151 | + session = live_session(session_id, service=service) | ||
| 152 | + epoch = (session.session_id, session.user_id, session.created_at) | ||
| 153 | + if not session.credential.id_token: | ||
| 154 | + return {'status': 'unauthenticated', 'models': []} | ||
| 155 | + models = get_models(session_id, service=service) | ||
| 156 | + current = live_session(session_id, service=service) | ||
| 157 | + if ((current.session_id, current.user_id, current.created_at) != epoch | ||
| 158 | + or not current.credential.id_token): | ||
| 159 | + return {'status': 'unauthenticated', 'models': []} | ||
| 160 | + result = validate_catalog_response({ | ||
| 161 | + 'status': 'ok', 'models': [model.to_dict() for model in models], | ||
| 162 | + }).to_dict() | ||
| 163 | + return _CatalogCommit(result, service._store, *epoch) | ||
| 164 | + except ModelAuthRequired: | ||
| 165 | + return {'status': 'unauthenticated', 'models': []} | ||
| 166 | + except CatalogError as error: | ||
| 167 | + return {'status': 'too_large' if error.reason == 'too_large' else 'unavailable', 'models': []} | ||
| 168 | + except Exception: | ||
| 169 | + # Provider/HTTP exceptions may include credentials or response bodies. | ||
| 170 | + return {'status': 'unavailable', 'models': []} | ||
| 171 | + | ||
| 172 | + def _load_snapshot(self, session_id: str) -> _CatalogCommit | dict[str, Any]: | ||
| 173 | + from agent_gateway.auth.apig import resolve_apig_config | ||
| 174 | + from agent_gateway.auth.model_catalog import get_models | ||
| 175 | + from agent_gateway.auth.public_model_catalog import ( | ||
| 176 | + CatalogError, validate_login_model_snapshot, | ||
| 177 | + ) | ||
| 178 | + from agent_gateway.auth.service import ModelAuthRequired, live_session | ||
| 179 | + | ||
| 180 | + try: | ||
| 181 | + service = self._provider() | ||
| 182 | + session = live_session(session_id, service=service) | ||
| 183 | + epoch = (session.session_id, session.user_id, session.created_at) | ||
| 184 | + if not session.credential.id_token: | ||
| 185 | + return self._unauthenticated_snapshot() | ||
| 186 | + config = resolve_apig_config(allow_refresh=False) | ||
| 187 | + if config is None: | ||
| 188 | + current = live_session(session_id, service=service) | ||
| 189 | + if ((current.session_id, current.user_id, current.created_at) != epoch | ||
| 190 | + or not current.credential.id_token): | ||
| 191 | + return self._unauthenticated_snapshot() | ||
| 192 | + result = {'version': 1, 'status': 'ok', 'api_base': '', 'models': []} | ||
| 193 | + return _CatalogCommit(result, service._store, *epoch) | ||
| 194 | + models = get_models(session_id, service=service) | ||
| 195 | + current = live_session(session_id, service=service) | ||
| 196 | + if ((current.session_id, current.user_id, current.created_at) != epoch | ||
| 197 | + or not current.credential.id_token): | ||
| 198 | + return self._unauthenticated_snapshot() | ||
| 199 | + result = validate_login_model_snapshot({ | ||
| 200 | + 'version': 1, | ||
| 201 | + 'status': 'ok', | ||
| 202 | + 'api_base': config.invoke_base_url, | ||
| 203 | + 'models': [model.to_dict() for model in models], | ||
| 204 | + }).to_dict() | ||
| 205 | + return _CatalogCommit(result, service._store, *epoch) | ||
| 206 | + except ModelAuthRequired: | ||
| 207 | + return self._unauthenticated_snapshot() | ||
| 208 | + except CatalogError as error: | ||
| 209 | + return { | ||
| 210 | + 'version': 1, | ||
| 211 | + 'status': 'too_large' if error.reason == 'too_large' else 'unavailable', | ||
| 212 | + 'api_base': '', | ||
| 213 | + 'models': [], | ||
| 214 | + } | ||
| 215 | + except Exception: | ||
| 216 | + # Provider/HTTP exceptions may include credentials or response bodies. | ||
| 217 | + return self._unavailable_snapshot() | ||
| @@ -3,7 +3,35 @@ | |||
| 3 | from __future__ import annotations | 3 | from __future__ import annotations |
| 4 | 4 | ||
| 5 | from dataclasses import dataclass, field | 5 | from dataclasses import dataclass, field |
| 6 | -from typing import Protocol | 6 | +from abc import ABC, abstractmethod |
| 7 | +from typing import TYPE_CHECKING, Protocol | ||
| 8 | + | ||
| 9 | +if TYPE_CHECKING: | ||
| 10 | + from agent_gateway.auth.worker_credential_runtime import WorkerCredentialLease | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +_CREDENTIAL_ACCESS_ERROR_REASONS = frozenset( | ||
| 14 | + {"unavailable", "invalid", "protocol", "not_enabled"} | ||
| 15 | +) | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class CredentialAccessError(Exception): | ||
| 19 | + """A remote credential or binding access failure without secret details.""" | ||
| 20 | + | ||
| 21 | + def __init__(self, reason: str = "unavailable") -> None: | ||
| 22 | + if reason not in _CREDENTIAL_ACCESS_ERROR_REASONS: | ||
| 23 | + raise ValueError("Unsupported credential failure reason") | ||
| 24 | + self.reason = reason | ||
| 25 | + super().__init__("Remote credential access failed") | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +class OwnsResolveDeadline(ABC): | ||
| 29 | + """Bindings that enforce their own typed resolve deadline.""" | ||
| 30 | + | ||
| 31 | + @property | ||
| 32 | + @abstractmethod | ||
| 33 | + def resolve_deadline_s(self) -> float: | ||
| 34 | + """Return the port-owned resolve deadline in seconds.""" | ||
| 7 | 35 | ||
| 8 | 36 | ||
| 9 | LOGIN_REFRESH_WAIT_S = 20.0 | 37 | LOGIN_REFRESH_WAIT_S = 20.0 |
| @@ -16,9 +44,42 @@ class ModelCredential: | |||
| 16 | api_base: str | 44 | api_base: str |
| 17 | api_key: str = field(repr=False) | 45 | api_key: str = field(repr=False) |
| 18 | credential_ref: str | 46 | credential_ref: str |
| 47 | + lease: "WorkerCredentialLease | None" = field(default=None, repr=False, compare=False) | ||
| 19 | 48 | ||
| 20 | - def to_params(self) -> dict[str, str]: | 49 | + def to_params(self) -> "CredentialParams": |
| 21 | - return {'api_base': self.api_base, 'api_key': self.api_key, 'credential_ref': self.credential_ref} | 50 | + return CredentialParams( |
| 51 | + api_base=self.api_base, | ||
| 52 | + api_key=self.api_key, | ||
| 53 | + credential_ref=self.credential_ref, | ||
| 54 | + credential_lease=self.lease, | ||
| 55 | + ) | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +class CredentialParams(dict[str, str]): | ||
| 59 | + """Wire-shaped credential params with a non-serialized request lease.""" | ||
| 60 | + | ||
| 61 | + def __init__( | ||
| 62 | + self, | ||
| 63 | + *, | ||
| 64 | + api_base: str, | ||
| 65 | + api_key: str, | ||
| 66 | + credential_ref: str, | ||
| 67 | + credential_lease: "WorkerCredentialLease | None" = None, | ||
| 68 | + ) -> None: | ||
| 69 | + super().__init__({ | ||
| 70 | + 'api_base': api_base, | ||
| 71 | + 'api_key': api_key, | ||
| 72 | + 'credential_ref': credential_ref, | ||
| 73 | + }) | ||
| 74 | + self.credential_lease = credential_lease | ||
| 75 | + | ||
| 76 | + def copy(self) -> "CredentialParams": | ||
| 77 | + return CredentialParams( | ||
| 78 | + api_base=self['api_base'], | ||
| 79 | + api_key=self['api_key'], | ||
| 80 | + credential_ref=self['credential_ref'], | ||
| 81 | + credential_lease=self.credential_lease, | ||
| 82 | + ) | ||
| 22 | 83 | ||
| 23 | 84 | ||
| 24 | @dataclass(frozen=True) | 85 | @dataclass(frozen=True) |
| @@ -40,6 +101,16 @@ class CredentialUpdate: | |||
| 40 | return {'credential_ref': self.credential_ref, 'api_key': self.api_key} | 101 | return {'credential_ref': self.credential_ref, 'api_key': self.api_key} |
| 41 | 102 | ||
| 42 | 103 | ||
| 104 | +@dataclass(frozen=True) | ||
| 105 | +class CredentialRefresh: | ||
| 106 | + """A Control-authorized credential update for one explicit target.""" | ||
| 107 | + | ||
| 108 | + operation_id: str | ||
| 109 | + server_id: str | ||
| 110 | + ref_revision: int | ||
| 111 | + update: CredentialUpdate | ||
| 112 | + | ||
| 113 | + | ||
| 43 | class CredentialAccess(Protocol): | 114 | class CredentialAccess(Protocol): |
| 44 | """Only return the credential information needed by this consumer.""" | 115 | """Only return the credential information needed by this consumer.""" |
| 45 | 116 | ||
| @@ -47,6 +118,10 @@ class CredentialAccess(Protocol): | |||
| 47 | 118 | ||
| 48 | async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None: ... | 119 | async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None: ... |
| 49 | 120 | ||
| 121 | + async def credential_refresh_for_ref( | ||
| 122 | + self, credential_ref: str, server_id: str | ||
| 123 | + ) -> CredentialRefresh | None: ... | ||
| 124 | + | ||
| 50 | async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None: ... | 125 | async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None: ... |
| 51 | 126 | ||
| 52 | async def model_auth_for_ref(self, credential_ref: str) -> ModelCredential | None: ... | 127 | async def model_auth_for_ref(self, credential_ref: str) -> ModelCredential | None: ... |
| @@ -0,0 +1,228 @@ | |||
| 1 | +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 2 | +"""Bounded, same-loop credential issuance facts without storing tokens.""" | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +from dataclasses import dataclass | ||
| 6 | +import secrets | ||
| 7 | +from typing import Any | ||
| 8 | + | ||
| 9 | +from agent_gateway.processes.control_service import ControlServiceBusy, ControlServiceIdentity | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +@dataclass | ||
| 13 | +class _RefState: | ||
| 14 | + epoch: str | ||
| 15 | + revision: int = 1 | ||
| 16 | + phase: str = 'active' | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +@dataclass(frozen=True) | ||
| 20 | +class CredentialTarget: | ||
| 21 | + identity: ControlServiceIdentity | ||
| 22 | + server_id: str | ||
| 23 | + credential_ref: str | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +@dataclass | ||
| 27 | +class CredentialOperation: | ||
| 28 | + target: CredentialTarget | ||
| 29 | + cutoff_revision: int | ||
| 30 | + revoked: bool | ||
| 31 | + local_ack: str = 'pending' | ||
| 32 | + outcome: str | None = None | ||
| 33 | + written: bool = False | ||
| 34 | + response_received: bool = False | ||
| 35 | + as_ok: bool | None = None | ||
| 36 | + as_applied: bool | None = None | ||
| 37 | + | ||
| 38 | + @property | ||
| 39 | + def settled(self) -> bool: | ||
| 40 | + """An uncertain written revoke remains a safety fact, not audit history.""" | ||
| 41 | + return (self.outcome in {'applied', 'rejected', 'superseded'} | ||
| 42 | + or (self.outcome in {'failed', 'timeout_unknown'} and not self.written)) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class CredentialIssuanceRegistry: | ||
| 46 | + """Retain watermarks until group shutdown; never evict safety facts for space.""" | ||
| 47 | + | ||
| 48 | + def __init__(self, *, max_refs: int = 1024, max_targets: int = 4096, | ||
| 49 | + max_operations: int = 4096, max_revocations: int = 4096) -> None: | ||
| 50 | + for limit in (max_refs, max_targets, max_operations, max_revocations): | ||
| 51 | + if type(limit) is not int or limit < 1: | ||
| 52 | + raise ValueError('credential budgets must be positive integers') | ||
| 53 | + self._max_refs = max_refs | ||
| 54 | + self._max_targets = max_targets | ||
| 55 | + self._max_operations = max_operations | ||
| 56 | + self._max_revocations = max_revocations | ||
| 57 | + self._refs: dict[str, _RefState] = {} | ||
| 58 | + self._targets: dict[CredentialTarget, int] = {} | ||
| 59 | + self.operations: dict[str, CredentialOperation] = {} | ||
| 60 | + self._revocations: dict[tuple[CredentialTarget, int], str | None] = {} | ||
| 61 | + | ||
| 62 | + @property | ||
| 63 | + def ref_count(self) -> int: | ||
| 64 | + return len(self._refs) | ||
| 65 | + | ||
| 66 | + @property | ||
| 67 | + def target_count(self) -> int: | ||
| 68 | + return len(self._targets) | ||
| 69 | + | ||
| 70 | + def issue(self, identity: ControlServiceIdentity, server_id: str, | ||
| 71 | + credential_ref: str, epoch: str) -> int: | ||
| 72 | + target = CredentialTarget(identity, server_id, credential_ref) | ||
| 73 | + if target not in self._targets and len(self._targets) >= self._max_targets: | ||
| 74 | + raise ControlServiceBusy() | ||
| 75 | + state = self._refs.get(credential_ref) | ||
| 76 | + revision = 1 if state is None else state.revision + (state.epoch != epoch) | ||
| 77 | + if state is None: | ||
| 78 | + if len(self._refs) >= self._max_refs: | ||
| 79 | + raise ControlServiceBusy() | ||
| 80 | + elif state.epoch == epoch and state.phase != 'active': | ||
| 81 | + raise ValueError('credential login is closing') | ||
| 82 | + # Reserve revocation capacity before returning any new credential. A | ||
| 83 | + # full refresh backlog must never consume a live lease's fence budget. | ||
| 84 | + self._reserve_revocation(target, revision) | ||
| 85 | + if state is None: | ||
| 86 | + state = _RefState(epoch) | ||
| 87 | + self._refs[credential_ref] = state | ||
| 88 | + elif state.epoch != epoch: | ||
| 89 | + state.epoch = epoch | ||
| 90 | + state.revision += 1 | ||
| 91 | + state.phase = 'active' | ||
| 92 | + self._targets[target] = state.revision | ||
| 93 | + return state.revision | ||
| 94 | + | ||
| 95 | + def active(self, credential_ref: str, epoch: str) -> bool: | ||
| 96 | + state = self._refs.get(credential_ref) | ||
| 97 | + return state is None or state.epoch != epoch or state.phase == 'active' | ||
| 98 | + | ||
| 99 | + def begin_logout(self, credential_ref: str, epoch: str) -> int: | ||
| 100 | + state = self._refs.get(credential_ref) | ||
| 101 | + if state is None: | ||
| 102 | + if len(self._refs) >= self._max_refs: | ||
| 103 | + raise ControlServiceBusy() | ||
| 104 | + state = _RefState(epoch) | ||
| 105 | + self._refs[credential_ref] = state | ||
| 106 | + elif state.epoch != epoch: | ||
| 107 | + state.epoch = epoch | ||
| 108 | + state.revision += 1 | ||
| 109 | + state.phase = 'closing' | ||
| 110 | + return state.revision | ||
| 111 | + | ||
| 112 | + def finish_logout(self, credential_ref: str, epoch: str) -> None: | ||
| 113 | + state = self._refs[credential_ref] | ||
| 114 | + if state.epoch == epoch and state.phase == 'closing': | ||
| 115 | + state.phase = 'revoked' | ||
| 116 | + | ||
| 117 | + def targets(self, credential_ref: str, cutoff: int) -> list[CredentialTarget]: | ||
| 118 | + return [target for target, revision in self._targets.items() | ||
| 119 | + if target.credential_ref == credential_ref and revision <= cutoff] | ||
| 120 | + | ||
| 121 | + def registered(self, identity: ControlServiceIdentity, server_id: str, | ||
| 122 | + credential_ref: str) -> bool: | ||
| 123 | + return CredentialTarget(identity, server_id, credential_ref) in self._targets | ||
| 124 | + | ||
| 125 | + def revision(self, credential_ref: str, epoch: str) -> int: | ||
| 126 | + state = self._refs.get(credential_ref) | ||
| 127 | + if state is None or state.epoch != epoch or state.phase != 'active': | ||
| 128 | + raise ValueError('credential login is not active') | ||
| 129 | + return state.revision | ||
| 130 | + | ||
| 131 | + def latest_revision(self, credential_ref: str) -> int: | ||
| 132 | + state = self._refs.get(credential_ref) | ||
| 133 | + if state is None: | ||
| 134 | + raise ValueError('credential has not been issued') | ||
| 135 | + return state.revision | ||
| 136 | + | ||
| 137 | + def operation(self, target: CredentialTarget, cutoff: int, *, revoked: bool) -> str: | ||
| 138 | + if revoked: | ||
| 139 | + # A historical consumer only needs to fence versions actually | ||
| 140 | + # issued to it, not a later login used by a different Worker. | ||
| 141 | + cutoff = min(cutoff, self._targets.get(target, cutoff)) | ||
| 142 | + key = (target, cutoff) | ||
| 143 | + operation_id = self._revocations.get(key) | ||
| 144 | + if operation_id is not None: | ||
| 145 | + return operation_id | ||
| 146 | + self._reserve_revocation(target, cutoff) | ||
| 147 | + elif sum(not operation.revoked for operation in self.operations.values()) >= self._max_operations: | ||
| 148 | + completed = next((key for key, operation in self.operations.items() | ||
| 149 | + if not operation.revoked and operation.outcome is not None), None) | ||
| 150 | + if completed is None: | ||
| 151 | + raise ControlServiceBusy() | ||
| 152 | + del self.operations[completed] | ||
| 153 | + operation_id = secrets.token_hex(16) | ||
| 154 | + self.operations[operation_id] = CredentialOperation(target, cutoff, revoked) | ||
| 155 | + if revoked: | ||
| 156 | + self._revocations[(target, cutoff)] = operation_id | ||
| 157 | + return operation_id | ||
| 158 | + | ||
| 159 | + def _reserve_revocation(self, target: CredentialTarget, revision: int) -> None: | ||
| 160 | + key = (target, revision) | ||
| 161 | + if key in self._revocations: | ||
| 162 | + return | ||
| 163 | + unused = next((old for old, operation_id in self._revocations.items() | ||
| 164 | + if old[0] == target and operation_id is None), None) | ||
| 165 | + if unused is not None: | ||
| 166 | + del self._revocations[unused] | ||
| 167 | + elif len(self._revocations) >= self._max_revocations: | ||
| 168 | + completed = next((old for old, operation_id in self._revocations.items() | ||
| 169 | + if operation_id is not None | ||
| 170 | + and self.operations[operation_id].settled | ||
| 171 | + and (old[0] == target or old[0] not in self._targets)), None) | ||
| 172 | + if completed is None: | ||
| 173 | + raise ControlServiceBusy() | ||
| 174 | + operation_id = self._revocations.pop(completed) | ||
| 175 | + del self.operations[operation_id] | ||
| 176 | + self._revocations[key] = None | ||
| 177 | + | ||
| 178 | + def result(self, identity: ControlServiceIdentity, result: dict[str, Any]) -> None: | ||
| 179 | + fields = {'operation_id', 'server_id', 'credential_ref', 'outcome', | ||
| 180 | + 'written', 'response_received', 'as_ok', 'as_applied'} | ||
| 181 | + if set(result) != fields: | ||
| 182 | + raise ValueError('invalid credential result') | ||
| 183 | + operation = self.operations.get(result['operation_id']) | ||
| 184 | + if operation is None or operation.target != CredentialTarget( | ||
| 185 | + identity, result['server_id'], result['credential_ref'], | ||
| 186 | + ): | ||
| 187 | + raise ValueError('unknown credential operation') | ||
| 188 | + outcome = result['outcome'] | ||
| 189 | + if outcome not in {'applied', 'rejected', 'failed', 'timeout_unknown', | ||
| 190 | + 'confirmed_unknown', 'superseded'}: | ||
| 191 | + raise ValueError('invalid credential outcome') | ||
| 192 | + for name in ('written', 'response_received'): | ||
| 193 | + if type(result[name]) is not bool: | ||
| 194 | + raise ValueError('invalid credential result flag') | ||
| 195 | + for name in ('as_ok', 'as_applied'): | ||
| 196 | + if result[name] is not None and type(result[name]) is not bool: | ||
| 197 | + raise ValueError('invalid credential result flag') | ||
| 198 | + if outcome == 'applied' and not all(result[name] is True for name in | ||
| 199 | + ('written', 'response_received', 'as_ok', 'as_applied')): | ||
| 200 | + raise ValueError('invalid applied credential outcome') | ||
| 201 | + if operation.outcome is not None: | ||
| 202 | + previous = (operation.outcome, operation.written, operation.response_received, | ||
| 203 | + operation.as_ok, operation.as_applied) | ||
| 204 | + current = tuple(result[name] for name in ('outcome', 'written', 'response_received', | ||
| 205 | + 'as_ok', 'as_applied')) | ||
| 206 | + if previous != current: | ||
| 207 | + raise ValueError('conflicting credential result') | ||
| 208 | + return | ||
| 209 | + operation.outcome = outcome | ||
| 210 | + operation.written = result['written'] | ||
| 211 | + operation.response_received = result['response_received'] | ||
| 212 | + operation.as_ok = result['as_ok'] | ||
| 213 | + operation.as_applied = result['as_applied'] | ||
| 214 | + if operation.revoked and outcome == 'applied': | ||
| 215 | + revision = self._targets.get(operation.target) | ||
| 216 | + if revision is not None and revision <= operation.cutoff_revision: | ||
| 217 | + del self._targets[operation.target] | ||
| 218 | + | ||
| 219 | + def release(self, identity: ControlServiceIdentity) -> None: | ||
| 220 | + for key in tuple(self._revocations): | ||
| 221 | + if key[0].identity == identity: | ||
| 222 | + del self._revocations[key] | ||
| 223 | + for target in tuple(self._targets): | ||
| 224 | + if target.identity == identity: | ||
| 225 | + del self._targets[target] | ||
| 226 | + for key, operation in tuple(self.operations.items()): | ||
| 227 | + if operation.target.identity == identity: | ||
| 228 | + del self.operations[key] | ||
| @@ -4,28 +4,93 @@ from __future__ import annotations | |||
| 4 | 4 | ||
| 5 | import asyncio | 5 | import asyncio |
| 6 | from collections.abc import Callable | 6 | from collections.abc import Callable |
| 7 | +from concurrent.futures import Future | ||
| 8 | +from dataclasses import dataclass, replace | ||
| 7 | import logging | 9 | import logging |
| 8 | -from typing import TYPE_CHECKING | 10 | +from typing import Any, TYPE_CHECKING |
| 9 | 11 | ||
| 10 | from agent_gateway.auth.credential_access import CredentialUpdate, ModelCredential, LOGIN_REFRESH_WAIT_S | 12 | from agent_gateway.auth.credential_access import CredentialUpdate, ModelCredential, LOGIN_REFRESH_WAIT_S |
| 11 | 13 | ||
| 12 | if TYPE_CHECKING: | 14 | if TYPE_CHECKING: |
| 13 | from agent_gateway.auth.service import AuthService | 15 | from agent_gateway.auth.service import AuthService |
| 16 | + from agent_gateway.auth.control_blocking_work import ControlBlockingWork | ||
| 17 | + from agent_gateway.auth.session_store import AuthSessionStore | ||
| 14 | 18 | ||
| 15 | logger = logging.getLogger(__name__) | 19 | logger = logging.getLogger(__name__) |
| 16 | _LOGIN_REFRESH_WAIT_S = LOGIN_REFRESH_WAIT_S | 20 | _LOGIN_REFRESH_WAIT_S = LOGIN_REFRESH_WAIT_S |
| 17 | 21 | ||
| 18 | 22 | ||
| 23 | +def _consume_refresh_result(future: asyncio.Future) -> None: | ||
| 24 | + """Retrieve late failures without logging credential-bearing exceptions.""" | ||
| 25 | + if not future.cancelled(): | ||
| 26 | + future.exception() | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def _finish_initial(future: asyncio.Future, value: Any) -> None: | ||
| 30 | + if not future.done(): | ||
| 31 | + future.set_result(value) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def _fail_initial(future: asyncio.Future, error: BaseException) -> None: | ||
| 35 | + if future.cancelled(): | ||
| 36 | + return | ||
| 37 | + if future.done(): | ||
| 38 | + _consume_refresh_result(future) | ||
| 39 | + return | ||
| 40 | + future.set_exception(error) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +@dataclass(frozen=True) | ||
| 44 | +class LocalCredentialSnapshot: | ||
| 45 | + """Immutable identity facts for a synchronous Control commit.""" | ||
| 46 | + | ||
| 47 | + store: AuthSessionStore | ||
| 48 | + session_id: str | ||
| 49 | + user_id: str | ||
| 50 | + created_at: float | ||
| 51 | + credential_ref: str | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +@dataclass(frozen=True) | ||
| 55 | +class LocalCredentialResult: | ||
| 56 | + """A request-scoped credential result and its immutable identity snapshot.""" | ||
| 57 | + | ||
| 58 | + credential: ModelCredential | None | ||
| 59 | + snapshot: LocalCredentialSnapshot | None | ||
| 60 | + model_required: bool | ||
| 61 | + expired: bool = False | ||
| 62 | + model_names: tuple[str, ...] = () | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +@dataclass(frozen=True) | ||
| 66 | +class _RequestWork: | ||
| 67 | + future: Future | ||
| 68 | + initial: asyncio.Future | ||
| 69 | + | ||
| 70 | + | ||
| 19 | class LocalCredentialAccess: | 71 | class LocalCredentialAccess: |
| 20 | """Lazily use the original service; construction has no login side effects.""" | 72 | """Lazily use the original service; construction has no login side effects.""" |
| 21 | 73 | ||
| 22 | - def __init__(self, auth_service_provider: Callable[[], AuthService]) -> None: | 74 | + def __init__( |
| 75 | + self, auth_service_provider: Callable[[], AuthService], *, | ||
| 76 | + blocking_work: ControlBlockingWork | None = None, | ||
| 77 | + ) -> None: | ||
| 23 | self._auth_service_provider = auth_service_provider | 78 | self._auth_service_provider = auth_service_provider |
| 79 | + self._blocking_work = blocking_work | ||
| 80 | + self._refreshing: dict[str, _RequestWork] = {} | ||
| 24 | 81 | ||
| 25 | async def request_model_auth(self, auth_session: str | None, model_name: str) -> ModelCredential | None: | 82 | async def request_model_auth(self, auth_session: str | None, model_name: str) -> ModelCredential | None: |
| 83 | + result = await self.request_model_auth_with_snapshot(auth_session, model_name) | ||
| 84 | + return None if result is None else result.credential | ||
| 85 | + | ||
| 86 | + async def request_model_auth_with_snapshot( | ||
| 87 | + self, auth_session: str | None, model_name: str, | ||
| 88 | + ) -> LocalCredentialResult | None: | ||
| 26 | from agent_gateway.auth.passthrough import _build_model_auth, _is_login_model, expired_login_session | 89 | from agent_gateway.auth.passthrough import _build_model_auth, _is_login_model, expired_login_session |
| 27 | 90 | ||
| 28 | model_name = model_name.strip() | 91 | model_name = model_name.strip() |
| 92 | + if self._blocking_work is not None: | ||
| 93 | + return await self._bounded_request_model_auth(auth_session, model_name) | ||
| 29 | if not auth_session or not model_name: | 94 | if not auth_session or not model_name: |
| 30 | return None | 95 | return None |
| 31 | service = self._auth_service_provider() | 96 | service = self._auth_service_provider() |
| @@ -39,13 +104,150 @@ class LocalCredentialAccess: | |||
| 39 | ) | 104 | ) |
| 40 | except asyncio.TimeoutError: | 105 | except asyncio.TimeoutError: |
| 41 | logger.warning('[ModelAuth] Login credential refresh timed out; checking current credentials') | 106 | logger.warning('[ModelAuth] Login credential refresh timed out; checking current credentials') |
| 42 | - except Exception: # A failed refresh must not prevent the original request. | 107 | + except Exception: |
| 43 | logger.debug('[ModelAuth] Login credential refresh failed', exc_info=True) | 108 | logger.debug('[ModelAuth] Login credential refresh failed', exc_info=True) |
| 44 | auth = _build_model_auth(model_name, auth_session, service=service) | 109 | auth = _build_model_auth(model_name, auth_session, service=service) |
| 45 | if auth is None: | 110 | if auth is None: |
| 46 | - return None | 111 | + return LocalCredentialResult(None, None, True) |
| 47 | - return ModelCredential( | 112 | + current = service.resolve_session(auth_session) |
| 48 | - api_base=auth['api_base'], api_key=auth['api_key'], credential_ref=auth['credential_ref'], | 113 | + if current is None: |
| 114 | + return LocalCredentialResult(None, None, True) | ||
| 115 | + snapshot = self._snapshot(service, current) | ||
| 116 | + return LocalCredentialResult( | ||
| 117 | + ModelCredential( | ||
| 118 | + api_base=auth['api_base'], | ||
| 119 | + api_key=auth['api_key'], | ||
| 120 | + credential_ref=auth['credential_ref'], | ||
| 121 | + ), | ||
| 122 | + snapshot, | ||
| 123 | + True, | ||
| 124 | + current.credential.is_expired(), | ||
| 125 | + ) | ||
| 126 | + | ||
| 127 | + async def _bounded_request_model_auth( | ||
| 128 | + self, auth_session: str | None, model_name: str, | ||
| 129 | + ) -> LocalCredentialResult | None: | ||
| 130 | + """Keep account refresh bounded while each request judges its own model.""" | ||
| 131 | + from agent_gateway.auth.apig import resolve_apig_config | ||
| 132 | + from agent_gateway.auth.login_credentials import bare_model_name | ||
| 133 | + from agent_gateway.auth.model_catalog import get_models | ||
| 134 | + from agent_gateway.auth.service import REFRESH_AHEAD_S | ||
| 135 | + | ||
| 136 | + if not auth_session or not model_name: | ||
| 137 | + return LocalCredentialResult(None, None, False) | ||
| 138 | + service = self._auth_service_provider() | ||
| 139 | + work = self._refreshing.get(auth_session) | ||
| 140 | + if work is None or work.future.done(): | ||
| 141 | + loop = asyncio.get_running_loop() | ||
| 142 | + initial = loop.create_future() | ||
| 143 | + initial.add_done_callback(_consume_refresh_result) | ||
| 144 | + | ||
| 145 | + def load_and_refresh(): | ||
| 146 | + try: | ||
| 147 | + models = get_models(auth_session, allow_refresh=False, service=service) | ||
| 148 | + model_names = tuple(model.model_name for model in models) | ||
| 149 | + current = service.resolve_session(auth_session) | ||
| 150 | + config = resolve_apig_config(allow_refresh=False) | ||
| 151 | + snapshot = None if current is None else self._snapshot(service, current) | ||
| 152 | + if current is None or config is None: | ||
| 153 | + result = LocalCredentialResult( | ||
| 154 | + None, snapshot, False, False, model_names, | ||
| 155 | + ) | ||
| 156 | + else: | ||
| 157 | + result = LocalCredentialResult( | ||
| 158 | + ModelCredential( | ||
| 159 | + api_base=config.invoke_base_url, | ||
| 160 | + api_key=current.credential.id_token, | ||
| 161 | + credential_ref=snapshot.credential_ref, | ||
| 162 | + ), | ||
| 163 | + snapshot, | ||
| 164 | + False, | ||
| 165 | + current.credential.is_expired(), | ||
| 166 | + model_names, | ||
| 167 | + ) | ||
| 168 | + loop.call_soon_threadsafe(_finish_initial, initial, result) | ||
| 169 | + if current is None or not current.credential.expires_within(REFRESH_AHEAD_S): | ||
| 170 | + return result | ||
| 171 | + try: | ||
| 172 | + service.try_refresh(current) | ||
| 173 | + except Exception: | ||
| 174 | + logger.debug('[ModelAuth] Control credential refresh failed', exc_info=True) | ||
| 175 | + current = service.resolve_session(auth_session) | ||
| 176 | + config = resolve_apig_config(allow_refresh=False) | ||
| 177 | + if current is None or config is None: | ||
| 178 | + return LocalCredentialResult( | ||
| 179 | + None, result.snapshot, False, True, model_names, | ||
| 180 | + ) | ||
| 181 | + snapshot = self._snapshot(service, current) | ||
| 182 | + return LocalCredentialResult( | ||
| 183 | + ModelCredential( | ||
| 184 | + api_base=config.invoke_base_url, | ||
| 185 | + api_key=current.credential.id_token, | ||
| 186 | + credential_ref=snapshot.credential_ref, | ||
| 187 | + ), | ||
| 188 | + snapshot, | ||
| 189 | + False, | ||
| 190 | + current.credential.is_expired(), | ||
| 191 | + model_names, | ||
| 192 | + ) | ||
| 193 | + except BaseException as error: | ||
| 194 | + loop.call_soon_threadsafe(_fail_initial, initial, error) | ||
| 195 | + raise | ||
| 196 | + | ||
| 197 | + future = self._blocking_work.submit(load_and_refresh) | ||
| 198 | + future.add_done_callback(_consume_refresh_result) | ||
| 199 | + work = _RequestWork(future, initial) | ||
| 200 | + self._refreshing[auth_session] = work | ||
| 201 | + | ||
| 202 | + def clear(completed: Future) -> None: | ||
| 203 | + def remove() -> None: | ||
| 204 | + if self._refreshing.get(auth_session) is work: | ||
| 205 | + self._refreshing.pop(auth_session, None) | ||
| 206 | + try: | ||
| 207 | + loop.call_soon_threadsafe(remove) | ||
| 208 | + except RuntimeError: | ||
| 209 | + pass | ||
| 210 | + | ||
| 211 | + future.add_done_callback(clear) | ||
| 212 | + | ||
| 213 | + initial_result: LocalCredentialResult = await asyncio.shield(work.initial) | ||
| 214 | + model_required = ( | ||
| 215 | + model_name in initial_result.model_names | ||
| 216 | + or bare_model_name(model_name) in initial_result.model_names | ||
| 217 | + ) | ||
| 218 | + if not model_required: | ||
| 219 | + return LocalCredentialResult( | ||
| 220 | + None, initial_result.snapshot, False, initial_result.expired, | ||
| 221 | + initial_result.model_names, | ||
| 222 | + ) | ||
| 223 | + if initial_result.credential is None or not initial_result.expired: | ||
| 224 | + return replace(initial_result, model_required=True) | ||
| 225 | + | ||
| 226 | + waiter = asyncio.wrap_future(work.future) | ||
| 227 | + waiter.add_done_callback(_consume_refresh_result) | ||
| 228 | + try: | ||
| 229 | + async with asyncio.timeout(_LOGIN_REFRESH_WAIT_S): | ||
| 230 | + final_result = await asyncio.shield(waiter) | ||
| 231 | + except asyncio.TimeoutError: | ||
| 232 | + logger.warning('[ModelAuth] Control credential refresh timed out') | ||
| 233 | + return LocalCredentialResult( | ||
| 234 | + None, initial_result.snapshot, True, True, initial_result.model_names, | ||
| 235 | + ) | ||
| 236 | + except Exception: | ||
| 237 | + return LocalCredentialResult( | ||
| 238 | + None, initial_result.snapshot, True, True, initial_result.model_names, | ||
| 239 | + ) | ||
| 240 | + return replace(final_result, model_required=True) | ||
| 241 | + | ||
| 242 | + def _snapshot(self, service: AuthService, session: Any) -> LocalCredentialSnapshot: | ||
| 243 | + from agent_gateway.auth.login_credentials import credential_ref_for_user | ||
| 244 | + | ||
| 245 | + return LocalCredentialSnapshot( | ||
| 246 | + store=service._store, | ||
| 247 | + session_id=session.session_id, | ||
| 248 | + user_id=session.user_id, | ||
| 249 | + created_at=session.created_at, | ||
| 250 | + credential_ref=credential_ref_for_user(session.user_id), | ||
| 49 | ) | 251 | ) |
| 50 | 252 | ||
| 51 | async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None: | 253 | async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None: |
| @@ -64,7 +266,6 @@ class LocalCredentialAccess: | |||
| 64 | api_key=update.get('api_key'), revoked=bool(update.get('revoked', False)), | 266 | api_key=update.get('api_key'), revoked=bool(update.get('revoked', False)), |
| 65 | ) | 267 | ) |
| 66 | 268 | ||
| 67 | - | ||
| 68 | async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None: | 269 | async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None: |
| 69 | from agent_gateway.auth.login_credentials import credential_ref_for_user | 270 | from agent_gateway.auth.login_credentials import credential_ref_for_user |
| 70 | from agent_gateway.auth.service import ModelAuthRequired, live_session | 271 | from agent_gateway.auth.service import ModelAuthRequired, live_session |
| @@ -0,0 +1,267 @@ | |||
| 1 | +"""Public login-model catalog contracts shared by Control and Worker.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import json | ||
| 5 | +from dataclasses import dataclass | ||
| 6 | +from typing import Literal, Protocol | ||
| 7 | +from urllib.parse import urlsplit | ||
| 8 | + | ||
| 9 | +from agent_gateway.processes import control_protocol | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +CatalogStatus = Literal["ok", "unauthenticated", "too_large", "unavailable"] | ||
| 13 | +CatalogErrorReason = Literal[ | ||
| 14 | + "too_large", "unavailable", "protocol", "busy", "not_enabled" | ||
| 15 | +] | ||
| 16 | + | ||
| 17 | +_CATALOG_STATUSES = frozenset( | ||
| 18 | + {"ok", "unauthenticated", "too_large", "unavailable"} | ||
| 19 | +) | ||
| 20 | +_CATALOG_ERROR_REASONS = frozenset( | ||
| 21 | + {"too_large", "unavailable", "protocol", "busy", "not_enabled"} | ||
| 22 | +) | ||
| 23 | +_MAX_AUTH_SESSION_LENGTH = 256 | ||
| 24 | +_MAX_MODELS = 48 | ||
| 25 | +_MAX_MODEL_NAME_LENGTH = 256 | ||
| 26 | +_MAX_DISPLAY_NAME_LENGTH = 256 | ||
| 27 | +_MAX_DESCRIPTION_LENGTH = 1024 | ||
| 28 | +_MAX_RESULT_BYTES = 48 * 1024 | ||
| 29 | +_MAX_API_BASE_LENGTH = 2048 | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +class CatalogError(ValueError): | ||
| 33 | + """A sanitized login-model catalog failure.""" | ||
| 34 | + | ||
| 35 | + def __init__(self, reason: CatalogErrorReason = "unavailable") -> None: | ||
| 36 | + if reason not in _CATALOG_ERROR_REASONS: | ||
| 37 | + raise ValueError("Unsupported login model catalog failure reason") | ||
| 38 | + self.reason = reason | ||
| 39 | + super().__init__("Public login model catalog failed") | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +@dataclass(frozen=True, slots=True) | ||
| 43 | +class PublicLoginModel: | ||
| 44 | + """The immutable, public projection of a login model.""" | ||
| 45 | + | ||
| 46 | + model_name: str | ||
| 47 | + display_name: str | ||
| 48 | + description: str | ||
| 49 | + | ||
| 50 | + def to_dict(self) -> dict[str, str]: | ||
| 51 | + return { | ||
| 52 | + "model_name": self.model_name, | ||
| 53 | + "display_name": self.display_name, | ||
| 54 | + "description": self.description, | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +@dataclass(frozen=True, slots=True) | ||
| 59 | +class CatalogResult: | ||
| 60 | + """An immutable catalog snapshot or fixed business failure status.""" | ||
| 61 | + | ||
| 62 | + status: CatalogStatus | ||
| 63 | + models: tuple[PublicLoginModel, ...] | ||
| 64 | + | ||
| 65 | + def to_dict(self) -> dict[str, object]: | ||
| 66 | + return { | ||
| 67 | + "status": self.status, | ||
| 68 | + "models": [model.to_dict() for model in self.models], | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +@dataclass(frozen=True, slots=True) | ||
| 73 | +class LoginModelSnapshot: | ||
| 74 | + """An immutable public model catalog snapshot with its API base.""" | ||
| 75 | + | ||
| 76 | + status: CatalogStatus | ||
| 77 | + api_base: str | ||
| 78 | + models: tuple[PublicLoginModel, ...] | ||
| 79 | + version: int = 1 | ||
| 80 | + | ||
| 81 | + def to_dict(self) -> dict[str, object]: | ||
| 82 | + return { | ||
| 83 | + "version": self.version, | ||
| 84 | + "status": self.status, | ||
| 85 | + "api_base": self.api_base, | ||
| 86 | + "models": [model.to_dict() for model in self.models], | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +class PublicLoginModelCatalog(Protocol): | ||
| 91 | + """Port for fetching the public login-model catalog.""" | ||
| 92 | + | ||
| 93 | + async def list_models(self, auth_session: str | None) -> CatalogResult: | ||
| 94 | + """Return a snapshot for the selected login session.""" | ||
| 95 | + ... | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +class LoginModelSnapshotPort(Protocol): | ||
| 99 | + """Port for fetching a complete public login-model snapshot.""" | ||
| 100 | + | ||
| 101 | + async def get_snapshot(self, auth_session: str | None) -> LoginModelSnapshot: | ||
| 102 | + """Return model metadata and its public inference API base.""" | ||
| 103 | + ... | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def validate_auth_session(value: object) -> str | None: | ||
| 107 | + """Validate and normalize a bounded auth-session identifier.""" | ||
| 108 | + if value is None: | ||
| 109 | + return None | ||
| 110 | + if type(value) is not str or len(value) > _MAX_AUTH_SESSION_LENGTH: | ||
| 111 | + raise CatalogError("protocol") | ||
| 112 | + normalized = value.strip() | ||
| 113 | + return normalized if normalized else None | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def _validate_models(status: CatalogStatus, models_value: object) -> tuple[PublicLoginModel, ...]: | ||
| 117 | + if type(models_value) is not list: | ||
| 118 | + raise CatalogError("protocol") | ||
| 119 | + if status != "ok" and models_value: | ||
| 120 | + raise CatalogError("protocol") | ||
| 121 | + if len(models_value) > _MAX_MODELS: | ||
| 122 | + raise CatalogError("too_large") | ||
| 123 | + | ||
| 124 | + models: list[PublicLoginModel] = [] | ||
| 125 | + for model_value in models_value: | ||
| 126 | + if type(model_value) is not dict or set(model_value) != { | ||
| 127 | + "model_name", | ||
| 128 | + "display_name", | ||
| 129 | + "description", | ||
| 130 | + }: | ||
| 131 | + raise CatalogError("protocol") | ||
| 132 | + | ||
| 133 | + model_name = model_value["model_name"] | ||
| 134 | + display_name = model_value["display_name"] | ||
| 135 | + description = model_value["description"] | ||
| 136 | + if ( | ||
| 137 | + type(model_name) is not str | ||
| 138 | + or type(display_name) is not str | ||
| 139 | + or type(description) is not str | ||
| 140 | + ): | ||
| 141 | + raise CatalogError("protocol") | ||
| 142 | + if ( | ||
| 143 | + len(model_name) > _MAX_MODEL_NAME_LENGTH | ||
| 144 | + or len(display_name) > _MAX_DISPLAY_NAME_LENGTH | ||
| 145 | + or len(description) > _MAX_DESCRIPTION_LENGTH | ||
| 146 | + ): | ||
| 147 | + raise CatalogError("too_large") | ||
| 148 | + | ||
| 149 | + models.append( | ||
| 150 | + PublicLoginModel( | ||
| 151 | + model_name=model_name, | ||
| 152 | + display_name=display_name, | ||
| 153 | + description=description, | ||
| 154 | + ) | ||
| 155 | + ) | ||
| 156 | + return tuple(models) | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +def _validate_wire_result(result_dict: dict[str, object]) -> None: | ||
| 160 | + try: | ||
| 161 | + encoded_result = json.dumps( | ||
| 162 | + result_dict, | ||
| 163 | + separators=(",", ":"), | ||
| 164 | + ensure_ascii=False, | ||
| 165 | + allow_nan=False, | ||
| 166 | + ).encode("utf-8") | ||
| 167 | + except UnicodeError: | ||
| 168 | + raise CatalogError("protocol") from None | ||
| 169 | + | ||
| 170 | + if len(encoded_result) > _MAX_RESULT_BYTES: | ||
| 171 | + raise CatalogError("too_large") | ||
| 172 | + | ||
| 173 | + try: | ||
| 174 | + control_protocol.encode_message( | ||
| 175 | + { | ||
| 176 | + "protocol_version": 1, | ||
| 177 | + # Budget for the longest UTF-8 group ID accepted by the codec. | ||
| 178 | + "group_id": "\U0010ffff" * 256, | ||
| 179 | + "slot_id": 0, | ||
| 180 | + "generation": 1, | ||
| 181 | + "type": "RESPONSE", | ||
| 182 | + "request_id": "a" * 32, | ||
| 183 | + "status": "OK", | ||
| 184 | + "result": result_dict, | ||
| 185 | + "error_code": None, | ||
| 186 | + } | ||
| 187 | + ) | ||
| 188 | + except control_protocol.ControlProtocolError: | ||
| 189 | + raise CatalogError("too_large") from None | ||
| 190 | + | ||
| 191 | + | ||
| 192 | +def _validate_api_base(value: object) -> str: | ||
| 193 | + if type(value) is not str: | ||
| 194 | + raise CatalogError("protocol") | ||
| 195 | + if len(value) > _MAX_API_BASE_LENGTH: | ||
| 196 | + raise CatalogError("too_large") | ||
| 197 | + if not value: | ||
| 198 | + return value | ||
| 199 | + | ||
| 200 | + try: | ||
| 201 | + parsed = urlsplit(value) | ||
| 202 | + port = parsed.port | ||
| 203 | + except ValueError: | ||
| 204 | + raise CatalogError("protocol") from None | ||
| 205 | + if ( | ||
| 206 | + parsed.scheme not in {"http", "https"} | ||
| 207 | + or not parsed.hostname | ||
| 208 | + or parsed.username is not None | ||
| 209 | + or parsed.password is not None | ||
| 210 | + or parsed.query | ||
| 211 | + or parsed.fragment | ||
| 212 | + or "?" in value | ||
| 213 | + or "#" in value | ||
| 214 | + or (port is not None and not 1 <= port <= 65535) | ||
| 215 | + ): | ||
| 216 | + raise CatalogError("protocol") | ||
| 217 | + return value | ||
| 218 | + | ||
| 219 | + | ||
| 220 | +def validate_catalog_response(value: object) -> CatalogResult: | ||
| 221 | + """Validate a complete Control catalog response without truncation.""" | ||
| 222 | + if type(value) is not dict or set(value) != {"status", "models"}: | ||
| 223 | + raise CatalogError("protocol") | ||
| 224 | + | ||
| 225 | + status = value["status"] | ||
| 226 | + models_value = value["models"] | ||
| 227 | + if type(status) is not str or status not in _CATALOG_STATUSES: | ||
| 228 | + raise CatalogError("protocol") | ||
| 229 | + models = _validate_models(status, models_value) | ||
| 230 | + | ||
| 231 | + result = CatalogResult(status=status, models=models) | ||
| 232 | + result_dict = result.to_dict() | ||
| 233 | + _validate_wire_result(result_dict) | ||
| 234 | + return result | ||
| 235 | + | ||
| 236 | + | ||
| 237 | +def validate_login_model_snapshot(value: object) -> LoginModelSnapshot: | ||
| 238 | + """Validate a complete Control snapshot without truncation or token leakage.""" | ||
| 239 | + if type(value) is not dict or set(value) != { | ||
| 240 | + "version", | ||
| 241 | + "status", | ||
| 242 | + "api_base", | ||
| 243 | + "models", | ||
| 244 | + }: | ||
| 245 | + raise CatalogError("protocol") | ||
| 246 | + | ||
| 247 | + version = value["version"] | ||
| 248 | + if type(version) is not int or version != 1: | ||
| 249 | + raise CatalogError("protocol") | ||
| 250 | + status = value["status"] | ||
| 251 | + if type(status) is not str or status not in _CATALOG_STATUSES: | ||
| 252 | + raise CatalogError("protocol") | ||
| 253 | + api_base = _validate_api_base(value["api_base"]) | ||
| 254 | + models = _validate_models(status, value["models"]) | ||
| 255 | + if status != "ok" and (api_base or models): | ||
| 256 | + raise CatalogError("protocol") | ||
| 257 | + if models and not api_base: | ||
| 258 | + raise CatalogError("protocol") | ||
| 259 | + | ||
| 260 | + result = LoginModelSnapshot( | ||
| 261 | + status=status, | ||
| 262 | + api_base=api_base, | ||
| 263 | + models=models, | ||
| 264 | + version=version, | ||
| 265 | + ) | ||
| 266 | + _validate_wire_result(result.to_dict()) | ||
| 267 | + return result | ||
| @@ -0,0 +1,383 @@ | |||
| 1 | +"""Worker-side ports with an explicit, endpoint-bound lifecycle mode.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import asyncio | ||
| 5 | +from dataclasses import dataclass | ||
| 6 | +from typing import TYPE_CHECKING, Any | ||
| 7 | + | ||
| 8 | +from agent_gateway.auth.credential_access import ( | ||
| 9 | + CredentialAccessError, | ||
| 10 | + CredentialRefresh, | ||
| 11 | + CredentialUpdate, | ||
| 12 | + ModelCredential, | ||
| 13 | + OwnsResolveDeadline, | ||
| 14 | +) | ||
| 15 | + | ||
| 16 | +if TYPE_CHECKING: | ||
| 17 | + from agent_gateway.auth.worker_credential_runtime import WorkerCredentialRuntime | ||
| 18 | +from agent_gateway.auth.login_credentials import is_credential_ref | ||
| 19 | +from agent_gateway.auth.session_login_bindings import SessionLoginBinding | ||
| 20 | +from agent_gateway.processes.control_service import ( | ||
| 21 | + ControlServiceClient, | ||
| 22 | + ControlServiceError, | ||
| 23 | + ControlServiceOperationError, | ||
| 24 | +) | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +_REQUEST_TIMEOUT_S = 25.0 | ||
| 28 | +_BINDING_TIMEOUT_S = 5.0 | ||
| 29 | +_BINDING_AUTH_TIMEOUT_S = _REQUEST_TIMEOUT_S | ||
| 30 | +_MAX_API_BASE_LENGTH = 2048 | ||
| 31 | +_MAX_API_KEY_LENGTH = 4096 | ||
| 32 | +_MAX_MODEL_NAME_LENGTH = 256 | ||
| 33 | +_MAX_SESSION_ID_LENGTH = 256 | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +class _BindingNotFound(Exception): | ||
| 37 | + pass | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +@dataclass(frozen=True) | ||
| 41 | +class _RemoteSessionLoginBinding(SessionLoginBinding): | ||
| 42 | + """A binding with the session identity needed for remote resolution.""" | ||
| 43 | + | ||
| 44 | + session_id: str | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def _validated_input( | ||
| 48 | + value: object, *, max_length: int, allow_empty: bool | ||
| 49 | +) -> str | None: | ||
| 50 | + if type(value) is not str: | ||
| 51 | + return None | ||
| 52 | + if len(value) > max_length: | ||
| 53 | + return None | ||
| 54 | + normalized = value.strip() | ||
| 55 | + if not allow_empty and not normalized: | ||
| 56 | + return None | ||
| 57 | + return normalized | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _is_remote_credential_ref(value: object) -> bool: | ||
| 61 | + return type(value) is str and len(value) == 32 and is_credential_ref(value) | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def _auth_session_value(auth_session: str | None) -> str | None: | ||
| 65 | + if auth_session is None: | ||
| 66 | + return None | ||
| 67 | + value = _validated_input( | ||
| 68 | + auth_session, | ||
| 69 | + max_length=_MAX_SESSION_ID_LENGTH, | ||
| 70 | + allow_empty=True, | ||
| 71 | + ) | ||
| 72 | + if value is None: | ||
| 73 | + raise CredentialAccessError("invalid") | ||
| 74 | + if value == "": | ||
| 75 | + return None | ||
| 76 | + return value | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +async def _call_control( | ||
| 80 | + client: ControlServiceClient, operation: str, arguments: dict[str, Any], timeout: float | ||
| 81 | +) -> dict[str, Any]: | ||
| 82 | + try: | ||
| 83 | + return await client.call(operation, arguments, timeout=timeout) | ||
| 84 | + except asyncio.CancelledError: | ||
| 85 | + raise | ||
| 86 | + except TimeoutError: | ||
| 87 | + raise CredentialAccessError("unavailable") from None | ||
| 88 | + except ControlServiceOperationError as error: | ||
| 89 | + reason = ( | ||
| 90 | + "not_enabled" | ||
| 91 | + if error.error_code == "OPERATION_NOT_ENABLED" | ||
| 92 | + else "unavailable" | ||
| 93 | + ) | ||
| 94 | + raise CredentialAccessError(reason) from None | ||
| 95 | + except ControlServiceError: | ||
| 96 | + raise CredentialAccessError("unavailable") from None | ||
| 97 | + except Exception: | ||
| 98 | + raise CredentialAccessError("unavailable") from None | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def _credential(response: dict[str, Any]) -> ModelCredential: | ||
| 102 | + if not isinstance(response, dict): | ||
| 103 | + raise CredentialAccessError("protocol") | ||
| 104 | + if set(response) != {"status", "credential"} or response.get("status") != "ok": | ||
| 105 | + raise CredentialAccessError("protocol") | ||
| 106 | + credential = response.get("credential") | ||
| 107 | + if not isinstance(credential, dict) or set(credential) != { | ||
| 108 | + "api_base", | ||
| 109 | + "api_key", | ||
| 110 | + "credential_ref", | ||
| 111 | + }: | ||
| 112 | + raise CredentialAccessError("protocol") | ||
| 113 | + api_base = credential.get("api_base") | ||
| 114 | + api_key = credential.get("api_key") | ||
| 115 | + credential_ref = credential.get("credential_ref") | ||
| 116 | + if ( | ||
| 117 | + type(api_base) is not str | ||
| 118 | + or type(api_key) is not str | ||
| 119 | + or type(credential_ref) is not str | ||
| 120 | + or len(api_base) > _MAX_API_BASE_LENGTH | ||
| 121 | + or len(api_key) > _MAX_API_KEY_LENGTH | ||
| 122 | + or not api_base.strip() | ||
| 123 | + or not api_key.strip() | ||
| 124 | + or not _is_remote_credential_ref(credential_ref) | ||
| 125 | + ): | ||
| 126 | + raise CredentialAccessError("protocol") | ||
| 127 | + return ModelCredential( | ||
| 128 | + api_base=api_base, api_key=api_key, credential_ref=credential_ref | ||
| 129 | + ) | ||
| 130 | + | ||
| 131 | + | ||
| 132 | +def _model_auth_response( | ||
| 133 | + response: dict[str, Any], *, allow_not_required: bool, | ||
| 134 | + client: ControlServiceClient | None = None, | ||
| 135 | + runtime: WorkerCredentialRuntime | None = None, | ||
| 136 | +) -> ModelCredential | None: | ||
| 137 | + if not isinstance(response, dict): | ||
| 138 | + raise CredentialAccessError("protocol") | ||
| 139 | + status = response.get("status") | ||
| 140 | + if status == "invalid" and set(response) == {"status"}: | ||
| 141 | + raise CredentialAccessError("invalid") | ||
| 142 | + if ( | ||
| 143 | + allow_not_required | ||
| 144 | + and status == "not_required" | ||
| 145 | + and set(response) == {"status"} | ||
| 146 | + ): | ||
| 147 | + return None | ||
| 148 | + if runtime is None: | ||
| 149 | + return _credential(response) | ||
| 150 | + if set(response) != {"status", "credential", "lease"} or client is None: | ||
| 151 | + raise CredentialAccessError("protocol") | ||
| 152 | + credential = _credential({"status": status, "credential": response["credential"]}) | ||
| 153 | + lease = response["lease"] | ||
| 154 | + identity = client.identity | ||
| 155 | + if ( | ||
| 156 | + not isinstance(lease, dict) | ||
| 157 | + or set(lease) != {"group_id", "slot_id", "generation", "server_id", | ||
| 158 | + "credential_ref", "ref_revision"} | ||
| 159 | + or lease["group_id"] != identity.group_id | ||
| 160 | + or type(lease["slot_id"]) is not int | ||
| 161 | + or lease["slot_id"] != identity.slot_id | ||
| 162 | + or type(lease["generation"]) is not int | ||
| 163 | + or lease["generation"] != identity.generation | ||
| 164 | + or lease["server_id"] != runtime.server_id | ||
| 165 | + or lease["credential_ref"] != credential.credential_ref | ||
| 166 | + or type(lease["ref_revision"]) is not int | ||
| 167 | + or lease["ref_revision"] <= 0 | ||
| 168 | + ): | ||
| 169 | + raise CredentialAccessError("protocol") | ||
| 170 | + return ModelCredential( | ||
| 171 | + api_base=credential.api_base, api_key=credential.api_key, | ||
| 172 | + credential_ref=credential.credential_ref, | ||
| 173 | + lease=runtime.issue(credential.credential_ref, lease["ref_revision"], lease["server_id"]), | ||
| 174 | + ) | ||
| 175 | + | ||
| 176 | + | ||
| 177 | +def _binding_response(response: dict[str, Any], session_id: str) -> _RemoteSessionLoginBinding: | ||
| 178 | + if not isinstance(response, dict): | ||
| 179 | + raise CredentialAccessError("protocol") | ||
| 180 | + status = response.get("status") | ||
| 181 | + if status == "not_found" and set(response) == {"status"}: | ||
| 182 | + raise _BindingNotFound() | ||
| 183 | + if set(response) != {"status", "binding"} or status != "ok": | ||
| 184 | + raise CredentialAccessError("protocol") | ||
| 185 | + binding = response.get("binding") | ||
| 186 | + if not isinstance(binding, dict) or set(binding) != {"credential_ref", "model_name"}: | ||
| 187 | + raise CredentialAccessError("protocol") | ||
| 188 | + credential_ref = binding.get("credential_ref") | ||
| 189 | + model_name = binding.get("model_name") | ||
| 190 | + if ( | ||
| 191 | + type(credential_ref) is not str | ||
| 192 | + or type(model_name) is not str | ||
| 193 | + or len(model_name) > _MAX_MODEL_NAME_LENGTH | ||
| 194 | + or not model_name.strip() | ||
| 195 | + or not _is_remote_credential_ref(credential_ref) | ||
| 196 | + ): | ||
| 197 | + raise CredentialAccessError("protocol") | ||
| 198 | + return _RemoteSessionLoginBinding( | ||
| 199 | + credential_ref=credential_ref, | ||
| 200 | + model_name=model_name, | ||
| 201 | + session_id=session_id, | ||
| 202 | + ) | ||
| 203 | + | ||
| 204 | + | ||
| 205 | +class RemoteCredentialAccess: | ||
| 206 | + """Request-scoped credential access without Worker-side auth state.""" | ||
| 207 | + | ||
| 208 | + def __init__( | ||
| 209 | + self, client: ControlServiceClient, *, runtime: WorkerCredentialRuntime | None = None, | ||
| 210 | + ) -> None: | ||
| 211 | + self._client = client | ||
| 212 | + self._runtime = runtime | ||
| 213 | + | ||
| 214 | + def release_request(self, envelope: Any) -> None: | ||
| 215 | + """Release an acquired lease if preprocessing aborts before MH owns it.""" | ||
| 216 | + if self._runtime is not None: | ||
| 217 | + self._runtime.release(envelope) | ||
| 218 | + | ||
| 219 | + async def request_model_auth( | ||
| 220 | + self, auth_session: str | None, model_name: str | ||
| 221 | + ) -> ModelCredential | None: | ||
| 222 | + normalized_session = _auth_session_value(auth_session) | ||
| 223 | + normalized_model = _validated_input( | ||
| 224 | + model_name, | ||
| 225 | + max_length=_MAX_MODEL_NAME_LENGTH, | ||
| 226 | + allow_empty=True, | ||
| 227 | + ) | ||
| 228 | + if normalized_model is None: | ||
| 229 | + raise CredentialAccessError("invalid") | ||
| 230 | + response = await _call_control( | ||
| 231 | + self._client, | ||
| 232 | + "credentials.request_model_auth", | ||
| 233 | + {"auth_session": normalized_session, "model_name": normalized_model}, | ||
| 234 | + timeout=_REQUEST_TIMEOUT_S, | ||
| 235 | + ) | ||
| 236 | + return _model_auth_response(response, allow_not_required=True, | ||
| 237 | + client=self._client, runtime=self._runtime) | ||
| 238 | + | ||
| 239 | + async def credential_update_for_ref(self, credential_ref: str) -> CredentialUpdate | None: | ||
| 240 | + raise CredentialAccessError("not_enabled") | ||
| 241 | + | ||
| 242 | + async def credential_refresh_for_ref( | ||
| 243 | + self, credential_ref: str, server_id: str, | ||
| 244 | + ) -> CredentialRefresh | None: | ||
| 245 | + if self._runtime is None: | ||
| 246 | + raise CredentialAccessError("not_enabled") | ||
| 247 | + if not _is_remote_credential_ref(credential_ref) or server_id != self._runtime.server_id: | ||
| 248 | + raise CredentialAccessError("invalid") | ||
| 249 | + response = await _call_control( | ||
| 250 | + self._client, "credentials.refresh_for_ref", | ||
| 251 | + {"credential_ref": credential_ref, "server_id": server_id}, | ||
| 252 | + timeout=_REQUEST_TIMEOUT_S, | ||
| 253 | + ) | ||
| 254 | + if response == {"status": "invalid"}: | ||
| 255 | + raise CredentialAccessError("invalid") | ||
| 256 | + if ( | ||
| 257 | + set(response) != {"status", "operation_id", "server_id", "ref_revision", "update"} | ||
| 258 | + or response["status"] != "ok" | ||
| 259 | + or not _is_remote_credential_ref(response["operation_id"]) | ||
| 260 | + or response["server_id"] != server_id | ||
| 261 | + or type(response["ref_revision"]) is not int | ||
| 262 | + or response["ref_revision"] <= 0 | ||
| 263 | + ): | ||
| 264 | + raise CredentialAccessError("protocol") | ||
| 265 | + update = response["update"] | ||
| 266 | + if not isinstance(update, dict) or update.get("credential_ref") != credential_ref: | ||
| 267 | + raise CredentialAccessError("protocol") | ||
| 268 | + if set(update) == {"credential_ref", "revoked"} and update["revoked"] is True: | ||
| 269 | + value = CredentialUpdate(credential_ref, revoked=True) | ||
| 270 | + elif ( | ||
| 271 | + set(update) == {"credential_ref", "api_key"} | ||
| 272 | + and type(update["api_key"]) is str | ||
| 273 | + and 0 < len(update["api_key"].strip()) <= _MAX_API_KEY_LENGTH | ||
| 274 | + ): | ||
| 275 | + value = CredentialUpdate(credential_ref, api_key=update["api_key"]) | ||
| 276 | + else: | ||
| 277 | + raise CredentialAccessError("protocol") | ||
| 278 | + return CredentialRefresh(response["operation_id"], server_id, | ||
| 279 | + response["ref_revision"], value) | ||
| 280 | + | ||
| 281 | + async def credential_ref_for_login_session(self, auth_session: str | None) -> str | None: | ||
| 282 | + raise CredentialAccessError("not_enabled") | ||
| 283 | + | ||
| 284 | + async def model_auth_for_ref(self, credential_ref: str) -> ModelCredential | None: | ||
| 285 | + raise CredentialAccessError("not_enabled") | ||
| 286 | + | ||
| 287 | + | ||
| 288 | +class RemoteSessionLoginBindings(OwnsResolveDeadline): | ||
| 289 | + """Request-scoped session binding access without Worker-side persistence.""" | ||
| 290 | + | ||
| 291 | + resolve_deadline_s = _BINDING_AUTH_TIMEOUT_S | ||
| 292 | + | ||
| 293 | + def __init__( | ||
| 294 | + self, client: ControlServiceClient, *, runtime: WorkerCredentialRuntime | None = None, | ||
| 295 | + ) -> None: | ||
| 296 | + self._client = client | ||
| 297 | + self._runtime = runtime | ||
| 298 | + | ||
| 299 | + async def remember( | ||
| 300 | + self, session_id: str, credential_ref: str, model_name: str | ||
| 301 | + ) -> None: | ||
| 302 | + normalized_session = _validated_input( | ||
| 303 | + session_id, | ||
| 304 | + max_length=_MAX_SESSION_ID_LENGTH, | ||
| 305 | + allow_empty=False, | ||
| 306 | + ) | ||
| 307 | + normalized_model = _validated_input( | ||
| 308 | + model_name, | ||
| 309 | + max_length=_MAX_MODEL_NAME_LENGTH, | ||
| 310 | + allow_empty=False, | ||
| 311 | + ) | ||
| 312 | + if ( | ||
| 313 | + normalized_session is None | ||
| 314 | + or normalized_model is None | ||
| 315 | + or type(credential_ref) is not str | ||
| 316 | + or not _is_remote_credential_ref(credential_ref) | ||
| 317 | + ): | ||
| 318 | + raise CredentialAccessError("invalid") | ||
| 319 | + response = await _call_control( | ||
| 320 | + self._client, | ||
| 321 | + "bindings.remember", | ||
| 322 | + { | ||
| 323 | + "session_id": normalized_session, | ||
| 324 | + "credential_ref": credential_ref, | ||
| 325 | + "model_name": normalized_model, | ||
| 326 | + }, | ||
| 327 | + timeout=_BINDING_TIMEOUT_S, | ||
| 328 | + ) | ||
| 329 | + if response != {"status": "ok"}: | ||
| 330 | + raise CredentialAccessError("protocol") | ||
| 331 | + | ||
| 332 | + async def lookup(self, session_id: str) -> SessionLoginBinding | None: | ||
| 333 | + normalized_session = _validated_input( | ||
| 334 | + session_id, | ||
| 335 | + max_length=_MAX_SESSION_ID_LENGTH, | ||
| 336 | + allow_empty=False, | ||
| 337 | + ) | ||
| 338 | + if normalized_session is None: | ||
| 339 | + raise CredentialAccessError("invalid") | ||
| 340 | + response = await _call_control( | ||
| 341 | + self._client, | ||
| 342 | + "bindings.lookup", | ||
| 343 | + {"session_id": normalized_session}, | ||
| 344 | + timeout=_BINDING_TIMEOUT_S, | ||
| 345 | + ) | ||
| 346 | + try: | ||
| 347 | + return _binding_response(response, normalized_session) | ||
| 348 | + except _BindingNotFound: | ||
| 349 | + return None | ||
| 350 | + | ||
| 351 | + async def model_auth_for_binding( | ||
| 352 | + self, binding: SessionLoginBinding | ||
| 353 | + ) -> ModelCredential | None: | ||
| 354 | + if not isinstance(binding, _RemoteSessionLoginBinding): | ||
| 355 | + raise CredentialAccessError("invalid") | ||
| 356 | + session_id = _validated_input( | ||
| 357 | + binding.session_id, | ||
| 358 | + max_length=_MAX_SESSION_ID_LENGTH, | ||
| 359 | + allow_empty=False, | ||
| 360 | + ) | ||
| 361 | + model_name = _validated_input( | ||
| 362 | + binding.model_name, | ||
| 363 | + max_length=_MAX_MODEL_NAME_LENGTH, | ||
| 364 | + allow_empty=False, | ||
| 365 | + ) | ||
| 366 | + if ( | ||
| 367 | + session_id is None | ||
| 368 | + or model_name is None | ||
| 369 | + or not _is_remote_credential_ref(binding.credential_ref) | ||
| 370 | + ): | ||
| 371 | + raise CredentialAccessError("invalid") | ||
| 372 | + response = await _call_control( | ||
| 373 | + self._client, | ||
| 374 | + "bindings.resolve_model_auth", | ||
| 375 | + { | ||
| 376 | + "session_id": session_id, | ||
| 377 | + "credential_ref": binding.credential_ref, | ||
| 378 | + "model_name": model_name, | ||
| 379 | + }, | ||
| 380 | + timeout=_BINDING_AUTH_TIMEOUT_S, | ||
| 381 | + ) | ||
| 382 | + return _model_auth_response(response, allow_not_required=False, | ||
| 383 | + client=self._client, runtime=self._runtime) | ||
| @@ -0,0 +1,104 @@ | |||
| 1 | +"""Worker-side remote adapter for the public login-model catalog.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import asyncio | ||
| 5 | + | ||
| 6 | +from agent_gateway.auth.public_model_catalog import ( | ||
| 7 | + CatalogError, | ||
| 8 | + CatalogResult, | ||
| 9 | + LoginModelSnapshot, | ||
| 10 | + validate_auth_session, | ||
| 11 | + validate_catalog_response, | ||
| 12 | + validate_login_model_snapshot, | ||
| 13 | +) | ||
| 14 | +from agent_gateway.processes.control_service import ( | ||
| 15 | + ControlServiceBusy, | ||
| 16 | + ControlServiceClient, | ||
| 17 | + ControlServiceError, | ||
| 18 | + ControlServiceOperationError, | ||
| 19 | + ControlProtocolError, | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +_REQUEST_TIMEOUT_S = 16.0 | ||
| 24 | +_SNAPSHOT_REQUEST_TIMEOUT_S = 9.0 | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +class RemoteLoginModelCatalog: | ||
| 28 | + """Fetch catalog snapshots through one explicit Control RPC.""" | ||
| 29 | + | ||
| 30 | + def __init__(self, client: ControlServiceClient) -> None: | ||
| 31 | + self._client = client | ||
| 32 | + | ||
| 33 | + async def list_models(self, auth_session: str | None) -> CatalogResult: | ||
| 34 | + normalized_session = validate_auth_session(auth_session) | ||
| 35 | + try: | ||
| 36 | + response = await self._client.call( | ||
| 37 | + "catalog.list_login_models", | ||
| 38 | + {"auth_session": normalized_session}, | ||
| 39 | + timeout=_REQUEST_TIMEOUT_S, | ||
| 40 | + ) | ||
| 41 | + except asyncio.CancelledError: | ||
| 42 | + raise | ||
| 43 | + except ControlServiceBusy: | ||
| 44 | + raise CatalogError("busy") from None | ||
| 45 | + except ControlServiceOperationError as error: | ||
| 46 | + reason = ( | ||
| 47 | + "not_enabled" | ||
| 48 | + if error.error_code == "OPERATION_NOT_ENABLED" | ||
| 49 | + else "unavailable" | ||
| 50 | + ) | ||
| 51 | + raise CatalogError(reason) from None | ||
| 52 | + except ControlProtocolError: | ||
| 53 | + raise CatalogError("protocol") from None | ||
| 54 | + except (TimeoutError, ControlServiceError): | ||
| 55 | + raise CatalogError("unavailable") from None | ||
| 56 | + except Exception: | ||
| 57 | + raise CatalogError("unavailable") from None | ||
| 58 | + | ||
| 59 | + result = validate_catalog_response(response) | ||
| 60 | + if result.status == "too_large": | ||
| 61 | + raise CatalogError("too_large") from None | ||
| 62 | + if result.status == "unavailable": | ||
| 63 | + raise CatalogError("unavailable") from None | ||
| 64 | + return result | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +class RemoteLoginModelSnapshot: | ||
| 68 | + """Fetch complete model snapshots through one explicit Control RPC.""" | ||
| 69 | + | ||
| 70 | + def __init__(self, client: ControlServiceClient) -> None: | ||
| 71 | + self._client = client | ||
| 72 | + | ||
| 73 | + async def get_snapshot(self, auth_session: str | None) -> LoginModelSnapshot: | ||
| 74 | + normalized_session = validate_auth_session(auth_session) | ||
| 75 | + try: | ||
| 76 | + response = await self._client.call( | ||
| 77 | + "catalog.get_login_model_snapshot", | ||
| 78 | + {"auth_session": normalized_session}, | ||
| 79 | + timeout=_SNAPSHOT_REQUEST_TIMEOUT_S, | ||
| 80 | + ) | ||
| 81 | + except asyncio.CancelledError: | ||
| 82 | + raise | ||
| 83 | + except ControlServiceBusy: | ||
| 84 | + raise CatalogError("busy") from None | ||
| 85 | + except ControlServiceOperationError as error: | ||
| 86 | + reason = ( | ||
| 87 | + "not_enabled" | ||
| 88 | + if error.error_code == "OPERATION_NOT_ENABLED" | ||
| 89 | + else "unavailable" | ||
| 90 | + ) | ||
| 91 | + raise CatalogError(reason) from None | ||
| 92 | + except ControlProtocolError: | ||
| 93 | + raise CatalogError("protocol") from None | ||
| 94 | + except (TimeoutError, ControlServiceError): | ||
| 95 | + raise CatalogError("unavailable") from None | ||
| 96 | + except Exception: | ||
| 97 | + raise CatalogError("unavailable") from None | ||
| 98 | + | ||
| 99 | + snapshot = validate_login_model_snapshot(response) | ||
| 100 | + if snapshot.status == "too_large": | ||
| 101 | + raise CatalogError("too_large") from None | ||
| 102 | + if snapshot.status == "unavailable": | ||
| 103 | + raise CatalogError("unavailable") from None | ||
| 104 | + return snapshot | ||
| @@ -11,6 +11,7 @@ from agent_gateway.auth.credential_access import ModelCredential | |||
| 11 | 11 | ||
| 12 | if TYPE_CHECKING: | 12 | if TYPE_CHECKING: |
| 13 | from agent_gateway.auth.service import AuthService | 13 | from agent_gateway.auth.service import AuthService |
| 14 | + from agent_gateway.auth.control_blocking_work import ControlBlockingWork | ||
| 14 | 15 | ||
| 15 | 16 | ||
| 16 | @dataclass(frozen=True) | 17 | @dataclass(frozen=True) |
| @@ -34,18 +35,30 @@ class SessionLoginBindings(Protocol): | |||
| 34 | class LocalSessionLoginBindings: | 35 | class LocalSessionLoginBindings: |
| 35 | """Reuse the original persistence, TTL and model availability rules.""" | 36 | """Reuse the original persistence, TTL and model availability rules.""" |
| 36 | 37 | ||
| 37 | - def __init__(self, auth_service_provider: Callable[[], AuthService]) -> None: | 38 | + def __init__( |
| 39 | + self, auth_service_provider: Callable[[], AuthService], *, | ||
| 40 | + blocking_work: ControlBlockingWork | None = None, | ||
| 41 | + ) -> None: | ||
| 38 | self._auth_service_provider = auth_service_provider | 42 | self._auth_service_provider = auth_service_provider |
| 43 | + self._blocking_work = blocking_work | ||
| 39 | 44 | ||
| 40 | async def remember(self, session_id: str, credential_ref: str, model_name: str) -> None: | 45 | async def remember(self, session_id: str, credential_ref: str, model_name: str) -> None: |
| 41 | from agent_gateway.auth import session_owners | 46 | from agent_gateway.auth import session_owners |
| 42 | 47 | ||
| 43 | - session_owners.remember(session_id, credential_ref, model_name) | 48 | + if self._blocking_work is None: |
| 49 | + session_owners.remember(session_id, credential_ref, model_name) | ||
| 50 | + else: | ||
| 51 | + await self._blocking_work.run( | ||
| 52 | + session_owners.remember, session_id, credential_ref, model_name, | ||
| 53 | + ) | ||
| 44 | 54 | ||
| 45 | async def lookup(self, session_id: str) -> SessionLoginBinding | None: | 55 | async def lookup(self, session_id: str) -> SessionLoginBinding | None: |
| 46 | from agent_gateway.auth import session_owners | 56 | from agent_gateway.auth import session_owners |
| 47 | 57 | ||
| 48 | - owner = session_owners.lookup(session_id) | 58 | + if self._blocking_work is None: |
| 59 | + owner = session_owners.lookup(session_id) | ||
| 60 | + else: | ||
| 61 | + owner = await self._blocking_work.run(session_owners.lookup, session_id) | ||
| 49 | if owner is None: | 62 | if owner is None: |
| 50 | return None | 63 | return None |
| 51 | return SessionLoginBinding(owner.credential_ref, owner.model_name) | 64 | return SessionLoginBinding(owner.credential_ref, owner.model_name) |
| @@ -59,7 +72,8 @@ class LocalSessionLoginBindings: | |||
| 59 | service=self._auth_service_provider(), | 72 | service=self._auth_service_provider(), |
| 60 | ) | 73 | ) |
| 61 | 74 | ||
| 62 | - auth = await asyncio.to_thread(resolve) | 75 | + auth = (await asyncio.to_thread(resolve) if self._blocking_work is None |
| 76 | + else await self._blocking_work.run(resolve)) | ||
| 63 | if auth is None: | 77 | if auth is None: |
| 64 | return None | 78 | return None |
| 65 | return ModelCredential( | 79 | return ModelCredential( |
| @@ -291,6 +291,48 @@ class AuthSessionStore: | |||
| 291 | return None | 291 | return None |
| 292 | return session | 292 | return session |
| 293 | 293 | ||
| 294 | + def matches_live_memory( | ||
| 295 | + self, session_id: str, user_id: str, created_at: float, | ||
| 296 | + *, expected_id_token: str | None = None, | ||
| 297 | + ) -> bool | None: | ||
| 298 | + """Check a Control commit without disk access or waiting for a store lock. | ||
| 299 | + | ||
| 300 | + Blocking lookup/refresh must precede this check. None means the memory | ||
| 301 | + view is busy; callers must fail closed rather than wait on the loop. | ||
| 302 | + """ | ||
| 303 | + if not self._lock.acquire(blocking=False): | ||
| 304 | + return None | ||
| 305 | + try: | ||
| 306 | + session = self._by_session.get(session_id) | ||
| 307 | + return bool( | ||
| 308 | + session is not None and session.user_id == user_id | ||
| 309 | + and session.created_at == created_at and not self._is_stale(session) | ||
| 310 | + and session.credential.id_token and not session.credential.is_expired() | ||
| 311 | + and (expected_id_token is None or session.credential.id_token == expected_id_token) | ||
| 312 | + ) | ||
| 313 | + finally: | ||
| 314 | + self._lock.release() | ||
| 315 | + | ||
| 316 | + def matches_identity_memory( | ||
| 317 | + self, session_id: str, user_id: str, created_at: float, | ||
| 318 | + *, expected_id_token: str | None = None, | ||
| 319 | + ) -> bool | None: | ||
| 320 | + """Check only stable identity, allowing logout of an expired token.""" | ||
| 321 | + if not self._lock.acquire(blocking=False): | ||
| 322 | + return None | ||
| 323 | + try: | ||
| 324 | + session = self._by_session.get(session_id) | ||
| 325 | + return bool( | ||
| 326 | + session is not None | ||
| 327 | + and session.user_id == user_id | ||
| 328 | + and session.created_at == created_at | ||
| 329 | + and self._by_user.get(user_id) == session_id | ||
| 330 | + and (expected_id_token is None | ||
| 331 | + or session.credential.id_token == expected_id_token) | ||
| 332 | + ) | ||
| 333 | + finally: | ||
| 334 | + self._lock.release() | ||
| 335 | + | ||
| 294 | def get_by_user(self, user_id: str) -> AuthSession | None: | 336 | def get_by_user(self, user_id: str) -> AuthSession | None: |
| 295 | with self._lock: | 337 | with self._lock: |
| 296 | self._ensure_loaded() | 338 | self._ensure_loaded() |