mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-02 13:48:43 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d2f891448 | ||
|
|
11ee185999 | ||
|
|
d5f4b2aa96 | ||
|
|
5a77be5e8b | ||
|
|
bdb8a9c7a4 |
@@ -31,7 +31,7 @@ jobs:
|
||||
sdk_py: ${{ steps.filter.outputs.sdk_py || 'true' }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dorny/paths-filter@7b450fff21473bca461d4b92ce414b9d0420d706 # v4
|
||||
- uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
id: filter
|
||||
with:
|
||||
|
||||
@@ -76,6 +76,7 @@ __pypackages__/
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.env.*
|
||||
.envrc
|
||||
*.crt
|
||||
*.key
|
||||
|
||||
@@ -7,7 +7,7 @@ import logging
|
||||
import re
|
||||
import threading
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable, Iterable, Iterator, Sequence
|
||||
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from typing import (
|
||||
@@ -354,7 +354,7 @@ class BasePostgresStore(Generic[C]):
|
||||
(
|
||||
_namespace_to_text(op.namespace),
|
||||
op.key,
|
||||
Jsonb(cast(dict, op.value)),
|
||||
Jsonb(dict(cast(Mapping[str, Any], op.value))),
|
||||
)
|
||||
)
|
||||
if op.ttl is not None:
|
||||
|
||||
@@ -7,7 +7,7 @@ import re
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable, Iterable, Iterator, Sequence
|
||||
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
||||
from contextlib import contextmanager
|
||||
from typing import Any, Literal, NamedTuple, cast
|
||||
|
||||
@@ -387,7 +387,7 @@ class BaseSqliteStore:
|
||||
[
|
||||
_namespace_to_text(op.namespace),
|
||||
op.key,
|
||||
orjson.dumps(cast(dict, op.value)),
|
||||
orjson.dumps(dict(cast(Mapping[str, Any], op.value))),
|
||||
expires_at,
|
||||
op.ttl,
|
||||
]
|
||||
|
||||
@@ -12,7 +12,7 @@ Core types:
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Iterable
|
||||
from collections.abc import Iterable, Mapping
|
||||
from datetime import datetime
|
||||
from typing import (
|
||||
Any,
|
||||
@@ -473,10 +473,10 @@ class PutOp(NamedTuple):
|
||||
the full path would effectively be `"documents/user123/report1"`
|
||||
"""
|
||||
|
||||
value: dict[str, Any] | None
|
||||
value: Mapping[str, Any] | None
|
||||
"""The data to store, or `None` to mark the item for deletion.
|
||||
|
||||
The value must be a dictionary with string keys and JSON-serializable values.
|
||||
The value must be a mapping with string keys and JSON-serializable values.
|
||||
Setting this to `None` signals that the item should be deleted.
|
||||
|
||||
Example:
|
||||
@@ -857,7 +857,7 @@ class BaseStore(ABC):
|
||||
self,
|
||||
namespace: tuple[str, ...],
|
||||
key: str,
|
||||
value: dict[str, Any],
|
||||
value: Mapping[str, Any],
|
||||
index: Literal[False] | list[str] | None = None,
|
||||
*,
|
||||
ttl: float | None | NotProvided = NOT_PROVIDED,
|
||||
@@ -869,7 +869,7 @@ class BaseStore(ABC):
|
||||
Example: `("documents", "user123")`
|
||||
key: Unique identifier within the namespace. Together with namespace forms
|
||||
the complete path to the item.
|
||||
value: Dictionary containing the item's data. Must contain string keys
|
||||
value: Mapping containing the item's data. Must contain string keys
|
||||
and JSON-serializable values.
|
||||
index: Controls how the item's fields are indexed for search:
|
||||
|
||||
@@ -1110,7 +1110,7 @@ class BaseStore(ABC):
|
||||
self,
|
||||
namespace: tuple[str, ...],
|
||||
key: str,
|
||||
value: dict[str, Any],
|
||||
value: Mapping[str, Any],
|
||||
index: Literal[False] | list[str] | None = None,
|
||||
*,
|
||||
ttl: float | None | NotProvided = NOT_PROVIDED,
|
||||
@@ -1122,7 +1122,7 @@ class BaseStore(ABC):
|
||||
Example: `("documents", "user123")`
|
||||
key: Unique identifier within the namespace. Together with namespace forms
|
||||
the complete path to the item.
|
||||
value: Dictionary containing the item's data. Must contain string keys
|
||||
value: Mapping containing the item's data. Must contain string keys
|
||||
and JSON-serializable values.
|
||||
index: Controls how the item's fields are indexed for search:
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import functools
|
||||
import weakref
|
||||
from collections.abc import Callable, Iterable
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from typing import Any, Literal, TypeVar
|
||||
|
||||
from langgraph.store.base import (
|
||||
@@ -132,7 +132,7 @@ class AsyncBatchedBaseStore(BaseStore):
|
||||
self,
|
||||
namespace: tuple[str, ...],
|
||||
key: str,
|
||||
value: dict[str, Any],
|
||||
value: Mapping[str, Any],
|
||||
index: Literal[False] | list[str] | None = None,
|
||||
*,
|
||||
ttl: float | None | NotProvided = NOT_PROVIDED,
|
||||
@@ -231,7 +231,7 @@ class AsyncBatchedBaseStore(BaseStore):
|
||||
self,
|
||||
namespace: tuple[str, ...],
|
||||
key: str,
|
||||
value: dict[str, Any],
|
||||
value: Mapping[str, Any],
|
||||
index: Literal[False] | list[str] | None = None,
|
||||
*,
|
||||
ttl: float | None | NotProvided = NOT_PROVIDED,
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import functools
|
||||
import json
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.embeddings import Embeddings
|
||||
@@ -244,6 +244,9 @@ def get_text_at_path(obj: Any, path: str | list[str]) -> list[str]:
|
||||
- Multi-field selection: "{field1,field2}"
|
||||
- Nested paths in multi-field: "{field1,nested.field2}"
|
||||
"""
|
||||
if isinstance(obj, Mapping) and not isinstance(obj, dict):
|
||||
obj = dict(obj)
|
||||
|
||||
if not path or path == "$":
|
||||
return [json.dumps(obj, sort_keys=True, ensure_ascii=False)]
|
||||
|
||||
|
||||
@@ -408,7 +408,7 @@ class InMemoryStore(BaseStore):
|
||||
self._vectors[namespace].pop(key, None)
|
||||
else:
|
||||
self._data[namespace][key] = Item(
|
||||
value=op.value,
|
||||
value=dict(op.value),
|
||||
key=key,
|
||||
namespace=namespace,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import asyncio
|
||||
import json
|
||||
from collections.abc import Iterable
|
||||
from collections import UserDict
|
||||
from collections.abc import Iterable, Mapping
|
||||
from datetime import datetime
|
||||
from types import MappingProxyType
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
@@ -137,6 +139,18 @@ def test_get_text_at_path() -> None:
|
||||
assert get_text_at_path(nested_data, "nested[{invalid}]") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mapping",
|
||||
[
|
||||
UserDict({"text": "searchable"}),
|
||||
MappingProxyType({"text": "searchable"}),
|
||||
],
|
||||
)
|
||||
def test_get_text_at_path_with_non_dict_mapping(mapping: Mapping[str, str]) -> None:
|
||||
assert get_text_at_path(mapping, "$") == ['{"text": "searchable"}']
|
||||
assert get_text_at_path(mapping, "text") == ["searchable"]
|
||||
|
||||
|
||||
async def test_async_batch_store(mocker: MockerFixture) -> None:
|
||||
abatch = mocker.stub()
|
||||
|
||||
|
||||
@@ -103,8 +103,6 @@ The CLI uses a `langgraph.json` configuration file with these key settings:
|
||||
}
|
||||
```
|
||||
|
||||
Git dependencies should use credential-free URLs. The CLI conservatively scans direct `langgraph.json` dependencies, common Python package files, uv project and lock files, and common Node.js package and lock files for HTTP Git URLs with userinfo. This check is not exhaustive: generated Docker builds can copy other files, including nested requirement or constraint files, into image layers without scanning them. For private dependencies, provide short-lived credentials through your build environment's secret-backed Git credential helper. Do not store credentials in copied files such as `langgraph.json` or `pip_config_file`.
|
||||
|
||||
See the [full documentation](https://reference.langchain.com/python/langgraph-cli) for detailed configuration options.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -6,7 +6,6 @@ import re
|
||||
import shlex
|
||||
import textwrap
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable
|
||||
from typing import Literal, NamedTuple
|
||||
|
||||
import click
|
||||
@@ -37,10 +36,6 @@ DISALLOWED_BUILD_COMMAND_CHARS = [
|
||||
# This blocks background execution (cmd &) while allowing command
|
||||
# chaining (cmd1 && cmd2) which is common in build commands.
|
||||
_SINGLE_AMPERSAND_RE = re.compile(r"(?<!&)&(?:&&)*(?!&)")
|
||||
_GIT_HTTP_AUTHORITY_RES = (
|
||||
re.compile(r"git\+https?://(?P<authority>[^/\s\"']+)", re.I),
|
||||
re.compile(r"\bgit\s*=\s*[\"']https?://(?P<authority>[^/\s\"']+)", re.I),
|
||||
)
|
||||
_API_VERSION_PATTERN = re.compile(
|
||||
r"^(?P<major>\d+)"
|
||||
r"(?:\.(?P<minor>\d+))?"
|
||||
@@ -83,62 +78,6 @@ def has_disallowed_build_command_content(command: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _has_git_http_url_userinfo(dependency: str) -> bool:
|
||||
"""Check whether a Git HTTP URL contains userinfo."""
|
||||
return any(
|
||||
"@" in match.group("authority")
|
||||
for pattern in _GIT_HTTP_AUTHORITY_RES
|
||||
for match in pattern.finditer(dependency)
|
||||
)
|
||||
|
||||
|
||||
def _validate_git_http_url_userinfo(
|
||||
values: Iterable[str], *, source: pathlib.Path | None = None
|
||||
) -> None:
|
||||
"""Reject credential-bearing Git HTTP URLs without echoing their values."""
|
||||
if not any(_has_git_http_url_userinfo(value) for value in values):
|
||||
return
|
||||
message = (
|
||||
"Git dependency URLs must not contain credentials or other URL "
|
||||
"userinfo because generated Dockerfiles and image layers can retain "
|
||||
"them. Use a credential-free Git URL and provide short-lived "
|
||||
"credentials through your build environment's secret-backed Git "
|
||||
"credential helper."
|
||||
)
|
||||
if source is not None:
|
||||
message += f" Found in: {source}"
|
||||
raise click.UsageError(message)
|
||||
|
||||
|
||||
def _validate_git_http_url_userinfo_files(paths: Iterable[pathlib.Path]) -> None:
|
||||
"""Reject credential-bearing Git HTTP URLs in dependency files."""
|
||||
for path in paths:
|
||||
path = path.resolve()
|
||||
if not path.is_file():
|
||||
continue
|
||||
try:
|
||||
contents = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
raise click.UsageError(
|
||||
f"Could not inspect dependency file for embedded credentials: {path}"
|
||||
) from None
|
||||
_validate_git_http_url_userinfo([contents], source=path)
|
||||
|
||||
|
||||
def _validate_local_dependency_files(config_path: pathlib.Path, config: Config) -> None:
|
||||
"""Validate dependency files copied into a non-uv Python image."""
|
||||
paths: list[pathlib.Path] = []
|
||||
for dependency in config["dependencies"]:
|
||||
if not isinstance(dependency, str) or not dependency.startswith("."):
|
||||
continue
|
||||
root = (config_path.parent / dependency).resolve()
|
||||
paths.extend(
|
||||
root / name
|
||||
for name in ("requirements.txt", "pyproject.toml", "setup.py", "setup.cfg")
|
||||
)
|
||||
_validate_git_http_url_userinfo_files(paths)
|
||||
|
||||
|
||||
MIN_PYTHON_VERSION = "3.11"
|
||||
DEFAULT_PYTHON_VERSION = "3.11"
|
||||
|
||||
@@ -381,9 +320,7 @@ def _get_source_kind(config: Config) -> str | None:
|
||||
return kind if isinstance(kind, str) else None
|
||||
|
||||
|
||||
def validate_config(
|
||||
config: Config, *, source_path: pathlib.Path | None = None
|
||||
) -> Config:
|
||||
def validate_config(config: Config) -> Config:
|
||||
"""Validate a configuration dictionary."""
|
||||
|
||||
graphs = config.get("graphs", {})
|
||||
@@ -478,15 +415,6 @@ def validate_config(
|
||||
' "source": {"kind": "uv", "root": ".."}'
|
||||
)
|
||||
|
||||
_validate_git_http_url_userinfo(
|
||||
(
|
||||
dependency
|
||||
for dependency in config["dependencies"]
|
||||
if isinstance(dependency, str)
|
||||
),
|
||||
source=source_path,
|
||||
)
|
||||
|
||||
source = config.get("source")
|
||||
source_kind = _get_source_kind(config)
|
||||
if source is not None and not isinstance(source, dict):
|
||||
@@ -681,7 +609,7 @@ def validate_config_file(config_path: pathlib.Path) -> Config:
|
||||
"""Load and validate a configuration file."""
|
||||
with open(config_path) as f:
|
||||
config = json.load(f)
|
||||
validated = validate_config(config, source_path=config_path.resolve())
|
||||
validated = validate_config(config)
|
||||
# Enforce the package.json doesn't enforce an
|
||||
# incompatible Node.js version
|
||||
if validated.get("node_version"):
|
||||
@@ -1352,7 +1280,6 @@ def python_config_to_docker(
|
||||
api_version=api_version,
|
||||
build_tools_to_uninstall=build_tools_to_uninstall,
|
||||
)
|
||||
_validate_local_dependency_files(config_path, config)
|
||||
if pip_installer == "auto":
|
||||
if _image_supports_uv(base_image):
|
||||
pip_installer = "uv"
|
||||
@@ -1563,18 +1490,7 @@ def node_config_to_docker(
|
||||
) -> tuple[str, dict[str, str]]:
|
||||
# Calculate paths for monorepo support
|
||||
install_root = (
|
||||
pathlib.Path(build_context).resolve()
|
||||
if build_context
|
||||
else config_path.parent.resolve()
|
||||
)
|
||||
config_root = config_path.parent.resolve()
|
||||
dependency_roots = (
|
||||
(install_root, config_root) if install_root != config_root else (install_root,)
|
||||
)
|
||||
_validate_git_http_url_userinfo_files(
|
||||
root / name
|
||||
for root in dependency_roots
|
||||
for name in ("package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml")
|
||||
pathlib.Path(build_context).resolve() if build_context else config_path.parent
|
||||
)
|
||||
install_cmd = install_command or _get_node_pm_install_cmd(install_root)
|
||||
if build_context:
|
||||
|
||||
@@ -650,8 +650,7 @@ class Config(TypedDict, total=False):
|
||||
|
||||
pip_config_file: str | None
|
||||
"""Optional. Path to a pip config file (e.g., "/etc/pip.conf" or "pip.ini") for controlling
|
||||
package installation (custom indices, timeouts, etc.). The file is copied into the
|
||||
generated image, so it must not contain credentials or other secrets.
|
||||
package installation (custom indices, credentials, etc.).
|
||||
|
||||
Only relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.
|
||||
"""
|
||||
@@ -690,9 +689,6 @@ class Config(TypedDict, total=False):
|
||||
- "." or "./src" if you have a local Python package
|
||||
- str (aka "anthropic") for a PyPI package
|
||||
- "git+https://github.com/org/repo.git@main" for a Git-based package
|
||||
Git HTTP URLs must not contain userinfo such as a username or token. For private
|
||||
dependencies, provide short-lived credentials through the build environment's
|
||||
secret-backed Git credential helper.
|
||||
Defaults to an empty list, meaning no additional packages installed beyond your base environment.
|
||||
|
||||
This field is not supported when `source.kind` is `uv`.
|
||||
|
||||
@@ -880,7 +880,6 @@ def python_config_to_docker_uv_lock(
|
||||
_get_node_pm_install_cmd,
|
||||
_get_pip_cleanup_lines,
|
||||
_image_supports_uv,
|
||||
_validate_git_http_url_userinfo_files,
|
||||
docker_tag,
|
||||
)
|
||||
|
||||
@@ -891,20 +890,11 @@ def python_config_to_docker_uv_lock(
|
||||
)
|
||||
|
||||
config_root = config_path.parent.resolve()
|
||||
source_root = config["source"].get("root", ".")
|
||||
project_root = (config_root / source_root).resolve()
|
||||
_validate_git_http_url_userinfo_files(
|
||||
[project_root / "pyproject.toml", project_root / "uv.lock"]
|
||||
)
|
||||
|
||||
install_cmd = "uv pip install --system"
|
||||
_, global_reqs_pip_install, pip_config_file_str = _build_python_install_commands(
|
||||
config, install_cmd
|
||||
)
|
||||
plan = _plan_uv_lock_workspace(config_path, config)
|
||||
_validate_git_http_url_userinfo_files(
|
||||
package.pyproject_path for package in plan.install_order
|
||||
)
|
||||
|
||||
_update_uv_lock_graph_paths(config_path, config, plan)
|
||||
for section, key in [
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
},
|
||||
"_INTERNAL_docker_tag": {
|
||||
"anyOf": [
|
||||
@@ -270,7 +270,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
},
|
||||
"_INTERNAL_docker_tag": {
|
||||
"anyOf": [
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
},
|
||||
"_INTERNAL_docker_tag": {
|
||||
"anyOf": [
|
||||
@@ -270,7 +270,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, timeouts, etc.). The file is copied into the\ngenerated image, so it must not contain credentials or other secrets.\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
"description": "Optional. Path to a pip config file (e.g., \"/etc/pip.conf\" or \"pip.ini\") for controlling\npackage installation (custom indices, credentials, etc.).\n\nOnly relevant if Python dependencies are installed via pip. If omitted, default pip settings are used.\n"
|
||||
},
|
||||
"_INTERNAL_docker_tag": {
|
||||
"anyOf": [
|
||||
|
||||
@@ -255,243 +255,6 @@ def test_validate_config():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dependency",
|
||||
[
|
||||
"git+https://user:secret-token@github.com/org/private.git@main",
|
||||
"private-package @ git+http://token@github.com/org/private.git",
|
||||
"git+HTTPS://user%40example.com:secret%2Ftoken@github.com/org/private.git",
|
||||
"git+https://${GIT_TOKEN}@github.com/org/private.git",
|
||||
],
|
||||
)
|
||||
def test_validate_config_rejects_git_http_url_userinfo(dependency: str):
|
||||
with pytest.raises(click.UsageError) as exc_info:
|
||||
validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": [dependency],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
}
|
||||
)
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "must not contain credentials or other URL userinfo" in message
|
||||
assert "secret-token" not in message
|
||||
assert "secret%2Ftoken" not in message
|
||||
|
||||
|
||||
def test_validate_config_file_reports_source_for_git_http_url_userinfo(
|
||||
tmp_path: pathlib.Path,
|
||||
):
|
||||
config_path = tmp_path / "langgraph.json"
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": ["git+https://secret-token@github.com/org/private.git"],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
with pytest.raises(click.UsageError) as exc_info:
|
||||
validate_config_file(config_path)
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "secret-token" not in message
|
||||
assert f"Found in: {config_path.resolve()}" in message
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"manifest", ["package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"]
|
||||
)
|
||||
def test_config_to_docker_rejects_git_http_url_userinfo_in_node_files(
|
||||
tmp_path: pathlib.Path, manifest: str
|
||||
):
|
||||
config_path = tmp_path / "langgraph.json"
|
||||
config_path.write_text("{}\n")
|
||||
(tmp_path / "agent.js").write_text("export const graph = {};\n")
|
||||
(tmp_path / "package.json").write_text('{"name":"agent"}\n')
|
||||
(tmp_path / manifest).write_text(
|
||||
'"priv": "git+https://user:secret-token@github.com/org/private.git"\n'
|
||||
)
|
||||
config = validate_config(
|
||||
{
|
||||
"node_version": "20",
|
||||
"graphs": {"agent": "./agent.js:graph"},
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(click.UsageError) as exc_info:
|
||||
config_to_docker(
|
||||
config_path,
|
||||
config,
|
||||
base_image="langchain/langgraphjs-api",
|
||||
)
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "must not contain credentials or other URL userinfo" in message
|
||||
assert "secret-token" not in message
|
||||
assert f"Found in: {(tmp_path / manifest).resolve()}" in message
|
||||
|
||||
|
||||
def test_config_to_docker_allows_node_git_urls_without_http_userinfo(
|
||||
tmp_path: pathlib.Path,
|
||||
):
|
||||
config_path = tmp_path / "langgraph.json"
|
||||
config_path.write_text("{}\n")
|
||||
(tmp_path / "agent.js").write_text("export const graph = {};\n")
|
||||
(tmp_path / "package.json").write_text(
|
||||
'{"dependencies":{"public":"git+https://github.com/org/public.git"}}\n'
|
||||
)
|
||||
config = validate_config(
|
||||
{
|
||||
"node_version": "20",
|
||||
"graphs": {"agent": "./agent.js:graph"},
|
||||
}
|
||||
)
|
||||
|
||||
docker, _ = config_to_docker(
|
||||
config_path,
|
||||
config,
|
||||
base_image="langchain/langgraphjs-api",
|
||||
)
|
||||
|
||||
assert f"ADD . /deps/{tmp_path.name}" in docker
|
||||
|
||||
|
||||
def test_config_to_docker_rejects_git_http_url_userinfo_in_node_workspace(
|
||||
tmp_path: pathlib.Path,
|
||||
):
|
||||
config_root = tmp_path / "apps" / "agent"
|
||||
config_root.mkdir(parents=True)
|
||||
config_path = config_root / "langgraph.json"
|
||||
config_path.write_text("{}\n")
|
||||
(config_root / "agent.js").write_text("export const graph = {};\n")
|
||||
(config_root / "package.json").write_text(
|
||||
'{"dependencies":{"priv":"git+https://secret-token@github.com/org/private.git"}}\n'
|
||||
)
|
||||
(tmp_path / "package.json").write_text('{"name":"workspace"}\n')
|
||||
config = validate_config(
|
||||
{
|
||||
"node_version": "20",
|
||||
"graphs": {"agent": "./agent.js:graph"},
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(click.UsageError) as exc_info:
|
||||
config_to_docker(
|
||||
config_path,
|
||||
config,
|
||||
base_image="langchain/langgraphjs-api",
|
||||
build_context=str(tmp_path),
|
||||
)
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "secret-token" not in message
|
||||
assert f"Found in: {(config_root / 'package.json').resolve()}" in message
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dependency",
|
||||
[
|
||||
"git+https://github.com/org/public.git@main",
|
||||
"private-package @ git+https://github.com/org/private.git@main",
|
||||
"git+ssh://git@github.com/org/private.git@main",
|
||||
],
|
||||
)
|
||||
def test_validate_config_allows_git_urls_without_http_userinfo(dependency: str):
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": [dependency],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
}
|
||||
)
|
||||
|
||||
assert config["dependencies"] == [dependency]
|
||||
|
||||
|
||||
def test_config_to_docker_rejects_git_http_url_userinfo_in_requirements(
|
||||
tmp_path: pathlib.Path,
|
||||
):
|
||||
config_path = tmp_path / "langgraph.json"
|
||||
config_path.write_text("{}\n")
|
||||
(tmp_path / "agent.py").write_text("graph = object()\n")
|
||||
(tmp_path / "requirements.txt").write_text(
|
||||
"private @ git+https://secret-token@github.com/org/private.git\n"
|
||||
)
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": ["."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(click.UsageError) as exc_info:
|
||||
config_to_docker(
|
||||
config_path,
|
||||
config,
|
||||
base_image="langchain/langgraph-api:0.2.47",
|
||||
)
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "must not contain credentials or other URL userinfo" in message
|
||||
assert "secret-token" not in message
|
||||
assert f"Found in: {(tmp_path / 'requirements.txt').resolve()}" in message
|
||||
|
||||
|
||||
@pytest.mark.parametrize("manifest", ["pyproject.toml", "uv.lock"])
|
||||
def test_config_to_docker_rejects_git_http_url_userinfo_in_uv_files(
|
||||
tmp_path: pathlib.Path, manifest: str
|
||||
):
|
||||
config_path = tmp_path / "langgraph.json"
|
||||
config_path.write_text("{}\n")
|
||||
(tmp_path / "src").mkdir()
|
||||
(tmp_path / "src" / "agent.py").write_text("graph = object()\n")
|
||||
pyproject = textwrap.dedent(
|
||||
"""
|
||||
[project]
|
||||
name = "agent"
|
||||
version = "0.1.0"
|
||||
dependencies = ["private"]
|
||||
|
||||
[tool.uv.sources]
|
||||
private = { git = "https://github.com/org/private.git" }
|
||||
"""
|
||||
).strip()
|
||||
uv_lock = "# uv lock file\n"
|
||||
if manifest == "pyproject.toml":
|
||||
pyproject = pyproject.replace(
|
||||
"https://github.com", "https://secret-token@github.com"
|
||||
)
|
||||
else:
|
||||
uv_lock += (
|
||||
'source = { git = "https://secret-token@github.com/org/private.git" }\n'
|
||||
)
|
||||
(tmp_path / "pyproject.toml").write_text(pyproject + "\n")
|
||||
(tmp_path / "uv.lock").write_text(uv_lock)
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"graphs": {"agent": "./src/agent.py:graph"},
|
||||
"source": {"kind": "uv"},
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(click.UsageError) as exc_info:
|
||||
config_to_docker(
|
||||
config_path,
|
||||
config,
|
||||
base_image="langchain/langgraph-api:0.2.47",
|
||||
)
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "must not contain credentials or other URL userinfo" in message
|
||||
assert "secret-token" not in message
|
||||
|
||||
|
||||
def test_validate_config_image_distro():
|
||||
"""Test validation of image_distro field."""
|
||||
# Valid image_distro values should work
|
||||
|
||||
@@ -39,6 +39,15 @@
|
||||
- `client.threads.stream()` now accepts `transport="sse"` (default) or
|
||||
`transport="websocket"` in place of the previous transport-agnostic default.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Resource-scoped auth decorators now honor `actions=` and reject empty or
|
||||
invalid action lists. Because unmatched custom-auth paths remain allowed,
|
||||
deployments using action-scoped handlers should configure a global
|
||||
default-deny handler; `langgraph-api` 0.10+ warns about uncovered paths at
|
||||
startup. Resource-specific decorators retain matching `resources=` selectors
|
||||
for backward compatibility; use `@auth.on(resources=...)` for other resources.
|
||||
|
||||
### Notes
|
||||
|
||||
- The v3 streaming surface (`AsyncThreadStream`, `SyncThreadStream`, and all
|
||||
|
||||
@@ -3,7 +3,7 @@ from langgraph_sdk.client import get_client, get_sync_client
|
||||
from langgraph_sdk.encryption import Encryption
|
||||
from langgraph_sdk.encryption.types import DecryptResult, EncryptionContext
|
||||
|
||||
__version__ = "0.4.3"
|
||||
__version__ = "0.4.4"
|
||||
|
||||
__all__ = [
|
||||
"Auth",
|
||||
|
||||
@@ -24,7 +24,7 @@ from langchain_core.language_models.chat_model_stream import AsyncChatModelStrea
|
||||
from langchain_protocol import Event, SubscribeParams
|
||||
|
||||
from langgraph_sdk._async.http import HttpClient
|
||||
from langgraph_sdk.schema import QueryParamTypes
|
||||
from langgraph_sdk.schema import LangSmithTracing, QueryParamTypes
|
||||
from langgraph_sdk.stream.controller import _SeenEventIds
|
||||
from langgraph_sdk.stream.decoders import (
|
||||
DataDecoder,
|
||||
@@ -172,6 +172,7 @@ class RunModule:
|
||||
input: Any = None,
|
||||
config: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
langsmith_tracing: LangSmithTracing | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Send `run.start` to the server. Returns the result (`{"run_id": ...}`)."""
|
||||
params: dict[str, Any] = {"assistant_id": self._owner.assistant_id}
|
||||
@@ -181,6 +182,8 @@ class RunModule:
|
||||
params["config"] = config
|
||||
if metadata is not None:
|
||||
params["metadata"] = metadata
|
||||
if langsmith_tracing is not None:
|
||||
params["langsmith_tracer"] = langsmith_tracing
|
||||
loop = asyncio.get_running_loop()
|
||||
gate: asyncio.Future[None] = loop.create_future()
|
||||
self._owner._run_start_ready = gate
|
||||
|
||||
@@ -23,7 +23,7 @@ from langchain_core.language_models.chat_model_stream import ChatModelStream
|
||||
from langchain_protocol import Event, SubscribeParams
|
||||
|
||||
from langgraph_sdk._sync.http import SyncHttpClient
|
||||
from langgraph_sdk.schema import QueryParamTypes
|
||||
from langgraph_sdk.schema import LangSmithTracing, QueryParamTypes
|
||||
from langgraph_sdk.stream.decoders import (
|
||||
DataDecoder,
|
||||
Decoder,
|
||||
@@ -215,6 +215,7 @@ class SyncRunModule:
|
||||
input: Any = None,
|
||||
config: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
langsmith_tracing: LangSmithTracing | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Send `run.start` to the server. Returns the result (`{"run_id": ...}`)."""
|
||||
params: dict[str, Any] = {"assistant_id": self._owner.assistant_id}
|
||||
@@ -224,6 +225,8 @@ class SyncRunModule:
|
||||
params["config"] = config
|
||||
if metadata is not None:
|
||||
params["metadata"] = metadata
|
||||
if langsmith_tracing is not None:
|
||||
params["langsmith_tracer"] = langsmith_tracing
|
||||
result = self._owner._send_command("run.start", params)
|
||||
self._owner._run_seen = True
|
||||
controller = self._owner._controller
|
||||
|
||||
@@ -341,9 +341,15 @@ VUpdate = typing.TypeVar("VUpdate", covariant=True)
|
||||
VRead = typing.TypeVar("VRead", covariant=True)
|
||||
VDelete = typing.TypeVar("VDelete", covariant=True)
|
||||
VSearch = typing.TypeVar("VSearch", covariant=True)
|
||||
ResourceActionT = typing.TypeVar("ResourceActionT", bound=str)
|
||||
|
||||
_ResourceAction = typing.Literal["create", "read", "update", "delete", "search"]
|
||||
_ThreadAction = _ResourceAction | typing.Literal["create_run"]
|
||||
|
||||
|
||||
class _ResourceOn(typing.Generic[VCreate, VRead, VUpdate, VDelete, VSearch]):
|
||||
class _ResourceOn(
|
||||
typing.Generic[VCreate, VRead, VUpdate, VDelete, VSearch, ResourceActionT]
|
||||
):
|
||||
"""
|
||||
Generic base class for resource-specific handlers.
|
||||
"""
|
||||
@@ -392,8 +398,8 @@ class _ResourceOn(typing.Generic[VCreate, VRead, VUpdate, VDelete, VSearch]):
|
||||
def __call__(
|
||||
self,
|
||||
*,
|
||||
resources: str | Sequence[str],
|
||||
actions: str | Sequence[str] | None = None,
|
||||
resources: str | Sequence[str] | None = None,
|
||||
actions: ResourceActionT | Sequence[ResourceActionT] | None = None,
|
||||
) -> Callable[
|
||||
[_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]],
|
||||
_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
|
||||
@@ -408,7 +414,7 @@ class _ResourceOn(typing.Generic[VCreate, VRead, VUpdate, VDelete, VSearch]):
|
||||
) = None,
|
||||
*,
|
||||
resources: str | Sequence[str] | None = None,
|
||||
actions: str | Sequence[str] | None = None,
|
||||
actions: ResourceActionT | Sequence[ResourceActionT] | None = None,
|
||||
) -> (
|
||||
_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]
|
||||
| Callable[
|
||||
@@ -416,24 +422,66 @@ class _ResourceOn(typing.Generic[VCreate, VRead, VUpdate, VDelete, VSearch]):
|
||||
_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
|
||||
]
|
||||
):
|
||||
if fn is not None:
|
||||
_validate_handler(fn)
|
||||
return typing.cast(
|
||||
"_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]",
|
||||
_register_handler(self.auth, self.resource, "*", fn),
|
||||
)
|
||||
|
||||
def decorator(
|
||||
handler: _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
|
||||
) -> _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]:
|
||||
_validate_handler(handler)
|
||||
return typing.cast(
|
||||
"_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]",
|
||||
_register_handler(self.auth, self.resource, "*", handler),
|
||||
if resources is None:
|
||||
resource_list = [self.resource]
|
||||
elif isinstance(resources, str):
|
||||
resource_list = [resources]
|
||||
elif isinstance(resources, Sequence):
|
||||
resource_list = list(resources)
|
||||
else:
|
||||
raise TypeError("resources must be a string or sequence of strings")
|
||||
if resource_list != [self.resource]:
|
||||
raise ValueError(
|
||||
f"Resource-specific decorator for {self.resource!r} cannot "
|
||||
f"register handlers for {resource_list!r}. Use @auth.on(...) "
|
||||
"for other or multiple resources."
|
||||
)
|
||||
if actions is None:
|
||||
action_list = ["*"]
|
||||
elif isinstance(actions, str):
|
||||
action_list = [actions]
|
||||
elif isinstance(actions, Sequence):
|
||||
action_list = list(actions)
|
||||
else:
|
||||
raise TypeError("actions must be a string or sequence of strings")
|
||||
if not action_list:
|
||||
raise ValueError("actions must not be empty")
|
||||
if not all(isinstance(action, str) for action in action_list):
|
||||
raise TypeError("actions must be a string or sequence of strings")
|
||||
valid_actions = {
|
||||
value.action
|
||||
for value in vars(self).values()
|
||||
if isinstance(value, _ResourceActionOn)
|
||||
}
|
||||
invalid_actions = (
|
||||
sorted(set(action_list) - valid_actions) if actions is not None else []
|
||||
)
|
||||
if invalid_actions:
|
||||
raise ValueError(
|
||||
f"Invalid action(s) for {self.resource}: {', '.join(invalid_actions)}"
|
||||
)
|
||||
if len(action_list) != len(set(action_list)):
|
||||
raise ValueError("actions must not contain duplicates")
|
||||
for action in action_list:
|
||||
if (self.resource, action) in self.auth._handlers:
|
||||
raise ValueError(
|
||||
f"types.Handler already set for {self.resource}, {action}."
|
||||
)
|
||||
for action in action_list:
|
||||
_register_handler(self.auth, self.resource, action, handler)
|
||||
return handler
|
||||
|
||||
# Accept keyword-only parameters for future filtering behavior; referenced to satisfy linters.
|
||||
_ = resources, actions
|
||||
if fn is not None:
|
||||
return decorator(
|
||||
typing.cast(
|
||||
"_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]",
|
||||
fn,
|
||||
)
|
||||
)
|
||||
return decorator
|
||||
|
||||
|
||||
@@ -444,6 +492,7 @@ class _AssistantsOn(
|
||||
types.AssistantsUpdate,
|
||||
types.AssistantsDelete,
|
||||
types.AssistantsSearch,
|
||||
_ResourceAction,
|
||||
]
|
||||
):
|
||||
value = (
|
||||
@@ -467,6 +516,7 @@ class _ThreadsOn(
|
||||
types.ThreadsUpdate,
|
||||
types.ThreadsDelete,
|
||||
types.ThreadsSearch,
|
||||
_ThreadAction,
|
||||
]
|
||||
):
|
||||
value = (
|
||||
@@ -502,6 +552,7 @@ class _CronsOn(
|
||||
types.CronsUpdate,
|
||||
types.CronsDelete,
|
||||
types.CronsSearch,
|
||||
_ResourceAction,
|
||||
]
|
||||
):
|
||||
value = type[
|
||||
|
||||
@@ -426,11 +426,17 @@ def test_sync_run_start_sends_command():
|
||||
with httpx.Client(transport=fake.transport, base_url="http://test") as raw:
|
||||
threads = SyncThreadsClient(SyncHttpClient(raw))
|
||||
with threads.stream(thread_id="t-1", assistant_id="agent") as thread:
|
||||
result = thread.run.start(input={"x": 1})
|
||||
result = thread.run.start(
|
||||
input={"x": 1},
|
||||
langsmith_tracing={"project_name": "replica-project"},
|
||||
)
|
||||
|
||||
assert result == {"run_id": "run-1"}
|
||||
assert fake.received_commands[0]["method"] == "run.start"
|
||||
assert fake.received_commands[0]["params"]["assistant_id"] == "agent"
|
||||
assert fake.received_commands[0]["params"]["langsmith_tracer"] == {
|
||||
"project_name": "replica-project"
|
||||
}
|
||||
|
||||
|
||||
def test_sync_events_iterates_raw_events():
|
||||
|
||||
@@ -287,7 +287,7 @@ async def test_command_ids_are_monotonic():
|
||||
assert [c["id"] for c in fake.received_commands] == [1, 2]
|
||||
|
||||
|
||||
async def test_run_start_forwards_config_and_metadata():
|
||||
async def test_run_start_forwards_config_metadata_and_langsmith_tracing():
|
||||
fake = FakeServer()
|
||||
transport = httpx.ASGITransport(app=fake.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as raw:
|
||||
@@ -297,10 +297,18 @@ async def test_run_start_forwards_config_and_metadata():
|
||||
input={"x": 1},
|
||||
config={"recursion_limit": 5},
|
||||
metadata={"trace": "abc"},
|
||||
langsmith_tracing={
|
||||
"project_name": "replica-project",
|
||||
"example_id": "example-1",
|
||||
},
|
||||
)
|
||||
params = fake.received_commands[0]["params"]
|
||||
assert params["config"] == {"recursion_limit": 5}
|
||||
assert params["metadata"] == {"trace": "abc"}
|
||||
assert params["langsmith_tracer"] == {
|
||||
"project_name": "replica-project",
|
||||
"example_id": "example-1",
|
||||
}
|
||||
|
||||
|
||||
async def test_run_start_raises_outside_context_manager():
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import pytest
|
||||
|
||||
from langgraph_sdk import Auth
|
||||
|
||||
|
||||
def test_handler_multiple_resources_and_actions() -> None:
|
||||
auth = Auth()
|
||||
|
||||
@auth.on(resources=["threads", "assistants"], actions=["read", "search"])
|
||||
async def allow_reads(ctx, value):
|
||||
del value
|
||||
return {"owner": ctx.user.identity}
|
||||
|
||||
assert auth._handlers == {
|
||||
("threads", "read"): [allow_reads],
|
||||
("threads", "search"): [allow_reads],
|
||||
("assistants", "read"): [allow_reads],
|
||||
("assistants", "search"): [allow_reads],
|
||||
}
|
||||
|
||||
|
||||
def test_resource_handler_actions_are_scoped() -> None:
|
||||
auth = Auth()
|
||||
|
||||
@auth.on
|
||||
async def deny_all(ctx, value):
|
||||
del ctx, value
|
||||
return False
|
||||
|
||||
@auth.on.threads(actions=["create", "search"])
|
||||
async def handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
@auth.on.threads(actions="create_run")
|
||||
async def run_handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
assert auth._handlers == {
|
||||
("threads", "create"): [handler],
|
||||
("threads", "search"): [handler],
|
||||
("threads", "create_run"): [run_handler],
|
||||
}
|
||||
assert auth._global_handlers == [deny_all]
|
||||
|
||||
|
||||
def test_resource_handler_preserves_wildcard() -> None:
|
||||
auth = Auth()
|
||||
|
||||
@auth.on.threads
|
||||
async def handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
assert auth._handlers == {("threads", "*"): [handler]}
|
||||
|
||||
|
||||
def test_resource_handler_preserves_wildcard_with_parentheses() -> None:
|
||||
auth = Auth()
|
||||
|
||||
@auth.on.threads()
|
||||
async def handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
assert auth._handlers == {("threads", "*"): [handler]}
|
||||
|
||||
|
||||
def test_resource_handler_accepts_matching_resource() -> None:
|
||||
auth = Auth()
|
||||
|
||||
@auth.on.threads(resources=["threads"], actions="read")
|
||||
async def handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
assert auth._handlers == {("threads", "read"): [handler]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"resources", [["assistants"], ["threads", "assistants"], [], [1]]
|
||||
)
|
||||
def test_resource_handler_rejects_nonmatching_resources(resources) -> None:
|
||||
auth = Auth()
|
||||
|
||||
async def handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
with pytest.raises(ValueError, match=r"Use @auth\.on"):
|
||||
auth.on.threads(resources=resources)(handler)
|
||||
assert auth._handlers == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("resource", "actions", "error"),
|
||||
[
|
||||
("threads", [], ValueError),
|
||||
("threads", ["reed"], ValueError),
|
||||
("threads", ["create", "create"], ValueError),
|
||||
("threads", {"create": True}, TypeError),
|
||||
("crons", ["create_run"], ValueError),
|
||||
],
|
||||
)
|
||||
def test_resource_handler_rejects_invalid_actions(resource, actions, error) -> None:
|
||||
auth = Auth()
|
||||
|
||||
async def handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
with pytest.raises(error):
|
||||
getattr(auth.on, resource)(actions=actions)(handler)
|
||||
assert auth._handlers == {}
|
||||
|
||||
|
||||
def test_resource_handler_registration_is_atomic() -> None:
|
||||
auth = Auth()
|
||||
|
||||
@auth.on.threads.read
|
||||
async def read_handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
async def handler(ctx, value):
|
||||
del ctx, value
|
||||
return None
|
||||
|
||||
with pytest.raises(ValueError, match="already set"):
|
||||
auth.on.threads(actions=["create", "read"])(handler)
|
||||
assert auth._handlers == {("threads", "read"): [read_handler]}
|
||||
Reference in New Issue
Block a user