langgraph-api 0.20.0.dev1__py3-none-any.whl → 0.20.0.dev2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langgraph_api/__init__.py +1 -1
- langgraph_api/_checkpointer/_adapter.py +65 -8
- langgraph_api/agent_auth.py +382 -0
- langgraph_api/auth/langsmith/backend.py +51 -2
- langgraph_api/auth/langsmith/client.py +8 -5
- langgraph_api/config/__init__.py +15 -4
- langgraph_api/errors.py +7 -0
- langgraph_api/event_streaming/session.py +14 -2
- langgraph_api/executor/__main__.py +11 -4
- langgraph_api/grpc/client.py +44 -1
- langgraph_api/http.py +29 -3
- langgraph_api/runtime/store.py +6 -0
- langgraph_api/sandbox_entrypoint.py +114 -0
- langgraph_api/sandbox_server.py +48 -0
- langgraph_api/sandbox_worker.py +296 -0
- langgraph_api/stream.py +9 -1
- langgraph_api/stream_v2.py +49 -2
- langgraph_api/validation.py +2 -0
- langgraph_api/web_identity.py +79 -20
- langgraph_api/worker.py +14 -3
- {langgraph_api-0.20.0.dev1.dist-info → langgraph_api-0.20.0.dev2.dist-info}/METADATA +1 -1
- {langgraph_api-0.20.0.dev1.dist-info → langgraph_api-0.20.0.dev2.dist-info}/RECORD +25 -21
- {langgraph_api-0.20.0.dev1.dist-info → langgraph_api-0.20.0.dev2.dist-info}/WHEEL +0 -0
- {langgraph_api-0.20.0.dev1.dist-info → langgraph_api-0.20.0.dev2.dist-info}/entry_points.txt +0 -0
- {langgraph_api-0.20.0.dev1.dist-info → langgraph_api-0.20.0.dev2.dist-info}/licenses/LICENSE +0 -0
langgraph_api/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "0.20.0.
|
|
1
|
+
__version__ = "0.20.0.dev2"
|
|
@@ -70,6 +70,9 @@ _REQUIRED = (
|
|
|
70
70
|
BaseCheckpointSaver.aget,
|
|
71
71
|
BaseCheckpointSaver.alist,
|
|
72
72
|
)
|
|
73
|
+
# Each check lists a thread's full history, which custom savers may load into
|
|
74
|
+
# memory at once (Redis: up to 10k checkpoints with values and writes).
|
|
75
|
+
_DELTA_HISTORY_CHECK_CONCURRENCY = 5
|
|
73
76
|
|
|
74
77
|
|
|
75
78
|
async def _get_shared_checkpointer_stub() -> CheckpointerStub:
|
|
@@ -230,6 +233,43 @@ class _CustomCheckpointerAdapter(BaseCheckpointSaver):
|
|
|
230
233
|
async def aprune(
|
|
231
234
|
self, thread_ids: Sequence[str], *, strategy: str = "keep_latest"
|
|
232
235
|
) -> None:
|
|
236
|
+
if strategy == "keep_latest" and not self._capabilities.has_aprune:
|
|
237
|
+
await logger.awarning(
|
|
238
|
+
"Skipping keep_latest prune: the custom checkpointer does not "
|
|
239
|
+
"implement aprune, so thread history is kept",
|
|
240
|
+
thread_ids=[str(tid) for tid in thread_ids],
|
|
241
|
+
)
|
|
242
|
+
return
|
|
243
|
+
if strategy == "keep_latest":
|
|
244
|
+
# A custom keep_latest keeps only each namespace's latest checkpoint,
|
|
245
|
+
# which would lose DeltaChannel values rebuilt from older ones.
|
|
246
|
+
semaphore = asyncio.Semaphore(_DELTA_HISTORY_CHECK_CONCURRENCY)
|
|
247
|
+
|
|
248
|
+
async def check(tid: str) -> bool:
|
|
249
|
+
async with semaphore:
|
|
250
|
+
return await self._head_needs_delta_history(tid)
|
|
251
|
+
|
|
252
|
+
needs_history = await asyncio.gather(
|
|
253
|
+
*(check(str(tid)) for tid in thread_ids)
|
|
254
|
+
)
|
|
255
|
+
skipped = [
|
|
256
|
+
str(tid)
|
|
257
|
+
for tid, needs in zip(thread_ids, needs_history, strict=True)
|
|
258
|
+
if needs
|
|
259
|
+
]
|
|
260
|
+
if skipped:
|
|
261
|
+
await logger.ainfo(
|
|
262
|
+
"Skipping keep_latest prune for threads whose DeltaChannel "
|
|
263
|
+
"state depends on older checkpoints",
|
|
264
|
+
thread_ids=skipped,
|
|
265
|
+
)
|
|
266
|
+
thread_ids = [
|
|
267
|
+
tid
|
|
268
|
+
for tid, needs in zip(thread_ids, needs_history, strict=True)
|
|
269
|
+
if not needs
|
|
270
|
+
]
|
|
271
|
+
if not thread_ids:
|
|
272
|
+
return
|
|
233
273
|
if self._capabilities.has_aprune:
|
|
234
274
|
await self._inner.aprune(thread_ids, strategy=strategy)
|
|
235
275
|
return
|
|
@@ -238,14 +278,31 @@ class _CustomCheckpointerAdapter(BaseCheckpointSaver):
|
|
|
238
278
|
tid = str(tid)
|
|
239
279
|
if strategy == "delete_all":
|
|
240
280
|
await self.adelete_thread(tid)
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
281
|
+
|
|
282
|
+
async def _head_needs_delta_history(self, thread_id: str) -> bool:
|
|
283
|
+
"""`update_state` checkpoints saved without counters count from their
|
|
284
|
+
parent, so the walk passes through them, as the core keep-set does."""
|
|
285
|
+
by_id: dict[tuple[str, str], CheckpointTuple] = {}
|
|
286
|
+
heads: dict[str, str] = {}
|
|
287
|
+
async for tup in self._inner.alist({"configurable": {"thread_id": thread_id}}):
|
|
288
|
+
conf = tup.config["configurable"]
|
|
289
|
+
ns = conf.get("checkpoint_ns", "")
|
|
290
|
+
checkpoint_id = conf["checkpoint_id"]
|
|
291
|
+
by_id[(ns, checkpoint_id)] = tup
|
|
292
|
+
if checkpoint_id > heads.get(ns, ""):
|
|
293
|
+
heads[ns] = checkpoint_id
|
|
294
|
+
for ns, head_id in heads.items():
|
|
295
|
+
cur: CheckpointTuple | None = by_id[(ns, head_id)]
|
|
296
|
+
while cur is not None:
|
|
297
|
+
counters = cur.metadata.get("counters_since_delta_snapshot")
|
|
298
|
+
if counters:
|
|
299
|
+
return True
|
|
300
|
+
if counters is not None or cur.metadata.get("source") == "loop":
|
|
301
|
+
break
|
|
302
|
+
parent = (cur.parent_config or {}).get("configurable", {})
|
|
303
|
+
parent_id = parent.get("checkpoint_id")
|
|
304
|
+
cur = by_id.get((ns, parent_id)) if parent_id else None
|
|
305
|
+
return False
|
|
249
306
|
|
|
250
307
|
async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
|
251
308
|
return await self._inner.aget_tuple(config)
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""Ask Agent Auth, with the pod's token, which agent this deployment runs as."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import math
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from email.utils import parsedate_to_datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from time import monotonic, time
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
import jwt
|
|
16
|
+
import structlog
|
|
17
|
+
|
|
18
|
+
from langgraph_api import config
|
|
19
|
+
from langgraph_api.errors import AgentDisabledError
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from langchain_core.runnables import RunnableConfig
|
|
23
|
+
|
|
24
|
+
logger = structlog.stdlib.get_logger(__name__)
|
|
25
|
+
|
|
26
|
+
AGENT_RUNTIME_AUDIENCE = "urn:langsmith:agent-runtime"
|
|
27
|
+
RUN_AGENT_IDENTIFIER = "run_agent_identifier"
|
|
28
|
+
_AGENT_DISABLED = "agent_disabled"
|
|
29
|
+
_TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
|
|
30
|
+
_POD_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt"
|
|
31
|
+
_ACCESS_TOKEN_TYPE = "at+jwt"
|
|
32
|
+
_SIGNING_ALGORITHM = "RS256"
|
|
33
|
+
_KEY_HEADERS = ("jku", "jwk", "x5u")
|
|
34
|
+
_CLOCK_SKEW_SECONDS = 60
|
|
35
|
+
# The longest a run start waits on Agent Auth, for the token and the keys together.
|
|
36
|
+
_CHECK_TIMEOUT_SECONDS = 2.0
|
|
37
|
+
# A refusal, such as a deployment bound to no agent, lasts; ask again after a run token's lifetime.
|
|
38
|
+
_REFUSAL_PAUSE_SECONDS = 300.0
|
|
39
|
+
# An outage is short; Agent Auth's Retry-After is honoured within these bounds.
|
|
40
|
+
_OUTAGE_PAUSE_SECONDS = 5.0
|
|
41
|
+
_MAX_OUTAGE_PAUSE_SECONDS = 60.0
|
|
42
|
+
# A token signed by an untrusted key refetches the keys, but only once they're this old.
|
|
43
|
+
_KEY_REFRESH_INTERVAL_SECONDS = 30.0
|
|
44
|
+
# Runs reuse a verified agent this long, so a disabled agent can start runs this long after.
|
|
45
|
+
_VERIFIED_AGENT_TTL_SECONDS = 60.0
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AgentAuthRefused(Exception):
|
|
49
|
+
"""Agent Auth issued no token, either because it said no or because it couldn't answer.
|
|
50
|
+
|
|
51
|
+
``reason`` is its ``ls_error``, the HTTP status, or the transport error's name.
|
|
52
|
+
``outage`` is true when it couldn't answer; ``retry_after`` is how many seconds
|
|
53
|
+
it then asked callers to wait.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self, reason: str, *, outage: bool = False, retry_after: float | None = None
|
|
58
|
+
) -> None:
|
|
59
|
+
super().__init__(reason)
|
|
60
|
+
self.reason = reason
|
|
61
|
+
self.outage = outage
|
|
62
|
+
self.retry_after = retry_after
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _InvalidRunToken(Exception):
|
|
66
|
+
def __init__(self, reason: str) -> None:
|
|
67
|
+
super().__init__(reason)
|
|
68
|
+
self.reason = reason
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _UntrustedKey(_InvalidRunToken):
|
|
72
|
+
"""The token's key isn't among Agent Auth's cached keys, which may be stale."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class _VerifiedAgent:
|
|
77
|
+
identifier: str
|
|
78
|
+
expires_at: float
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class _AgentAuthKeys:
|
|
83
|
+
issuer: str
|
|
84
|
+
keys: dict[str, jwt.PyJWK]
|
|
85
|
+
fetched_at: float
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_paused_until = 0.0
|
|
89
|
+
_verified_agent: _VerifiedAgent | None = None
|
|
90
|
+
_agent_auth_keys_cache: _AgentAuthKeys | None = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def verify_and_strip(
|
|
94
|
+
config: RunnableConfig, context: Any
|
|
95
|
+
) -> tuple[RunnableConfig, Any, str | None]:
|
|
96
|
+
"""Verify this deployment's agent with Agent Auth, and strip any caller's ``run_agent_identifier``.
|
|
97
|
+
|
|
98
|
+
Returns copies of config and context without the key, and the verified
|
|
99
|
+
identifier to stamp, or None. Raises ``AgentDisabledError`` when Agent Auth
|
|
100
|
+
reports the agent disabled.
|
|
101
|
+
"""
|
|
102
|
+
run_agent_identifier = await verified_run_agent_identifier()
|
|
103
|
+
config, context = _without_run_agent_identifier(config, context)
|
|
104
|
+
return config, context, run_agent_identifier
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _without_run_agent_identifier(
|
|
108
|
+
config: RunnableConfig, context: Any
|
|
109
|
+
) -> tuple[RunnableConfig, Any]:
|
|
110
|
+
"""Copies of a run's config and context without ``run_agent_identifier``, which only the server sets.
|
|
111
|
+
|
|
112
|
+
The top level of config counts too: ``ensure_config`` moves unknown keys there into configurable.
|
|
113
|
+
"""
|
|
114
|
+
config = {
|
|
115
|
+
**_without_identifier(config),
|
|
116
|
+
"metadata": _without_identifier(config.get("metadata") or {}),
|
|
117
|
+
"configurable": _without_identifier(config.get("configurable") or {}),
|
|
118
|
+
}
|
|
119
|
+
if isinstance(context, dict):
|
|
120
|
+
context = _without_identifier(context)
|
|
121
|
+
return config, context
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _without_identifier(values: dict[str, Any]) -> dict[str, Any]:
|
|
125
|
+
return {k: v for k, v in values.items() if k != RUN_AGENT_IDENTIFIER}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def verified_run_agent_identifier() -> str | None:
|
|
129
|
+
"""The agent a verified run token from Agent Auth names, or None.
|
|
130
|
+
|
|
131
|
+
A verified agent is reused until ``_VERIFIED_AGENT_TTL_SECONDS`` pass or its
|
|
132
|
+
run token expires. Raises ``AgentDisabledError`` when Agent Auth reports the
|
|
133
|
+
agent disabled.
|
|
134
|
+
"""
|
|
135
|
+
global _verified_agent
|
|
136
|
+
if not config.LANGSMITH_AGENT_AUTH_POD_TOKEN_PATH:
|
|
137
|
+
return None
|
|
138
|
+
verified = _verified_agent
|
|
139
|
+
if verified is not None and monotonic() < verified.expires_at:
|
|
140
|
+
return verified.identifier
|
|
141
|
+
if monotonic() < _paused_until:
|
|
142
|
+
await logger.ainfo(
|
|
143
|
+
"Run agent access token check paused", agent_access_token="paused"
|
|
144
|
+
)
|
|
145
|
+
return None
|
|
146
|
+
try:
|
|
147
|
+
claims = await _fresh_run_claims()
|
|
148
|
+
except AgentAuthRefused as refusal:
|
|
149
|
+
if refusal.reason == _AGENT_DISABLED:
|
|
150
|
+
await logger.awarning(
|
|
151
|
+
"Agent Auth reports the agent disabled",
|
|
152
|
+
agent_access_token=_AGENT_DISABLED,
|
|
153
|
+
)
|
|
154
|
+
raise AgentDisabledError from None
|
|
155
|
+
_pause(
|
|
156
|
+
_outage_pause(refusal.retry_after)
|
|
157
|
+
if refusal.outage
|
|
158
|
+
else _REFUSAL_PAUSE_SECONDS
|
|
159
|
+
)
|
|
160
|
+
await logger.awarning(
|
|
161
|
+
"Run agent access token unavailable",
|
|
162
|
+
agent_access_token="unavailable",
|
|
163
|
+
agent_access_token_error=refusal.reason,
|
|
164
|
+
)
|
|
165
|
+
return None
|
|
166
|
+
except _InvalidRunToken as invalid:
|
|
167
|
+
await logger.aerror(
|
|
168
|
+
"Run agent access token rejected",
|
|
169
|
+
agent_access_token="invalid",
|
|
170
|
+
agent_access_token_error=invalid.reason,
|
|
171
|
+
)
|
|
172
|
+
return None
|
|
173
|
+
except Exception as error:
|
|
174
|
+
_pause(_OUTAGE_PAUSE_SECONDS)
|
|
175
|
+
await logger.awarning(
|
|
176
|
+
"Run agent access token unavailable",
|
|
177
|
+
agent_access_token="unavailable",
|
|
178
|
+
agent_access_token_error=type(error).__name__,
|
|
179
|
+
exc_info=error,
|
|
180
|
+
)
|
|
181
|
+
return None
|
|
182
|
+
await logger.ainfo(
|
|
183
|
+
"Run agent access token verified",
|
|
184
|
+
agent_access_token="verified",
|
|
185
|
+
agent_access_token_jti=claims["jti"],
|
|
186
|
+
)
|
|
187
|
+
_verified_agent = _VerifiedAgent(
|
|
188
|
+
identifier=str(claims["sub"]),
|
|
189
|
+
expires_at=monotonic()
|
|
190
|
+
+ min(_VERIFIED_AGENT_TTL_SECONDS, claims["exp"] - time()),
|
|
191
|
+
)
|
|
192
|
+
return _verified_agent.identifier
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
async def _fresh_run_claims() -> dict[str, Any]:
|
|
196
|
+
try:
|
|
197
|
+
async with asyncio.timeout(_CHECK_TIMEOUT_SECONDS):
|
|
198
|
+
# A client per check: with BG_JOB_ISOLATED_LOOPS, runs start on their own event loops.
|
|
199
|
+
async with httpx.AsyncClient(
|
|
200
|
+
timeout=_CHECK_TIMEOUT_SECONDS, follow_redirects=False
|
|
201
|
+
) as client:
|
|
202
|
+
token = await exchange_pod_token(client, AGENT_RUNTIME_AUDIENCE)
|
|
203
|
+
return await _verified_claims(client, token)
|
|
204
|
+
except TimeoutError:
|
|
205
|
+
raise AgentAuthRefused("timeout", outage=True) from None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _pause(seconds: float) -> None:
|
|
209
|
+
global _paused_until
|
|
210
|
+
_paused_until = monotonic() + seconds
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _outage_pause(retry_after: float | None) -> float:
|
|
214
|
+
return min(
|
|
215
|
+
max(retry_after or 0.0, _OUTAGE_PAUSE_SECONDS), _MAX_OUTAGE_PAUSE_SECONDS
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
async def exchange_pod_token(client: httpx.AsyncClient, audience: str) -> str:
|
|
220
|
+
"""Trade the pod's token for an Agent Auth token for ``audience``."""
|
|
221
|
+
try:
|
|
222
|
+
form = await pod_token_form(audience)
|
|
223
|
+
except FileNotFoundError:
|
|
224
|
+
raise AgentAuthRefused("pod_token_missing") from None
|
|
225
|
+
except OSError as error:
|
|
226
|
+
raise AgentAuthRefused(f"pod_token_unreadable:{type(error).__name__}") from None
|
|
227
|
+
body = await _agent_auth_answer(
|
|
228
|
+
client, "POST", config.langsmith_api_url("/agent-auth/token"), data=form
|
|
229
|
+
)
|
|
230
|
+
token = body.get("access_token")
|
|
231
|
+
if not isinstance(token, str) or not token:
|
|
232
|
+
raise AgentAuthRefused("malformed_token_response", outage=True)
|
|
233
|
+
return token
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
async def pod_token_form(audience: str) -> dict[str, str]:
|
|
237
|
+
return {
|
|
238
|
+
"grant_type": _TOKEN_EXCHANGE_GRANT_TYPE,
|
|
239
|
+
"subject_token": await asyncio.to_thread(_read_pod_token),
|
|
240
|
+
"subject_token_type": _POD_TOKEN_TYPE,
|
|
241
|
+
"resource": audience,
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
async def _agent_auth_answer(
|
|
246
|
+
client: httpx.AsyncClient, method: str, url: str, **kwargs: Any
|
|
247
|
+
) -> dict[str, Any]:
|
|
248
|
+
"""Agent Auth's JSON answer, or ``AgentAuthRefused`` when it says no or can't answer."""
|
|
249
|
+
try:
|
|
250
|
+
response = await client.request(method, url, **kwargs)
|
|
251
|
+
except httpx.HTTPError as error:
|
|
252
|
+
raise AgentAuthRefused(type(error).__name__, outage=True) from None
|
|
253
|
+
if response.status_code != httpx.codes.OK:
|
|
254
|
+
raise _refusal(response)
|
|
255
|
+
try:
|
|
256
|
+
body = response.json()
|
|
257
|
+
except ValueError:
|
|
258
|
+
raise AgentAuthRefused("malformed_response", outage=True) from None
|
|
259
|
+
if not isinstance(body, dict):
|
|
260
|
+
raise AgentAuthRefused("malformed_response", outage=True)
|
|
261
|
+
return body
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _refusal(response: httpx.Response) -> AgentAuthRefused:
|
|
265
|
+
status = response.status_code
|
|
266
|
+
outage = (
|
|
267
|
+
status in (httpx.codes.REQUEST_TIMEOUT, httpx.codes.TOO_MANY_REQUESTS)
|
|
268
|
+
or status >= 500
|
|
269
|
+
)
|
|
270
|
+
return AgentAuthRefused(
|
|
271
|
+
_ls_error(response) or str(status),
|
|
272
|
+
outage=outage,
|
|
273
|
+
retry_after=_retry_after_seconds(response) if outage else None,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _retry_after_seconds(response: httpx.Response) -> float | None:
|
|
278
|
+
"""Retry-After in seconds, given either as seconds or as an HTTP date."""
|
|
279
|
+
header = response.headers.get("Retry-After", "")
|
|
280
|
+
try:
|
|
281
|
+
seconds = float(header)
|
|
282
|
+
except ValueError:
|
|
283
|
+
try:
|
|
284
|
+
seconds = (
|
|
285
|
+
parsedate_to_datetime(header) - datetime.now(UTC)
|
|
286
|
+
).total_seconds()
|
|
287
|
+
except (TypeError, ValueError):
|
|
288
|
+
return None
|
|
289
|
+
return seconds if math.isfinite(seconds) else None
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _ls_error(response: httpx.Response) -> str | None:
|
|
293
|
+
try:
|
|
294
|
+
body = response.json()
|
|
295
|
+
except ValueError:
|
|
296
|
+
return None
|
|
297
|
+
value = body.get("ls_error") if isinstance(body, dict) else None
|
|
298
|
+
return value if isinstance(value, str) else None
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _read_pod_token() -> str:
|
|
302
|
+
# Kubernetes rotates the token in place, so read it fresh each time.
|
|
303
|
+
return Path(config.LANGSMITH_AGENT_AUTH_POD_TOKEN_PATH or "").read_text().strip()
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
async def _verified_claims(client: httpx.AsyncClient, token: str) -> dict[str, Any]:
|
|
307
|
+
"""Claims checked as Agent Auth's own verifier checks them, for this deployment."""
|
|
308
|
+
kid = _checked_header(token)
|
|
309
|
+
try:
|
|
310
|
+
claims = _decoded(token, kid, await _agent_auth_keys(client, refresh=False))
|
|
311
|
+
except _UntrustedKey:
|
|
312
|
+
claims = _decoded(token, kid, await _agent_auth_keys(client, refresh=True))
|
|
313
|
+
for claim, expected in (
|
|
314
|
+
("ls_deployment_id", config.LANGSMITH_HOST_PROJECT_ID),
|
|
315
|
+
("ls_workspace_id", config.LANGSMITH_TENANT_ID),
|
|
316
|
+
):
|
|
317
|
+
if not expected or claims.get(claim) != expected:
|
|
318
|
+
raise _InvalidRunToken(f"{claim}_mismatch")
|
|
319
|
+
return claims
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _checked_header(token: str) -> str:
|
|
323
|
+
try:
|
|
324
|
+
header = jwt.get_unverified_header(token)
|
|
325
|
+
except jwt.InvalidTokenError as error:
|
|
326
|
+
raise _InvalidRunToken(type(error).__name__) from None
|
|
327
|
+
token_type = str(header.get("typ", "")).lower().removeprefix("application/")
|
|
328
|
+
if token_type != _ACCESS_TOKEN_TYPE:
|
|
329
|
+
raise _InvalidRunToken("typ_not_access_token")
|
|
330
|
+
if any(name in header for name in _KEY_HEADERS):
|
|
331
|
+
raise _InvalidRunToken("key_header_not_allowed")
|
|
332
|
+
return str(header.get("kid", ""))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _decoded(token: str, kid: str, agent_auth: _AgentAuthKeys) -> dict[str, Any]:
|
|
336
|
+
key = agent_auth.keys.get(kid)
|
|
337
|
+
if key is None:
|
|
338
|
+
raise _UntrustedKey("kid_not_trusted")
|
|
339
|
+
try:
|
|
340
|
+
return jwt.decode(
|
|
341
|
+
token,
|
|
342
|
+
key.key,
|
|
343
|
+
algorithms=[_SIGNING_ALGORITHM],
|
|
344
|
+
audience=AGENT_RUNTIME_AUDIENCE,
|
|
345
|
+
issuer=agent_auth.issuer,
|
|
346
|
+
leeway=_CLOCK_SKEW_SECONDS,
|
|
347
|
+
options={"require": ["exp", "iat", "iss", "aud", "sub", "jti"]},
|
|
348
|
+
)
|
|
349
|
+
except jwt.InvalidSignatureError:
|
|
350
|
+
raise _UntrustedKey("InvalidSignatureError") from None
|
|
351
|
+
except jwt.InvalidTokenError as error:
|
|
352
|
+
raise _InvalidRunToken(type(error).__name__) from None
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
async def _agent_auth_keys(
|
|
356
|
+
client: httpx.AsyncClient, *, refresh: bool
|
|
357
|
+
) -> _AgentAuthKeys:
|
|
358
|
+
"""The issuer and RSA signing keys of the Agent Auth that minted the run token."""
|
|
359
|
+
global _agent_auth_keys_cache
|
|
360
|
+
cached = _agent_auth_keys_cache
|
|
361
|
+
if cached is not None and (
|
|
362
|
+
not refresh or monotonic() < cached.fetched_at + _KEY_REFRESH_INTERVAL_SECONDS
|
|
363
|
+
):
|
|
364
|
+
return cached
|
|
365
|
+
base = config.langsmith_api_url("/agent-auth")
|
|
366
|
+
discovery = await _agent_auth_answer(
|
|
367
|
+
client, "GET", f"{base}/.well-known/openid-configuration"
|
|
368
|
+
)
|
|
369
|
+
jwks = jwt.PyJWKSet.from_dict(
|
|
370
|
+
await _agent_auth_answer(client, "GET", f"{base}/.well-known/jwks.json")
|
|
371
|
+
)
|
|
372
|
+
issuer = discovery.get("issuer")
|
|
373
|
+
if not isinstance(issuer, str) or not issuer:
|
|
374
|
+
raise AgentAuthRefused("malformed_response", outage=True)
|
|
375
|
+
_agent_auth_keys_cache = _AgentAuthKeys(
|
|
376
|
+
issuer=issuer,
|
|
377
|
+
keys={
|
|
378
|
+
key.key_id: key for key in jwks.keys if key.key_id and key.key_type == "RSA"
|
|
379
|
+
},
|
|
380
|
+
fetched_at=monotonic(),
|
|
381
|
+
)
|
|
382
|
+
return _agent_auth_keys_cache
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
from typing import NotRequired
|
|
2
|
+
from uuid import UUID
|
|
2
3
|
|
|
3
4
|
from starlette.authentication import (
|
|
4
5
|
AuthCredentials,
|
|
@@ -6,6 +7,7 @@ from starlette.authentication import (
|
|
|
6
7
|
AuthenticationError,
|
|
7
8
|
BaseUser,
|
|
8
9
|
)
|
|
10
|
+
from starlette.exceptions import HTTPException
|
|
9
11
|
from starlette.requests import HTTPConnection
|
|
10
12
|
from typing_extensions import TypedDict
|
|
11
13
|
|
|
@@ -13,6 +15,9 @@ from langgraph_api.auth.langsmith.client import auth_client
|
|
|
13
15
|
from langgraph_api.auth.studio_user import StudioUser
|
|
14
16
|
from langgraph_api.config import (
|
|
15
17
|
LANGSMITH_AUTH_VERIFY_TENANT_ID,
|
|
18
|
+
LANGSMITH_DEPLOYMENT_AUTH_ENABLED,
|
|
19
|
+
LANGSMITH_DEPLOYMENT_AUTH_ENDPOINT,
|
|
20
|
+
LANGSMITH_HOST_PROJECT_ID,
|
|
16
21
|
LANGSMITH_TENANT_ID,
|
|
17
22
|
)
|
|
18
23
|
|
|
@@ -23,6 +28,7 @@ class AuthDict(TypedDict):
|
|
|
23
28
|
user_id: NotRequired[str]
|
|
24
29
|
ls_user_id: NotRequired[str]
|
|
25
30
|
user_email: NotRequired[str]
|
|
31
|
+
authorized_deployment_id: NotRequired[str]
|
|
26
32
|
|
|
27
33
|
|
|
28
34
|
class AuthCacheEntry(TypedDict):
|
|
@@ -36,6 +42,28 @@ class LangsmithAuthBackend(AuthenticationBackend):
|
|
|
36
42
|
|
|
37
43
|
self._cache = LRUCache[AuthCacheEntry](max_size=1000, ttl=60)
|
|
38
44
|
self._base_url = base_url
|
|
45
|
+
self._deployment_id = None
|
|
46
|
+
if LANGSMITH_DEPLOYMENT_AUTH_ENABLED:
|
|
47
|
+
if not LANGSMITH_AUTH_VERIFY_TENANT_ID:
|
|
48
|
+
raise ValueError(
|
|
49
|
+
"Deployment authorization does not support shareable deployments; "
|
|
50
|
+
"disable deployment authorization or tenantless authentication"
|
|
51
|
+
)
|
|
52
|
+
if not (
|
|
53
|
+
LANGSMITH_DEPLOYMENT_AUTH_ENDPOINT
|
|
54
|
+
and LANGSMITH_TENANT_ID
|
|
55
|
+
and LANGSMITH_HOST_PROJECT_ID
|
|
56
|
+
):
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"Deployment authorization requires a data-plane auth endpoint, "
|
|
59
|
+
"tenant ID, and deployment ID"
|
|
60
|
+
)
|
|
61
|
+
self._deployment_id = str(UUID(LANGSMITH_HOST_PROJECT_ID))
|
|
62
|
+
if UUID(self._deployment_id).int == 0:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"Deployment authorization requires a nonzero deployment ID"
|
|
65
|
+
)
|
|
66
|
+
self._base_url = LANGSMITH_DEPLOYMENT_AUTH_ENDPOINT
|
|
39
67
|
|
|
40
68
|
def _get_cache_key(self, headers):
|
|
41
69
|
"""Generate cache key from authentication headers"""
|
|
@@ -58,13 +86,24 @@ class LangsmithAuthBackend(AuthenticationBackend):
|
|
|
58
86
|
if not any(h[1] for h in headers):
|
|
59
87
|
raise AuthenticationError("Missing authentication headers")
|
|
60
88
|
|
|
89
|
+
if self._deployment_id:
|
|
90
|
+
tenant_id = conn.headers.get("x-tenant-id")
|
|
91
|
+
if tenant_id and tenant_id != LANGSMITH_TENANT_ID:
|
|
92
|
+
raise AuthenticationError("Invalid tenant ID")
|
|
93
|
+
headers[1] = ("X-Tenant-Id", LANGSMITH_TENANT_ID)
|
|
94
|
+
|
|
61
95
|
# Check cache first
|
|
62
96
|
cache_key = self._get_cache_key(headers)
|
|
63
97
|
if cached_entry := await self._cache.get(cache_key):
|
|
64
98
|
return cached_entry["credentials"], cached_entry["user"]
|
|
65
99
|
|
|
66
100
|
async with auth_client(base_url=self._base_url) as auth:
|
|
67
|
-
if
|
|
101
|
+
if self._deployment_id:
|
|
102
|
+
res = await auth.get(
|
|
103
|
+
f"/v1/platform/host-projects/{self._deployment_id}/auth",
|
|
104
|
+
headers=[h for h in headers if h[1] is not None],
|
|
105
|
+
)
|
|
106
|
+
elif not LANGSMITH_AUTH_VERIFY_TENANT_ID and not conn.headers.get(
|
|
68
107
|
"x-api-key"
|
|
69
108
|
):
|
|
70
109
|
# when LANGSMITH_AUTH_VERIFY_TENANT_ID is false, we allow
|
|
@@ -77,7 +116,11 @@ class LangsmithAuthBackend(AuthenticationBackend):
|
|
|
77
116
|
res = await auth.get(
|
|
78
117
|
"/auth/public", headers=[h for h in headers if h[1] is not None]
|
|
79
118
|
)
|
|
80
|
-
if res.status_code
|
|
119
|
+
if self._deployment_id and res.status_code in (400, 404):
|
|
120
|
+
raise AuthenticationError("Deployment authorization failed")
|
|
121
|
+
elif self._deployment_id and 500 <= res.status_code < 600:
|
|
122
|
+
raise HTTPException(status_code=503, detail="Service Unavailable")
|
|
123
|
+
elif res.status_code == 401:
|
|
81
124
|
raise AuthenticationError("Invalid token")
|
|
82
125
|
elif res.status_code == 403:
|
|
83
126
|
raise AuthenticationError("Forbidden")
|
|
@@ -85,6 +128,12 @@ class LangsmithAuthBackend(AuthenticationBackend):
|
|
|
85
128
|
res.raise_for_status()
|
|
86
129
|
auth_dict: AuthDict = res.json()
|
|
87
130
|
|
|
131
|
+
if self._deployment_id and (
|
|
132
|
+
auth_dict.get("authorized_deployment_id") != self._deployment_id
|
|
133
|
+
or auth_dict.get("tenant_id") != LANGSMITH_TENANT_ID
|
|
134
|
+
):
|
|
135
|
+
raise AuthenticationError("Deployment authorization failed")
|
|
136
|
+
|
|
88
137
|
# If tenant id verification is disabled, the bearer token requests
|
|
89
138
|
# are not required to match the tenant id. Api key requests are
|
|
90
139
|
# always required to match the tenant id.
|
|
@@ -124,19 +124,22 @@ async def auth_client(
|
|
|
124
124
|
) -> AsyncGenerator[JsonHttpClient, None]:
|
|
125
125
|
"""Get the auth http client."""
|
|
126
126
|
url = base_url if base_url is not None else LANGSMITH_AUTH_ENDPOINT
|
|
127
|
+
try:
|
|
128
|
+
found = not _client.client.is_closed
|
|
129
|
+
except NameError:
|
|
130
|
+
found = False
|
|
127
131
|
# pytest does something funny with event loops,
|
|
128
132
|
# so we can't use a global pool for tests
|
|
129
|
-
|
|
133
|
+
# A deployment's authorization endpoint can differ from its control-plane auth endpoint.
|
|
134
|
+
if url.startswith("http://localhost") or (
|
|
135
|
+
found and _client.client.base_url != httpx.URL(url.rstrip("/") + "/")
|
|
136
|
+
):
|
|
130
137
|
client = create_client(base_url=url)
|
|
131
138
|
try:
|
|
132
139
|
yield client
|
|
133
140
|
finally:
|
|
134
141
|
await client.client.aclose()
|
|
135
142
|
else:
|
|
136
|
-
try:
|
|
137
|
-
found = bool(not _client.client.is_closed)
|
|
138
|
-
except NameError:
|
|
139
|
-
found = False
|
|
140
143
|
if found:
|
|
141
144
|
yield _client
|
|
142
145
|
else:
|
langgraph_api/config/__init__.py
CHANGED
|
@@ -588,12 +588,12 @@ STREAM_PUBLISH_RETRY_JITTER = env(
|
|
|
588
588
|
FF_ASYNC_PUBLISH_QUEUE = env("FF_ASYNC_PUBLISH_QUEUE", cast=bool, default=False)
|
|
589
589
|
FF_CRONS_ENABLED = env("FF_CRONS_ENABLED", cast=bool, default=True)
|
|
590
590
|
FF_LOG_QUERY_AND_PARAMS = env("FF_LOG_QUERY_AND_PARAMS", cast=bool, default=False)
|
|
591
|
-
#
|
|
591
|
+
# Default-on handling of drained runs: the server's control signalling to the
|
|
592
592
|
# graph and its handling of drained runs, together. On, a Postgres-backed
|
|
593
593
|
# replica that is shutting down also drains its in-flight runs.
|
|
594
594
|
# Off: no control is created or seeded, and GraphDrained lands in the
|
|
595
595
|
# catch-all error branch.
|
|
596
|
-
FF_RESUME_DRAINED_RUNS = env("FF_RESUME_DRAINED_RUNS", cast=bool, default=
|
|
596
|
+
FF_RESUME_DRAINED_RUNS = env("FF_RESUME_DRAINED_RUNS", cast=bool, default=True)
|
|
597
597
|
|
|
598
598
|
|
|
599
599
|
def _resolve_resume_drained_runs(
|
|
@@ -605,8 +605,9 @@ def _resolve_resume_drained_runs(
|
|
|
605
605
|
return False
|
|
606
606
|
if not langgraph_supported:
|
|
607
607
|
logger.warning(
|
|
608
|
-
"
|
|
609
|
-
"
|
|
608
|
+
"Resuming drained runs is only supported in langgraph 1.2.15 or "
|
|
609
|
+
"greater. Please upgrade langgraph to enable this behavior. "
|
|
610
|
+
"See https://docs.langchain.com/oss/python/langgraph/fault-tolerance#graceful-shutdown",
|
|
610
611
|
langgraph_version=langgraph_version,
|
|
611
612
|
)
|
|
612
613
|
return False
|
|
@@ -656,6 +657,12 @@ PRIORITY_CALLBACK_CONFIGURED = bool(LANGGRAPH_PRIORITY)
|
|
|
656
657
|
# Not in public docs: set by SaaS control plane, not user-configurable
|
|
657
658
|
LANGSMITH_TENANT_ID = env("LANGSMITH_TENANT_ID", cast=str, default=None)
|
|
658
659
|
LANGSMITH_HOST_PROJECT_ID = env("LANGSMITH_HOST_PROJECT_ID", cast=str, default=None)
|
|
660
|
+
LANGSMITH_DEPLOYMENT_AUTH_ENABLED = env(
|
|
661
|
+
"LANGSMITH_DEPLOYMENT_AUTH_ENABLED", cast=bool, default=False
|
|
662
|
+
)
|
|
663
|
+
LANGSMITH_DEPLOYMENT_AUTH_ENDPOINT = env(
|
|
664
|
+
"LANGSMITH_DEPLOYMENT_AUTH_ENDPOINT", cast=str, default=None
|
|
665
|
+
)
|
|
659
666
|
LANGSMITH_AUTH_VERIFY_TENANT_ID = env(
|
|
660
667
|
"LANGSMITH_AUTH_VERIFY_TENANT_ID",
|
|
661
668
|
cast=bool,
|
|
@@ -736,6 +743,10 @@ LANGSMITH_GCP_WORKLOAD_IDENTITY_PROVIDER = env(
|
|
|
736
743
|
LANGSMITH_GCP_SERVICE_ACCOUNT = env(
|
|
737
744
|
"LANGSMITH_GCP_SERVICE_ACCOUNT", cast=str, default=None
|
|
738
745
|
)
|
|
746
|
+
# Not in public docs: set by the SaaS control plane on deployments that prove their agent identity with a pod token.
|
|
747
|
+
LANGSMITH_AGENT_AUTH_POD_TOKEN_PATH = env(
|
|
748
|
+
"LANGSMITH_AGENT_AUTH_POD_TOKEN_PATH", cast=str, default=None
|
|
749
|
+
)
|
|
739
750
|
|
|
740
751
|
|
|
741
752
|
# if langsmith api key is set, enable tracing unless explicitly disabled
|
langgraph_api/errors.py
CHANGED
|
@@ -122,6 +122,13 @@ class UserTimeout(Exception):
|
|
|
122
122
|
self.timeout_error = timeout_error
|
|
123
123
|
|
|
124
124
|
|
|
125
|
+
class AgentDisabledError(RuntimeError):
|
|
126
|
+
"""Agent Auth reports the deployment's agent disabled, so the run fails before it starts."""
|
|
127
|
+
|
|
128
|
+
def __init__(self, message="Agent is disabled, so it can't start new runs."):
|
|
129
|
+
super().__init__(message)
|
|
130
|
+
|
|
131
|
+
|
|
125
132
|
class StreamCutError(Exception):
|
|
126
133
|
"""The event stream behind a response ended before its run did.
|
|
127
134
|
|