From 09173193ea866c7b2c64a7900282d2cfbeca0c11 Mon Sep 17 00:00:00 2001 From: Piotr Mlocek Date: Thu, 3 Dec 2026 08:37:47 -0800 Subject: [PATCH] chore(python)!: remove the Python SDK from core The Python SDK lives in ai-openshell/sdk-python, which publishes `openshell` to PyPI. Core's E2E suites no longer need it (#5624), so delete `python/` and the binding generator. - Turn the root pyproject.toml into a tooling-only, non-package project and drop the SDK runtime and build dependencies from uv.lock. - Drop the python:proto and python:dev tasks, test:python, and the Python SDK Freeze job and frozen-paths group. - Drop the python3-openshell RPM sub-package. It shipped without generated bindings, so it could not be imported; `openshell` now obsoletes it. - Remove python-sdk from the compatibility review surfaces and the SDK paths from CodeQL, license, linguist, and ignore rules. - Point README, docs, AGENTS.md, and the issue template links at sdk-python. Part of #5287. Signed-off-by: Piotr Mlocek --- .agents/skills/update-docs/SKILL.md | 3 +- .gitattributes | 5 - .github/ISSUE_TEMPLATE/config.yml | 5 + .github/codeql/codeql-config.yml | 2 - .github/frozen-paths.toml | 11 - .github/prompts/compatibility-review.md | 8 +- .github/workflows/branch-checks.yml | 29 +- .gitignore | 5 - .packit.yaml | 5 +- AGENTS.md | 6 +- CI.md | 7 +- CONTRIBUTING.md | 1 - README.md | 2 +- TESTING.md | 30 +- docs/sdk/python.mdx | 4 +- mise.toml | 2 +- openshell.spec | 94 +- pyproject.toml | 87 +- python/credential_driver_proto_test.py | 58 - python/generate_python_proto_test.py | 59 - python/grpc_transport_test.py | 101 - python/grpc_typing_test.py | 81 - python/openshell/__init__.py | 69 - python/openshell/_proto/__init__.py | 15 - python/openshell/errors.py | 149 - python/openshell/errors_test.py | 127 - python/openshell/mutations.py | 33 - python/openshell/openshell_test.py | 15 - python/openshell/providers.py | 111 - python/openshell/providers_test.py | 230 -- python/openshell/py.typed | 0 python/openshell/sandbox.py | 2689 --------------- python/openshell/sandbox_cleanup_test.py | 286 -- python/openshell/sandbox_test.py | 3300 ------------------- scripts/update_license_headers.py | 1 - tasks/python.toml | 22 +- tasks/scripts/check_frozen_paths_test.py | 22 +- tasks/scripts/codex_compatibility_report.py | 1 - tasks/scripts/generate_python_proto.py | 72 - tasks/test.toml | 8 - uv.lock | 485 +-- 41 files changed, 54 insertions(+), 8186 deletions(-) delete mode 100644 python/credential_driver_proto_test.py delete mode 100644 python/generate_python_proto_test.py delete mode 100644 python/grpc_transport_test.py delete mode 100644 python/grpc_typing_test.py delete mode 100644 python/openshell/__init__.py delete mode 100644 python/openshell/_proto/__init__.py delete mode 100644 python/openshell/errors.py delete mode 100644 python/openshell/errors_test.py delete mode 100644 python/openshell/mutations.py delete mode 100644 python/openshell/openshell_test.py delete mode 100644 python/openshell/providers.py delete mode 100644 python/openshell/providers_test.py delete mode 100644 python/openshell/py.typed delete mode 100644 python/openshell/sandbox.py delete mode 100644 python/openshell/sandbox_cleanup_test.py delete mode 100644 python/openshell/sandbox_test.py delete mode 100644 tasks/scripts/generate_python_proto.py diff --git a/.agents/skills/update-docs/SKILL.md b/.agents/skills/update-docs/SKILL.md index 62dde17f4f..e67a3ab7e1 100644 --- a/.agents/skills/update-docs/SKILL.md +++ b/.agents/skills/update-docs/SKILL.md @@ -36,7 +36,7 @@ git log -50 --oneline --no-merges Filter to commits that are likely to affect docs. Look for these signals: 1. **Commit type**: `feat`, `fix`, `refactor`, `perf` commits often change behavior. `docs` commits are already doc changes. `chore`, `ci`, `test` commits rarely need doc updates. -2. **Files changed**: Changes to `crates/openshell-cli/`, `python/`, `proto/`, `deploy/`, gateway config parsing, driver config structs, or policy-related code are high-signal. +2. **Files changed**: Changes to `crates/openshell-cli/`, `proto/`, `deploy/`, gateway config parsing, driver config structs, or policy-related code are high-signal. 3. **Ignore**: Changes limited to `tests/`, `e2e/`, `.github/`, `tasks/`, or internal-only modules. ```bash @@ -60,7 +60,6 @@ For each relevant commit, determine which doc page(s) it affects. Use this mappi | `deploy/helm/openshell/templates/gateway-config.yaml` | `docs/how-it-works/gateways/configuration.mdx`, `docs/how-it-works/sandboxes/runtimes.mdx`, Helm docs if values change | | Proxy or policy code | `docs/how-it-works/policies/overview.mdx`, `docs/how-it-works/policies/schema.mdx` | | Inference code | `docs/inference/configure.mdx` | -| `python/` (SDK changes) | `docs/reference/` or `docs/get-started/quickstart.mdx` | | `proto/` (API changes) | `docs/reference/` | | `deploy/` (Dockerfile, Helm) | `docs/how-it-works/gateways/overview.mdx`, `docs/about/architecture.mdx` | | Sandbox image behavior | `docs/how-it-works/sandboxes/overview.mdx` | diff --git a/.gitattributes b/.gitattributes index 56d9e6abce..53bb4736d3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,11 +1,6 @@ # Mark auto-generated protobuf files so GitHub linguist ignores them in # diffs, stats, and language detection. -# Generated Python protobuf stubs -python/openshell/_proto/*_pb2.py linguist-generated -python/openshell/_proto/*_pb2_grpc.py linguist-generated -python/openshell/_proto/*_pb2.pyi linguist-generated - # Generated Rust protobuf code (excludes hand-written mod.rs) crates/openshell-core/src/proto/openshell.*.rs linguist-generated diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index f99e11894d..c20ebc6307 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -5,6 +5,11 @@ contact_links: about: > Install the public OpenShell skills for CLI usage, cluster and inference debugging, and policy generation. See CONTRIBUTING.md for details. + - name: Python SDK issue? + url: https://github.com/ai-openshell/sdk-python/issues + about: > + The Python SDK (the `openshell` package on PyPI) lives in + ai-openshell/sdk-python. Report SDK bugs and requests there. - name: Security vulnerability? url: https://github.com/ai-openshell/openshell/blob/main/SECURITY.md about: > diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml index 986c349658..005a5ae9aa 100644 --- a/.github/codeql/codeql-config.yml +++ b/.github/codeql/codeql-config.yml @@ -6,9 +6,7 @@ name: OpenShell Rust and SDKs paths: - crates - examples - - python/openshell paths-ignore: # Integration-test targets are not removed by the Rust cfg override. - crates/*/tests - - python/openshell/_proto diff --git a/.github/frozen-paths.toml b/.github/frozen-paths.toml index 594b6f2fa5..038980906d 100644 --- a/.github/frozen-paths.toml +++ b/.github/frozen-paths.toml @@ -24,14 +24,3 @@ paths = [ "tasks/scripts/vm", ".github/workflows/release-vm-kernel.yml", ] - -# The Python SDK moved to ai-openshell/sdk-python, which imported it at v0.1.7. -# Its files stay only until core removes them. The shared root pyproject.toml -# and uv.lock stay editable. -[[freeze]] -name = "python-sdk" -message = "The Python SDK moved to https://github.com/ai-openshell/sdk-python. Drop the Python SDK changes from this PR and open SDK changes there. Regenerated bindings are not needed here; sdk-python regenerates them from core releases." -paths = [ - "python", - "tasks/scripts/generate_python_proto.py", -] diff --git a/.github/prompts/compatibility-review.md b/.github/prompts/compatibility-review.md index d8e2cea704..71afb7fd4b 100644 --- a/.github/prompts/compatibility-review.md +++ b/.github/prompts/compatibility-review.md @@ -113,10 +113,10 @@ needed. ## Required surfaces -Account for every surface: `rust-sdk`, `python-sdk`, `api-behavior`, `cli`, -`configuration`, `policy`, `helm`, and `state`. The Go SDK moved to -ai-openshell/sdk-go and is not a surface of this repository. The TypeScript SDK -moved to ai-openshell/sdk-typescript and is not a surface of this repository. +Account for every surface: `rust-sdk`, `api-behavior`, `cli`, `configuration`, +`policy`, `helm`, and `state`. The Go SDK moved to ai-openshell/sdk-go, the +TypeScript SDK to ai-openshell/sdk-typescript, and the Python SDK to +ai-openshell/sdk-python; none is a surface of this repository. Scope `rust-sdk` to the public API reachable through `openshell-sdk`, including its `raw` module and transitive public re-exports. Trace the export path before diff --git a/.github/workflows/branch-checks.yml b/.github/workflows/branch-checks.yml index 411572ee33..3f90350535 100644 --- a/.github/workflows/branch-checks.yml +++ b/.github/workflows/branch-checks.yml @@ -221,7 +221,7 @@ jobs: sdk/conformance/oidc-token-bundle.json exclude: >- target/* e2e/rust/target/* plans/* architecture/plans/* - .cache/* .venv/* python/openshell/_proto/* + .cache/* .venv/* .github/* .agents/* .claude/* :(glob)**/node_modules/** .gitlab-ci.yml */.gitlab-ci.yml base: ${{ github.event.merge_group.base_sha || github.event.pull_request.base.sha }} @@ -622,9 +622,6 @@ jobs: - name: Typecheck run: mise run python:typecheck - - name: Test - run: mise run test:python - - name: Test Python scripts run: mise run test:python-scripts @@ -642,30 +639,6 @@ jobs: - name: Test labeling agent run: mise run test:labeling-agent - python-sdk-freeze: - # The Python SDK moved to ai-openshell/sdk-python (#5287). PRs must not add - # or change its files; deleting them is allowed (the removal PR). The paths - # and message live in .github/frozen-paths.toml ("python-sdk" freeze). - # Merge queue runs skip this job; the PR already passed it. - name: Python SDK Freeze - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Reject changes to the Python SDK - env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - # Compare against the PR head, not the checked-out merge commit: the - # recorded base SHA can lag main, and diffing the merge commit would - # then report main's own changes as the PR's. - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: python3 tasks/scripts/check_frozen_paths.py --group python-sdk --base "$BASE_SHA" --head "$HEAD_SHA" - markdown: name: Markdown runs-on: ubuntu-24.04 diff --git a/.gitignore b/.gitignore index 3e29a0cfb0..cc094d623b 100644 --- a/.gitignore +++ b/.gitignore @@ -53,7 +53,6 @@ share/python-wheels/ *.egg MANIFEST -python/*.data # Virtual environments .venv/ @@ -104,10 +103,6 @@ dmypy.json # Cython debug symbols cython_debug/ -# Generated Python protobuf stubs (keep package marker) -python/openshell/_proto/* -!python/openshell/_proto/__init__.py - # ============================================================================= # IDE / Editor # ============================================================================= diff --git a/.packit.yaml b/.packit.yaml index 88348841a7..c78fae3755 100644 --- a/.packit.yaml +++ b/.packit.yaml @@ -42,9 +42,8 @@ actions: - 'bash -c "sed -i -r \"s/^%global openshell_version .*/%global openshell_version ${PACKIT_RPMSPEC_VERSION}/\" openshell.spec"' # Update Release - 'bash -c "RELEASE=${OPENSHELL_RPM_RELEASE:-${PACKIT_RPMSPEC_RELEASE}} && sed -i -r \"s/^Release:(\\s*)\\S+/Release:\\1${RELEASE}%{?dist}/\" openshell.spec"' - # Keep embedded binary metadata aligned with the release workflow. Python - # dist-info stays at the RPM Version; dev build identity is carried by - # Release so Fedora's Python RPM post-processing can normalize metadata. + # Keep embedded binary metadata aligned with the release workflow. Dev + # build identity is carried by Release. - 'bash -c "if [ -n \"${OPENSHELL_CARGO_VERSION:-}\" ]; then sed -i -r \"s/^%global openshell_cargo_version .*/%global openshell_cargo_version ${OPENSHELL_CARGO_VERSION}/\" openshell.spec; fi"' jobs: diff --git a/AGENTS.md b/AGENTS.md index 0133dd3de3..6b4e1b44fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,6 @@ Do not rely on this file for a full inventory. The detailed public and contribut | `crates/openshell-supervisor-network/` | Network supervisor | Proxying, L7 enforcement, policy evaluation, and provider credential injection | | `crates/openshell-supervisor-process/` | Process supervisor | Process lifecycle, namespace, and bypass monitoring | | `crates/openshell-vfio/` | VFIO support | PCI and GPU passthrough preparation and lifecycle | -| `python/openshell/` | Python SDK (frozen) | Moved to ai-openshell/sdk-python; kept until removal | | `proto/` | Protobuf definitions | gRPC service contracts | | `tests/testkit/` | E2E testkit | Support library and `#[testkit::test]` attribute for SDK-driven E2E suites | | `tests/suites/` | E2E suites | One directory per test family, such as `conformance` | @@ -216,10 +215,9 @@ Create PRs with `gh pr create`, which enables "Allow edits by maintainers" by de - The Go SDK lives in [ai-openshell/sdk-go](https://github.com/ai-openshell/sdk-go) (module `github.com/ai-openshell/sdk-go`). Open SDK changes, including dependency and security updates, there; proto changes here need no Go bindings. -## Python SDK (`python/openshell/`) +## Python SDK -- The Python SDK moved to [ai-openshell/sdk-python](https://github.com/ai-openshell/sdk-python), which publishes `openshell` to PyPI. Open SDK changes there. -- `python/` and the SDK build script `tasks/scripts/generate_python_proto.py` are frozen until core removes them; Branch Checks fails PRs that change them. Put tests for core Python scripts next to the scripts, not under `python/`. +- The Python SDK lives in [ai-openshell/sdk-python](https://github.com/ai-openshell/sdk-python), which publishes `openshell` to PyPI. Open SDK changes there; proto changes here need no Python bindings. ## Python diff --git a/CI.md b/CI.md index 8eaf6b1787..4d53716b39 100644 --- a/CI.md +++ b/CI.md @@ -685,10 +685,7 @@ and reads the changed files through the API, so a pull request cannot edit its own rules. `.github/frozen-paths.toml` is the one place that lists frozen paths, each freeze -with its own failure message. It also holds the `python-sdk` freeze, which the -`Python SDK Freeze` job in `Branch Checks` enforces through the same script -(`--group python-sdk`); that job has no label bypass. Edit the file as moves -are decided. +with its own failure message. Edit the file as moves are decided. To bypass the check for a porting or removal pull request, a maintainer applies the `tmp:migrate` label; the check re-runs and passes. Run it @@ -789,7 +786,7 @@ Maintainers should add ready PRs to the queue rather than pressing a direct merg | `.github/workflows/review-readiness.yml` | Labels newly opened accepted-work PRs using the shared read-only acceptance library, including drafts; routes matching reviewers when a PR is ready and classified. | | `.github/workflows/workflow-security.yml` | Runs informational Actionlint and High-severity Zizmor reports on GitHub-hosted runners. | | `.github/workflows/dependency-review.yml` | Reports dependency changes when GitHub Dependency Graph is available; otherwise publishes a neutral warning. | -| `.github/workflows/codeql.yml` | Runs nightly informational CodeQL analysis on `main` for Rust and the Python SDK and retains SARIF artifacts. | +| `.github/workflows/codeql.yml` | Runs nightly informational CodeQL analysis on `main` for Rust, Python and JavaScript/TypeScript and retains SARIF artifacts. | | `.github/workflows/codex-security.yml` | Advisory scan during prerelease qualification; scans the stable-to-candidate diff and publishes train-scoped SARIF on `main`. | | `.github/workflows/codex-compatibility.yml` | Reviews branch and cumulative tagged-release compatibility with Codex and retains advisory findings, PR acknowledgements, and coverage; it does not gate merging or publication. | | `.github/workflows/trivy-changes.yml` | Blocks pull requests and merge groups that introduce new High or Critical Helm or Dockerfile misconfigurations. | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 214db74a21..0cba880c66 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -441,7 +441,6 @@ These are the primary `mise` tasks for day-to-day development: | `crates/openshell-policy-cedar-runtime/` | Cedar implementation of the shared runtime contracts, selected by supervisor composition | | `crates/openshell-policy-runtime-interface/` | Shared policy decisions, request metadata, snapshots, and staged reload contracts; no engine implementations | | `crates/openshell-prover-cli/` | Standalone local policy boundary checker | -| `python/` | Python SDK (frozen, moved to ai-openshell/sdk-python) | | `proto/` | Protocol buffer definitions and [public API conventions](proto/README.md) | | `tasks/` | `mise` task definitions and build scripts | | `tests/testkit/` | Support library for SDK-driven end-to-end suites | diff --git a/README.md b/README.md index 0752ddaf13..c6e12dbb29 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ SDKs connect applications to an OpenShell gateway. They do not install the CLI. | Language | Install | Docs | |---|---|---| -| Python | `uv add openshell` | [README](python/openshell/) | +| Python | `uv add openshell` | [ai-openshell/sdk-python](https://github.com/ai-openshell/sdk-python) | | TypeScript | `npm install @ai-openshell/sdk` | [ai-openshell/sdk-typescript](https://github.com/ai-openshell/sdk-typescript) | | Go | `go get github.com/ai-openshell/sdk-go@vX.Y.Z` | [ai-openshell/sdk-go](https://github.com/ai-openshell/sdk-go) | | Rust | `cargo add openshell-sdk --git https://github.com/ai-openshell/openshell --tag ` | [Installation and usage](docs/sdk/rust.mdx) | diff --git a/TESTING.md b/TESTING.md index 9c766747a5..6df2435f82 100644 --- a/TESTING.md +++ b/TESTING.md @@ -3,7 +3,7 @@ ## Running Tests ```bash -mise run test # Rust + Python unit tests +mise run test # Rust unit tests and Python script tests mise run e2e # End-to-end tests (starts a Docker-backed gateway) mise run ci # Everything: lint, compile checks, and tests ``` @@ -13,7 +13,6 @@ mise run ci # Everything: lint, compile checks, and tests ```text crates/*/src/ # Inline #[cfg(test)] modules crates/*/tests/ # Rust integration tests -python/openshell/ # Python unit tests (*_test.py suffix) e2e/workload/ # E2E Python image the sandboxes run python3, curl, and git from e2e/rust/ # Rust CLI E2E tests tests/testkit/ # Support library for SDK-driven E2E suites @@ -188,29 +187,12 @@ Windows token-file tests explicitly skip POSIX mode-bit assertions; those skips do not establish Windows ACL protection. Use a checkout with LF text files when running Unix-shell fixture checks. -## Python Unit Tests +## Python Script Tests -Python unit tests use the `*_test.py` suffix convention (not `test_*` prefix) -and live alongside the source in `python/openshell/`. They use mock-based -patterns with fake gRPC stubs: - -```python -def test_exec_python_serializes_callable_payload() -> None: - stub = _FakeStub() - client = _client_with_fake_stub(stub) - - def add(a: int, b: int) -> int: - return a + b - - result = client.exec_python("sandbox-1", add, args=(2, 3)) - assert result.exit_code == 0 -``` - -Run Python unit tests only: - -```bash -mise run test:python # uv run pytest python/ -``` +Tests for the repository's Python scripts use the `*_test.py` suffix and live +next to the script they test. `mise run test:python-scripts` runs the release, +RPM, E2E gateway config, and license header script tests; other script tests +have their own `test:*` tasks in `tasks/test.toml`. ## E2E Tests diff --git a/docs/sdk/python.mdx b/docs/sdk/python.mdx index ac806ef496..045058c728 100644 --- a/docs/sdk/python.mdx +++ b/docs/sdk/python.mdx @@ -15,7 +15,9 @@ when possible. ## Install the SDK -The package requires Python 3.11 or later. Add it to your project with `uv`: +The package requires Python 3.11 or later. It is developed in +[ai-openshell/sdk-python](https://github.com/ai-openshell/sdk-python) and +published to PyPI. Add it to your project with `uv`: ```shell uv add openshell diff --git a/mise.toml b/mise.toml index 7952f95571..17fd067011 100644 --- a/mise.toml +++ b/mise.toml @@ -71,7 +71,7 @@ DOCKER_BUILDKIT = "1" [vars] # Python paths to include in formatting/linting -python_paths = "python/ tasks/scripts/*.py e2e/mcp-conformance/*.py e2e/kubernetes/app-listener/*.py deploy/sbom/*.py deploy/rpm/*.py e2e/configs/gateway/*.py" +python_paths = "tasks/scripts/*.py e2e/mcp-conformance/*.py e2e/kubernetes/app-listener/*.py deploy/sbom/*.py deploy/rpm/*.py e2e/configs/gateway/*.py" [task_config] includes = ["tasks/*.toml"] diff --git a/openshell.spec b/openshell.spec index a226b5eb83..74118c6629 100644 --- a/openshell.spec +++ b/openshell.spec @@ -4,9 +4,6 @@ %global crate openshell %global openshell_version 0.0.37 %global openshell_cargo_version %{openshell_version} -# Python dist-info metadata intentionally follows the RPM Version. Dev build -# identity is represented by Release for RPM packages. -%global openshell_python_version %{openshell_version} # Cargo/Rust builds with vendored deps do not produce debugsource listings # in the format redhat-rpm-config expects (especially on EPEL). @@ -21,7 +18,7 @@ Summary: Safe, sandboxed runtimes for autonomous AI agents # crates; this is the minimal SPDX expression covering every crate linked into # openshell, openshell-gateway and openshell-prover (computed from `cargo tree` # license metadata, treating "X OR MIT" as satisfied by MIT or Apache-2.0). -# The docs, man page sources, config templates and Python SDK sources carry +# The docs, man page sources and config templates carry # Apache-2.0 SPDX headers or fall under the repository LICENSE. The unit file is # generated from this spec. Re-check when Cargo.lock changes. License: Apache-2.0 AND BSD-3-Clause AND CC0-1.0 AND CDLA-Permissive-2.0 AND ISC AND MIT AND Unicode-3.0 AND Zlib @@ -39,13 +36,14 @@ BuildRequires: systemd-rpm-macros # Man page generation BuildRequires: pandoc -# Python sub-package build dependencies -BuildRequires: python3-devel - # Runtime: container runtime for package-managed gateway sandboxes. # The gateway auto-detects Podman when the package-managed service starts. Recommends: podman +# The Python SDK sub-package was dropped when the SDK moved to +# https://github.com/ai-openshell/sdk-python, which publishes it to PyPI. +Obsoletes: python3-%{name} < %{version}-%{release} + %description OpenShell provides safe, sandboxed runtimes for autonomous AI agents. It offers a CLI for managing gateway registrations, sandboxes, and providers with @@ -73,25 +71,6 @@ Summary: Standalone OpenShell policy boundary prover OpenShell policy prover for checking whether a local candidate policy stays within an operator-supplied maximum without connecting to a gateway. -# --- Python SDK sub-package --- -%package -n python3-%{name} -Summary: OpenShell Python SDK for agent execution and management -# Pure Python; links none of the crates covered by the main License tag. -License: Apache-2.0 -# Use Recommends instead of Requires because Fedora 43+ ships older -# versions of grpcio (1.48) and protobuf (3.19) than the SDK needs. -# Users on distros with older packages can install these via pip/uv. -Recommends: python3-cloudpickle >= 3.0 -Recommends: python3-googleapis-common-protos >= 1.63 -Recommends: python3-grpcio >= 1.60 -Recommends: python3-httpx >= 0.27 -Recommends: python3-protobuf >= 4.25 -Recommends: %{name} - -%description -n python3-%{name} -Python SDK for OpenShell providing programmatic access to sandbox -management, agent execution, and provider access via gRPC. - %prep %autosetup -n %{name}-%{version} @@ -213,42 +192,6 @@ install -pm 0644 deploy/rpm/TROUBLESHOOTING.md %{buildroot}%{_docdir}/%{name}-ga install -Dpm 0644 openshell.1 %{buildroot}%{_mandir}/man1/openshell.1 install -Dpm 0644 openshell-gateway.8 %{buildroot}%{_mandir}/man8/openshell-gateway.8 -# --- Python SDK --- -# Install Python SDK modules (test files are intentionally excluded) -install -d %{buildroot}%{python3_sitelib}/%{name} -install -d %{buildroot}%{python3_sitelib}/%{name}/_proto - -install -pm 0644 python/%{name}/__init__.py %{buildroot}%{python3_sitelib}/%{name}/ -install -pm 0644 python/%{name}/errors.py %{buildroot}%{python3_sitelib}/%{name}/ -install -pm 0644 python/%{name}/mutations.py %{buildroot}%{python3_sitelib}/%{name}/ -install -pm 0644 python/%{name}/providers.py %{buildroot}%{python3_sitelib}/%{name}/ -install -pm 0644 python/%{name}/sandbox.py %{buildroot}%{python3_sitelib}/%{name}/ -install -pm 0644 python/%{name}/py.typed %{buildroot}%{python3_sitelib}/%{name}/ -install -pm 0644 python/%{name}/_proto/__init__.py %{buildroot}%{python3_sitelib}/%{name}/_proto/ -install -pm 0644 python/%{name}/_proto/*.py %{buildroot}%{python3_sitelib}/%{name}/_proto/ - -# Create dist-info so importlib.metadata can resolve the package version -install -d %{buildroot}%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-info -cat > %{buildroot}%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-info/METADATA << EOF -Metadata-Version: 2.1 -Name: %{name} -Version: %{openshell_python_version} -Summary: OpenShell Python SDK for agent execution and management -License: Apache-2.0 -Requires-Python: >=3.12 -Requires-Dist: cloudpickle>=3.0 -Requires-Dist: googleapis-common-protos>=1.63 -Requires-Dist: grpcio>=1.60 -Requires-Dist: httpx>=0.27 -Requires-Dist: protobuf>=4.25 -EOF - -# INSTALLER marker per PEP 376 -echo "rpm" > %{buildroot}%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-info/INSTALLER - -# RECORD can be empty for RPM-managed installs -touch %{buildroot}%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-info/RECORD - %check # Smoke-test the CLI binary %{buildroot}%{_bindir}/%{name} --version @@ -259,28 +202,6 @@ touch %{buildroot}%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-in # Smoke-test the gateway binary %{buildroot}%{_bindir}/%{name}-gateway --version -# Smoke-test the Python SDK version metadata via importlib.metadata. -# We query the dist-info directly rather than importing the package because -# the full import pulls in grpcio and other runtime deps not present in the -# build environment. -PYTHONPATH=%{buildroot}%{python3_sitelib} %{python3} -c "from importlib.metadata import version; v = version('openshell'); print(v); assert v == '%{openshell_python_version}', f'expected %{openshell_python_version}, got {v}'" - -# Verify every module the installed SDK pulls in with a relative import was -# installed. Importing the package needs grpcio, which the build environment -# does not have, so check the imports statically. -%{python3} - %{buildroot}%{python3_sitelib}/%{name} <<'PY' -import ast, pathlib, sys -pkg = pathlib.Path(sys.argv[1]) -missing = [] -for source in pkg.glob("*.py"): - for node in ast.walk(ast.parse(source.read_text())): - if isinstance(node, ast.ImportFrom) and node.level == 1 and node.module: - base = pkg.joinpath(*node.module.split(".")) - if not (base.with_suffix(".py").exists() or (base / "__init__.py").exists()): - missing.append(f"{source.name}: .{node.module}") -assert not missing, f"installed SDK imports modules that were not installed: {missing}" -PY - # Verify the RPM default TOML config template was installed. # A missing template means first-start seeding silently falls back to the # binary default of 127.0.0.1, which breaks Podman sandbox connectivity. @@ -331,10 +252,5 @@ grep -q 'gateway.toml.default.v1' %{buildroot}%{_userunitdir}/%{name}-gateway.se %{_datadir}/%{name}-gateway/gateway.toml.default.v1 %{_mandir}/man8/openshell-gateway.8* -%files -n python3-%{name} -%license LICENSE -%{python3_sitelib}/%{name}/ -%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-info/ - %changelog %autochangelog diff --git a/pyproject.toml b/pyproject.toml index 099699db54..53a7db18c8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,84 +1,29 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -[build-system] -requires = ["setuptools>=84.1.0", "setuptools-scm[simple]>=8"] -build-backend = "setuptools.build_meta" - +# Python tooling for this repository's scripts and checks. Core ships no Python +# package: the Python SDK lives in https://github.com/ai-openshell/sdk-python. [project] -name = "openshell" -dynamic = ["version"] -description = "OpenShell is the safe, private runtime for autonomous AI agents. " -license = "Apache-2.0" -readme = "README.md" -authors = [{ name = "NVIDIA Inc." }] +name = "openshell-tooling" +version = "0.0.0" requires-python = ">=3.11" -dependencies = [ - "cloudpickle>=3.0", - "grpcio>=1.60", - "googleapis-common-protos>=1.63", - "httpx>=0.27", - "protobuf>=4.25", -] -classifiers = [ - "Development Status :: 3 - Alpha", - "Intended Audience :: Developers", - "Intended Audience :: Science/Research", - "Intended Audience :: Information Technology", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Programming Language :: Python :: 3.14", - "Topic :: Security", - "Topic :: Scientific/Engineering", - "Topic :: Scientific/Engineering :: Artificial Intelligence", - "Operating System :: POSIX :: Linux", - "Operating System :: MacOS :: MacOS X", -] -keywords = ["agent", "sandbox", "nvidia"] -[project.urls] -source = "https://github.com/ai-openshell/openshell" -documentation = "https://docs.nvidia.com/openshell/latest/" +[tool.uv] +package = false [dependency-groups] dev = [ "pytest>=9.0.3", - "pytest-asyncio>=0.23", - "pytest-cov>=4.0", - "pytest-xdist>=3.0", "ruff>=0.4", "ty>=0.0.94", - "grpcio-tools>=1.60", "pyelftools>=0.30", "pyyaml==6.0.2", "types-pyyaml>=6.0.12.20260518", - "mypy-protobuf>=5.1", - "types-grpcio>=1.0.0.20251009", - "types-protobuf>=6.32,<7", ] -[tool.setuptools] -package-dir = { "" = "python" } -include-package-data = false - -[tool.setuptools.packages.find] -where = ["python"] -include = ["openshell*"] -namespaces = false - -[tool.setuptools.package-data] -openshell = ["py.typed", "_proto/*.py", "_proto/*.pyi"] - -# Ignore non-release tags such as sdk/go/vX.Y.Z, which share the release commit. -[tool.setuptools_scm] -git_describe_command = ["git", "describe", "--dirty", "--tags", "--long", "--match", "v[0-9]*"] - [tool.ruff] target-version = "py311" line-length = 88 -exclude = ["python/openshell/_proto"] [tool.ruff.lint] select = [ @@ -99,9 +44,6 @@ ignore = [ "E501", # line too long (handled by formatter) ] -[tool.ruff.lint.isort] -known-first-party = ["openshell"] - [tool.ruff.format] quote-style = "double" indent-style = "space" @@ -109,23 +51,6 @@ skip-magic-trailing-comma = false line-ending = "auto" [tool.pytest.ini_options] -testpaths = ["python"] python_files = ["*_test.py"] python_functions = ["test_*"] addopts = "-v --tb=short" -asyncio_mode = "auto" -markers = [ - "gpu: requires a GPU-capable gateway and GPU-enabled sandbox image", -] - -[tool.coverage.run] -source = ["python"] -branch = true - -[tool.coverage.report] -exclude_lines = [ - "pragma: no cover", - "def __repr__", - "raise NotImplementedError", - "if TYPE_CHECKING:", -] diff --git a/python/credential_driver_proto_test.py b/python/credential_driver_proto_test.py deleted file mode 100644 index f3bd96289d..0000000000 --- a/python/credential_driver_proto_test.py +++ /dev/null @@ -1,58 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Credential-driver bindings must share SDK datamodel types and dispatch RPCs.""" - -import grpc.aio -import pytest - -from openshell._proto import credential_driver_pb2 as credentials -from openshell._proto import credential_driver_pb2_grpc as driver_grpc -from openshell._proto import datamodel_pb2 as datamodel -from openshell._proto import extension_pb2 as extension -from openshell._proto import openshell_pb2 as gateway - - -def test_driver_messages_share_sdk_descriptors() -> None: - request = credentials.ResolveCredentialRequest( - handle=datamodel.CredentialHandle(driver="test", handle="opaque"), - ) - assert isinstance(request.handle, datamodel.CredentialHandle) - assert request.handle.DESCRIPTOR is datamodel.CredentialHandle.DESCRIPTOR - assert ( - credentials.GetCredentialDriverCapabilitiesRequest( - gateway=extension.PeerMetadata() - ).gateway.DESCRIPTOR - is extension.PeerMetadata.DESCRIPTOR - ) - assert ( - gateway.CreateProviderRequest().provider.DESCRIPTOR - is datamodel.Provider.DESCRIPTOR - ) - - -@pytest.mark.asyncio -async def test_generated_servicer_and_stub_exchange() -> None: - class Driver(driver_grpc.CredentialDriverServicer): - async def StoreCredential(self, request, context): # noqa: ARG002 - assert request.value == "registration-ticket" - return credentials.StoreCredentialResponse( - handle=datamodel.CredentialHandle(driver="test", handle="opaque") - ) - - server = grpc.aio.server() - driver_grpc.add_CredentialDriverServicer_to_server(Driver(), server) - address = "127.0.0.1" - port = server.add_insecure_port(f"{address}:0") - await server.start() - try: - async with grpc.aio.insecure_channel(f"{address}:{port}") as channel: - stub = driver_grpc.CredentialDriverStub(channel) - result = await stub.StoreCredential( - credentials.StoreCredentialRequest(value="registration-ticket"), - timeout=5, - ) - assert isinstance(result.handle, datamodel.CredentialHandle) - assert result.handle.handle == "opaque" - finally: - await server.stop(0) diff --git a/python/generate_python_proto_test.py b/python/generate_python_proto_test.py deleted file mode 100644 index b242c375e5..0000000000 --- a/python/generate_python_proto_test.py +++ /dev/null @@ -1,59 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Exercise generation in a clean tree so stale bindings cannot hide failures.""" - -import ast -import shutil -import subprocess -import sys -from pathlib import Path - -import pytest - - -@pytest.mark.parametrize("no_pyi", [False, True]) -def test_generate_package_relative_bindings(tmp_path: Path, no_pyi: bool) -> None: - root = Path(__file__).resolve().parents[1] - shutil.copytree(root / "proto", tmp_path / "proto") - output = tmp_path / "python/openshell/_proto" - output.mkdir(parents=True) - command = [ - sys.executable, - str(root / "tasks/scripts/generate_python_proto.py"), - *(["--no-pyi"] if no_pyi else []), - ] - subprocess.run(command, cwd=tmp_path, check=True, capture_output=True, text=True) - - stems = { - "credential_driver", - "datamodel", - "extension", - "openshell", - "options", - "sandbox", - } - suffixes = ["_pb2.py", "_pb2_grpc.py"] - if not no_pyi: - suffixes.extend(["_pb2.pyi", "_pb2_grpc.pyi"]) - assert {path.name for path in output.iterdir()} == { - f"{stem}{suffix}" for stem in stems for suffix in suffixes - } - for path in output.iterdir(): - for node in ast.walk(ast.parse(path.read_text())): - if isinstance(node, ast.Import): - assert not any(alias.name.endswith("_pb2") for alias in node.names), ( - f"Absolute generated import in {path.name}" - ) - - # Skipping type generation must also leave existing stubs untouched. - sentinel = output / "credential_driver_pb2.pyi" - sentinel.write_text("# existing type stub\n") - subprocess.run( - command if no_pyi else [*command, "--no-pyi"], - cwd=tmp_path, - check=True, - capture_output=True, - text=True, - ) - assert sentinel.read_text() == "# existing type stub\n" diff --git a/python/grpc_transport_test.py b/python/grpc_transport_test.py deleted file mode 100644 index 52ce86a16e..0000000000 --- a/python/grpc_transport_test.py +++ /dev/null @@ -1,101 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Generated async stubs retain native gRPC transport behavior.""" - -import asyncio -from collections.abc import AsyncGenerator -from contextlib import asynccontextmanager - -import grpc -import grpc.aio -import pytest - -from openshell._proto import datamodel_pb2 as dm -from openshell._proto import openshell_pb2 as pb -from openshell._proto import openshell_pb2_grpc as rpc - - -class Gateway(rpc.OpenShellServicer): - def __init__(self) -> None: - self.started = asyncio.Event() - self.cancelled = asyncio.Event() - - async def GetProvider( - self, request: pb.GetProviderRequest, context: grpc.aio.ServicerContext - ) -> pb.ProviderResponse: - assert ("authorization", "Bearer test-token") in ( - context.invocation_metadata() or () - ) - if request.name == "missing": - await context.abort(grpc.StatusCode.NOT_FOUND, "No provider") - if request.name == "blocked": - self.started.set() - try: - await asyncio.Future() - finally: - self.cancelled.set() - return pb.ProviderResponse( - provider=dm.Provider(metadata=dm.ObjectMeta(name=request.name)) - ) - - -@asynccontextmanager -async def gateway() -> AsyncGenerator[tuple[Gateway, grpc.aio.Channel]]: - service = Gateway() - server = grpc.aio.server() - rpc.add_OpenShellServicer_to_server(service, server) - port = server.add_insecure_port("127.0.0.1:0") - await server.start() - try: - async with grpc.aio.insecure_channel(f"127.0.0.1:{port}") as channel: - yield service, channel - finally: - await server.stop(0) - - -_METADATA = (("authorization", "Bearer test-token"),) - - -async def test_concurrent_calls_and_task_cancellation() -> None: - async with gateway() as (service, channel): - stub = rpc.OpenShellStub(channel) - - async def blocked_call() -> pb.ProviderResponse: - return await stub.GetProvider( - pb.GetProviderRequest(name="blocked"), timeout=5, metadata=_METADATA - ) - - pending = asyncio.create_task(blocked_call()) - try: - await asyncio.wait_for(service.started.wait(), timeout=5) - response = await stub.GetProvider( - pb.GetProviderRequest(name="ready"), timeout=5, metadata=_METADATA - ) - assert response.provider.metadata.name == "ready" - finally: - pending.cancel() - with pytest.raises(asyncio.CancelledError): - await pending - await asyncio.wait_for(service.cancelled.wait(), timeout=5) - response = await stub.GetProvider( - pb.GetProviderRequest(name="still-ready"), timeout=5, metadata=_METADATA - ) - assert response.provider.metadata.name == "still-ready" - - -@pytest.mark.parametrize( - ("name", "expected"), - [ - ("missing", grpc.StatusCode.NOT_FOUND), - ("blocked", grpc.StatusCode.DEADLINE_EXCEEDED), - ], -) -async def test_status_and_deadline(name: str, expected: grpc.StatusCode) -> None: - async with gateway() as (_, channel): - stub = rpc.OpenShellStub(channel) - with pytest.raises(grpc.aio.AioRpcError) as error: - await stub.GetProvider( - pb.GetProviderRequest(name=name), timeout=0.2, metadata=_METADATA - ) - assert error.value.code() == expected diff --git a/python/grpc_typing_test.py b/python/grpc_typing_test.py deleted file mode 100644 index cfb4342dc7..0000000000 --- a/python/grpc_typing_test.py +++ /dev/null @@ -1,81 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Check the consumer-facing types of generated sync and async RPCs.""" - -import subprocess -import sys -from pathlib import Path - -import pytest - - -@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) -def test_generated_rpc_types(tmp_path: Path, asynchronous: bool) -> None: - channel = "grpc.aio.Channel" if asynchronous else "grpc.Channel" - function = "async def" if asynchronous else "def" - await_call = "await " if asynchronous else "" - iterate = "async for" if asynchronous else "for" - source = f""" -from typing import assert_type -import grpc -import grpc.aio -from openshell._proto import credential_driver_pb2 as credentials -from openshell._proto import credential_driver_pb2_grpc as driver -from openshell._proto import openshell_pb2 as pb -from openshell._proto import openshell_pb2_grpc as rpc - -{function} check(channel: {channel}) -> None: - stub = rpc.OpenShellStub(channel) - assert_type({await_call}stub.GetProvider(pb.GetProviderRequest()), pb.ProviderResponse) - assert_type({await_call}stub.CreateProvider(pb.CreateProviderRequest()), pb.ProviderResponse) - assert_type({await_call}stub.UpdateProvider(pb.UpdateProviderRequest()), pb.ProviderResponse) - assert_type({await_call}stub.DeleteProvider(pb.DeleteProviderRequest()), pb.DeleteProviderResponse) - assert_type({await_call}stub.ListProviders(pb.ListProvidersRequest()), pb.ListProvidersResponse) - assert_type({await_call}stub.GetProviderProfile(pb.GetProviderProfileRequest()), pb.ProviderProfileResponse) - assert_type({await_call}stub.GetSandbox(pb.GetSandboxRequest()), pb.SandboxResponse) - assert_type({await_call}stub.DetachSandboxProvider(pb.DetachSandboxProviderRequest()), pb.DetachSandboxProviderResponse) - {iterate} event in stub.ExecSandbox(pb.ExecSandboxRequest()): - assert_type(event, pb.ExecSandboxEvent) - {iterate} frame in stub.ForwardTcp(iter([pb.TcpForwardFrame()])): - assert_type(frame, pb.TcpForwardFrame) - credential_stub = driver.CredentialDriverStub(channel) - assert_type({await_call}credential_stub.StoreCredential(credentials.StoreCredentialRequest()), credentials.StoreCredentialResponse) -""" - path = tmp_path / "consumer.py" - path.write_text(source) - result = _check_types(path) - assert result.returncode == 0, result.stdout + result.stderr - - # A missing import or Any-typed callable must not make this test pass. - path.write_text( - source.replace( - "stub.GetProvider(pb.GetProviderRequest())", - "stub.GetProvider(pb.DeleteProviderRequest())", - ) - ) - result = _check_types(path) - assert result.returncode != 0 - assert "invalid-argument-type" in result.stdout - assert "GetProviderRequest" in result.stdout - assert "DeleteProviderRequest" in result.stdout - - -def _check_types(path: Path) -> subprocess.CompletedProcess[str]: - return subprocess.run( - [ - sys.executable, - "-m", - "ty", - "check", - "--python", - sys.executable, - "--output-format", - "concise", - str(path), - ], - cwd=Path(__file__).resolve().parents[1], - capture_output=True, - text=True, - check=False, - ) diff --git a/python/openshell/__init__.py b/python/openshell/__init__.py deleted file mode 100644 index c99c3b48e0..0000000000 --- a/python/openshell/__init__.py +++ /dev/null @@ -1,69 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""OpenShell - Agent execution and management SDK.""" - -from __future__ import annotations - -from .errors import ErrorInfo, FieldViolation, GatewayError, from_grpc_error -from .mutations import DeletionOutcome, DeletionResult -from .providers import ProviderClient, ProviderCredentialValue -from .sandbox import ( - ClientCredentialsAuth, - ExecChunk, - ExecResult, - Page, - Pager, - Sandbox, - SandboxClient, - SandboxConditionRef, - SandboxError, - SandboxRef, - SandboxSession, - SandboxStatusRef, - SandboxTemplateClient, - SandboxWorkloadTemplateProvenanceRef, - ServiceAuthorizationMode, - ServiceExposure, - TlsConfig, - WorkspaceClient, - WorkspaceRef, -) - -try: - from importlib.metadata import version - - __version__ = version("openshell") -except Exception: - __version__ = "0.0.0" - -__all__ = [ - "ClientCredentialsAuth", - "DeletionOutcome", - "DeletionResult", - "ErrorInfo", - "ExecChunk", - "ExecResult", - "FieldViolation", - "GatewayError", - "Page", - "Pager", - "ProviderClient", - "ProviderCredentialValue", - "Sandbox", - "SandboxClient", - "SandboxConditionRef", - "SandboxError", - "SandboxRef", - "SandboxSession", - "SandboxStatusRef", - "SandboxTemplateClient", - "SandboxWorkloadTemplateProvenanceRef", - "ServiceAuthorizationMode", - "ServiceExposure", - "TlsConfig", - "WorkspaceClient", - "WorkspaceRef", - "__version__", - "from_grpc_error", -] diff --git a/python/openshell/_proto/__init__.py b/python/openshell/_proto/__init__.py deleted file mode 100644 index ee4cf2db8b..0000000000 --- a/python/openshell/_proto/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from . import datamodel_pb2, openshell_pb2 - -# Sandbox messages and phase enums moved into openshell.proto. Keep aliases on -# datamodel_pb2 so existing Python callers and E2E tests continue to work. -for _name in ( - "Sandbox", - "SandboxSpec", - "SandboxTemplate", -): - if not hasattr(datamodel_pb2, _name): - setattr(datamodel_pb2, _name, getattr(openshell_pb2, _name)) - -for _name in dir(openshell_pb2): - if _name.startswith("SANDBOX_PHASE_") and not hasattr(datamodel_pb2, _name): - setattr(datamodel_pb2, _name, getattr(openshell_pb2, _name)) diff --git a/python/openshell/errors.py b/python/openshell/errors.py deleted file mode 100644 index f1085e1a36..0000000000 --- a/python/openshell/errors.py +++ /dev/null @@ -1,149 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Typed gateway errors that retain the original gRPC status and metadata.""" - -from __future__ import annotations - -from dataclasses import dataclass - -import grpc -from google.protobuf.message import DecodeError -from google.rpc import error_details_pb2, status_pb2 - - -@dataclass(frozen=True) -class FieldViolation: - """A request field rejected by the gateway.""" - - field: str - description: str - - -@dataclass(frozen=True) -class ErrorInfo: - """A machine-readable error reason scoped to its producing service.""" - - reason: str - domain: str - metadata: dict[str, str] - - -class GatewayError(grpc.RpcError): - """A gRPC failure with decoded standard details. - - ``raw_error`` retains the complete original exception and metadata. - ``raw_status`` retains all decoded Any messages, including unknown types. - A retry delay is guidance only; it does not make a mutation safe to repeat. - Existing ``except grpc.RpcError`` handlers continue to match this type. - """ - - def __init__(self, error: grpc.RpcError) -> None: - super().__init__(str(error)) - self.raw_error = error - self.raw_status: status_pb2.Status | None = None - self.field_violations: tuple[FieldViolation, ...] = () - self.error_info: ErrorInfo | None = None - self.retry_delay: float | None = None - trailing = getattr(error, "trailing_metadata", lambda: None)() or () - for key, value in trailing: - if key != "grpc-status-details-bin" or not isinstance(value, bytes): - continue - try: - status = status_pb2.Status.FromString(value) - except DecodeError: - continue - # The transport status is authoritative. Inconsistent rich status - # must not provide misleading recovery guidance. - code = self.code() - if ( - code is None - or status.code != code.value[0] - or status.message != self.details() - ): - continue - self.raw_status = status - break - if self.raw_status is None: - return - violations = [] - for detail in self.raw_status.details: - try: - if detail.Is(error_details_pb2.BadRequest.DESCRIPTOR): - bad_request = error_details_pb2.BadRequest() - detail.Unpack(bad_request) - violations.extend( - FieldViolation(v.field, v.description) - for v in bad_request.field_violations - ) - elif detail.Is(error_details_pb2.ErrorInfo.DESCRIPTOR): - info = error_details_pb2.ErrorInfo() - detail.Unpack(info) - self.error_info = ErrorInfo( - info.reason, info.domain, dict(info.metadata) - ) - elif detail.Is(error_details_pb2.RetryInfo.DESCRIPTOR): - retry = error_details_pb2.RetryInfo() - detail.Unpack(retry) - delay = retry.retry_delay - if ( - retry.HasField("retry_delay") - and 0 <= delay.seconds <= 315_576_000_000 - and 0 <= delay.nanos < 1_000_000_000 - ): - self.retry_delay = delay.seconds + delay.nanos / 1_000_000_000 - except DecodeError: - continue - self.field_violations = tuple(violations) - - def code(self): - """Return the original gRPC status code.""" - return getattr(self.raw_error, "code", lambda: None)() - - def details(self): - """Return the original human-readable gRPC message.""" - return getattr(self.raw_error, "details", lambda: str(self.raw_error))() - - def __getattr__(self, name): - return getattr(self.raw_error, name) - - -def from_grpc_error(error: grpc.RpcError) -> GatewayError: - """Decode a raw RPC failure without discarding unrecognized details.""" - return error if isinstance(error, GatewayError) else GatewayError(error) - - -class _ErrorMappingStream: - def __init__(self, call): - self._call = call - self._iterator = iter(call) - - def __iter__(self): - return self - - def __next__(self): - try: - return next(self._iterator) - except grpc.RpcError as error: - raise from_grpc_error(error) from error - - def __getattr__(self, name): - return getattr(self._call, name) - - -class _ErrorMappingInterceptor( - grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor -): - def intercept_unary_unary(self, continuation, client_call_details, request): - call = continuation(client_call_details, request) - error = call.exception() - if isinstance(error, grpc.RpcError): - raise from_grpc_error(error) from error - return call - - def intercept_unary_stream(self, continuation, client_call_details, request): - return _ErrorMappingStream(continuation(client_call_details, request)) - - -def _error_mapping_channel(channel): - return grpc.intercept_channel(channel, _ErrorMappingInterceptor()) diff --git a/python/openshell/errors_test.py b/python/openshell/errors_test.py deleted file mode 100644 index a60b6fe360..0000000000 --- a/python/openshell/errors_test.py +++ /dev/null @@ -1,127 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Rich error decoding and preservation across unary and streaming calls.""" - -from concurrent import futures - -import grpc -import pytest -from google.rpc import error_details_pb2, status_pb2 - -from openshell.errors import GatewayError, _error_mapping_channel, from_grpc_error - - -def rich_status(): - status = status_pb2.Status( - code=grpc.StatusCode.UNAVAILABLE.value[0], message="try later" - ) - retry = error_details_pb2.RetryInfo() - retry.retry_delay.seconds = 1 - retry.retry_delay.nanos = 250_000_000 - for message in [ - error_details_pb2.BadRequest( - field_violations=[ - error_details_pb2.BadRequest.FieldViolation( - field="name", description="invalid name" - ), - ] - ), - error_details_pb2.ErrorInfo( - reason="GATEWAY_NOT_READY", - domain="openshell.nvidia.com", - metadata={"scope": "test"}, - ), - retry, - ]: - detail = status.details.add() - detail.Pack(message) - status.details.add( - type_url="type.googleapis.com/future.ErrorDetail", value=b"\x08\x01" - ) - return status - - -@pytest.mark.parametrize("streaming", [False, True]) -def test_maps_real_rpc_errors_without_losing_details(streaming): - status = rich_status() - - def fail(_request, context): - context.set_trailing_metadata( - ( - ("grpc-status-details-bin", status.SerializeToString()), - ("request-id", "test-correlation"), - ) - ) - context.abort(grpc.StatusCode.UNAVAILABLE, "try later") - - server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) - handler = ( - grpc.unary_stream_rpc_method_handler - if streaming - else grpc.unary_unary_rpc_method_handler - ) - server.add_generic_rpc_handlers( - (grpc.method_handlers_generic_handler("test.Errors", {"Fail": handler(fail)}),) - ) - port = server.add_insecure_port("127.0.0.1:0") - server.start() - try: - with _error_mapping_channel( - grpc.insecure_channel(f"127.0.0.1:{port}") - ) as channel: - call = channel.unary_stream if streaming else channel.unary_unary - with pytest.raises(GatewayError) as caught: - response = call("/test.Errors/Fail")(b"", timeout=5) - if streaming: - list(response) - error = caught.value - assert error.code() == grpc.StatusCode.UNAVAILABLE - assert error.details() == "try later" - assert error.field_violations[0].field == "name" - assert error.error_info is not None - assert error.error_info.reason == "GATEWAY_NOT_READY" - assert error.retry_delay == 1.25 - assert error.raw_status == status - assert ("request-id", "test-correlation") in error.trailing_metadata() - assert from_grpc_error(error) is error - finally: - server.stop(0).wait() - - -class RawError(grpc.RpcError): - def __init__(self, details): - self._details = details - - def code(self): - return grpc.StatusCode.UNAVAILABLE - - def details(self): - return "try later" - - def trailing_metadata(self): - return [("grpc-status-details-bin", self._details)] - - -def test_malformed_or_inconsistent_details_preserve_raw_error(): - for payload in [ - b"\xff", - status_pb2.Status(code=3, message="different").SerializeToString(), - ]: - raw = RawError(payload) - error = from_grpc_error(raw) - assert error.raw_error is raw - assert error.raw_status is None - assert error.retry_delay is None - assert error.trailing_metadata() == raw.trailing_metadata() - - -def test_malformed_known_detail_does_not_hide_other_details(): - status = rich_status() - status.details.add( - type_url="type.googleapis.com/google.rpc.BadRequest", value=b"\xff" - ) - error = from_grpc_error(RawError(status.SerializeToString())) - assert error.field_violations[0].field == "name" - assert error.raw_status is not None - assert len(error.raw_status.details) == 5 diff --git a/python/openshell/mutations.py b/python/openshell/mutations.py deleted file mode 100644 index efa538c95a..0000000000 --- a/python/openshell/mutations.py +++ /dev/null @@ -1,33 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Typed mutation results, separate from transport success.""" - -from dataclasses import dataclass -from enum import IntEnum - - -class DeletionOutcome(IntEnum): - """Only COMPLETED and ALREADY_ABSENT establish logical deletion completion.""" - - UNSPECIFIED = 0 - COMPLETED = 1 - ACCEPTED = 2 - ALREADY_ABSENT = 3 - - @classmethod - def _missing_(cls, value): - if not isinstance(value, int): - return None - member = int.__new__(cls, value) - member._name_ = f"UNKNOWN_{value}" - member._value_ = value - return member - - -@dataclass(frozen=True) -class DeletionResult: - """Outcome for the original target; unknown outcomes never imply completion.""" - - outcome: DeletionOutcome - sandbox_id: str | None = None diff --git a/python/openshell/openshell_test.py b/python/openshell/openshell_test.py deleted file mode 100644 index 101b7b6833..0000000000 --- a/python/openshell/openshell_test.py +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Basic tests for the openshell package.""" - -import openshell - - -def test_version() -> None: - """Test that version is defined.""" - assert openshell.__version__ - - -def test_sandbox_template_client_exported() -> None: - assert openshell.SandboxTemplateClient diff --git a/python/openshell/providers.py b/python/openshell/providers.py deleted file mode 100644 index f3312f5407..0000000000 --- a/python/openshell/providers.py +++ /dev/null @@ -1,111 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Privileged provider credential retrieval over the caller's gRPC channel.""" - -from __future__ import annotations - -import re -from dataclasses import dataclass, field -from datetime import UTC, datetime, timedelta -from typing import TYPE_CHECKING - -from ._proto import datamodel_pb2, openshell_pb2, openshell_pb2_grpc -from .errors import _error_mapping_channel - -if TYPE_CHECKING: - from collections.abc import Sequence - - import grpc - - from .sandbox import SandboxClient - - -@dataclass(frozen=True) -class ProviderCredentialValue: - """An exported runtime secret and its optional, UTC expiration. - - The value is omitted from repr, but explicit serialization still exposes it. - Do not log or persist exported credentials in shared output. - """ - - value: str = field(repr=False) - expiration_time: datetime | None = None - - -class ProviderClient: - """Provider credential operations on a shared gRPC channel. - - Retrieval requires direct gateway mTLS with a trusted OU=operator certificate - and no bearer authentication. The gateway must enable operator authentication. - This client does not own or close the supplied channel. - """ - - def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None: - self._stub = openshell_pb2_grpc.OpenShellStub(_error_mapping_channel(channel)) - self._timeout = timeout - - @classmethod - def from_sandbox_client(cls, client: SandboxClient) -> ProviderClient: - """Reuse a client's transport and timeout; no sandbox is required.""" - return client.providers() - - def get_credentials( - self, - name: str, - credential_keys: Sequence[str], - *, - workspace: str, - minimum_remaining_lifetime: timedelta | None = None, - ) -> dict[str, ProviderCredentialValue]: - """Export exactly the selected runtime keys, or raise without a result. - - Omitted or zero lifetime uses the gateway's five-minute margin; the - maximum is 24 hours. The gateway refreshes eligible missing or short-lived - outputs. Refresh effects can persist even when delivery fails. This - method does not retry or cache secrets and never exports refresh inputs. - """ - if not workspace or workspace.strip() != workspace: - raise ValueError("an explicit canonical workspace is required") - if not name or name.strip() != name or len(name.encode("utf-8")) > 253: - raise ValueError("a canonical provider name is required") - # Copy the selection so caller mutation cannot change response validation. - if isinstance(credential_keys, str): - raise ValueError("select between 1 and 32 unique runtime environment keys") - keys = list(credential_keys) - if ( - not 1 <= len(keys) <= 32 - or any( - len(key) > 256 or re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key) is None - for key in keys - ) - or len(set(keys)) != len(keys) - ): - raise ValueError("select between 1 and 32 unique runtime environment keys") - if minimum_remaining_lifetime is not None and not ( - timedelta(0) <= minimum_remaining_lifetime <= timedelta(days=1) - ): - raise ValueError( - "minimum_remaining_lifetime must be between zero and 24 hours" - ) - request = openshell_pb2.GetProviderCredentialsRequest( - workspace_scope=datamodel_pb2.WorkspaceSelector(workspace=workspace), - name=name, - credential_keys=keys, - ) - if minimum_remaining_lifetime is not None: - request.minimum_remaining_lifetime.FromTimedelta(minimum_remaining_lifetime) - response = self._stub.GetProviderCredentials(request, timeout=self._timeout) - if set(response.credentials) != set(keys): - raise ValueError("gateway returned an unexpected credential selection") - return { - key: ProviderCredentialValue( - value=credential.value, - expiration_time=( - credential.expiration_time.ToDatetime(tzinfo=UTC) - if credential.HasField("expiration_time") - else None - ), - ) - for key, credential in response.credentials.items() - } diff --git a/python/openshell/providers_test.py b/python/openshell/providers_test.py deleted file mode 100644 index b8a9b20152..0000000000 --- a/python/openshell/providers_test.py +++ /dev/null @@ -1,230 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Curated provider retrieval through generated stubs and real gRPC error mapping.""" - -from concurrent import futures -from datetime import UTC, datetime, timedelta -from types import SimpleNamespace - -import grpc -import pytest - -from openshell import ProviderClient, ProviderCredentialValue, SandboxClient, TlsConfig -from openshell._proto import openshell_pb2, openshell_pb2_grpc -from openshell.errors import GatewayError - - -@pytest.fixture -def provider_client(): - state = SimpleNamespace(calls=[], deadlines=[], code=None, response=None) - - def retrieve(request, context): - state.calls.append(request) - state.deadlines.append(context.time_remaining()) - if state.code is not None: - context.set_trailing_metadata((("request-id", "provider-export"),)) - context.abort(state.code, "runtime credential retrieval failed") - if state.response is not None: - return state.response - response = openshell_pb2.GetProviderCredentialsResponse() - for key in request.credential_keys: - response.credentials[key].value = f"secret-{key}" - if key == "ACCESS_TOKEN": - response.credentials[key].expiration_time.FromDatetime( - datetime(2030, 1, 1, tzinfo=UTC) - ) - elif key == "EPOCH_KEY": - response.credentials[key].expiration_time.FromNanoseconds(123_456_789) - return response - - server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) - server.add_generic_rpc_handlers( - ( - grpc.method_handlers_generic_handler( - "openshell.v1.OpenShell", - { - "GetProviderCredentials": grpc.unary_unary_rpc_method_handler( - retrieve, - request_deserializer=openshell_pb2.GetProviderCredentialsRequest.FromString, - response_serializer=openshell_pb2.GetProviderCredentialsResponse.SerializeToString, - ), - }, - ), - ) - ) - port = server.add_insecure_port("127.0.0.1:0") - server.start() - with SandboxClient(f"127.0.0.1:{port}", timeout=3) as connection: - try: - yield ProviderClient.from_sandbox_client(connection), state - finally: - server.stop(0).wait() - - -def test_selected_values_and_expiration_are_curated_and_repr_safe( - provider_client, caplog -): - client, state = provider_client - values = client.get_credentials( - "my-provider", - ["ACCESS_TOKEN", "STATIC_KEY", "EPOCH_KEY"], - workspace="production", - minimum_remaining_lifetime=timedelta(seconds=300, microseconds=123456), - ) - assert set(values) == {"ACCESS_TOKEN", "STATIC_KEY", "EPOCH_KEY"} - assert isinstance(values["ACCESS_TOKEN"], ProviderCredentialValue) - assert values["ACCESS_TOKEN"].value == "secret-ACCESS_TOKEN" - assert values["ACCESS_TOKEN"].expiration_time == datetime(2030, 1, 1, tzinfo=UTC) - assert values["STATIC_KEY"].expiration_time is None - assert values["EPOCH_KEY"].expiration_time == datetime( - 1970, 1, 1, microsecond=123456, tzinfo=UTC - ) - assert "secret-" not in repr(values) - assert "secret-" not in caplog.text - request = state.calls[0] - assert request.name == "my-provider" - assert request.workspace_scope.WhichOneof("selection") == "workspace" - assert request.workspace_scope.workspace == "production" - assert list(request.credential_keys) == ["ACCESS_TOKEN", "STATIC_KEY", "EPOCH_KEY"] - assert request.minimum_remaining_lifetime.seconds == 300 - assert request.minimum_remaining_lifetime.nanos == 123456000 - assert 0 < state.deadlines[0] <= 3.1 - - -@pytest.mark.parametrize("lifetime", [None, timedelta(0), timedelta(days=1)]) -def test_lifetime_default_zero_and_maximum(provider_client, lifetime): - client, state = provider_client - client.get_credentials( - "provider", - ["STATIC_KEY"], - workspace="default", - minimum_remaining_lifetime=lifetime, - ) - request = state.calls[0] - assert request.HasField("minimum_remaining_lifetime") == (lifetime is not None) - if lifetime is not None: - assert request.minimum_remaining_lifetime.ToTimedelta() == lifetime - - -@pytest.mark.parametrize( - "name,keys,workspace,lifetime", - [ - ("", ["KEY"], "default", None), - (" provider", ["KEY"], "default", None), - ("x" * 254, ["KEY"], "default", None), - ("provider", [], "default", None), - ("provider", ["KEY", "KEY"], "default", None), - ("provider", [f"KEY_{i}" for i in range(33)], "default", None), - ("provider", ["KEY=secret-input"], "default", None), - ("provider", ["1KEY"], "default", None), - ("provider", ["é"], "default", None), - ("provider", ["K" * 257], "default", None), - ("provider", "KEY", "default", None), - ("provider", ["KEY"], "", None), - ("provider", ["KEY"], " default", None), - ("provider", ["KEY"], "default", timedelta(microseconds=-1)), - ("provider", ["KEY"], "default", timedelta(days=1, microseconds=1)), - ], -) -def test_invalid_requests_never_contact_gateway( - provider_client, name, keys, workspace, lifetime -): - client, state = provider_client - with pytest.raises(ValueError) as error: - client.get_credentials( - name, keys, workspace=workspace, minimum_remaining_lifetime=lifetime - ) - assert "secret-input" not in str(error.value) - assert not state.calls - - -@pytest.mark.parametrize( - "code", - [ - grpc.StatusCode.UNAUTHENTICATED, - grpc.StatusCode.PERMISSION_DENIED, - grpc.StatusCode.NOT_FOUND, - grpc.StatusCode.FAILED_PRECONDITION, - grpc.StatusCode.UNAVAILABLE, - grpc.StatusCode.ABORTED, - grpc.StatusCode.DEADLINE_EXCEEDED, - ], -) -def test_errors_preserve_status_and_metadata_without_retry(provider_client, code): - client, state = provider_client - state.code = code - with pytest.raises(GatewayError) as error: - client.get_credentials( - "provider", ["ACCESS_TOKEN", "STATIC_KEY"], workspace="other" - ) - assert error.value.code() == code - assert ("request-id", "provider-export") in error.value.trailing_metadata() - assert len(state.calls) == 1 - assert "secret-" not in str(error.value) - - -@pytest.mark.parametrize( - "keys", [["ACCESS_TOKEN"], ["ACCESS_TOKEN", "STATIC_KEY", "PRIVATE_KEY"]] -) -def test_unexpected_or_partial_responses_are_not_delivered(provider_client, keys): - client, state = provider_client - state.response = openshell_pb2.GetProviderCredentialsResponse( - credentials={ - key: openshell_pb2.ProviderCredentialValue(value="must-not-deliver") - for key in keys - } - ) - with pytest.raises(ValueError, match="unexpected credential selection") as error: - client.get_credentials( - "provider", ["ACCESS_TOKEN", "STATIC_KEY"], workspace="other" - ) - assert "must-not-deliver" not in str(error.value) - - -def test_shared_client_preserves_mtls_and_does_not_attach_bearer(monkeypatch, tmp_path): - ca = tmp_path / "ca.crt" - cert = tmp_path / "operator.crt" - key = tmp_path / "operator.key" - for path, value in [(ca, b"ca"), (cert, b"operator-cert"), (key, b"operator-key")]: - path.write_bytes(value) - seen = {} - - def credentials(**kwargs): - seen.update(kwargs) - return "tls-credentials" - - channel = SimpleNamespace(close=lambda: None) - monkeypatch.setattr(grpc, "ssl_channel_credentials", credentials) - - def secure_channel(endpoint, creds): - assert endpoint == "gateway.example.com:443" - assert creds == "tls-credentials" - return channel - - monkeypatch.setattr(grpc, "secure_channel", secure_channel) - monkeypatch.setattr("openshell.sandbox._error_mapping_channel", lambda c: c) - monkeypatch.setattr("openshell.providers._error_mapping_channel", lambda c: c) - stub_channels = [] - - def stub(c): - stub_channels.append(c) - return SimpleNamespace() - - monkeypatch.setattr(openshell_pb2_grpc, "OpenShellStub", stub) - - def reject_bearer(*_args): - pytest.fail("operator connection must not attach a bearer interceptor") - - monkeypatch.setattr(grpc, "intercept_channel", reject_bearer) - with SandboxClient( - "gateway.example.com:443", - tls=TlsConfig(ca_path=ca, cert_path=cert, key_path=key), - ) as connection: - assert isinstance(connection.providers(), ProviderClient) - assert stub_channels == [channel, channel] - assert seen == { - "root_certificates": b"ca", - "private_key": b"operator-key", - "certificate_chain": b"operator-cert", - } diff --git a/python/openshell/py.typed b/python/openshell/py.typed deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/python/openshell/sandbox.py b/python/openshell/sandbox.py deleted file mode 100644 index 0670f1d3a6..0000000000 --- a/python/openshell/sandbox.py +++ /dev/null @@ -1,2689 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -from __future__ import annotations - -import base64 -import contextlib -import errno -import ipaddress -import json -import math -import os -import pathlib -import sys -import tempfile -import threading -import time -from collections import namedtuple -from dataclasses import dataclass, field -from enum import IntEnum -from typing import TYPE_CHECKING, Any, Generic, Never, SupportsIndex, TypeVar, cast -from urllib.parse import urlparse - -import grpc -import httpx - -from ._proto import ( - datamodel_pb2, - openshell_pb2, - openshell_pb2_grpc, -) -from .errors import _error_mapping_channel, from_grpc_error -from .mutations import DeletionOutcome, DeletionResult - -_ClientCallDetailsBase = namedtuple( - "_ClientCallDetailsBase", - ("method", "timeout", "metadata", "credentials", "wait_for_ready", "compression"), -) - -_OAUTH_MAX_RESPONSE_BYTES = 1 << 20 -_PAGER_MAX_CONSUMED_TOKENS = 10_000 -_PAGER_MAX_CONSUMED_TOKEN_BYTES = 1 << 20 -# Replica routing headers and retry rule: docs/kubernetes/ingress.mdx. -_OWNER_REPLICA_HEADER = "x-openshell-owner" -_OWNER_REQUEST_HEADER = "x-openshell-want-owner" -_ROUTE_REPLICA_HEADER = "x-openshell-replica" -T = TypeVar("T") - - -@dataclass(frozen=True) -class Page(Generic[T]): - """One response page from a list operation.""" - - items: builtins.list[T] - next_page_token: str - - -class Pager(Generic[T]): - """Lazy, single-pass iterator over the continuation-token contract. - - The repeated-token guard has bounded memory and raises ``SandboxError`` if - the traversal exceeds that guard's token-count or byte budget. - """ - - def __init__(self, fetch: Callable[[str], Page[T]], page_token: str = "") -> None: - self._fetch = fetch - self._page_token: str | None = page_token - self._consumed_page_tokens: set[str] = set() - self._consumed_page_token_bytes = 0 - - def __iter__(self) -> Pager[T]: - return self - - def _validate_page_token_budget(self, page_token: str) -> int: - if not page_token: - return 0 - token_bytes = len(page_token.encode("utf-8")) - if ( - len(self._consumed_page_tokens) >= _PAGER_MAX_CONSUMED_TOKENS - or self._consumed_page_token_bytes + token_bytes - > _PAGER_MAX_CONSUMED_TOKEN_BYTES - ): - raise SandboxError("pager continuation token history limit exceeded") - return token_bytes - - def __next__(self) -> Page[T]: - if self._page_token is None: - raise StopIteration - page_token = self._page_token - token_bytes = self._validate_page_token_budget(page_token) - page = self._fetch(page_token) - if page_token: - self._consumed_page_tokens.add(page_token) - self._consumed_page_token_bytes += token_bytes - next_page_token = page.next_page_token - if next_page_token and next_page_token in self._consumed_page_tokens: - raise SandboxError("pager received a repeated continuation token") - self._page_token = next_page_token or None - return page - - def all(self) -> builtins.list[T]: - """Consume the pager and collect every remaining item.""" - return [item for page in self for item in page.items] - - -class _OwnerCache: - """Owner replicas the gateway last reported, keyed by workspace and name. - - An empty owner means the gateway reported none. A stale owner is safe: a - live non-owner replica relays the call. - """ - - _TTL_SECONDS = 30.0 - _MAX_ENTRIES = 1024 - - def __init__(self) -> None: - self._lock = threading.Lock() - self._entries: dict[tuple[str, str], tuple[float, str]] = {} - - def get(self, workspace: str, name: str) -> str | None: - with self._lock: - entry = self._entries.get((workspace, name)) - if entry is None or time.monotonic() - entry[0] >= self._TTL_SECONDS: - return None - return entry[1] - - def put(self, workspace: str, name: str, owner: str) -> None: - with self._lock: - if len(self._entries) >= self._MAX_ENTRIES: - self._entries.clear() - self._entries[(workspace, name)] = (time.monotonic(), owner) - - def forget(self, workspace: str, name: str) -> None: - with self._lock: - self._entries.pop((workspace, name), None) - - -def _retry_unrouted(error: grpc.RpcError) -> bool: - """Envoy Gateway answers a replica route with no ready endpoints with - UNAVAILABLE and no message; gateway errors always carry one.""" - status = from_grpc_error(error) - details = status.details() or "" - return status.code() == grpc.StatusCode.UNAVAILABLE and ( - details == "" - or "no healthy upstream" in details - or "connection failure" in details - ) - - -def _workspace_scope(workspace: str) -> datamodel_pb2.WorkspaceSelector: - if not workspace: - raise ValueError("workspace must be non-empty") - return datamodel_pb2.WorkspaceSelector(workspace=workspace) - - -def _get_sandbox_request(name: str, workspace: str) -> openshell_pb2.GetSandboxRequest: - return openshell_pb2.GetSandboxRequest( - workspace_scope=_workspace_scope(workspace), name=name - ) - - -def _all_workspaces_scope() -> datamodel_pb2.WorkspaceSelector: - return datamodel_pb2.WorkspaceSelector(all_workspaces=datamodel_pb2.AllWorkspaces()) - - -def _service_exposure_messages( - exposures: Sequence[ServiceExposure] | None, -) -> list[openshell_pb2.SandboxServiceExposure]: - return [ - openshell_pb2.SandboxServiceExposure( - service=exposure.service, - target_port=exposure.target_port, - authorization_mode=( - openshell_pb2.SERVICE_AUTHORIZATION_MODE_BEARER_PASSTHROUGH - if exposure.authorization_mode - == ServiceAuthorizationMode.BEARER_PASSTHROUGH - else openshell_pb2.SERVICE_AUTHORIZATION_MODE_STRIP - ), - ) - for exposure in exposures or () - ] - - -class _ClientCallDetails(_ClientCallDetailsBase, grpc.ClientCallDetails): - pass - - -if TYPE_CHECKING: - import builtins - from collections.abc import Callable, Iterator, Mapping, Sequence - - from .providers import ProviderClient - - -@dataclass(frozen=True) -class TlsConfig: - """Channel TLS material. - - All three fields are optional so callers can pick the trust profile: - - - Full mTLS: pass all three (server trusts client identity). - - CA-only: pass `ca_path` (custom CA, no client identity). - - System roots: pass no fields (`TlsConfig()`) — uses the OS trust - store. Useful for OIDC gateways behind a public CA. - - `cert_path` and `key_path` must be set together or not at all. - """ - - ca_path: pathlib.Path | None = None - cert_path: pathlib.Path | None = None - key_path: pathlib.Path | None = None - - def __post_init__(self) -> None: - if (self.cert_path is None) != (self.key_path is None): - raise ValueError("TlsConfig: cert_path and key_path must be set together") - - -class _BearerAuthInterceptor( - grpc.UnaryUnaryClientInterceptor, - grpc.UnaryStreamClientInterceptor, - grpc.StreamUnaryClientInterceptor, - grpc.StreamStreamClientInterceptor, -): - """Add `authorization: Bearer ` to every outgoing RPC. - - Implemented as an interceptor (not call credentials) so it works on - both plaintext and TLS channels without needing - `grpc.composite_channel_credentials`. The token provider is invoked - per call, so callers can swap tokens at runtime by mutating shared - state or returning a fresh value from the callable. - """ - - def __init__(self, token_provider: Callable[[], str]) -> None: - self._token_provider = token_provider - - def _attach(self, details: grpc.ClientCallDetails) -> grpc.ClientCallDetails: - original_metadata = getattr(details, "metadata", None) - metadata = list(original_metadata) if original_metadata else [] - metadata.append(("authorization", f"Bearer {self._token_provider()}")) - return _ClientCallDetails( - getattr(details, "method", None), - getattr(details, "timeout", None), - metadata, - getattr(details, "credentials", None), - getattr(details, "wait_for_ready", None), - getattr(details, "compression", None), - ) - - def intercept_unary_unary(self, continuation, client_call_details, request): - return continuation(self._attach(client_call_details), request) - - def intercept_unary_stream(self, continuation, client_call_details, request): - return continuation(self._attach(client_call_details), request) - - def intercept_stream_unary( - self, continuation, client_call_details, request_iterator - ): - return continuation(self._attach(client_call_details), request_iterator) - - def intercept_stream_stream( - self, continuation, client_call_details, request_iterator - ): - return continuation(self._attach(client_call_details), request_iterator) - - -def _normalize_bearer( - bearer: str | Callable[[], str] | None, -) -> Callable[[], str] | None: - if bearer is None: - return None - if callable(bearer): - return cast("Callable[[], str]", bearer) - token = bearer - return lambda: token - - -def _is_loopback_host(hostname: str | None) -> bool: - if hostname is None: - return False - if hostname.lower() == "localhost": - return True - with contextlib.suppress(ValueError): - return ipaddress.ip_address(hostname).is_loopback - return False - - -def _is_local_grpc_endpoint(endpoint: str) -> bool: - if endpoint.startswith("unix:"): - return True - return _is_loopback_host(urlparse(f"//{endpoint}").hostname) - - -def _validate_oauth_url(name: str, raw: str) -> str: - """Validate an OAuth endpoint without reflecting attacker-controlled URLs.""" - parsed = urlparse(raw) - if not parsed.scheme or not parsed.hostname or parsed.username or parsed.password: - raise SandboxError(f"invalid OAuth {name} URL") - if parsed.fragment: - raise SandboxError(f"OAuth {name} URL must not contain a fragment") - if parsed.scheme == "https": - return raw - if parsed.scheme == "http" and _is_loopback_host(parsed.hostname): - return raw - raise SandboxError( - f"OAuth {name} URL must use HTTPS (HTTP is allowed only for loopback hosts)" - ) - - -def _oauth_json_request( - client: httpx.Client, - method: str, - url: str, - *, - kind: str, - headers: Mapping[str, str], - data: Mapping[str, str] | None = None, -) -> tuple[int, dict[str, object]]: - """Read a bounded JSON response without retaining arbitrary error bodies.""" - with client.stream(method, url, headers=headers, data=data) as response: - if response.status_code != 200: - return response.status_code, {} - content = bytearray() - for chunk in response.iter_bytes(): - content.extend(chunk) - if len(content) > _OAUTH_MAX_RESPONSE_BYTES: - raise SandboxError(f"OAuth {kind} response is too large") - try: - payload = json.loads(content) - except (UnicodeDecodeError, json.JSONDecodeError): - raise SandboxError(f"OAuth {kind} returned invalid JSON") from None - if not isinstance(payload, dict): - raise SandboxError(f"OAuth {kind} returned invalid JSON") - return 200, payload - - -class ClientCredentialsAuth: - """Renewable OAuth 2.0 client-credentials bearer provider. - - Tokens and client secrets remain in memory. The first RPC lazily performs - discovery and an exchange; later RPCs share the cached token until it is - within 30 seconds of expiry. Concurrent callers share one exchange. - """ - - def __init__( - self, - *, - client_secret: str | Callable[[], str], - issuer: str | None = None, - client_id: str | None = None, - scopes: Sequence[str] | None = None, - audience: str | None = None, - insecure: bool = False, - timeout: float = 30.0, - _transport: httpx.BaseTransport | None = None, - ) -> None: - if not isinstance(client_secret, str) and not callable(client_secret): - raise TypeError("client_secret must be a string or zero-argument callable") - if isinstance(client_secret, str) and not client_secret: - raise SandboxError("OAuth client secret must not be empty") - self._secret = client_secret - self._issuer = issuer - self._client_id = client_id - self._scopes = tuple(scopes) if scopes is not None else None - self._audience = audience - self._insecure = insecure - self._timeout = timeout - self._transport = _transport - self._lock = threading.Lock() - self._access_token: str | None = None - self._expires_at = 0.0 - self._token_endpoint: str | None = None - - def __repr__(self) -> str: - return ( - "ClientCredentialsAuth(issuer=" - f"{self._issuer!r}, client_id={self._client_id!r}, " - f"scopes={self._scopes!r}, audience={self._audience!r})" - ) - - def _apply_gateway_metadata( - self, metadata: Mapping[str, object], *, insecure: bool = False - ) -> None: - """Fill omitted fields and apply active-gateway transport settings.""" - if self._issuer is None: - value = metadata.get("oidc_issuer") - self._issuer = value if isinstance(value, str) and value else None - if self._client_id is None: - value = metadata.get("oidc_client_id") - self._client_id = value if isinstance(value, str) and value else None - if self._audience is None: - value = metadata.get("oidc_audience") - self._audience = value if isinstance(value, str) and value else None - if self._scopes is None: - value = metadata.get("oidc_scopes") - if isinstance(value, str): - self._scopes = tuple(value.split()) - # Preserve an explicit provider-level opt-in while also honoring the - # active-gateway construction flag used by the existing OIDC refresher. - self._insecure = self._insecure or insecure - - def __call__(self) -> str: - if ( - self._access_token is not None - and time.time() + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS < self._expires_at - ): - return self._access_token - with self._lock: - if ( - self._access_token is not None - and time.time() + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS < self._expires_at - ): - return self._access_token - token, expires_at = self._exchange() - self._access_token = token - self._expires_at = expires_at - return token - - def _exchange(self) -> tuple[str, float]: - if not self._issuer or not self._client_id: - raise SandboxError("OAuth client credentials require issuer and client_id") - issuer = _validate_oauth_url("issuer", self._issuer).rstrip("/") - headers = {"accept": "application/json"} - try: - with httpx.Client( - verify=not self._insecure, - follow_redirects=False, - timeout=self._timeout, - transport=self._transport, - ) as client: - if self._token_endpoint is None: - status, discovery = _oauth_json_request( - client, - "GET", - f"{issuer}/.well-known/openid-configuration", - kind="discovery", - headers=headers, - ) - if status != 200: - raise SandboxError(f"OAuth discovery failed with HTTP {status}") - discovered = discovery.get("issuer") - if ( - not isinstance(discovered, str) - or discovered.rstrip("/") != issuer - ): - raise SandboxError("OAuth discovery issuer mismatch") - endpoint = discovery.get("token_endpoint") - if not isinstance(endpoint, str) or not endpoint: - raise SandboxError( - "OAuth discovery document is missing token_endpoint" - ) - self._token_endpoint = _validate_oauth_url( - "token endpoint", endpoint - ) - secret = self._resolve_secret() - data = { - "grant_type": "client_credentials", - "client_id": self._client_id, - "client_secret": secret, - } - if self._scopes: - data["scope"] = " ".join(self._scopes) - if self._audience: - data["audience"] = self._audience - status, payload = _oauth_json_request( - client, - "POST", - self._token_endpoint, - kind="client credentials response", - data=data, - headers=headers, - ) - except SandboxError: - raise - except httpx.HTTPError: - raise SandboxError("OAuth client credentials request failed") from None - if status != 200: - raise SandboxError( - f"OAuth client credentials exchange failed with HTTP {status}" - ) - access_token = payload.get("access_token") - expires_in = payload.get("expires_in") - if not isinstance(access_token, str) or not access_token: - raise SandboxError( - "OAuth client credentials response is missing access_token" - ) - if ( - isinstance(expires_in, bool) - or not isinstance(expires_in, (int, float)) - or not math.isfinite(expires_in) - or expires_in <= 0 - ): - raise SandboxError( - "OAuth client credentials response requires a positive finite expires_in" - ) - return access_token, time.time() + float(expires_in) - - def _resolve_secret(self) -> str: - if isinstance(self._secret, str): - return self._secret - try: - value = self._secret() - except Exception: - raise SandboxError("OAuth client secret supplier failed") from None - if not isinstance(value, str) or not value: - raise SandboxError("OAuth client secret supplier returned an empty secret") - return value - - -@dataclass(frozen=True) -class SandboxConditionRef: - type: str - status: str - reason: str = "" - message: str = "" - transition_time_ms: int | None = None - - -@dataclass(frozen=True) -class SandboxStatusRef: - phase: int - current_policy_version: int - exit_code: int | None = None - restart_count: int = 0 - next_restart_at_ms: int | None = None - main_process_started_at_ms: int | None = None - conditions: tuple[SandboxConditionRef, ...] = () - - -class ServiceAuthorizationMode(IntEnum): - """Handling for an incoming application Authorization header.""" - - STRIP = 1 - BEARER_PASSTHROUGH = 2 - - -@dataclass(frozen=True) -class ServiceExposure: - """A loopback HTTP service to expose during sandbox creation.""" - - target_port: int - service: str = "" - authorization_mode: ServiceAuthorizationMode = ServiceAuthorizationMode.STRIP - - -class _ImmutableLabels(dict[str, str]): - """A read-only, copy- and pickle-safe label mapping.""" - - def _deny_mutation(self, *args: object, **kwargs: object) -> Never: - del args, kwargs - raise TypeError("sandbox labels are immutable") - - __setitem__ = _deny_mutation - __delitem__ = _deny_mutation - clear = _deny_mutation - pop = _deny_mutation - popitem = _deny_mutation - setdefault = _deny_mutation - update = _deny_mutation - __ior__ = _deny_mutation - - def __deepcopy__(self, memo: dict[int, object]) -> _ImmutableLabels: - del memo - return type(self)(self) - - def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: - del protocol - return type(self), (dict(self),) - - -@dataclass(frozen=True) -class SandboxWorkloadTemplateProvenanceRef: - name: str - resource_version: str - - -@dataclass(frozen=True) -class SandboxRef: - id: str - name: str - workspace: str - status: SandboxStatusRef - # Excluded from equality/hash to preserve the original identity while the - # immutable mapping remains safe for deepcopy, pickle, and asdict. - labels: Mapping[str, str] = field(default_factory=_ImmutableLabels, compare=False) - created_from_workload_template: SandboxWorkloadTemplateProvenanceRef | None = None - # Populated by create operations. The empty key identifies the unnamed service. - service_urls: Mapping[str, str] = field( - default_factory=_ImmutableLabels, compare=False - ) - # Stable SSH host identity; absent on older runtimes. - host_key_fingerprint: str | None = None - - def __post_init__(self) -> None: - object.__setattr__(self, "labels", _ImmutableLabels(self.labels)) - object.__setattr__(self, "service_urls", _ImmutableLabels(self.service_urls)) - - @property - def phase(self) -> int: - return self.status.phase - - @property - def current_policy_version(self) -> int: - return self.status.current_policy_version - - @property - def conditions(self) -> tuple[SandboxConditionRef, ...]: - return self.status.conditions - - -@dataclass(frozen=True) -class ExecChunk: - stream: str - data: bytes - - -@dataclass(frozen=True) -class ExecResult: - exit_code: int - stdout: str - stderr: str - - -class SandboxError(RuntimeError): - pass - - -class SandboxSession: - def __init__(self, client: SandboxClient, sandbox: SandboxRef) -> None: - self._client = client - self.sandbox = sandbox - self._workspace = sandbox.workspace - - @property - def id(self) -> str: - return self.sandbox.id - - def exec( - self, - command: Sequence[str], - *, - stream_output: bool = False, - workdir: str | None = None, - env: Mapping[str, str] | None = None, - stdin: bytes | None = None, - timeout_seconds: int | None = None, - no_login_shell: bool = False, - ) -> ExecResult: - return self._client.exec( - self.sandbox.name, - command, - workspace=self._workspace, - stream_output=stream_output, - workdir=workdir, - env=env, - stdin=stdin, - timeout_seconds=timeout_seconds, - no_login_shell=no_login_shell, - ) - - def exec_python( - self, - function: Callable[..., object], - *, - args: Sequence[object] = (), - kwargs: Mapping[str, object] | None = None, - stream_output: bool = False, - workdir: str | None = None, - env: Mapping[str, str] | None = None, - timeout_seconds: int | None = None, - ) -> ExecResult: - return self._client.exec_python( - self.sandbox.name, - function, - workspace=self._workspace, - args=args, - kwargs=kwargs, - stream_output=stream_output, - workdir=workdir, - env=env, - timeout_seconds=timeout_seconds, - ) - - def delete( - self, *, allow_missing: bool = False, timeout_seconds: float | None = None - ) -> DeletionResult: - # Forward `timeout_seconds` only on opt-in so older clients still work. - extra = {} if timeout_seconds is None else {"timeout_seconds": timeout_seconds} - return self._client.delete( - self.sandbox.name, - workspace=self._workspace, - allow_missing=allow_missing, - **extra, - ) - - def stop(self) -> SandboxRef: - self.sandbox = self._client.stop(self.sandbox.name, workspace=self._workspace) - return self.sandbox - - def start(self) -> SandboxRef: - self.sandbox = self._client.start(self.sandbox.name, workspace=self._workspace) - return self.sandbox - - def suspend(self) -> SandboxRef: - self.sandbox = self._client.suspend( - self.sandbox.name, workspace=self._workspace - ) - return self.sandbox - - def resume(self, *, restart_if_restore_fails: bool = False) -> SandboxRef: - self.sandbox = self._client.resume( - self.sandbox.name, - workspace=self._workspace, - restart_if_restore_fails=restart_if_restore_fails, - ) - return self.sandbox - - -class SandboxClient: - """gRPC client for sandbox CRUD and command execution.""" - - def __init__( - self, - endpoint: str, - *, - tls: TlsConfig | None = None, - bearer_token: str | Callable[[], str] | None = None, - client_credentials: ClientCredentialsAuth | None = None, - timeout: float = 30.0, - cluster_name: str | None = None, - _bearer_close: Callable[[], None] | None = None, - ) -> None: - """Create a SandboxClient. - - Args: - endpoint: host:port for the gateway gRPC service. - tls: mTLS material. None for a plaintext channel. - bearer_token: OIDC access token, or a zero-arg callable - returning the current token (called per RPC; supports - runtime refresh). Combines with `tls` — pass both when - the gateway uses mTLS for transport identity and OIDC - for user identity. - client_credentials: renewable OAuth client-credentials provider. - Mutually exclusive with `bearer_token`. A non-loopback endpoint - requires `tls` so the acquired bearer is never sent in cleartext. - timeout: default per-call timeout in seconds. - cluster_name: optional friendly name for error messages. - _bearer_close: internal — wired by `from_active_cluster` - when an `_OidcRefresher` owns the bearer callable, so - `close()` can release the refresher's HTTP client. - Public callers should not pass this; they own the - lifecycle of any callable they supplied as - `bearer_token`. - """ - if bearer_token is not None and client_credentials is not None: - raise SandboxError( - "bearer_token and client_credentials are mutually exclusive" - ) - if ( - client_credentials is not None - and tls is None - and not _is_local_grpc_endpoint(endpoint) - ): - raise SandboxError( - "OAuth client credentials require TLS for non-loopback gateway endpoints" - ) - self._endpoint = endpoint - self._timeout = timeout - self._cluster_name = cluster_name - self._bearer_close = _bearer_close - if tls is None: - self._channel = grpc.insecure_channel(endpoint) - else: - # Build credentials from whatever subset of mTLS material the - # caller supplied. None for `root_certificates` makes gRPC use - # the system trust store, which is what we want for OIDC - # gateways behind a public CA. - credentials = grpc.ssl_channel_credentials( - root_certificates=(tls.ca_path.read_bytes() if tls.ca_path else None), - private_key=(tls.key_path.read_bytes() if tls.key_path else None), - certificate_chain=( - tls.cert_path.read_bytes() if tls.cert_path else None - ), - ) - self._channel = grpc.secure_channel(endpoint, credentials) - provider = _normalize_bearer(client_credentials or bearer_token) - if provider is not None: - self._channel = grpc.intercept_channel( - self._channel, - _BearerAuthInterceptor(provider), - ) - self._stub = openshell_pb2_grpc.OpenShellStub( - _error_mapping_channel(self._channel) - ) - self._owners = _OwnerCache() - - @classmethod - def from_active_cluster( - cls, - *, - cluster: str | None = None, - timeout: float = 30.0, - auto_refresh: bool = True, - write_back: bool = True, - insecure: bool = False, - client_credentials: ClientCredentialsAuth | None = None, - ) -> SandboxClient: - """Construct a `SandboxClient` from the active gateway's on-disk state. - - Args: - cluster: explicit gateway name; otherwise reads - `$OPENSHELL_GATEWAY` or `~/.config/openshell/active_gateway`. - timeout: per-call gRPC timeout in seconds. - auto_refresh: when True (default) and the gateway uses OIDC, - lazily refresh the access token via the IdP's token endpoint - if the cached `oidc_token.json` is near expiry. Matches the - lazy-refresh patterns used by `google-auth` and `botocore`. - Set False to keep the SDK as a read-only consumer of the - CLI's cache (fail closed on expiry). - write_back: when True (default, and `auto_refresh=True`), - atomically persist refreshed bundles back to - `oidc_token.json` so other processes — including the - Rust CLI — see the rotation. Required for IdPs with - refresh-token rotation enabled (Keycloak, Entra in - strict mode): an in-memory-only refresh would leave the - on-disk `refresh_token` pointing at an invalidated - value, and any other process starting from that disk - state would fail on its first refresh. Set False only - when you know the SDK is the sole consumer of this - gateway directory. - insecure: when True, disables TLS certificate verification - for OIDC discovery and refresh calls. Mirrors the Rust - CLI's `--insecure` flag for issuers behind self-signed - certs. Off by default. - client_credentials: renewable OAuth client-credentials provider. - Omitted issuer, client ID, audience, and scopes are filled from - the registered gateway metadata. This provider does not read or - write `oidc_token.json`. Remote plaintext gateways are rejected. - """ - cluster_name = cluster or _resolve_active_cluster() - gateway_dir = _xdg_config_home() / "openshell" / "gateways" / cluster_name - metadata_path = gateway_dir / "metadata.json" - try: - metadata = json.loads(metadata_path.read_text(encoding="utf-8")) - except FileNotFoundError: - raise SandboxError(f"gateway '{cluster_name}' not found") from None - if "gateway_endpoint" not in metadata: - raise SandboxError(f"gateway '{cluster_name}' metadata missing endpoint") - parsed = urlparse(metadata["gateway_endpoint"]) - host = parsed.hostname or "127.0.0.1" - port = parsed.port or (443 if parsed.scheme == "https" else 80) - endpoint = f"{host}:{port}" - - # TLS transport. Mirror crates/openshell-tui/src/lib.rs - # `build_oidc_channel` — for an https gateway, always build a - # secure channel and pick the strongest available trust profile. - tls: TlsConfig | None = None - if parsed.scheme == "https": - mtls_dir = gateway_dir / "mtls" - ca = mtls_dir / "ca.crt" if (mtls_dir / "ca.crt").exists() else None - cert = mtls_dir / "tls.crt" if (mtls_dir / "tls.crt").exists() else None - key = mtls_dir / "tls.key" if (mtls_dir / "tls.key").exists() else None - if ca is not None and cert is not None and key is not None: - # Full mTLS. - tls = TlsConfig(ca_path=ca, cert_path=cert, key_path=key) - elif ca is not None: - # CA-only trust (no client identity). - tls = TlsConfig(ca_path=ca) - else: - # System roots (e.g. OIDC gateway behind a public CA). - tls = TlsConfig() - - # OIDC bearer. Mirror the Rust CLI/TUI: the gateway metadata's - # `auth_mode` is authoritative — a stale oidc_token.json next to - # a non-OIDC gateway should NOT cause us to attach a bearer. - bearer_token: Callable[[], str] | None = None - bearer_close: Callable[[], None] | None = None - if client_credentials is not None: - if metadata.get("auth_mode") != "oidc": - raise SandboxError( - f"gateway '{cluster_name}' is not configured for OIDC" - ) - client_credentials._apply_gateway_metadata(metadata, insecure=insecure) - elif metadata.get("auth_mode") == "oidc": - bearer_token, bearer_close = _make_cluster_bearer_provider( - gateway_dir, - cluster_name, - auto_refresh=auto_refresh, - write_back=write_back, - insecure=insecure, - ) - - return cls( - endpoint, - tls=tls, - bearer_token=bearer_token, - client_credentials=client_credentials, - timeout=timeout, - cluster_name=cluster_name, - _bearer_close=bearer_close, - ) - - def close(self) -> None: - """Release the gRPC channel and any bearer-auth resources. - - Idempotent. If `from_active_cluster` wired up an OIDC refresher - for this client, the refresher's underlying httpx.Client is - closed here too — otherwise long-lived services that churn - clients would leak sockets / file descriptors until GC. - """ - self._channel.close() - if self._bearer_close is not None: - with contextlib.suppress(Exception): - self._bearer_close() - self._bearer_close = None - - def __enter__(self) -> SandboxClient: - return self - - def __exit__(self, *args: object) -> None: - self.close() - - def health(self) -> openshell_pb2.HealthResponse: - return self._stub.Health(openshell_pb2.HealthRequest(), timeout=self._timeout) - - def create( - self, - *, - workspace: str, - spec: openshell_pb2.SandboxSpec | None = None, - name: str | None = None, - labels: Mapping[str, str] | None = None, - service_exposures: Sequence[ServiceExposure] | None = None, - ) -> SandboxRef: - request_spec = spec if spec is not None else _default_spec() - response = self._stub.CreateSandbox( - openshell_pb2.CreateSandboxRequest( - workspace_scope=_workspace_scope(workspace), - spec=request_spec, - name=name or "", - labels=dict(labels) if labels else {}, - service_exposures=_service_exposure_messages(service_exposures), - ), - timeout=self._timeout, - ) - sandbox_ref = _sandbox_ref(response.sandbox, response.service_urls) - if sandbox_ref.id == "": - raise SandboxError("CreateSandbox returned empty sandbox id") - return sandbox_ref - - def create_from_template( - self, - *, - workspace: str, - workload_template: str, - spec: openshell_pb2.SandboxSpec | None = None, - name: str | None = None, - labels: Mapping[str, str] | None = None, - service_exposures: Sequence[ServiceExposure] | None = None, - ) -> SandboxRef: - if not workload_template.strip(): - raise SandboxError("workload_template is required") - request_spec = spec if spec is not None else openshell_pb2.SandboxSpec() - response = self._stub.CreateSandbox( - openshell_pb2.CreateSandboxRequest( - workspace_scope=_workspace_scope(workspace), - spec=request_spec, - name=name or "", - labels=dict(labels) if labels else {}, - workload_template=workload_template, - service_exposures=_service_exposure_messages(service_exposures), - ), - timeout=self._timeout, - ) - sandbox_ref = _sandbox_ref(response.sandbox, response.service_urls) - if sandbox_ref.id == "": - raise SandboxError("CreateSandbox returned empty sandbox id") - return sandbox_ref - - def create_session( - self, - *, - workspace: str, - spec: openshell_pb2.SandboxSpec | None = None, - name: str | None = None, - labels: Mapping[str, str] | None = None, - service_exposures: Sequence[ServiceExposure] | None = None, - ) -> SandboxSession: - return SandboxSession( - self, - self.create( - workspace=workspace, - spec=spec, - name=name, - labels=labels, - service_exposures=service_exposures, - ), - ) - - def create_session_from_template( - self, - *, - workspace: str, - workload_template: str, - spec: openshell_pb2.SandboxSpec | None = None, - name: str | None = None, - labels: Mapping[str, str] | None = None, - service_exposures: Sequence[ServiceExposure] | None = None, - ) -> SandboxSession: - return SandboxSession( - self, - self.create_from_template( - workspace=workspace, - workload_template=workload_template, - spec=spec, - name=name, - labels=labels, - service_exposures=service_exposures, - ), - ) - - def sandbox_templates(self) -> SandboxTemplateClient: - return SandboxTemplateClient(self._channel, timeout=self._timeout) - - def providers(self) -> ProviderClient: - """Reuse this transport for provider operations; no sandbox is required.""" - from .providers import ProviderClient - - return ProviderClient(self._channel, timeout=self._timeout) - - def get(self, name: str, *, workspace: str) -> SandboxRef: - response = self._stub.GetSandbox( - _get_sandbox_request(name, workspace), - timeout=self._timeout, - ) - return _sandbox_ref(response.sandbox) - - def get_session(self, name: str, *, workspace: str) -> SandboxSession: - return SandboxSession(self, self.get(name, workspace=workspace)) - - def list( - self, - *, - workspace: str, - page_size: int = 100, - page_token: str = "", - label_selector: str | None = None, - ) -> Pager[SandboxRef]: - def fetch(token: str) -> Page[SandboxRef]: - response = self._stub.ListSandboxes( - openshell_pb2.ListSandboxesRequest( - workspace_scope=_workspace_scope(workspace), - page_size=page_size, - page_token=token, - label_selector=label_selector or "", - ), - timeout=self._timeout, - ) - return Page( - items=[_sandbox_ref(item) for item in response.sandboxes], - next_page_token=getattr(response, "next_page_token", ""), - ) - - return Pager(fetch, page_token) - - def list_all( - self, - *, - workspace: str, - page_size: int = 100, - page_token: str = "", - label_selector: str | None = None, - ) -> builtins.list[SandboxRef]: - return self.list( - workspace=workspace, - page_size=page_size, - page_token=page_token, - label_selector=label_selector, - ).all() - - def list_for_all_workspaces( - self, - *, - page_size: int = 100, - page_token: str = "", - label_selector: str | None = None, - ) -> Pager[SandboxRef]: - def fetch(token: str) -> Page[SandboxRef]: - response = self._stub.ListSandboxes( - openshell_pb2.ListSandboxesRequest( - workspace_scope=_all_workspaces_scope(), - page_size=page_size, - page_token=token, - label_selector=label_selector or "", - ), - timeout=self._timeout, - ) - return Page( - items=[_sandbox_ref(item) for item in response.sandboxes], - next_page_token=getattr(response, "next_page_token", ""), - ) - - return Pager(fetch, page_token) - - def list_all_for_all_workspaces( - self, - *, - page_size: int = 100, - page_token: str = "", - label_selector: str | None = None, - ) -> builtins.list[SandboxRef]: - return self.list_for_all_workspaces( - page_size=page_size, - page_token=page_token, - label_selector=label_selector, - ).all() - - def list_ids( - self, - *, - workspace: str, - page_size: int = 100, - label_selector: str | None = None, - ) -> builtins.list[str]: - return [ - item.id - for item in self.list_all( - workspace=workspace, - page_size=page_size, - label_selector=label_selector, - ) - ] - - def list_ids_for_all_workspaces( - self, - *, - page_size: int = 100, - label_selector: str | None = None, - ) -> builtins.list[str]: - return [ - item.id - for item in self.list_all_for_all_workspaces( - page_size=page_size, - label_selector=label_selector, - ) - ] - - def delete( - self, - name: str, - *, - workspace: str, - allow_missing: bool = False, - timeout_seconds: float | None = None, - ) -> DeletionResult: - """Delete a sandbox. - - `timeout_seconds` is the gRPC deadline for this call (default: the - client timeout). - """ - response = self._stub.DeleteSandbox( - openshell_pb2.DeleteSandboxRequest( - workspace_scope=_workspace_scope(workspace), - name=name, - allow_missing=allow_missing, - ), - timeout=self._timeout if timeout_seconds is None else timeout_seconds, - ) - return DeletionResult( - DeletionOutcome(response.outcome), response.sandbox_id or None - ) - - def stop(self, name: str, *, workspace: str) -> SandboxRef: - response = self._stub.StopSandbox( - openshell_pb2.StopSandboxRequest( - workspace_scope=_workspace_scope(workspace), - name=name, - ), - timeout=self._timeout, - ) - return _sandbox_ref(response.sandbox) - - def start(self, name: str, *, workspace: str) -> SandboxRef: - response = self._stub.StartSandbox( - openshell_pb2.StartSandboxRequest( - workspace_scope=_workspace_scope(workspace), - name=name, - ), - timeout=self._timeout, - ) - return _sandbox_ref(response.sandbox) - - def suspend(self, name: str, *, workspace: str) -> SandboxRef: - """Suspend a ready sandbox, retaining its memory state. - - Requires a compute driver and isolation backend that support suspend - and resume. - """ - response = self._stub.SuspendSandbox( - openshell_pb2.SuspendSandboxRequest( - workspace_scope=_workspace_scope(workspace), - name=name, - ), - timeout=self._timeout, - ) - return _sandbox_ref(response.sandbox) - - def resume( - self, - name: str, - *, - workspace: str, - restart_if_restore_fails: bool = False, - ) -> SandboxRef: - """Resume a suspended sandbox in a new runtime generation.""" - response = self._stub.ResumeSandbox( - openshell_pb2.ResumeSandboxRequest( - workspace_scope=_workspace_scope(workspace), - name=name, - restart_if_restore_fails=restart_if_restore_fails, - ), - timeout=self._timeout, - ) - return _sandbox_ref(response.sandbox) - - def wait_deleted( - self, - name: str, - *, - workspace: str, - timeout_seconds: float = 60.0, - expected_sandbox_id: str | None = None, - ) -> None: - deadline = time.time() + timeout_seconds - while time.time() < deadline: - try: - current = self.get(name, workspace=workspace) - if ( - expected_sandbox_id is not None - and current.id != expected_sandbox_id - ): - return - except grpc.RpcError as exc: - if getattr(exc, "code", lambda: None)() == grpc.StatusCode.NOT_FOUND: - return - raise - time.sleep(1) - raise SandboxError(f"sandbox {name} was not deleted within timeout") - - def wait_ready( - self, name: str, *, workspace: str, timeout_seconds: float = 300.0 - ) -> SandboxRef: - return self._wait_for_phase( - name, - workspace=workspace, - target_phase=openshell_pb2.SANDBOX_PHASE_READY, - target_name="ready", - timeout_seconds=timeout_seconds, - ) - - def wait_stopped( - self, name: str, *, workspace: str, timeout_seconds: float = 300.0 - ) -> SandboxRef: - return self._wait_for_phase( - name, - workspace=workspace, - target_phase=openshell_pb2.SANDBOX_PHASE_STOPPED, - target_name="stopped", - timeout_seconds=timeout_seconds, - ) - - def wait_suspended( - self, name: str, *, workspace: str, timeout_seconds: float = 300.0 - ) -> SandboxRef: - return self._wait_for_phase( - name, - workspace=workspace, - target_phase=openshell_pb2.SANDBOX_PHASE_SUSPENDED, - target_name="suspended", - timeout_seconds=timeout_seconds, - ) - - def _wait_for_phase( - self, - name: str, - *, - workspace: str, - target_phase: int, - target_name: str, - timeout_seconds: float, - ) -> SandboxRef: - deadline = time.time() + timeout_seconds - while time.time() < deadline: - sandbox = self.get(name, workspace=workspace) - if sandbox.status.phase == target_phase: - return sandbox - if ( - target_phase == openshell_pb2.SANDBOX_PHASE_READY - and sandbox.status.phase == openshell_pb2.SANDBOX_PHASE_COMPLETED - ): - return sandbox - if ( - target_phase == openshell_pb2.SANDBOX_PHASE_READY - and sandbox.status.phase == openshell_pb2.SANDBOX_PHASE_STOPPED - ): - raise SandboxError(f"sandbox {name} stopped before becoming ready") - if target_phase == openshell_pb2.SANDBOX_PHASE_READY and ( - sandbox.status.phase - in ( - openshell_pb2.SANDBOX_PHASE_SUSPENDING, - openshell_pb2.SANDBOX_PHASE_SUSPENDED, - ) - ): - raise SandboxError( - f"sandbox {name} is suspended; resume it before waiting for ready" - ) - if sandbox.status.phase == openshell_pb2.SANDBOX_PHASE_ERROR: - raise SandboxError(f"sandbox {name} entered error phase") - time.sleep(1) - raise SandboxError(f"sandbox {name} was not {target_name} within timeout") - - def exec_stream( - self, - sandbox: str, - command: Sequence[str], - *, - workspace: str, - workdir: str | None = None, - env: Mapping[str, str] | None = None, - stdin: bytes | None = None, - timeout_seconds: int | None = None, - no_login_shell: bool = False, - ) -> Iterator[ExecChunk | ExecResult]: - if not command: - raise SandboxError("command must not be empty") - - request = openshell_pb2.ExecSandboxRequest( - workspace_scope=_workspace_scope(workspace), - sandbox=sandbox, - command=list(command), - workdir=workdir or "", - environment=dict(env or {}), - stdin=stdin or b"", - no_login_shell=no_login_shell, - ) - if timeout_seconds: - request.execution_timeout.seconds = timeout_seconds - # Use whichever is larger: the default client timeout or the command - # timeout plus headroom for SSH setup / teardown overhead. - grpc_deadline = self._timeout - if timeout_seconds and timeout_seconds + 10 > grpc_deadline: - grpc_deadline = timeout_seconds + 10 - stream = self._open_exec(request, workspace, grpc_deadline) - - stdout_parts: list[bytes] = [] - stderr_parts: list[bytes] = [] - exit_code: int | None = None - - for event in stream: - payload = event.WhichOneof("payload") - if payload == "stdout": - data = bytes(event.stdout.data) - stdout_parts.append(data) - yield ExecChunk(stream="stdout", data=data) - elif payload == "stderr": - data = bytes(event.stderr.data) - stderr_parts.append(data) - yield ExecChunk(stream="stderr", data=data) - elif payload == "exit": - exit_code = int(event.exit.exit_code) - - if exit_code is None: - raise SandboxError("ExecSandbox stream ended without an exit event") - - yield ExecResult( - exit_code=exit_code, - stdout=b"".join(stdout_parts).decode("utf-8", errors="replace"), - stderr=b"".join(stderr_parts).decode("utf-8", errors="replace"), - ) - - def _owner_of(self, workspace: str, sandbox: str) -> str: - """Best effort: a failed lookup leaves the call unrouted.""" - owner = self._owners.get(workspace, sandbox) - if owner is not None: - return owner - try: - _, call = self._stub.GetSandbox.with_call( - _get_sandbox_request(sandbox, workspace), - timeout=self._timeout, - metadata=((_OWNER_REQUEST_HEADER, "1"),), - ) - except grpc.RpcError: - return "" - value = dict(call.initial_metadata() or ()).get(_OWNER_REPLICA_HEADER) - owner = value if isinstance(value, str) else "" - self._owners.put(workspace, sandbox, owner) - return owner - - def _open_exec( - self, - request: openshell_pb2.ExecSandboxRequest, - workspace: str, - timeout: float, - ) -> Iterator[openshell_pb2.ExecSandboxEvent]: - """Open ExecSandbox on the owner replica, retrying once unrouted.""" - owner = self._owner_of(workspace, request.sandbox) - if owner: - events = self._stub.ExecSandbox( - request, - timeout=timeout, - metadata=((_ROUTE_REPLICA_HEADER, owner),), - ) - try: - first = next(events, None) - except grpc.RpcError as error: - if not _retry_unrouted(error): - raise - self._owners.forget(workspace, request.sandbox) - else: - if first is not None: - yield first - yield from events - return - yield from self._stub.ExecSandbox(request, timeout=timeout) - - def exec( - self, - sandbox: str, - command: Sequence[str], - *, - workspace: str, - stream_output: bool = False, - workdir: str | None = None, - env: Mapping[str, str] | None = None, - stdin: bytes | None = None, - timeout_seconds: int | None = None, - no_login_shell: bool = False, - ) -> ExecResult: - result: ExecResult | None = None - for item in self.exec_stream( - sandbox, - command, - workspace=workspace, - workdir=workdir, - env=env, - stdin=stdin, - timeout_seconds=timeout_seconds, - no_login_shell=no_login_shell, - ): - if stream_output and isinstance(item, ExecChunk): - if item.stream == "stdout": - sys.stdout.buffer.write(item.data) - sys.stdout.flush() - else: - sys.stderr.buffer.write(item.data) - sys.stderr.flush() - if isinstance(item, ExecResult): - result = item - if result is None: - raise SandboxError("ExecSandbox did not return a result") - return result - - def exec_python( - self, - sandbox: str, - function: Callable[..., object], - *, - workspace: str, - args: Sequence[object] = (), - kwargs: Mapping[str, object] | None = None, - stream_output: bool = False, - workdir: str | None = None, - env: Mapping[str, str] | None = None, - timeout_seconds: int | None = None, - ) -> ExecResult: - exec_env = dict(env or {}) - exec_env["OPENSHELL_PYFUNC_B64"] = _serialize_python_callable( - function, - args=args, - kwargs=kwargs, - ) - return self.exec( - sandbox, - [_SANDBOX_PYTHON_BIN, "-c", _PYTHON_CLOUDPICKLE_BOOTSTRAP], - workspace=workspace, - stream_output=stream_output, - workdir=workdir, - env=exec_env, - timeout_seconds=timeout_seconds, - ) - - -class SandboxTemplateClient: - """gRPC client for reusable sandbox template lifecycle operations.""" - - def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None: - self._stub = openshell_pb2_grpc.OpenShellStub(_error_mapping_channel(channel)) - self._timeout = timeout - - @classmethod - def from_sandbox_client(cls, client: SandboxClient) -> SandboxTemplateClient: - return client.sandbox_templates() - - def create( - self, - *, - workspace: str, - template: openshell_pb2.SandboxWorkloadTemplate | None = None, - name: str | None = None, - image: str | None = None, - labels: Mapping[str, str] | None = None, - annotations: Mapping[str, str] | None = None, - environment: Mapping[str, str] | None = None, - cpu: str | None = None, - memory: str | None = None, - gpu_count: int | None = None, - gpu: bool = False, - driver_config: Mapping[str, Any] | None = None, - ) -> openshell_pb2.SandboxWorkloadTemplate: - if template is None: - if name is None or not name.strip(): - raise SandboxError("name is required when template is omitted") - template = _sandbox_workload_template( - name=name, - image=image, - labels=labels, - annotations=annotations, - environment=environment, - cpu=cpu, - memory=memory, - gpu_count=gpu_count, - gpu=gpu, - driver_config=driver_config, - ) - elif ( - any(value is not None for value in (name, image, cpu, memory, gpu_count)) - or any( - bool(value) - for value in (labels, annotations, environment, driver_config) - ) - or gpu - ): - raise SandboxError( - "template cannot be combined with template builder fields" - ) - - response = self._stub.CreateSandboxTemplate( - openshell_pb2.CreateSandboxTemplateRequest( - workspace_scope=_workspace_scope(workspace), - template=template, - ), - timeout=self._timeout, - ) - return response.template - - def get( - self, - name: str, - *, - workspace: str, - ) -> openshell_pb2.SandboxWorkloadTemplate: - response = self._stub.GetSandboxTemplate( - openshell_pb2.GetSandboxTemplateRequest( - workspace_scope=_workspace_scope(workspace), name=name - ), - timeout=self._timeout, - ) - return response.template - - def list( - self, - *, - workspace: str, - page_size: int = 100, - page_token: str = "", - label_selector: str = "", - ) -> Pager[openshell_pb2.SandboxWorkloadTemplate]: - def fetch(token: str) -> Page[openshell_pb2.SandboxWorkloadTemplate]: - response = self._stub.ListSandboxTemplates( - openshell_pb2.ListSandboxTemplatesRequest( - workspace_scope=_workspace_scope(workspace), - page_size=page_size, - page_token=token, - label_selector=label_selector, - ), - timeout=self._timeout, - ) - return Page( - items=list(response.templates), - next_page_token=getattr(response, "next_page_token", ""), - ) - - return Pager(fetch, page_token) - - def list_all( - self, - *, - workspace: str, - page_size: int = 100, - page_token: str = "", - label_selector: str = "", - ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: - return self.list( - workspace=workspace, - page_size=page_size, - page_token=page_token, - label_selector=label_selector, - ).all() - - def list_for_all_workspaces( - self, - *, - page_size: int = 100, - page_token: str = "", - label_selector: str = "", - ) -> Pager[openshell_pb2.SandboxWorkloadTemplate]: - def fetch(token: str) -> Page[openshell_pb2.SandboxWorkloadTemplate]: - response = self._stub.ListSandboxTemplates( - openshell_pb2.ListSandboxTemplatesRequest( - workspace_scope=_all_workspaces_scope(), - page_size=page_size, - page_token=token, - label_selector=label_selector, - ), - timeout=self._timeout, - ) - return Page( - items=list(response.templates), - next_page_token=getattr(response, "next_page_token", ""), - ) - - return Pager(fetch, page_token) - - def list_all_for_all_workspaces( - self, - *, - page_size: int = 100, - page_token: str = "", - label_selector: str = "", - ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: - return self.list_for_all_workspaces( - page_size=page_size, - page_token=page_token, - label_selector=label_selector, - ).all() - - def delete( - self, name: str, *, workspace: str, allow_missing: bool = False - ) -> DeletionResult: - response = self._stub.DeleteSandboxTemplate( - openshell_pb2.DeleteSandboxTemplateRequest( - workspace_scope=_workspace_scope(workspace), - name=name, - allow_missing=allow_missing, - ), - timeout=self._timeout, - ) - return DeletionResult(DeletionOutcome(response.outcome)) - - -@dataclass(frozen=True) -class WorkspaceRef: - name: str - phase: str - labels: dict[str, str] - - -def _workspace_ref(ws: datamodel_pb2.Workspace) -> WorkspaceRef: - meta = ws.metadata - return WorkspaceRef( - name=meta.name, - phase=datamodel_pb2.WorkspacePhase.Name(ws.status.phase), - labels=dict(meta.labels), - ) - - -class WorkspaceClient: - """gRPC client for workspace lifecycle operations.""" - - def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None: - self._stub = openshell_pb2_grpc.OpenShellStub(_error_mapping_channel(channel)) - self._timeout = timeout - - @classmethod - def from_sandbox_client(cls, client: SandboxClient) -> WorkspaceClient: - return cls(client._channel, timeout=client._timeout) - - def create( - self, - name: str, - *, - labels: Mapping[str, str] | None = None, - ) -> WorkspaceRef: - response = self._stub.CreateWorkspace( - openshell_pb2.CreateWorkspaceRequest( - name=name, - labels=dict(labels) if labels else {}, - ), - timeout=self._timeout, - ) - return _workspace_ref(response.workspace) - - def get(self, name: str) -> WorkspaceRef: - response = self._stub.GetWorkspace( - openshell_pb2.GetWorkspaceRequest(name=name), - timeout=self._timeout, - ) - return _workspace_ref(response.workspace) - - def list( - self, - *, - page_size: int = 100, - page_token: str = "", - label_selector: str | None = None, - ) -> Pager[WorkspaceRef]: - def fetch(token: str) -> Page[WorkspaceRef]: - response = self._stub.ListWorkspaces( - openshell_pb2.ListWorkspacesRequest( - page_size=page_size, - page_token=token, - label_selector=label_selector or "", - ), - timeout=self._timeout, - ) - return Page( - items=[_workspace_ref(ws) for ws in response.workspaces], - next_page_token=getattr(response, "next_page_token", ""), - ) - - return Pager(fetch, page_token) - - def list_all( - self, - *, - page_size: int = 100, - page_token: str = "", - label_selector: str | None = None, - ) -> builtins.list[WorkspaceRef]: - return self.list( - page_size=page_size, - page_token=page_token, - label_selector=label_selector, - ).all() - - def delete(self, name: str, *, allow_missing: bool = False) -> DeletionResult: - response = self._stub.DeleteWorkspace( - openshell_pb2.DeleteWorkspaceRequest( - name=name, allow_missing=allow_missing - ), - timeout=self._timeout, - ) - return DeletionResult(DeletionOutcome(response.outcome)) - - -class Sandbox: - """Context-managed sandbox session bound to one sandbox id.""" - - def __init__( - self, - *, - workspace: str, - cluster: str | None = None, - sandbox: str | SandboxRef | None = None, - delete_on_exit: bool = True, - spec: openshell_pb2.SandboxSpec | None = None, - name: str | None = None, - labels: Mapping[str, str] | None = None, - workload_template: str | None = None, - timeout: float = 30.0, - ready_timeout_seconds: float = 120.0, - delete_timeout_seconds: float | None = None, - auto_refresh: bool = True, - write_back: bool = True, - insecure: bool = False, - client_credentials: ClientCredentialsAuth | None = None, - ) -> None: - """Bind a Sandbox context to the active gateway. - - `delete_timeout_seconds` bounds the delete RPC on exit and defaults to - `timeout`. Raise it for drivers that hold the delete open while the - workload terminates. - - OIDC kwargs (`auto_refresh`, `write_back`, `insecure`, and - `client_credentials`) forward - directly to `SandboxClient.from_active_cluster` and have the - same semantics. They're surfaced on `Sandbox` so callers using - the higher-level wrapper get parity with `SandboxClient` for - OIDC-protected gateways (e.g. passing `insecure=True` for a - self-signed dev IdP). Non-OIDC gateways ignore them. - """ - self._workspace = workspace - self._cluster = cluster - self._sandbox_input = sandbox - self._delete_on_exit = delete_on_exit - self._spec = spec - self._name = name - # Copy so later caller mutation cannot change what gets sent on enter. - self._labels = dict(labels) if labels is not None else None - self._workload_template = workload_template - self._timeout = timeout - self._ready_timeout_seconds = ready_timeout_seconds - self._delete_timeout_seconds = delete_timeout_seconds - self._auto_refresh = auto_refresh - self._write_back = write_back - self._insecure = insecure - self._client_credentials = client_credentials - self._client: SandboxClient | None = None - self._session: SandboxSession | None = None - - @property - def id(self) -> str: - if self._session is None: - raise SandboxError("sandbox context has not been entered") - return self._session.id - - @property - def sandbox(self) -> SandboxRef: - if self._session is None: - raise SandboxError("sandbox context has not been entered") - return self._session.sandbox - - def __enter__(self) -> Sandbox: - # Creation metadata cannot be applied when attaching to an existing - # sandbox; reject it before opening a connection. - if self._sandbox_input is not None and ( - self._name is not None - or self._labels is not None - or self._workload_template is not None - ): - raise SandboxError( - "name, labels, and workload_template cannot be set when attaching to an existing sandbox" - ) - - self._client = SandboxClient.from_active_cluster( - cluster=self._cluster, - timeout=self._timeout, - auto_refresh=self._auto_refresh, - write_back=self._write_back, - insecure=self._insecure, - client_credentials=self._client_credentials, - ) - try: - self._open_session(self._client) - except BaseException: - # Python skips __exit__ when __enter__ raises, so release here - # and keep the original error even if the close fails. - with contextlib.suppress(Exception): - self._release() - raise - return self - - def _open_session(self, client: SandboxClient) -> None: - if self._sandbox_input is None and self._workload_template is not None: - self._session = client.create_session_from_template( - workspace=self._workspace, - workload_template=self._workload_template, - spec=self._spec, - name=self._name, - labels=self._labels, - ) - elif self._sandbox_input is None: - self._session = client.create_session( - workspace=self._workspace, - spec=self._spec, - name=self._name, - labels=self._labels, - ) - elif isinstance(self._sandbox_input, SandboxRef): - self._session = SandboxSession(client, self._sandbox_input) - else: - self._session = client.get_session( - self._sandbox_input, workspace=self._workspace - ) - - self._workspace = getattr(self._session, "_workspace", self._workspace) - - ready = client.wait_ready( - self._session.sandbox.name, - workspace=self._workspace, - timeout_seconds=self._ready_timeout_seconds, - ) - self._session = SandboxSession(client, ready) - - def _release(self) -> None: - client = self._client - self._session = None - self._client = None - if client is not None: - client.close() - - def __exit__(self, *args: object) -> None: - try: - if ( - self._delete_on_exit - and self._session is not None - and self._client is not None - ): - result = self._session.delete( - allow_missing=True, timeout_seconds=self._delete_timeout_seconds - ) - if result.outcome == DeletionOutcome.ACCEPTED: - self._client.wait_deleted( - self._session.sandbox.name, - workspace=self._workspace, - expected_sandbox_id=result.sandbox_id, - ) - elif result.outcome not in ( - DeletionOutcome.COMPLETED, - DeletionOutcome.ALREADY_ABSENT, - ): - raise SandboxError( - f"unsupported deletion outcome: {result.outcome}" - ) - finally: - self._release() - - def exec( - self, - command: Sequence[str], - *, - stream_output: bool = False, - workdir: str | None = None, - env: Mapping[str, str] | None = None, - stdin: bytes | None = None, - timeout_seconds: int | None = None, - no_login_shell: bool = False, - ) -> ExecResult: - if self._session is None: - raise SandboxError("sandbox context has not been entered") - return self._session.exec( - command, - stream_output=stream_output, - workdir=workdir, - env=env, - stdin=stdin, - timeout_seconds=timeout_seconds, - no_login_shell=no_login_shell, - ) - - def exec_python( - self, - function: Callable[..., object], - *, - args: Sequence[object] = (), - kwargs: Mapping[str, object] | None = None, - stream_output: bool = False, - workdir: str | None = None, - env: Mapping[str, str] | None = None, - timeout_seconds: int | None = None, - ) -> ExecResult: - if self._session is None: - raise SandboxError("sandbox context has not been entered") - return self._session.exec_python( - function, - args=args, - kwargs=kwargs, - stream_output=stream_output, - workdir=workdir, - env=env, - timeout_seconds=timeout_seconds, - ) - - -_PYTHON_CLOUDPICKLE_BOOTSTRAP = ( - "import base64,cloudpickle,os;" - "payload=base64.b64decode(os.environ['OPENSHELL_PYFUNC_B64']);" - "func,args,kwargs=cloudpickle.loads(payload);" - "result=func(*args,**kwargs);" - "print(result) if result is not None else None" -) - -_SANDBOX_PYTHON_BIN = "python" - - -def _serialize_python_callable( - function: Callable[..., object], - *, - args: Sequence[object], - kwargs: Mapping[str, object] | None, -) -> str: - try: - import cloudpickle - except ImportError as exc: # pragma: no cover - import error path - raise SandboxError("cloudpickle is required for exec_python") from exc - - payload = cloudpickle.dumps((function, tuple(args), dict(kwargs or {}))) - return base64.b64encode(payload).decode("ascii") - - -def _sandbox_conditions( - status: openshell_pb2.SandboxStatus | None, -) -> tuple[SandboxConditionRef, ...]: - if status is None: - return () - return tuple( - SandboxConditionRef( - type=condition.type, - status=condition.status, - reason=condition.reason, - message=condition.message, - transition_time_ms=condition.transition_time.ToMilliseconds() - if condition.HasField("transition_time") - else None, - ) - for condition in status.conditions - ) - - -def _sandbox_ref( - sandbox: openshell_pb2.Sandbox, - service_urls: Mapping[str, str] | None = None, -) -> SandboxRef: - status = sandbox.status if sandbox.HasField("status") else None - provenance = ( - SandboxWorkloadTemplateProvenanceRef( - name=sandbox.created_from_workload_template.name, - resource_version=sandbox.created_from_workload_template.resource_version, - ) - if sandbox.HasField("created_from_workload_template") - else None - ) - return SandboxRef( - id=sandbox.metadata.id if sandbox.metadata else "", - name=sandbox.metadata.name if sandbox.metadata else "", - workspace=sandbox.metadata.workspace if sandbox.metadata else "", - status=SandboxStatusRef( - phase=status.phase if status else 0, - current_policy_version=status.current_policy_version if status else 0, - exit_code=status.exit_code - if status is not None and status.HasField("exit_code") - else None, - restart_count=status.restart_count if status is not None else 0, - next_restart_at_ms=status.next_restart_time.ToMilliseconds() - if status is not None and status.HasField("next_restart_time") - else None, - main_process_started_at_ms=status.main_process_started_time.ToMilliseconds() - if status is not None and status.HasField("main_process_started_time") - else None, - conditions=_sandbox_conditions(status), - ), - labels=sandbox.metadata.labels if sandbox.metadata else {}, - created_from_workload_template=provenance, - service_urls=service_urls or {}, - host_key_fingerprint=sandbox.host_key_fingerprint or None, - ) - - -def _default_spec() -> openshell_pb2.SandboxSpec: - # Omit the policy field so the sandbox container discovers its policy - # from /etc/openshell/policy.yaml (baked into the image at build time). - # This avoids duplicating policy defaults between the SDK and the - # container image and ensures sandboxes get the full dev-sandbox-policy - # (including network_policies) out of the box. - return openshell_pb2.SandboxSpec() - - -def _sandbox_workload_template( - *, - name: str, - image: str | None = None, - labels: Mapping[str, str] | None = None, - annotations: Mapping[str, str] | None = None, - environment: Mapping[str, str] | None = None, - cpu: str | None = None, - memory: str | None = None, - gpu_count: int | None = None, - gpu: bool = False, - driver_config: Mapping[str, Any] | None = None, -) -> openshell_pb2.SandboxWorkloadTemplate: - if gpu_count is not None and gpu_count <= 0: - raise SandboxError("gpu_count must be greater than zero") - - template = openshell_pb2.SandboxWorkloadTemplate() - template.metadata.name = name - # The gateway permits an empty workload so it can apply the default image - # at sandbox create time, but the workload message itself is required. - template.spec.workload.SetInParent() - if labels: - template.metadata.labels.update(dict(labels)) - if annotations: - template.metadata.annotations.update(dict(annotations)) - - if image is not None: - template.spec.workload.image = image - if environment: - template.spec.workload.environment.update(dict(environment)) - if cpu is not None: - template.spec.workload.resources.cpu = cpu - if memory is not None: - template.spec.workload.resources.memory = memory - if gpu or gpu_count is not None: - template.spec.workload.resources.gpu.SetInParent() - if gpu_count is not None: - template.spec.workload.resources.gpu.count = gpu_count - if driver_config: - template.spec.driver_config.update(dict(driver_config)) - - return template - - -def _xdg_config_home() -> pathlib.Path: - configured = os.environ.get("XDG_CONFIG_HOME") - if configured: - return pathlib.Path(configured) - return pathlib.Path.home() / ".config" - - -# Re-check the cached token roughly 30 seconds before the issuer's -# stated expiry, to leave room for in-flight RPCs and clock skew. This -# matches `openshell-bootstrap::oidc_token::is_token_expired`. -_OIDC_TOKEN_EXPIRY_GRACE_SECONDS = 30 - -_IS_WINDOWS = os.name == "nt" -_WINDOWS_REPLACE_RETRYABLE_ERRORS = frozenset({5, 32}) -_WINDOWS_REPLACE_TIMEOUT_SECONDS = 0.25 -_WINDOWS_REPLACE_INITIAL_DELAY_SECONDS = 0.005 -_WINDOWS_REPLACE_MAX_DELAY_SECONDS = 0.05 -_WINDOWS_REPLACE_LOCK = threading.Lock() - - -def _atomic_replace(source: pathlib.Path, destination: pathlib.Path) -> None: - """Atomically replace a file, retrying transient Windows sharing errors.""" - if not _IS_WINDOWS: - source.replace(destination) - return - - # Serialize writers in this process. The retry still handles other - # processes (including the Rust CLI) and filesystem scanners that briefly - # open the destination without delete sharing. - with _WINDOWS_REPLACE_LOCK: - deadline = time.monotonic() + _WINDOWS_REPLACE_TIMEOUT_SECONDS - delay = _WINDOWS_REPLACE_INITIAL_DELAY_SECONDS - while True: - try: - source.replace(destination) - return - except PermissionError as error: - winerror = getattr(error, "winerror", None) - retryable = winerror in _WINDOWS_REPLACE_RETRYABLE_ERRORS or ( - winerror is None and error.errno == errno.EACCES - ) - if not retryable or time.monotonic() >= deadline: - raise - time.sleep(delay) - delay = min(delay * 2, _WINDOWS_REPLACE_MAX_DELAY_SECONDS) - - -def _read_oidc_token_bundle(gateway_dir: pathlib.Path) -> dict | None: - """Read and parse `oidc_token.json` for a gateway. - - Returns the parsed dict, or `None` if the file is absent or unreadable. - See `openshell-bootstrap::oidc_token::store_oidc_token` for the writer. - """ - token_path = gateway_dir / "oidc_token.json" - try: - return json.loads(token_path.read_text(encoding="utf-8")) - except FileNotFoundError: - return None - except (OSError, UnicodeDecodeError, json.JSONDecodeError): - return None - - -def _normalize_issuer(bundle: dict) -> str | None: - """Return the bundle's issuer with a trailing slash stripped. - - Used to detect whether the issuer changed when adopting a bundle - re-read from disk, so a cached token endpoint computed for the old - issuer can be invalidated. Trailing-slash differences are treated as - equal, matching `_discover_token_endpoint`'s normalization. - """ - issuer = bundle.get("issuer") - return issuer.rstrip("/") if isinstance(issuer, str) else None - - -def _load_cluster_bearer_token(gateway_dir: pathlib.Path) -> str | None: - """Read a single (possibly expired) access token from disk. - - Lower-level helper used by both the legacy single-shot path and the - refreshing provider. Returns the raw access_token string or None. - """ - bundle = _read_oidc_token_bundle(gateway_dir) - if bundle is None: - return None - access_token = bundle.get("access_token") - if not isinstance(access_token, str) or not access_token: - return None - return access_token - - -def _make_fail_closed_bearer_provider( - gateway_dir: pathlib.Path, - cluster_name: str, -) -> Callable[[], str]: - """Per-RPC provider that re-reads `oidc_token.json` but does NOT refresh. - - Raises `SandboxError` when the token is missing or expired. Available as - an opt-out from the default `_OidcRefresher` for callers (e.g. tests) - that want to assert expiry behavior or that don't want the SDK to make - outbound HTTP calls to the IdP. - """ - - def provider() -> str: - bundle = _read_oidc_token_bundle(gateway_dir) - if bundle is None: - raise SandboxError( - f"OIDC token for gateway '{cluster_name}' is missing or " - f"unreadable. Re-authenticate with: openshell gateway login" - ) - access_token = bundle.get("access_token") - if not isinstance(access_token, str) or not access_token: - raise SandboxError( - f"OIDC token for gateway '{cluster_name}' has no access " - f"token. Re-authenticate with: openshell gateway login" - ) - expires_at = bundle.get("expires_at") - if isinstance(expires_at, int): - now = int(time.time()) - if now + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS >= expires_at: - raise SandboxError( - f"OIDC token for gateway '{cluster_name}' has expired. " - f"Re-authenticate with: openshell gateway login" - ) - return access_token - - return provider - - -class _InvalidGrantError(SandboxError): - """Refresh failed with OAuth2 `invalid_grant` (RFC 6749 §5.2). - - The refresh_token was rejected — expired, revoked, or rotated out by - a concurrent refresh in another process. Subclass of `SandboxError` - so an uncaught instance still surfaces the standard re-authenticate - hint; `current_access_token` catches it to retry once with a - peer-rotated bundle before giving up. - """ - - -class _OidcRefresher: - """Thread-safe in-process OAuth2 refresh for a gateway's `oidc_token.json`. - - Mirrors the lazy-refresh pattern used by `google-auth`'s `Credentials` - and `botocore`'s `SSOTokenProvider`. Uses `httpx` for transport so - we can pin `follow_redirects=False` and the TLS verification policy - explicitly — same posture as the Rust CLI's use of `reqwest` with - `Policy::none()` and an opt-in `danger_accept_invalid_certs` (see - `crates/openshell-cli/src/oidc_auth.rs::http_client`). The OAuth2 - refresh-token grant itself (RFC 6749 §6) is a single form-encoded - POST, handled inline rather than via an OAuth2 library. - - Properties: - - - **Lazy**: check expiry on every RPC; refresh only when stale. - - **Lock-coordinated**: concurrent RPCs share a single refresh, not - one per call. Plain `threading.Lock` (no separate worker thread, - unlike `google-auth`'s `RefreshThreadManager` — sufficient for - our use case). - - **Disk-aware**: before refreshing, re-read `oidc_token.json` — - the CLI or another process may have already rotated the bundle. - - **Discovery-validated**: fetches the OIDC discovery document - from `/.well-known/openid-configuration`, rejects - responses whose `issuer` field doesn't match the configured one - (preventing SSRF / misdirection of the refresh_token to an - attacker-controlled endpoint). Mirrors the Rust CLI's - `discover()` function. - - **Redirect-hardened**: `follow_redirects=False` on the underlying - `httpx.Client` so a 3xx during discovery or refresh is treated - as a failure rather than silently chasing the redirect to an - arbitrary host. - - **Write-back by default**: when `auto_refresh=True`, refreshed - bundles are atomically persisted to `oidc_token.json` at mode - 0600 so other processes (Rust CLI, TUI, other Python clients) - see the rotated `refresh_token`. Required for IdPs that - invalidate the old `refresh_token` on rotation (Keycloak with - rotation enabled, Entra in strict mode); without write-back, a - second process would `invalid_grant` on next refresh. - - **`insecure=True` flag** disables TLS certificate verification - for the discovery and refresh calls. Matches the Rust CLI's - `--insecure` plumbing for OIDC issuers behind self-signed certs. - - **Refresh failures** surface as `SandboxError` with a - "re-authenticate with: openshell gateway login" hint. - """ - - def __init__( - self, - gateway_dir: pathlib.Path, - cluster_name: str, - *, - write_back: bool = True, - insecure: bool = False, - ) -> None: - self._gateway_dir = gateway_dir - self._cluster_name = cluster_name - self._write_back = write_back - self._lock = threading.Lock() - self._bundle: dict | None = None - self._token_endpoint: str | None = None - # Single httpx.Client serves both discovery (unauthenticated - # GET) and refresh (POST with form-encoded body) — they share - # the same security posture. - # - # - follow_redirects=False: a 3xx during discovery would - # otherwise steer us to an attacker-controlled token - # endpoint. Matches `reqwest::redirect::Policy::none()` in - # the Rust CLI's `oidc_auth.rs::http_client`. - # - verify=not insecure: opt-in TLS-verification disable for - # self-signed issuers. Matches the Rust CLI's `--insecure` - # flag plumbing. - # - # We don't use authlib's `OAuth2Client` here because it - # auto-injects an Authorization header on every request from - # its stored token, which would break the unauthenticated - # discovery GET. The refresh_token grant for a public client - # is a single form-encoded POST — small enough to spell out - # directly with httpx, and easier to test. - self._http = httpx.Client( - follow_redirects=False, - verify=not insecure, - timeout=15.0, - ) - - def close(self) -> None: - self._http.close() - - def __del__(self) -> None: - # Best-effort cleanup; tests + short-lived callers may not call - # close() explicitly. - with contextlib.suppress(Exception): - self._http.close() - - def current_access_token(self) -> str: - """Return a non-expired access token, refreshing if needed.""" - with self._lock: - if self._bundle is None: - self._bundle = _read_oidc_token_bundle(self._gateway_dir) - if self._bundle is None: - raise SandboxError( - f"OIDC token for gateway '{self._cluster_name}' is " - f"missing or unreadable. Re-authenticate with: " - f"openshell gateway login" - ) - if self._is_fresh(self._bundle): - return self._bundle["access_token"] - # Cached bundle is stale. Before refreshing, re-read disk — - # another process (CLI, TUI, another SDK client) may have - # rotated the bundle while we were idle. Adopt the disk - # bundle when it was refreshed more recently than ours, EVEN - # WHEN its access token is also stale: otherwise we'd refresh - # with our in-memory refresh_token, which a rotating IdP may - # have already invalidated when the other process refreshed - # (Keycloak with rotation, Entra in strict mode). - # - # "More recently" is judged by `expires_at`: a refresh issues - # a new access token with a forward expiry alongside the - # (possibly rotated) refresh_token, so the bundle with the - # later expiry carries the newest refresh_token. This also - # preserves the write_back=False case, where our in-memory - # bundle has already rotated past the on-disk one and must - # NOT be clobbered by the older disk copy. - disk = _read_oidc_token_bundle(self._gateway_dir) - if disk is not None and self._expiry(disk) > self._expiry(self._bundle): - # If the issuer changed under us, the cached token - # endpoint no longer applies — force re-discovery. - if _normalize_issuer(disk) != _normalize_issuer(self._bundle): - self._token_endpoint = None - self._bundle = disk - if self._is_fresh(disk): - return disk["access_token"] - # Truly stale; refresh against the IdP using the freshest - # bundle we have (disk if it was newer, else in-memory). - try: - self._bundle = self._refresh(self._bundle) - except _InvalidGrantError as exc: - # We lost a cross-process rotation race: between our disk - # re-read above and our refresh POST, a peer (CLI, TUI, - # another SDK client) rotated the refresh_token and the - # IdP invalidated ours. This is the residual window that - # neither google-auth nor botocore close without an OS - # file lock. Rather than lock, recover: re-read disk once - # and, if a peer wrote a *different* refresh_token, retry - # with it before surfacing a re-authenticate error. - self._bundle = self._recover_from_invalid_grant(self._bundle, exc) - if self._write_back: - self._write_to_disk(self._bundle) - return self._bundle["access_token"] - - def _recover_from_invalid_grant( - self, attempted: dict, exc: _InvalidGrantError - ) -> dict: - """Re-read disk after an `invalid_grant` and retry once if a peer - rotated the refresh_token. - - `attempted` is the bundle whose refresh_token the IdP just - rejected. If disk now holds a different refresh_token, a - concurrent process won the rotation race — adopt and reuse it - (returning early if it is already fresh, otherwise refreshing - with it). If disk offers nothing new, the rejection is genuine: - re-raise so the caller sees the re-authenticate hint. - """ - disk = _read_oidc_token_bundle(self._gateway_dir) - if disk is None or disk.get("refresh_token") == attempted.get("refresh_token"): - # No peer rotation — the refresh_token really is dead. - raise exc - if _normalize_issuer(disk) != _normalize_issuer(attempted): - self._token_endpoint = None - if self._is_fresh(disk): - return disk - # Single retry with the peer's rotated token; a second - # _InvalidGrantError here propagates (no further retry). - return self._refresh(disk) - - @staticmethod - def _is_fresh(bundle: dict) -> bool: - access_token = bundle.get("access_token") - if not isinstance(access_token, str) or not access_token: - return False - exp = bundle.get("expires_at") - if not isinstance(exp, int): - # No expiry info — treat as fresh (matches the - # `is_token_expired` semantics in the Rust CLI). - return True - return int(time.time()) + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS < exp - - @staticmethod - def _expiry(bundle: dict) -> float: - """Access-token expiry as a comparable number. - - A bundle without an `expires_at` is treated as non-expiring - (`+inf`) — consistent with `_is_fresh`, which treats a missing - expiry as always fresh. Used to decide which of two stale - bundles (in-memory vs. on-disk) was refreshed more recently and - therefore holds the newest refresh_token. - """ - exp = bundle.get("expires_at") - return float(exp) if isinstance(exp, int) else float("inf") - - def _discover_token_endpoint(self, bundle: dict) -> str: - if self._token_endpoint is not None: - return self._token_endpoint - issuer = bundle.get("issuer") - if not isinstance(issuer, str) or not issuer: - raise SandboxError( - f"OIDC bundle for gateway '{self._cluster_name}' has no " - f"`issuer`; cannot refresh. Re-authenticate with: openshell " - f"gateway login" - ) - normalized_issuer = issuer.rstrip("/") - discovery_url = f"{normalized_issuer}/.well-known/openid-configuration" - try: - resp = self._http.get(discovery_url) - except httpx.HTTPError as e: - raise SandboxError( - f"OIDC discovery failed for gateway " - f"'{self._cluster_name}': {e}. Re-authenticate with: " - f"openshell gateway login" - ) from e - # follow_redirects=False means a 3xx surfaces as a non-2xx - # status; treat any non-success as a discovery failure rather - # than silently following. - if not 200 <= resp.status_code < 300: - raise SandboxError( - f"OIDC discovery failed for gateway " - f"'{self._cluster_name}': HTTP {resp.status_code} " - f"from {discovery_url}. Re-authenticate with: openshell " - f"gateway login" - ) - try: - disco = resp.json() - except ValueError as e: - raise SandboxError( - f"OIDC discovery returned invalid JSON for gateway " - f"'{self._cluster_name}': {e}" - ) from e - # Critical: validate that the discovery document's `issuer` - # matches the configured one. Without this, a misdirected or - # malicious discovery response could steer the refresh_token - # POST to an attacker-controlled endpoint. - discovered_issuer = disco.get("issuer", "") - if not isinstance(discovered_issuer, str) or ( - discovered_issuer.rstrip("/") != normalized_issuer - ): - raise SandboxError( - f"OIDC discovery issuer mismatch for gateway " - f"'{self._cluster_name}': expected '{normalized_issuer}', " - f"got '{discovered_issuer}'." - ) - endpoint = disco.get("token_endpoint") - if not isinstance(endpoint, str) or not endpoint: - raise SandboxError( - f"OIDC discovery for gateway '{self._cluster_name}' did " - f"not include a token_endpoint." - ) - self._token_endpoint = endpoint - return endpoint - - def _refresh(self, bundle: dict) -> dict: - refresh_token = bundle.get("refresh_token") - if not isinstance(refresh_token, str) or not refresh_token: - raise SandboxError( - f"OIDC token for gateway '{self._cluster_name}' has no " - f"refresh token. Re-authenticate with: openshell gateway " - f"login" - ) - token_endpoint = self._discover_token_endpoint(bundle) - client_id = bundle.get("client_id", "openshell-cli") - - # RFC 6749 §6: refresh_token grant. Form-encoded POST with - # grant_type, refresh_token, and (for a public client) client_id. - # No Authorization header (token_endpoint_auth_method="none"). - try: - resp = self._http.post( - token_endpoint, - data={ - "grant_type": "refresh_token", - "refresh_token": refresh_token, - "client_id": client_id, - }, - ) - except httpx.HTTPError as e: - raise SandboxError( - f"OIDC token refresh failed for gateway " - f"'{self._cluster_name}': {type(e).__name__}: {e}. " - f"Re-authenticate with: openshell gateway login" - ) from e - if resp.status_code != 200: - # Include the IdP's error body for diagnostics — RFC 6749 - # mandates a JSON body like {"error":"invalid_grant", ...} - # on failure, which is the most useful signal to surface. - error_code = None - with contextlib.suppress(Exception): - body = resp.json() - if isinstance(body, dict): - error_code = body.get("error") - detail = "" - with contextlib.suppress(Exception): - detail = f": {resp.text[:200]}" - message = ( - f"OIDC token refresh failed for gateway " - f"'{self._cluster_name}': HTTP {resp.status_code}" - f"{detail}. Re-authenticate with: openshell gateway " - f"login" - ) - # `invalid_grant` specifically means the refresh_token was - # rejected — distinguished from transport/5xx errors so the - # caller can retry once with a peer-rotated bundle (a lost - # cross-process rotation race) before surfacing the failure. - if error_code == "invalid_grant": - raise _InvalidGrantError(message) - raise SandboxError(message) - try: - token = resp.json() - except ValueError as e: - raise SandboxError( - f"OIDC refresh response for gateway '{self._cluster_name}' " - f"is not JSON: {e}" - ) from e - - access_token = token.get("access_token") - if not isinstance(access_token, str) or not access_token: - raise SandboxError( - f"OIDC refresh response for gateway '{self._cluster_name}' " - f"is missing access_token." - ) - expires_at = token.get("expires_at") - if expires_at is None: - expires_in = token.get("expires_in") - if isinstance(expires_in, (int, float)): - expires_at = int(time.time()) + int(expires_in) - return { - "access_token": access_token, - # Refresh-token rotation: some IdPs (Keycloak with rotation - # enabled, Entra in strict mode) reissue and invalidate the - # old one. Honor the new value when present. - "refresh_token": token.get("refresh_token", refresh_token), - "expires_at": int(expires_at) if expires_at is not None else None, - "issuer": bundle.get("issuer", ""), - "client_id": client_id, - } - - def _write_to_disk(self, bundle: dict) -> None: - """Atomic-replace `oidc_token.json` with the refreshed bundle. - - Strips `None` values to match the Rust writer's - `skip_serializing_if = "Option::is_none"` behavior so a Python- - written file is byte-identical in shape to what the CLI writes. - - Uses `tempfile.mkstemp` (PID + random suffix) so two writers - racing on the same gateway directory don't share a tmp file - and trample each other's content. Each writer gets a unique - path; `.replace()` is atomic per-writer, and POSIX rename - semantics ensure the final `oidc_token.json` is always - complete-and-readable to anyone observing. - """ - path = self._gateway_dir / "oidc_token.json" - serializable = {k: v for k, v in bundle.items() if v is not None} - payload = json.dumps(serializable, indent=2) - - # mkstemp creates the file with mode 0600 already on POSIX - # (it uses O_CREAT | O_EXCL with restrictive umask), so chmod - # is a belt-and-braces step for filesystems that don't honor - # the initial mode. - fd, tmp_name = tempfile.mkstemp( - prefix=".oidc_token.", - suffix=".tmp", - dir=str(self._gateway_dir), - ) - tmp_path = pathlib.Path(tmp_name) - try: - with os.fdopen(fd, "w", encoding="utf-8") as f: - f.write(payload) - with contextlib.suppress(OSError): - tmp_path.chmod(0o600) - _atomic_replace(tmp_path, path) - except BaseException: - # Clean up our tmp on failure so we don't leave orphaned - # `.oidc_token..tmp` files lying around. The replace - # already moved the file on the success path. - with contextlib.suppress(OSError): - tmp_path.unlink() - raise - - -def _make_cluster_bearer_provider( - gateway_dir: pathlib.Path, - cluster_name: str, - *, - auto_refresh: bool = True, - write_back: bool = True, - insecure: bool = False, -) -> tuple[Callable[[], str], Callable[[], None] | None]: - """Build a per-RPC token provider for a gateway directory. - - Returns `(token_provider, close_fn_or_none)`. `close_fn` is non-None - only when an `_OidcRefresher` was constructed; callers that own the - provider's lifecycle (e.g. `SandboxClient.close()`) should invoke - it during teardown so the underlying httpx.Client is released - rather than relying on `__del__`. - - With `auto_refresh=True` (the default), returns an `_OidcRefresher`- - backed callable that lazily refreshes against the IdP's token endpoint - when the cached bundle is stale. This mirrors the lazy-refresh pattern - used by `google.oauth2.credentials.Credentials` and - `botocore.tokens.SSOTokenProvider` and lets long-running scripts - survive token rotation without intervention. - - With `auto_refresh=False`, falls back to the read-only / fail-closed - behavior: the SDK consumes whatever the CLI most recently wrote and - raises `SandboxError` when the token expires. Useful for tests or - callers that don't want the SDK to make outbound HTTP calls to the - IdP. No close_fn is returned in this case. - - `write_back=True` (only meaningful when `auto_refresh=True`) makes the - refresher atomically persist the rotated bundle back to - `oidc_token.json` so other processes — including the Rust CLI — see - the new token. Defaults to True because OIDC providers with - refresh-token rotation (Keycloak, Entra) invalidate the old - refresh_token on rotation; an in-memory-only refresh would leave the - on-disk bundle pointing at an invalidated value, and any other - process starting from that disk state would fail on its first - refresh. - - `insecure=True` disables TLS certificate verification for both the - OIDC discovery document fetch and the refresh-token POST. Mirrors - the Rust CLI's `--insecure` flag for OIDC issuers behind self-signed - certs. - """ - if not auto_refresh: - return _make_fail_closed_bearer_provider(gateway_dir, cluster_name), None - refresher = _OidcRefresher( - gateway_dir, - cluster_name, - write_back=write_back, - insecure=insecure, - ) - return refresher.current_access_token, refresher.close - - -def _resolve_active_cluster() -> str: - env_gateway = os.environ.get("OPENSHELL_GATEWAY") - if env_gateway: - return env_gateway - active_file = _xdg_config_home() / "openshell" / "active_gateway" - try: - value = active_file.read_text(encoding="utf-8").strip() - except FileNotFoundError: - raise SandboxError("no active gateway configured") from None - if value == "": - raise SandboxError("no active gateway configured") - return value diff --git a/python/openshell/sandbox_cleanup_test.py b/python/openshell/sandbox_cleanup_test.py deleted file mode 100644 index 0450877b51..0000000000 --- a/python/openshell/sandbox_cleanup_test.py +++ /dev/null @@ -1,286 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Cleanup status handling through the curated client's real gRPC interceptor.""" - -import time -from concurrent import futures -from contextlib import nullcontext -from types import SimpleNamespace - -import grpc -import pytest - -from openshell._proto import openshell_pb2 -from openshell.errors import GatewayError -from openshell.sandbox import Sandbox, SandboxClient - - -@pytest.fixture -def cleanup_client(): - state = SimpleNamespace( - exists=False, - code=grpc.StatusCode.NOT_FOUND, - delete_delay=0.0, - calls=[], - closed=[], - ) - - def fail(context): - context.set_trailing_metadata((("request-id", "cleanup-regression"),)) - context.abort(state.code, "cleanup status") - - def get(request, context): - state.calls.append("GetSandbox") - assert request.name == "cleanup-test" - assert request.workspace_scope.workspace == "default" - if not state.exists: - fail(context) - response = openshell_pb2.SandboxResponse() - response.sandbox.metadata.id = "sandbox-1" - response.sandbox.metadata.name = request.name - response.sandbox.metadata.workspace = "default" - response.sandbox.status.phase = openshell_pb2.SANDBOX_PHASE_READY - return response - - def delete(request, context): - state.calls.append("DeleteSandbox") - assert request.name == "cleanup-test" - assert request.workspace_scope.workspace == "default" - assert request.allow_missing - time.sleep(state.delete_delay) - if state.code == grpc.StatusCode.NOT_FOUND: - return openshell_pb2.DeleteSandboxResponse( - outcome=openshell_pb2.DELETION_OUTCOME_ALREADY_ABSENT - ) - fail(context) - - server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) - server.add_generic_rpc_handlers( - ( - grpc.method_handlers_generic_handler( - "openshell.v1.OpenShell", - { - "GetSandbox": grpc.unary_unary_rpc_method_handler( - get, - request_deserializer=openshell_pb2.GetSandboxRequest.FromString, - response_serializer=openshell_pb2.SandboxResponse.SerializeToString, - ), - "DeleteSandbox": grpc.unary_unary_rpc_method_handler( - delete, - request_deserializer=openshell_pb2.DeleteSandboxRequest.FromString, - response_serializer=openshell_pb2.DeleteSandboxResponse.SerializeToString, - ), - }, - ), - ) - ) - port = server.add_insecure_port("127.0.0.1:0") - server.start() - client = SandboxClient( - f"127.0.0.1:{port}", - timeout=5, - _bearer_close=lambda: state.closed.append(True), - ) - try: - yield client, state - finally: - client.close() - server.stop(0).wait() - - -def assert_original_call(error, code): - assert isinstance(error, GatewayError) - assert isinstance(error.raw_error, grpc.Call) - assert error.code() == error.raw_error.code() == code - assert error.details() == "cleanup status" - assert ("request-id", "cleanup-regression") in error.trailing_metadata() - - -@pytest.mark.parametrize( - "code", - [ - grpc.StatusCode.NOT_FOUND, - grpc.StatusCode.PERMISSION_DENIED, - grpc.StatusCode.UNAVAILABLE, - ], -) -def test_wait_deleted_handles_intercepted_status(cleanup_client, code): - client, state = cleanup_client - state.code = code - # Prove this is the curated intercepted stub, not a fake raw exception. - with pytest.raises(GatewayError) as observed: - client.get("cleanup-test", workspace="default") - assert_original_call(observed.value, code) - - expected = ( - nullcontext() - if code == grpc.StatusCode.NOT_FOUND - else pytest.raises(GatewayError) - ) - with expected as caught: - client.wait_deleted("cleanup-test", workspace="default", timeout_seconds=5) - if caught is not None: - assert_original_call(caught.value, code) - assert state.calls == ["GetSandbox", "GetSandbox"] - - -@pytest.mark.parametrize( - "code", - [ - grpc.StatusCode.NOT_FOUND, - grpc.StatusCode.PERMISSION_DENIED, - grpc.StatusCode.UNAVAILABLE, - ], -) -def test_context_cleanup_handles_absence_and_intercepted_errors( - cleanup_client, monkeypatch, code -): - client, state = cleanup_client - state.code = code - state.exists = True - monkeypatch.setattr( - SandboxClient, - "from_active_cluster", - classmethod(lambda _cls, **_kwargs: client), - ) - - managed = Sandbox(workspace="default", sandbox="cleanup-test") - expected = ( - nullcontext() - if code == grpc.StatusCode.NOT_FOUND - else pytest.raises(GatewayError) - ) - with expected as caught, managed: - state.exists = False - if caught is not None: - assert_original_call(caught.value, code) - assert state.calls == ["GetSandbox", "GetSandbox", "DeleteSandbox"] - assert state.closed == [True] - assert managed._client is None - assert managed._session is None - - -@pytest.mark.parametrize( - ("client_timeout", "delete_timeout_seconds", "expect_deadline"), - [(0.2, None, True), (0.2, 5, False), (5, 0.2, True)], -) -def test_context_cleanup_delete_timeout_is_opt_in( - cleanup_client, - monkeypatch, - client_timeout, - delete_timeout_seconds, - expect_deadline, -): - client, state = cleanup_client - state.exists = True - state.delete_delay = 0.5 - monkeypatch.setattr( - SandboxClient, - "from_active_cluster", - classmethod(lambda _cls, **_kwargs: client), - ) - - managed = Sandbox( - workspace="default", - sandbox="cleanup-test", - delete_timeout_seconds=delete_timeout_seconds, - ) - expected = pytest.raises(GatewayError) if expect_deadline else nullcontext() - with expected as caught, managed: - # Only the exit delete runs under the short deadline. - client._timeout = client_timeout - state.exists = False - if caught is not None: - assert caught.value.code() == grpc.StatusCode.DEADLINE_EXCEEDED - assert state.calls == ["GetSandbox", "GetSandbox", "DeleteSandbox"] - assert state.closed == [True] - assert managed._client is None - assert managed._session is None - - -class _EntryFailureClient: - """Fails the named client call and records close().""" - - def __init__(self, fail_at, close_error=None): - self.fail_at = fail_at - self.close_error = close_error - self.closed = 0 - self.error = RuntimeError(f"{fail_at} failed") - - def _step(self, name): - if name == self.fail_at: - raise self.error - return SimpleNamespace(sandbox=SimpleNamespace(name="s1")) - - def create_session(self, **_kwargs): - return self._step("create_session") - - def create_session_from_template(self, **_kwargs): - return self._step("create_session_from_template") - - def get_session(self, *_args, **_kwargs): - return self._step("get_session") - - def wait_ready(self, *_args, **_kwargs): - self._step("wait_ready") - return SimpleNamespace(name="s1", workspace="default") - - def close(self): - self.closed += 1 - if self.close_error is not None: - raise self.close_error - - -def _use_client(monkeypatch, client): - monkeypatch.setattr( - SandboxClient, "from_active_cluster", classmethod(lambda _cls, **_kw: client) - ) - - -@pytest.mark.parametrize( - ("fail_at", "kwargs"), - [ - ("create_session", {}), - ("create_session_from_template", {"workload_template": "t"}), - ("get_session", {"sandbox": "existing"}), - ("wait_ready", {}), - ("wait_ready", {"sandbox": "existing"}), - ], -) -def test_context_entry_failure_closes_client(monkeypatch, fail_at, kwargs): - client = _EntryFailureClient(fail_at) - _use_client(monkeypatch, client) - managed = Sandbox(workspace="default", delete_on_exit=False, **kwargs) - - with pytest.raises(RuntimeError) as observed, managed: - pass - - assert observed.value is client.error - assert client.closed == 1 - assert managed._client is None - assert managed._session is None - - -def test_context_entry_failure_keeps_original_error_when_close_fails(monkeypatch): - client = _EntryFailureClient("wait_ready", close_error=OSError("close failed")) - _use_client(monkeypatch, client) - managed = Sandbox(workspace="default") - - with pytest.raises(RuntimeError) as observed, managed: - pass - - assert observed.value is client.error - assert client.closed == 1 - assert managed._client is None - assert managed._session is None - - -def test_context_closes_client_once_on_success(monkeypatch): - client = _EntryFailureClient(None) - _use_client(monkeypatch, client) - - with Sandbox(workspace="default", delete_on_exit=False): - assert client.closed == 0 - - assert client.closed == 1 diff --git a/python/openshell/sandbox_test.py b/python/openshell/sandbox_test.py deleted file mode 100644 index b9b059f00b..0000000000 --- a/python/openshell/sandbox_test.py +++ /dev/null @@ -1,3300 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -from __future__ import annotations - -import contextlib -import json -import os -import pickle -import threading -import time -from concurrent import futures -from copy import deepcopy -from dataclasses import asdict -from pathlib import Path -from types import SimpleNamespace -from typing import TYPE_CHECKING, Any, Never, cast - -import grpc -import pytest -from google.protobuf.struct_pb2 import Struct - -import openshell.sandbox as sandbox_module -from openshell._proto import openshell_pb2, openshell_pb2_grpc -from openshell.mutations import DeletionOutcome -from openshell.sandbox import ( - _OIDC_TOKEN_EXPIRY_GRACE_SECONDS, - _PYTHON_CLOUDPICKLE_BOOTSTRAP, - _SANDBOX_PYTHON_BIN, - ClientCredentialsAuth, - Page, - Pager, - Sandbox, - SandboxClient, - SandboxConditionRef, - SandboxError, - SandboxRef, - SandboxStatusRef, - SandboxTemplateClient, - ServiceAuthorizationMode, - ServiceExposure, - TlsConfig, - _atomic_replace, - _BearerAuthInterceptor, - _load_cluster_bearer_token, - _make_cluster_bearer_provider, - _normalize_bearer, - _OidcRefresher, - _OwnerCache, - _read_oidc_token_bundle, - _sandbox_ref, - _validate_oauth_url, -) - -if TYPE_CHECKING: - from collections.abc import Generator - - -def _request_workspace(request: Any) -> str | None: - scope = request.workspace_scope - if scope.WhichOneof("selection") == "workspace": - return cast("str", scope.workspace) - return None - - -def _request_selects_all_workspaces(request: Any) -> bool: - return request.workspace_scope.WhichOneof("selection") == "all_workspaces" - - -def _request_sandbox(request: Any) -> str: - name = getattr(request, "name", "") - if name: - return cast("str", name) - return cast("str", request.sandbox) - - -def _client_credentials_fixture() -> dict[str, Any]: - return json.loads( - ( - Path(__file__).parents[2] / "sdk/conformance/oauth-client-credentials.json" - ).read_text() - ) - - -def test_oauth_client_credentials_conformance_fixture() -> None: - fixture = _client_credentials_fixture() - assert fixture["expiry"]["leeway_seconds"] == _OIDC_TOKEN_EXPIRY_GRACE_SECONDS - for value in fixture["urls"]["allowed"]: - assert _validate_oauth_url("issuer", value) == value - for value in fixture["urls"]["rejected"]: - with pytest.raises(SandboxError): - _validate_oauth_url("issuer", value) - - -def test_client_credentials_auth_exact_form_cache_and_redaction() -> None: - fixture = _client_credentials_fixture() - seen: list[tuple[str, bytes]] = [] - - def handler(request: Any) -> Any: - import httpx - - seen.append((str(request.url), bytes(request.content))) - if request.method == "GET": - return httpx.Response( - 200, - json={ - "issuer": "https://issuer.example.com/", - "token_endpoint": "https://issuer.example.com/token", - }, - ) - return httpx.Response( - 200, - json={ - "access_token": "service-token", - "expires_in": fixture["expiry"]["valid_expires_in"], - }, - ) - - import httpx - - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="service-client", - client_secret="conformance-secret", - scopes=("sandbox:read", "sandbox:write"), - audience="openshell-gateway", - _transport=httpx.MockTransport(handler), - ) - assert auth() == "service-token" - assert auth() == "service-token" - assert len(seen) == 2 - form = dict(__import__("urllib.parse").parse.parse_qsl(seen[1][1].decode())) - assert form == { - field: fixture["request"][field] - for field in ( - "grant_type", - "client_id", - "client_secret", - "scope", - "audience", - ) - } - assert "conformance-secret" not in repr(auth) - - -def test_client_credentials_auth_preserves_explicit_empty_scopes() -> None: - import httpx - - form: dict[str, str] = {} - - def handler(request: Any) -> Any: - if request.method == "GET": - return httpx.Response( - 200, - json={ - "issuer": "https://issuer.example.com", - "token_endpoint": "https://issuer.example.com/token", - }, - ) - form.update( - __import__("urllib.parse").parse.parse_qsl(request.content.decode()) - ) - return httpx.Response(200, json={"access_token": "token", "expires_in": 120}) - - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="client", - client_secret="secret", - scopes=(), - _transport=httpx.MockTransport(handler), - ) - auth._apply_gateway_metadata({"oidc_scopes": "sandbox:read sandbox:write"}) - - assert auth() == "token" - assert auth._scopes == () - assert "scope" not in form - - -@pytest.mark.parametrize( - "expires_in", _client_credentials_fixture()["expiry"]["invalid_expires_in"] -) -def test_client_credentials_auth_rejects_invalid_expiry(expires_in: object) -> None: - import httpx - - fixture = _client_credentials_fixture() - - def handler(request: Any) -> Any: - if request.method == "GET": - return httpx.Response( - 200, - json={ - "issuer": fixture["discovery"]["matching_issuer"], - "token_endpoint": "https://issuer.example.com/token", - }, - ) - return httpx.Response( - 200, json={"access_token": "token", "expires_in": expires_in} - ) - - auth = ClientCredentialsAuth( - issuer=fixture["discovery"]["configured_issuer"], - client_id="client", - client_secret="secret", - _transport=httpx.MockTransport(handler), - ) - with pytest.raises(SandboxError, match="positive finite expires_in"): - auth() - - -@pytest.mark.parametrize( - "status", _client_credentials_fixture()["discovery"]["redirect_statuses"] -) -def test_client_credentials_auth_refuses_discovery_redirect(status: int) -> None: - import httpx - - requests = 0 - - def handler(_request: Any) -> Any: - nonlocal requests - requests += 1 - return httpx.Response( - status, - headers={"location": "https://attacker.example.com/discovery"}, - ) - - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="client", - client_secret="secret", - _transport=httpx.MockTransport(handler), - ) - with pytest.raises(SandboxError, match=f"HTTP {status}"): - auth() - assert requests == 1 - - -@pytest.mark.parametrize( - "status", _client_credentials_fixture()["discovery"]["redirect_statuses"] -) -def test_client_credentials_auth_refuses_token_redirect(status: int) -> None: - import httpx - - requests: list[str] = [] - - def handler(request: Any) -> Any: - requests.append(str(request.url)) - if request.method == "GET": - return httpx.Response( - 200, - json={ - "issuer": "https://issuer.example.com", - "token_endpoint": "https://issuer.example.com/token", - }, - ) - return httpx.Response( - status, - headers={"location": "https://attacker.example.com/token"}, - ) - - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="client", - client_secret="secret", - _transport=httpx.MockTransport(handler), - ) - with pytest.raises(SandboxError, match=f"HTTP {status}"): - auth() - assert requests == [ - "https://issuer.example.com/.well-known/openid-configuration", - "https://issuer.example.com/token", - ] - - -def test_client_credentials_auth_rejects_discovery_issuer_mismatch() -> None: - import httpx - - fixture = _client_credentials_fixture() - auth = ClientCredentialsAuth( - issuer=fixture["discovery"]["configured_issuer"], - client_id="client", - client_secret="secret", - _transport=httpx.MockTransport( - lambda _request: httpx.Response( - 200, - json={ - "issuer": fixture["discovery"]["mismatched_issuer"], - "token_endpoint": "https://attacker.example.com/token", - }, - ) - ), - ) - with pytest.raises(SandboxError, match="issuer mismatch"): - auth() - - -def test_client_credentials_auth_rejects_oversized_response() -> None: - import httpx - - fixture = _client_credentials_fixture() - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="client", - client_secret="secret", - _transport=httpx.MockTransport( - lambda _request: httpx.Response( - 200, content=b"x" * (fixture["limits"]["max_response_bytes"] + 1) - ) - ), - ) - with pytest.raises(SandboxError, match="too large"): - auth() - - -def test_client_credentials_auth_single_flight_and_retry() -> None: - import httpx - - token_calls = 0 - release = threading.Event() - - def handler(request: Any) -> Any: - nonlocal token_calls - if request.method == "GET": - return httpx.Response( - 200, - json={ - "issuer": "http://127.0.0.1:8080", - "token_endpoint": "http://127.0.0.1:8080/token", - }, - ) - token_calls += 1 - release.wait(timeout=2) - return httpx.Response(200, json={"access_token": "shared", "expires_in": 120}) - - auth = ClientCredentialsAuth( - issuer="http://127.0.0.1:8080", - client_id="client", - client_secret="secret", - _transport=httpx.MockTransport(handler), - ) - results: list[str] = [] - threads = [ - threading.Thread(target=lambda: results.append(auth())) for _ in range(8) - ] - for thread in threads: - thread.start() - while token_calls == 0: - time.sleep(0.001) - release.set() - for thread in threads: - thread.join() - assert results == ["shared"] * 8 - assert token_calls == 1 - - -def test_client_credentials_auth_fails_closed_and_redacts_errors() -> None: - import httpx - - def supplier() -> str: - raise RuntimeError("supplier-sensitive-detail") - - auth = ClientCredentialsAuth( - issuer="http://localhost:8080", - client_id="client", - client_secret=supplier, - _transport=httpx.MockTransport( - lambda _request: httpx.Response( - 200, - json={ - "issuer": "http://localhost:8080", - "token_endpoint": "http://localhost:8080/token", - }, - ) - ), - ) - with pytest.raises(SandboxError, match="supplier failed") as exc_info: - auth() - assert "supplier-sensitive-detail" not in str(exc_info.value) - with pytest.raises(SandboxError, match="must use HTTPS"): - ClientCredentialsAuth( - issuer="http://remote.example.com", - client_id="client", - client_secret="secret", - )() - - -def test_client_credentials_auth_does_not_use_stale_token_after_renewal_failure() -> ( - None -): - import httpx - - exchanges = 0 - - def handler(request: Any) -> Any: - nonlocal exchanges - if request.method == "GET": - return httpx.Response( - 200, - json={ - "issuer": "http://localhost:8080", - "token_endpoint": "http://localhost:8080/token", - }, - ) - exchanges += 1 - if exchanges == 1: - return httpx.Response(200, json={"access_token": "stale", "expires_in": 30}) - return httpx.Response(503, json={"error": "provider-sensitive-detail"}) - - auth = ClientCredentialsAuth( - issuer="http://localhost:8080", - client_id="client", - client_secret="secret", - _transport=httpx.MockTransport(handler), - ) - assert auth() == "stale" - with pytest.raises(SandboxError, match="HTTP 503") as exc_info: - auth() - assert "stale" not in str(exc_info.value) - assert "provider-sensitive-detail" not in str(exc_info.value) - - -class _FakeStub: - class GetSandbox: - @staticmethod - def with_call(*_args: object, **_kwargs: object) -> Never: - raise grpc.RpcError() - - def __init__(self) -> None: - self.request: openshell_pb2.ExecSandboxRequest | None = None - - def ExecSandbox( - self, - request: openshell_pb2.ExecSandboxRequest, - timeout: float | None = None, - ): - self.request = request - _ = timeout - yield openshell_pb2.ExecSandboxEvent( - exit=openshell_pb2.ExecSandboxExit(exit_code=0) - ) - - -def _client_with_fake_stub(stub: object) -> SandboxClient: - client = object.__new__(SandboxClient) - client._timeout = 30.0 - client._stub = cast("Any", stub) - client._owners = _OwnerCache() - return client - - -class _RoutingGateway(openshell_pb2_grpc.OpenShellServicer): - """Gateway that reports an owner and, behind a replica route, can answer - like Envoy with a trailers-only UNAVAILABLE.""" - - def __init__( - self, owner: str, *, reject_routed: str | None = None, fail: str = "" - ) -> None: - self.owner = owner - self.reject_routed = reject_routed - self.fail = fail - self.wanted_owner: list[str] = [] - self.routes: list[str] = [] - - def GetSandbox(self, request, context): - _ = request - headers = dict(context.invocation_metadata()) - self.wanted_owner.append(headers.get("x-openshell-want-owner", "")) - if self.owner: - context.send_initial_metadata((("x-openshell-owner", self.owner),)) - return openshell_pb2.SandboxResponse() - - def ExecSandbox(self, request, context): - _ = request - route = dict(context.invocation_metadata()).get("x-openshell-replica", "") - self.routes.append(route) - if route and self.reject_routed is not None: - context.abort(grpc.StatusCode.UNAVAILABLE, self.reject_routed) - if self.fail: - context.abort(grpc.StatusCode.UNAVAILABLE, self.fail) - yield openshell_pb2.ExecSandboxEvent( - stdout=openshell_pb2.ExecSandboxStdout(data=b"ok") - ) - yield openshell_pb2.ExecSandboxEvent( - exit=openshell_pb2.ExecSandboxExit(exit_code=0) - ) - - -@contextlib.contextmanager -def _routing_client(gateway: _RoutingGateway) -> Generator[SandboxClient]: - server = grpc.server(futures.ThreadPoolExecutor(max_workers=2)) - openshell_pb2_grpc.add_OpenShellServicer_to_server(gateway, server) - port = server.add_insecure_port("127.0.0.1:0") - server.start() - try: - with SandboxClient(f"127.0.0.1:{port}", timeout=5) as client: - yield client - finally: - server.stop(None) - - -def test_exec_routes_to_reported_owner_and_caches_it() -> None: - gateway = _RoutingGateway("openshell-1") - with _routing_client(gateway) as client: - for _ in range(2): - result = client.exec("box", ["true"], workspace="default") - assert result.stdout == "ok" - - assert gateway.wanted_owner == ["1"] - assert gateway.routes == ["openshell-1", "openshell-1"] - - -def test_exec_without_owner_sends_no_hint() -> None: - gateway = _RoutingGateway("") - with _routing_client(gateway) as client: - assert client.exec("box", ["true"], workspace="default").exit_code == 0 - - assert gateway.routes == [""] - - -@pytest.mark.parametrize("message", ["", "no healthy upstream"]) -def test_exec_retries_once_unrouted_when_owner_route_is_empty(message: str) -> None: - gateway = _RoutingGateway("openshell-1", reject_routed=message) - with _routing_client(gateway) as client: - for _ in range(2): - result = client.exec("box", ["true"], workspace="default") - assert result.stdout == "ok" - - assert gateway.routes == ["openshell-1", "", "openshell-1", ""] - assert gateway.wanted_owner == ["1", "1"] - - -def test_exec_does_not_retry_gateway_errors() -> None: - gateway = _RoutingGateway("openshell-1", fail="supervisor not connected") - with ( - _routing_client(gateway) as client, - pytest.raises(grpc.RpcError, match="supervisor not connected"), - ): - client.exec("box", ["true"], workspace="default") - - assert gateway.routes == ["openshell-1"] - - -def _template_client_with_fake_stub(stub: object) -> SandboxTemplateClient: - client = object.__new__(SandboxTemplateClient) - client._timeout = 30.0 - client._stub = cast("Any", stub) - return client - - -def test_exec_sends_stdin_payload() -> None: - stub = _FakeStub() - client = _client_with_fake_stub(stub) - - result = client.exec( - "sandbox-1", - ["python", "-c", "print('ok')"], - workspace="default", - stdin=b"payload", - ) - - assert result.exit_code == 0 - assert stub.request is not None - assert stub.request.stdin == b"payload" - - -def test_exec_python_serializes_callable_payload() -> None: - stub = _FakeStub() - client = _client_with_fake_stub(stub) - - def add(a: int, b: int) -> int: - return a + b - - result = client.exec_python("sandbox-1", add, workspace="default", args=(2, 3)) - - assert result.exit_code == 0 - assert stub.request is not None - assert stub.request.command == [ - _SANDBOX_PYTHON_BIN, - "-c", - _PYTHON_CLOUDPICKLE_BOOTSTRAP, - ] - assert stub.request.environment["OPENSHELL_PYFUNC_B64"] - assert stub.request.stdin == b"" - - -def test_from_active_cluster_reads_gateway_metadata_layout( - tmp_path: Path, - monkeypatch: Any, -) -> None: - gateway_name = "test-gateway" - gateway_dir = tmp_path / "openshell" / "gateways" / gateway_name - mtls_dir = gateway_dir / "mtls" - mtls_dir.mkdir(parents=True) - (tmp_path / "openshell" / "active_gateway").write_text(gateway_name) - (gateway_dir / "metadata.json").write_text( - json.dumps({"gateway_endpoint": "https://127.0.0.1:8443"}) - ) - (mtls_dir / "ca.crt").write_text("ca") - (mtls_dir / "tls.crt").write_text("cert") - (mtls_dir / "tls.key").write_text("key") - - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) - monkeypatch.delenv("OPENSHELL_GATEWAY", raising=False) - - client = SandboxClient.from_active_cluster() - try: - assert client._cluster_name == gateway_name - finally: - client.close() - - -def test_from_active_cluster_prefers_openshell_gateway_env( - tmp_path: Path, - monkeypatch: Any, -) -> None: - gateway_name = "env-gateway" - gateway_dir = tmp_path / "openshell" / "gateways" / gateway_name - mtls_dir = gateway_dir / "mtls" - mtls_dir.mkdir(parents=True) - (gateway_dir / "metadata.json").write_text( - json.dumps({"gateway_endpoint": "https://127.0.0.1:8443"}) - ) - (mtls_dir / "ca.crt").write_text("ca") - (mtls_dir / "tls.crt").write_text("cert") - (mtls_dir / "tls.key").write_text("key") - - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) - monkeypatch.setenv("OPENSHELL_GATEWAY", gateway_name) - - client = SandboxClient.from_active_cluster() - try: - assert client._cluster_name == gateway_name - finally: - client.close() - - -# --------------------------------------------------------------------------- -# OIDC bearer auth -# --------------------------------------------------------------------------- - - -class _FakeClientCallDetails: - """grpc.ClientCallDetails is a NamedTuple in real gRPC; for unit tests we - just need an object with the same field set and a ._replace shim.""" - - __slots__ = ("credentials", "metadata", "method", "timeout", "wait_for_ready") - - def __init__( - self, - method: str = "/Test/Method", - timeout: float | None = None, - metadata: Any = None, - credentials: Any = None, - wait_for_ready: Any = None, - ) -> None: - self.method = method - self.timeout = timeout - self.metadata = metadata - self.credentials = credentials - self.wait_for_ready = wait_for_ready - - def _replace(self, **kwargs: Any) -> _FakeClientCallDetails: - return _FakeClientCallDetails( - method=kwargs.get("method", self.method), - timeout=kwargs.get("timeout", self.timeout), - metadata=kwargs.get("metadata", self.metadata), - credentials=kwargs.get("credentials", self.credentials), - wait_for_ready=kwargs.get("wait_for_ready", self.wait_for_ready), - ) - - -def test_normalize_bearer_accepts_str_or_callable() -> None: - assert _normalize_bearer(None) is None - - static = _normalize_bearer("abc") - assert static is not None - assert static() == "abc" - - counter = [0] - - def provider() -> str: - counter[0] += 1 - return f"token-{counter[0]}" - - dynamic = _normalize_bearer(provider) - assert dynamic is not None - assert dynamic() == "token-1" - assert dynamic() == "token-2" - - -def test_bearer_interceptor_attaches_authorization_header() -> None: - interceptor = _BearerAuthInterceptor(lambda: "secret-token") - captured: dict[str, Any] = {} - - def continuation(details: Any, request: Any) -> str: - captured["details"] = details - captured["request"] = request - return "result" - - details = _FakeClientCallDetails(metadata=[("x-existing", "yes")]) - result = interceptor.intercept_unary_unary(continuation, details, "payload") - - assert result == "result" - md = list(captured["details"].metadata) - # Pre-existing metadata preserved, authorization appended last. - assert ("x-existing", "yes") in md - assert ("authorization", "Bearer secret-token") in md - assert captured["request"] == "payload" - - -def test_bearer_interceptor_handles_empty_metadata() -> None: - interceptor = _BearerAuthInterceptor(lambda: "t") - captured: dict[str, Any] = {} - - def continuation(details: Any, _request: Any) -> None: - captured["metadata"] = list(details.metadata) - - details = _FakeClientCallDetails(metadata=None) - interceptor.intercept_unary_unary(continuation, details, request="x") - - assert captured["metadata"] == [("authorization", "Bearer t")] - - -def test_bearer_interceptor_calls_token_provider_per_request() -> None: - tokens = iter(["t1", "t2", "t3"]) - interceptor = _BearerAuthInterceptor(lambda: next(tokens)) - seen: list[str] = [] - - def continuation(details: Any, _request: Any) -> None: - for key, value in details.metadata: - if key == "authorization": - seen.append(value) - - for _ in range(3): - interceptor.intercept_unary_unary( - continuation, _FakeClientCallDetails(), request="x" - ) - - assert seen == ["Bearer t1", "Bearer t2", "Bearer t3"] - - -def test_load_cluster_bearer_token_reads_oidc_token_json(tmp_path: Path) -> None: - gateway_dir = tmp_path / "gw" - gateway_dir.mkdir() - (gateway_dir / "oidc_token.json").write_text( - json.dumps( - { - "access_token": "jwt-blob", - "refresh_token": "rt", - "expires_at": 9999999999, - "issuer": "https://idp.example/realms/openshell", - "client_id": "openshell-cli", - } - ) - ) - assert _load_cluster_bearer_token(gateway_dir) == "jwt-blob" - - -def test_load_cluster_bearer_token_returns_none_when_missing( - tmp_path: Path, -) -> None: - assert _load_cluster_bearer_token(tmp_path / "absent") is None - - -def test_load_cluster_bearer_token_tolerates_unreadable_file( - tmp_path: Path, -) -> None: - gateway_dir = tmp_path / "gw" - gateway_dir.mkdir() - (gateway_dir / "oidc_token.json").write_text("not json") - assert _load_cluster_bearer_token(gateway_dir) is None - - -def test_load_cluster_bearer_token_rejects_missing_access_token( - tmp_path: Path, -) -> None: - gateway_dir = tmp_path / "gw" - gateway_dir.mkdir() - (gateway_dir / "oidc_token.json").write_text(json.dumps({"refresh_token": "rt"})) - assert _load_cluster_bearer_token(gateway_dir) is None - - -def _setup_gateway_dir( - tmp_path: Path, - monkeypatch: Any, - *, - name: str = "g", - endpoint: str = "http://127.0.0.1:8080", - auth_mode: str | None = None, - mtls_files: dict[str, str] | None = None, - oidc_bundle: dict | None = None, -) -> Path: - gateway_dir = tmp_path / "openshell" / "gateways" / name - gateway_dir.mkdir(parents=True) - (tmp_path / "openshell" / "active_gateway").write_text(name) - meta: dict[str, Any] = {"gateway_endpoint": endpoint} - if auth_mode is not None: - meta["auth_mode"] = auth_mode - (gateway_dir / "metadata.json").write_text(json.dumps(meta)) - if mtls_files: - mtls_dir = gateway_dir / "mtls" - mtls_dir.mkdir() - for fname, body in mtls_files.items(): - (mtls_dir / fname).write_text(body) - if oidc_bundle is not None: - (gateway_dir / "oidc_token.json").write_text(json.dumps(oidc_bundle)) - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) - monkeypatch.delenv("OPENSHELL_GATEWAY", raising=False) - return gateway_dir - - -def _channel_is_intercepted(channel: Any) -> bool: - """grpc.intercept_channel returns a _Channel whose module name ends in - `interceptor`. We don't depend on the class name (it varies across - gRPC versions); module is stable.""" - return type(channel).__module__.endswith("interceptor") - - -def test_from_active_cluster_loads_bearer_when_auth_mode_is_oidc( - tmp_path: Path, - monkeypatch: Any, -) -> None: - """Finding 3: bearer is attached iff metadata.auth_mode == "oidc".""" - _setup_gateway_dir( - tmp_path, - monkeypatch, - auth_mode="oidc", - oidc_bundle={"access_token": "from-disk"}, - ) - client = SandboxClient.from_active_cluster() - try: - assert _channel_is_intercepted(client._channel) - finally: - client.close() - - -def test_from_active_cluster_ignores_stale_token_when_auth_mode_not_oidc( - tmp_path: Path, - monkeypatch: Any, -) -> None: - """Finding 3: a stale oidc_token.json alongside a non-OIDC gateway must - NOT cause bearer auth to be attached.""" - _setup_gateway_dir( - tmp_path, - monkeypatch, - # auth_mode omitted (or "mtls", "plaintext") — anything but "oidc". - oidc_bundle={"access_token": "stale-from-disk"}, - ) - client = SandboxClient.from_active_cluster() - try: - # Plain channel, no interceptor wrapper. - assert not _channel_is_intercepted(client._channel) - finally: - client.close() - - -def test_from_active_cluster_https_oidc_without_mtls_uses_tls_with_system_roots( - tmp_path: Path, - monkeypatch: Any, -) -> None: - """Finding 1: https OIDC gateways without mTLS material must still use a - TLS channel (system roots) — NOT fall back to insecure_channel.""" - _setup_gateway_dir( - tmp_path, - monkeypatch, - endpoint="https://gateway.example:443", - auth_mode="oidc", - oidc_bundle={"access_token": "t"}, - ) - client = SandboxClient.from_active_cluster() - try: - # The bearer interceptor wraps the channel, so inspect the - # wrapped channel's class to confirm it's a secure (TLS) channel. - inner = getattr(client._channel, "_channel", client._channel) - # gRPC's `grpc.secure_channel` returns a `_Channel` from - # `grpc._channel`; we can't trivially introspect "secure" vs - # "insecure" on the wrapper itself. Probe by attempting to - # extract the connectivity state — both kinds expose it — and - # rely on a behavioral assertion: an insecure channel against - # a hostname-only endpoint would have already attached TCP-only - # subchannels. Easier: verify TlsConfig() was used by checking - # the SandboxClient endpoint normalized correctly. - # The most direct assertion is on the client config: - assert client._endpoint == "gateway.example:443" - # And the channel must not be insecure. - assert "InsecureChannelCredentials" not in repr(inner) - finally: - client.close() - - -def test_from_active_cluster_https_ca_only_layout( - tmp_path: Path, - monkeypatch: Any, -) -> None: - """Finding 1: a CA-only mtls directory (ca.crt but no tls.crt/tls.key) - must produce a CA-only TLS channel, not a FileNotFoundError.""" - _setup_gateway_dir( - tmp_path, - monkeypatch, - endpoint="https://gateway.example:443", - auth_mode="oidc", - mtls_files={ - "ca.crt": "-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n" - }, - oidc_bundle={"access_token": "t"}, - ) - # Should not raise. - client = SandboxClient.from_active_cluster() - try: - assert client._endpoint == "gateway.example:443" - finally: - client.close() - - -def test_tls_config_rejects_partial_client_identity() -> None: - """Cert without key (or vice versa) is a misconfiguration.""" - import pytest as _pytest - - with _pytest.raises(ValueError, match="cert_path and key_path"): - TlsConfig(cert_path=Path("/x.crt")) - - -def test_tls_config_allows_empty_for_system_roots() -> None: - """`TlsConfig()` is the system-roots-trust flavor.""" - cfg = TlsConfig() - assert cfg.ca_path is None and cfg.cert_path is None and cfg.key_path is None - - -# --------------------------------------------------------------------------- -# Provider semantics: per-RPC reload + expiry -# --------------------------------------------------------------------------- - - -def test_cluster_bearer_provider_reloads_on_every_call(tmp_path: Path) -> None: - """The fail-closed (no-refresh) provider re-reads oidc_token.json each - invocation, so a long-lived SandboxClient picks up CLI rotations - without reconstruction.""" - gateway_dir = tmp_path - token_file = gateway_dir / "oidc_token.json" - token_file.write_text(json.dumps({"access_token": "first"})) - provider, _ = _make_cluster_bearer_provider(gateway_dir, "g", auto_refresh=False) - - assert provider() == "first" - # Simulate `openshell gateway login` writing a new token. - token_file.write_text(json.dumps({"access_token": "second"})) - assert provider() == "second" - - -def test_cluster_bearer_provider_raises_on_expired_token(tmp_path: Path) -> None: - """Fail-closed provider raises on expiry with a clear re-login hint.""" - gateway_dir = tmp_path - (gateway_dir / "oidc_token.json").write_text( - json.dumps({"access_token": "expired", "expires_at": 1}) - ) - provider, _ = _make_cluster_bearer_provider( - gateway_dir, "stale-gateway", auto_refresh=False - ) - - import pytest as _pytest - - with _pytest.raises(SandboxError, match="expired"): - provider() - - -def test_cluster_bearer_provider_raises_when_file_missing(tmp_path: Path) -> None: - provider, _ = _make_cluster_bearer_provider( - tmp_path / "absent", "g", auto_refresh=False - ) - import pytest as _pytest - - with _pytest.raises(SandboxError, match="missing or unreadable"): - provider() - - -def test_cluster_bearer_provider_raises_on_missing_access_token( - tmp_path: Path, -) -> None: - (tmp_path / "oidc_token.json").write_text(json.dumps({"refresh_token": "r"})) - provider, _ = _make_cluster_bearer_provider(tmp_path, "g", auto_refresh=False) - import pytest as _pytest - - with _pytest.raises(SandboxError, match="no access token"): - provider() - - -# --------------------------------------------------------------------------- -# OAuth2 native refresh (_OidcRefresher) — opt-in via auto_refresh=True. -# --------------------------------------------------------------------------- - - -def _write_bundle( - gateway_dir: Path, - *, - access_token: str = "fresh", - refresh_token: str = "r-orig", - expires_at: int | None = None, - issuer: str = "https://idp.example/realms/openshell", - client_id: str = "openshell-cli", -) -> None: - bundle: dict[str, Any] = { - "access_token": access_token, - "refresh_token": refresh_token, - "issuer": issuer, - "client_id": client_id, - } - if expires_at is not None: - bundle["expires_at"] = expires_at - (gateway_dir / "oidc_token.json").write_text(json.dumps(bundle)) - - -DEFAULT_ISSUER = "https://idp.example/realms/openshell" -DEFAULT_TOKEN_ENDPOINT = ( - "https://idp.example/realms/openshell/protocol/openid-connect/token" -) - - -def _make_mock_transport( - *, - discovery: dict | None = None, - refresh_responses: list[dict] | None = None, - discovery_status: int = 200, - refresh_status: int = 200, - seen_refresh: list[Any] | None = None, - seen_discovery: list[Any] | None = None, -): - """Build an httpx.MockTransport that serves OIDC discovery + token - refresh from an in-memory script. - - `refresh_responses` is consumed in order across successive POSTs to - the token endpoint (which lets tests assert refresh-token rotation - semantics across multiple refreshes). - """ - import httpx as _httpx - - refresh_iter = iter( - refresh_responses or [{"access_token": "refreshed-jwt", "expires_in": 3600}] - ) - - def handler(request: _httpx.Request) -> _httpx.Response: - if request.url.path.endswith("/.well-known/openid-configuration"): - if seen_discovery is not None: - seen_discovery.append(str(request.url)) - body = discovery or { - "issuer": DEFAULT_ISSUER, - "token_endpoint": DEFAULT_TOKEN_ENDPOINT, - } - return _httpx.Response(discovery_status, json=body) - # Anything else is a refresh exchange. - if seen_refresh is not None: - seen_refresh.append((str(request.url), bytes(request.content))) - try: - body = next(refresh_iter) - except StopIteration: - return _httpx.Response(500, json={"error": "test_script_exhausted"}) - return _httpx.Response(refresh_status, json=body) - - return _httpx.MockTransport(handler) - - -def _install_mock_transport(refresher: Any, transport: Any) -> None: - """Swap the refresher's httpx.Client for one bound to a mock transport. - - We rebuild with `follow_redirects=False` so the redirect-rejection - test still exercises the real policy. - """ - import httpx as _httpx - - refresher._http.close() - refresher._http = _httpx.Client(transport=transport, follow_redirects=False) - - -def test_refresher_returns_cached_token_when_fresh(tmp_path: Path) -> None: - """No refresh round-trip when the cached bundle is still fresh.""" - _write_bundle(tmp_path, expires_at=int(time.time()) + 3600) - seen: list[Any] = [] - transport = _make_mock_transport( - seen_discovery=seen, - seen_refresh=seen, - ) - r = _OidcRefresher(tmp_path, "g") - _install_mock_transport(r, transport) - assert r.current_access_token() == "fresh" - assert seen == [] # no discovery, no refresh - - -def test_refresher_picks_up_disk_rotation_before_refreshing( - tmp_path: Path, -) -> None: - """If the in-memory bundle is stale but the CLI just wrote a fresh one, - re-read disk instead of hitting the IdP.""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - seen_refresh: list[Any] = [] - transport = _make_mock_transport(seen_refresh=seen_refresh) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - # First call: refresh against IdP — exercise that path first. - assert r.current_access_token() == "refreshed-jwt" - assert len(seen_refresh) == 1 - - # Now simulate the CLI writing a fresh bundle. Force the in-memory - # state to look stale so the disk re-read path triggers. - _write_bundle( - tmp_path, access_token="cli-rotated", expires_at=int(time.time()) + 3600 - ) - r._bundle = { - "access_token": "stale-in-memory", - "expires_at": 1, - "refresh_token": "r", - } - # Replace the transport with one that asserts on any request. - import httpx as _httpx - - def assert_no_calls(_req: _httpx.Request) -> _httpx.Response: - raise AssertionError("should not refresh — disk was fresh") - - _install_mock_transport(r, _httpx.MockTransport(assert_no_calls)) - assert r.current_access_token() == "cli-rotated" - - -def test_refresher_adopts_stale_disk_refresh_token_before_refreshing( - tmp_path: Path, -) -> None: - """Regression: when both the in-memory and on-disk access tokens are - stale but another process rotated the on-disk refresh_token, refresh - with the disk refresh_token (r2), not the invalidated in-memory one (r1). - - Without this, a rotating IdP (Keycloak with rotation, Entra strict) would - invalid_grant because process A still holds the pre-rotation r1. - """ - # Disk holds a rotated-but-stale bundle (r2) written by another process. - # Its access token was minted more recently than ours (later expiry, - # though still inside the grace window), so disk carries the newer - # refresh_token even though both are due for refresh. - disk_exp = int(time.time()) + 5 - _write_bundle( - tmp_path, access_token="disk-old", expires_at=disk_exp, refresh_token="r2" - ) - seen: list[Any] = [] - transport = _make_mock_transport( - refresh_responses=[ - {"access_token": "a-new", "refresh_token": "r3", "expires_in": 3600}, - ], - seen_refresh=seen, - ) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - # Seed older stale in-memory state holding the pre-rotation token r1. - r._bundle = { - "access_token": "mem-old", - "expires_at": 1, - "refresh_token": "r1", - "issuer": DEFAULT_ISSUER, - } - - assert r.current_access_token() == "a-new" - # The refresh POST must carry the disk's r2, never the stale r1. - _, body = seen[-1] - assert b"refresh_token=r2" in body - assert b"refresh_token=r1" not in body - - -def test_refresher_resets_token_endpoint_when_disk_issuer_changes( - tmp_path: Path, -) -> None: - """When the adopted disk bundle has a different issuer than the cached - one, the previously discovered token endpoint must be re-discovered - against the new issuer rather than reused.""" - new_issuer = "https://other-idp.example/realms/openshell" - # Disk is newer than the in-memory bundle (later expiry) so it is - # adopted, but still stale so a refresh — and thus re-discovery — runs. - _write_bundle( - tmp_path, - access_token="disk-old", - expires_at=int(time.time()) + 5, - refresh_token="r2", - issuer=new_issuer, - ) - seen_discovery: list[Any] = [] - transport = _make_mock_transport( - discovery={ - "issuer": new_issuer, - "token_endpoint": f"{new_issuer}/protocol/openid-connect/token", - }, - seen_discovery=seen_discovery, - ) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - # Pretend we already discovered an endpoint for the OLD issuer. - r._token_endpoint = f"{DEFAULT_ISSUER}/protocol/openid-connect/token" - r._bundle = { - "access_token": "mem-old", - "expires_at": 1, - "refresh_token": "r1", - "issuer": DEFAULT_ISSUER, - } - - r.current_access_token() - # Re-discovery happened against the new issuer. - assert len(seen_discovery) == 1 - assert new_issuer in seen_discovery[0] - - -def test_refresher_recovers_from_invalid_grant_after_peer_rotation( - tmp_path: Path, -) -> None: - """If our refresh POST loses a rotation race (peer already rotated r1→r2 - and the IdP rejects our r1 with invalid_grant), re-read disk, pick up the - peer's r2, and retry — succeeding without forcing a re-authenticate.""" - import httpx as _httpx - - _write_bundle(tmp_path, access_token="old", expires_at=1, refresh_token="r1") - posts: list[bytes] = [] - - def handler(request: _httpx.Request) -> _httpx.Response: - if request.url.path.endswith("/.well-known/openid-configuration"): - return _httpx.Response( - 200, - json={ - "issuer": DEFAULT_ISSUER, - "token_endpoint": DEFAULT_TOKEN_ENDPOINT, - }, - ) - body = bytes(request.content) - posts.append(body) - if b"refresh_token=r1" in body: - # Simulate the peer: it already rotated r1→r2 and wrote r2 to - # disk, so the IdP rejects our now-stale r1. - _write_bundle( - tmp_path, - access_token="peer", - expires_at=int(time.time()) + 5, - refresh_token="r2", - ) - return _httpx.Response(400, json={"error": "invalid_grant"}) - # The retry carries the peer's r2 and succeeds. - return _httpx.Response( - 200, - json={"access_token": "a-final", "refresh_token": "r3", "expires_in": 3600}, - ) - - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, _httpx.MockTransport(handler)) - - assert r.current_access_token() == "a-final" - # Exactly two refresh POSTs: the failed r1 then the recovered r2. - assert any(b"refresh_token=r1" in p for p in posts) - assert any(b"refresh_token=r2" in p for p in posts) - assert len(posts) == 2 - - -def test_refresher_reraises_invalid_grant_without_peer_rotation( - tmp_path: Path, -) -> None: - """invalid_grant with no peer rotation (disk still holds our refresh_token) - is a genuine dead token — surface the re-authenticate hint and do NOT loop - on the retry path.""" - import httpx as _httpx - import pytest as _pytest - - _write_bundle(tmp_path, access_token="old", expires_at=1, refresh_token="r1") - posts: list[bytes] = [] - - def handler(request: _httpx.Request) -> _httpx.Response: - if request.url.path.endswith("/.well-known/openid-configuration"): - return _httpx.Response( - 200, - json={ - "issuer": DEFAULT_ISSUER, - "token_endpoint": DEFAULT_TOKEN_ENDPOINT, - }, - ) - posts.append(bytes(request.content)) - return _httpx.Response(400, json={"error": "invalid_grant"}) - - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, _httpx.MockTransport(handler)) - - with _pytest.raises(SandboxError, match="Re-authenticate"): - r.current_access_token() - # Only one POST — disk offered no new refresh_token, so no retry. - assert len(posts) == 1 - - -def test_refresher_exchanges_refresh_token_when_stale(tmp_path: Path) -> None: - """When both memory and disk are stale, do the OAuth2 refresh exchange.""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - seen_refresh: list[Any] = [] - transport = _make_mock_transport(seen_refresh=seen_refresh) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - - assert r.current_access_token() == "refreshed-jwt" - # The refresh request should be a POST to the discovered token endpoint - # with grant_type=refresh_token in the body. - url, body = seen_refresh[-1] - assert url.endswith("/protocol/openid-connect/token") - assert b"grant_type=refresh_token" in body - assert b"refresh_token=r-orig" in body - - -def test_refresher_writes_back_when_enabled(tmp_path: Path) -> None: - """write_back=True persists rotated bundle to disk atomically with 0600.""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - transport = _make_mock_transport( - refresh_responses=[ - { - "access_token": "rotated", - "refresh_token": "r-new", - "expires_in": 3600, - } - ], - ) - r = _OidcRefresher(tmp_path, "g", write_back=True) - _install_mock_transport(r, transport) - - assert r.current_access_token() == "rotated" - on_disk = json.loads((tmp_path / "oidc_token.json").read_text()) - assert on_disk["access_token"] == "rotated" - assert on_disk["refresh_token"] == "r-new" - # Mode should be 0600 on POSIX. - if os.name == "posix": - mode = (tmp_path / "oidc_token.json").stat().st_mode & 0o777 - assert mode == 0o600, f"got {oct(mode)}" - - -def test_refresher_write_back_is_default(tmp_path: Path) -> None: - """Default IS write_back=True so refresh-token rotation propagates to - disk for other processes (Rust CLI, TUI, second Python client).""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - transport = _make_mock_transport( - refresh_responses=[ - { - "access_token": "rotated", - "refresh_token": "r-new", - "expires_in": 3600, - } - ], - ) - r = _OidcRefresher(tmp_path, "g") # default write_back=True - _install_mock_transport(r, transport) - - r.current_access_token() - on_disk = json.loads((tmp_path / "oidc_token.json").read_text()) - assert on_disk["access_token"] == "rotated" - assert on_disk["refresh_token"] == "r-new" - - -def test_refresher_honors_refresh_token_rotation(tmp_path: Path) -> None: - """When the IdP returns a new refresh_token, use it for subsequent refreshes - instead of the original. Some IdPs (Keycloak with rotation enabled, Entra - in strict mode) reissue and invalidate the old refresh_token.""" - _write_bundle(tmp_path, access_token="old", expires_at=1, refresh_token="r1") - seen: list[Any] = [] - transport = _make_mock_transport( - refresh_responses=[ - {"access_token": "a2", "refresh_token": "r2", "expires_in": 1}, - {"access_token": "a3", "refresh_token": "r3", "expires_in": 3600}, - ], - seen_refresh=seen, - ) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - - assert r.current_access_token() == "a2" - # Second call: a2 is also expired (expires_in=1), so we refresh again, - # this time the request body should carry the rotated r2 (not r1). - assert r.current_access_token() == "a3" - assert b"refresh_token=r1" in seen[0][1] - assert b"refresh_token=r2" in seen[1][1] - - -def test_refresher_second_process_can_refresh_after_rotation( - tmp_path: Path, -) -> None: - """Two-process simulation (Finding #2): process A refreshes r1→r2 with - write_back=True (default). Process B starts from disk and successfully - uses r2 — proving the rotation reached the shared cache.""" - _write_bundle(tmp_path, access_token="old", expires_at=1, refresh_token="r1") - transport_a = _make_mock_transport( - refresh_responses=[ - {"access_token": "a2", "refresh_token": "r2", "expires_in": 1}, - ], - ) - process_a = _OidcRefresher(tmp_path, "g") # write_back=True (default) - _install_mock_transport(process_a, transport_a) - assert process_a.current_access_token() == "a2" - - # Process B picks up the cache fresh. The IdP now expects r2; if the - # disk still held r1, this would fail at the IdP. With write_back the - # disk has r2, and B refreshes successfully. - seen_b: list[Any] = [] - transport_b = _make_mock_transport( - refresh_responses=[ - {"access_token": "a3", "refresh_token": "r3", "expires_in": 3600}, - ], - seen_refresh=seen_b, - ) - process_b = _OidcRefresher(tmp_path, "g") - _install_mock_transport(process_b, transport_b) - assert process_b.current_access_token() == "a3" - # Process B should have presented r2, not r1. - assert b"refresh_token=r2" in seen_b[0][1] - - -def test_refresher_concurrent_calls_share_one_refresh(tmp_path: Path) -> None: - """N threads racing on a stale token should produce exactly one - refresh exchange (not N). Mirrors google-auth's RefreshThreadManager - coordination.""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - refresh_count = [0] - barrier = threading.Barrier(8) - - import httpx as _httpx - - def handler(request: _httpx.Request) -> _httpx.Response: - if request.url.path.endswith("/.well-known/openid-configuration"): - return _httpx.Response( - 200, - json={ - "issuer": DEFAULT_ISSUER, - "token_endpoint": DEFAULT_TOKEN_ENDPOINT, - }, - ) - refresh_count[0] += 1 - return _httpx.Response( - 200, - json={ - "access_token": "refreshed", - "expires_in": 3600, - }, - ) - - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, _httpx.MockTransport(handler)) - - results: list[str] = [] - errors: list[BaseException] = [] - - def worker() -> None: - try: - barrier.wait() - results.append(r.current_access_token()) - except BaseException as e: - errors.append(e) - - threads = [threading.Thread(target=worker) for _ in range(8)] - for t in threads: - t.start() - for t in threads: - t.join() - - assert not errors, errors - assert results == ["refreshed"] * 8 - # One refresh exchange, regardless of thread count. - assert refresh_count[0] == 1, f"expected one refresh, got {refresh_count[0]}" - - -def test_refresher_surfaces_idp_failure_as_sandbox_error( - tmp_path: Path, -) -> None: - """A non-2xx from the token endpoint becomes a SandboxError.""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - transport = _make_mock_transport( - refresh_status=400, - refresh_responses=[ - { - "error": "invalid_grant", - "error_description": "Token is not active", - } - ], - ) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - - import pytest as _pytest - - with _pytest.raises(SandboxError, match="refresh failed"): - r.current_access_token() - - -def test_refresher_rejects_issuer_mismatch_in_discovery(tmp_path: Path) -> None: - """Finding #1 (Critical): a discovery doc claiming a different issuer - must be rejected. Without this, a malicious or misdirected discovery - response could steer the refresh_token POST to an attacker- - controlled endpoint.""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - transport = _make_mock_transport( - discovery={ - "issuer": "https://evil.example/realms/openshell", - "token_endpoint": "https://evil.example/token", - }, - ) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - - import pytest as _pytest - - with _pytest.raises(SandboxError, match="issuer mismatch"): - r.current_access_token() - - -def test_refresher_rejects_redirect_during_discovery(tmp_path: Path) -> None: - """Finding #1 (Critical): a 3xx during OIDC discovery must NOT be - auto-followed — that would let a network attacker steer the SDK to - an arbitrary token_endpoint URL. The Rust CLI sets - `Policy::none()`; we set httpx's `follow_redirects=False`.""" - _write_bundle(tmp_path, access_token="old", expires_at=1) - transport = _make_mock_transport( - discovery_status=302, - discovery={"location": "https://evil.example/...."}, - ) - r = _OidcRefresher(tmp_path, "g", write_back=False) - _install_mock_transport(r, transport) - - import pytest as _pytest - - with _pytest.raises(SandboxError, match=r"discovery failed.*HTTP 302"): - r.current_access_token() - - -def test_refresher_insecure_disables_tls_verification() -> None: - """Finding #3: insecure=True propagates to httpx as verify=False so - self-signed OIDC issuers work the same way they do in the Rust CLI's - `--insecure` plumbing.""" - import pathlib - - r = _OidcRefresher( - pathlib.Path("/tmp/does-not-exist"), - "g", - insecure=True, - ) - try: - # httpx exposes the configured verify policy on the client; we - # don't depend on its precise type, just on it being a falsy - # value (the default is True / an SSLContext). - # In recent httpx versions this lives on the underlying transport. - # The simplest stable check is: an insecure client allows - # connect to self-signed hosts; the rest of the contract is - # httpx's responsibility. - # Verify the client's verify attribute (whether top-level or via - # transport) is False. - assert _client_verify_is_disabled(r._http) - finally: - r.close() - - -def _client_verify_is_disabled(client: Any) -> bool: - """Inspect an httpx.Client for verify=False. httpx surfaces verify - either on the client directly (older) or via the default transport - (newer).""" - if getattr(client, "verify", None) is False: - return True - transport = getattr(client, "_transport", None) - if transport is None: - return False - # httpx's default HTTPTransport wraps an SSL context or a bool. - pool = getattr(transport, "_pool", None) - if pool is not None: - ssl_context = getattr(pool, "_ssl_context", None) - # When verify=False, httpx builds a context without verification. - if ssl_context is not None: - import ssl - - return ssl_context.verify_mode == ssl.CERT_NONE - # Fallback: check for any internal `_verify` attribute set to False. - return getattr(transport, "_verify", None) is False - - -def test_refresher_raises_when_bundle_has_no_refresh_token( - tmp_path: Path, -) -> None: - """Without a refresh_token (e.g. client_credentials grant — different - code path entirely), refresh has nothing to exchange and surfaces a - clear error.""" - (tmp_path / "oidc_token.json").write_text( - json.dumps({"access_token": "old", "expires_at": 1, "issuer": "x"}) - ) - r = _OidcRefresher(tmp_path, "g", write_back=False) - import pytest as _pytest - - with _pytest.raises(SandboxError, match="no refresh token"): - r.current_access_token() - - -# --------------------------------------------------------------------------- -# auth_mode gate: only metadata.json["auth_mode"] == "oidc" wires the bearer -# interceptor. A stray oidc_token.json next to a non-OIDC gateway must not -# trigger it. -# --------------------------------------------------------------------------- - - -def test_mtls_only_from_active_cluster_skips_bearer_interceptor( - tmp_path: Path, - monkeypatch: Any, -) -> None: - """from_active_cluster against an mTLS-only gateway (no auth_mode set) - does not wrap the channel with a bearer interceptor, even if a stale - oidc_token.json is present in the gateway directory.""" - gateway_name = "mtls-only" - gateway_dir = tmp_path / "openshell" / "gateways" / gateway_name - mtls_dir = gateway_dir / "mtls" - mtls_dir.mkdir(parents=True) - (tmp_path / "openshell" / "active_gateway").write_text(gateway_name) - # No auth_mode field — the chart-default path. - (gateway_dir / "metadata.json").write_text( - json.dumps({"gateway_endpoint": "https://127.0.0.1:8443"}) - ) - for f in ("ca.crt", "tls.crt", "tls.key"): - (mtls_dir / f).write_text(f"-----BEGIN {f}-----\n-----END {f}-----\n") - # Stray oidc_token.json — proving the auth_mode gate (and not the - # file's presence) is what would trigger the refresher. - (gateway_dir / "oidc_token.json").write_text(json.dumps({"access_token": "stale"})) - - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) - monkeypatch.delenv("OPENSHELL_GATEWAY", raising=False) - - client = SandboxClient.from_active_cluster() - try: - # No bearer interceptor wraps the channel. - assert not type(client._channel).__module__.endswith("interceptor") - finally: - client.close() - - -# --------------------------------------------------------------------------- -# Lifecycle plumbing: close() releases refresher resources, concurrent -# write-back doesn't trample. -# --------------------------------------------------------------------------- - - -def test_sandbox_client_close_invokes_bearer_close() -> None: - """`SandboxClient.close()` must invoke the `_bearer_close` callable - wired by `from_active_cluster`. Otherwise the refresher's - httpx.Client leaks sockets/FDs until GC runs.""" - closed = [0] - - def bearer_close() -> None: - closed[0] += 1 - - client = SandboxClient( - "localhost:8080", - bearer_token="tok", - _bearer_close=bearer_close, - ) - client.close() - assert closed[0] == 1 - # close() is idempotent — re-invoking does not double-call. - client.close() - assert closed[0] == 1 - - -def test_from_active_cluster_fills_client_credentials_from_metadata( - tmp_path: Path, - monkeypatch: Any, -) -> None: - gateway_dir = _setup_gateway_dir(tmp_path, monkeypatch, auth_mode="oidc") - metadata_path = gateway_dir / "metadata.json" - metadata = json.loads(metadata_path.read_text()) - metadata.update( - { - "oidc_issuer": "https://issuer.example.com", - "oidc_client_id": "service-client", - "oidc_audience": "gateway", - "oidc_scopes": "sandbox:read sandbox:write", - } - ) - metadata_path.write_text(json.dumps(metadata)) - auth = ClientCredentialsAuth(client_secret="secret") - client = SandboxClient.from_active_cluster( - client_credentials=auth, - insecure=True, - ) - try: - assert auth._issuer == "https://issuer.example.com" - assert auth._client_id == "service-client" - assert auth._audience == "gateway" - assert auth._scopes == ("sandbox:read", "sandbox:write") - assert auth._insecure is True - finally: - client.close() - - -def test_sandbox_client_rejects_client_credentials_on_remote_plaintext( - monkeypatch: Any, -) -> None: - channel_opened = False - - def insecure_channel(_endpoint: str) -> Any: - nonlocal channel_opened - channel_opened = True - raise AssertionError("plaintext channel must not be opened") - - monkeypatch.setattr(sandbox_module.grpc, "insecure_channel", insecure_channel) - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="client", - client_secret="secret", - ) - with pytest.raises(SandboxError, match="require TLS"): - SandboxClient("gateway.example.com:50051", client_credentials=auth) - assert not channel_opened - - -@pytest.mark.parametrize( - "endpoint", - ["localhost:50051", "127.42.0.1:50051", "[::1]:50051"], -) -def test_sandbox_client_allows_client_credentials_on_plaintext_loopback( - endpoint: str, -) -> None: - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="client", - client_secret="secret", - ) - client = SandboxClient(endpoint, client_credentials=auth) - client.close() - - -def test_from_active_cluster_rejects_client_credentials_on_remote_plaintext( - tmp_path: Path, - monkeypatch: Any, -) -> None: - gateway_dir = _setup_gateway_dir( - tmp_path, - monkeypatch, - endpoint="http://gateway.example.com:8080", - auth_mode="oidc", - ) - metadata_path = gateway_dir / "metadata.json" - metadata = json.loads(metadata_path.read_text()) - metadata.update( - { - "oidc_issuer": "https://issuer.example.com", - "oidc_client_id": "service-client", - } - ) - metadata_path.write_text(json.dumps(metadata)) - - auth = ClientCredentialsAuth(client_secret="secret") - with pytest.raises(SandboxError, match="require TLS"): - SandboxClient.from_active_cluster(client_credentials=auth) - - -def test_sandbox_client_rejects_ambiguous_bearer_configuration() -> None: - auth = ClientCredentialsAuth( - issuer="https://issuer.example.com", - client_id="client", - client_secret="secret", - ) - with pytest.raises(SandboxError, match="mutually exclusive"): - SandboxClient( - "localhost:50051", - bearer_token="static", - client_credentials=auth, - ) - - -def test_sandbox_client_close_releases_refresher_http_client( - tmp_path: Path, - monkeypatch: Any, -) -> None: - """End-to-end check: an OIDC-backed client built by - from_active_cluster() must close the refresher's httpx.Client when - the SandboxClient is closed.""" - gateway_name = "oidc-gw" - gateway_dir = tmp_path / "openshell" / "gateways" / gateway_name - mtls_dir = gateway_dir / "mtls" - mtls_dir.mkdir(parents=True) - (tmp_path / "openshell" / "active_gateway").write_text(gateway_name) - (gateway_dir / "metadata.json").write_text( - json.dumps( - { - "gateway_endpoint": "https://127.0.0.1:8443", - "auth_mode": "oidc", - } - ) - ) - for f in ("ca.crt", "tls.crt", "tls.key"): - (mtls_dir / f).write_text(f"-----BEGIN {f}-----\n-----END {f}-----\n") - _write_bundle(gateway_dir, expires_at=int(time.time()) + 3600) - - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) - monkeypatch.delenv("OPENSHELL_GATEWAY", raising=False) - - # Capture the httpx.Client instance created inside the refresher by - # monkey-patching _OidcRefresher to record it on construction. - created: list[Any] = [] - real_init = _OidcRefresher.__init__ - - def recording_init(self: Any, *args: Any, **kwargs: Any) -> None: - real_init(self, *args, **kwargs) - created.append(self._http) - - monkeypatch.setattr(_OidcRefresher, "__init__", recording_init) - - client = SandboxClient.from_active_cluster() - assert len(created) == 1 - http_client = created[0] - assert not http_client.is_closed - client.close() - assert http_client.is_closed - - -def test_refresher_concurrent_write_back_does_not_trample(tmp_path: Path) -> None: - """Two writers calling `_write_to_disk` concurrently must each use - their own tempfile (PID+random) and not corrupt each other's content. - The final file must be valid JSON from exactly one of the writers, - and no orphaned `.oidc_token..tmp` files should remain.""" - _write_bundle(tmp_path, expires_at=int(time.time()) + 3600) - r = _OidcRefresher(tmp_path, "g", write_back=False) - try: - N = 16 - barrier = threading.Barrier(N) - errors: list[BaseException] = [] - - def writer(idx: int) -> None: - try: - barrier.wait() - r._write_to_disk( - { - "access_token": f"a-{idx}", - "refresh_token": f"r-{idx}", - "expires_at": 1_700_000_000 + idx, - "issuer": DEFAULT_ISSUER, - "client_id": "openshell-cli", - } - ) - except BaseException as e: - errors.append(e) - - threads = [threading.Thread(target=writer, args=(i,)) for i in range(N)] - for t in threads: - t.start() - for t in threads: - t.join() - - assert not errors, errors - - # Final file is valid JSON from one of the writers (race winner). - final = json.loads((tmp_path / "oidc_token.json").read_text()) - assert final["access_token"].startswith("a-") - assert final["refresh_token"].startswith("r-") - - # No orphan tmp files left behind. mkstemp uses a random suffix - # so each writer's tmp is distinct; the cleanup path on the - # success branch is `.replace()`, which atomically moves the - # tmp to the final path — no straggler tmp should remain. - leftovers = sorted(tmp_path.glob(".oidc_token.*.tmp")) - assert leftovers == [], f"orphan tmp files: {leftovers}" - finally: - r.close() - - -class _WindowsPermissionError(PermissionError): - winerror: int - - -def test_atomic_replace_retries_windows_sharing_violations( - tmp_path: Path, monkeypatch: Any -) -> None: - source = tmp_path / "source" - destination = tmp_path / "destination" - source.write_text("new") - destination.write_text("old") - attempts = 0 - delays: list[float] = [] - real_replace = Path.replace - - def replace(path: Path, target: Path) -> Path: - nonlocal attempts - attempts += 1 - if attempts < 3: - error = _WindowsPermissionError("destination is busy") - error.winerror = 32 - raise error - return real_replace(path, target) - - monkeypatch.setattr(sandbox_module, "_IS_WINDOWS", True) - monkeypatch.setattr(Path, "replace", replace) - monkeypatch.setattr(time, "sleep", delays.append) - - _atomic_replace(source, destination) - - assert attempts == 3 - assert delays == [0.005, 0.01] - assert destination.read_text() == "new" - - -def test_atomic_replace_does_not_retry_permanent_windows_errors( - tmp_path: Path, monkeypatch: Any -) -> None: - source = tmp_path / "source" - destination = tmp_path / "destination" - source.write_text("new") - attempts = 0 - - def replace(_path: Path, _target: Path) -> Path: - nonlocal attempts - attempts += 1 - error = _WindowsPermissionError("access denied") - error.winerror = 13 - raise error - - monkeypatch.setattr(sandbox_module, "_IS_WINDOWS", True) - monkeypatch.setattr(Path, "replace", replace) - - with pytest.raises(PermissionError, match="access denied"): - _atomic_replace(source, destination) - - assert attempts == 1 - - -def test_sandbox_wrapper_forwards_auth_kwargs_to_from_active_cluster( - monkeypatch: Any, -) -> None: - """The high-level `Sandbox` context manager must pass auto_refresh, - write_back, and insecure through to SandboxClient.from_active_cluster - so callers using the wrapper get parity with SandboxClient for - OIDC-protected gateways.""" - captured: dict[str, Any] = {} - - class _Sentinel(Exception): - pass - - def fake_from_active_cluster(**kwargs: Any) -> Any: - captured.update(kwargs) - # Short-circuit the rest of __enter__ (which would try to create - # a session against a real gateway). The kwargs we care about - # have already been recorded. - raise _Sentinel - - monkeypatch.setattr( - SandboxClient, "from_active_cluster", staticmethod(fake_from_active_cluster) - ) - - sandbox = Sandbox( - workspace="default", - cluster="my-gw", - timeout=42.0, - auto_refresh=False, - write_back=False, - insecure=True, - ) - import pytest as _pytest - - with _pytest.raises(_Sentinel): - sandbox.__enter__() - - assert captured["cluster"] == "my-gw" - assert captured["timeout"] == 42.0 - assert captured["auto_refresh"] is False - assert captured["write_back"] is False - assert captured["insecure"] is True - - -def test_sandbox_wrapper_defaults_match_from_active_cluster( - monkeypatch: Any, -) -> None: - """Sandbox(...) with no auth kwargs forwards the same defaults - (auto_refresh=True, write_back=True, insecure=False) that - SandboxClient.from_active_cluster uses, so the wrapper doesn't - silently weaken the security posture.""" - captured: dict[str, Any] = {} - - class _Sentinel(Exception): - pass - - def fake_from_active_cluster(**kwargs: Any) -> Any: - captured.update(kwargs) - raise _Sentinel - - monkeypatch.setattr( - SandboxClient, "from_active_cluster", staticmethod(fake_from_active_cluster) - ) - - import pytest as _pytest - - with _pytest.raises(_Sentinel): - Sandbox(workspace="default").__enter__() - - assert captured["auto_refresh"] is True - assert captured["write_back"] is True - assert captured["insecure"] is False - - -# --------------------------------------------------------------------------- -# Encoding regression tests (utf-8 explicit on all config file reads/writes) -# --------------------------------------------------------------------------- - - -def test_read_oidc_token_bundle_parses_non_ascii_utf8(tmp_path: Path) -> None: - gateway_dir = tmp_path / "gw" - gateway_dir.mkdir() - payload = {"refresh_token": "tok", "issuer": "https://example.com/é"} - (gateway_dir / "oidc_token.json").write_bytes( - json.dumps(payload, ensure_ascii=False).encode("utf-8") - ) - result = _read_oidc_token_bundle(gateway_dir) - assert result == payload - - -def test_read_oidc_token_bundle_returns_none_on_corrupt_bytes(tmp_path: Path) -> None: - gateway_dir = tmp_path / "gw" - gateway_dir.mkdir() - (gateway_dir / "oidc_token.json").write_bytes(b"\xff\xfe not utf-8") - assert _read_oidc_token_bundle(gateway_dir) is None - - -def test_load_cluster_bearer_token_handles_non_ascii_utf8_oidc(tmp_path: Path) -> None: - gateway_dir = tmp_path / "gw" - gateway_dir.mkdir() - bundle = { - "access_token": "accéss", - "refresh_token": "ref", - "expiry": "2099-01-01T00:00:00Z", - "issuer": "https://example.com", - "client_id": "c", - "client_secret": "s", - } - (gateway_dir / "oidc_token.json").write_bytes( - json.dumps(bundle, ensure_ascii=False).encode("utf-8") - ) - token = _load_cluster_bearer_token(gateway_dir) - assert token == "accéss" - - -def test_from_active_cluster_reads_utf8_bytes_from_active_gateway_and_metadata( - tmp_path: Path, - monkeypatch: Any, -) -> None: - gateway_name = "gw-é" - gateway_dir = tmp_path / "openshell" / "gateways" / gateway_name - gateway_dir.mkdir(parents=True) - (tmp_path / "openshell" / "active_gateway").write_bytes( - gateway_name.encode("utf-8") - ) - meta = {"gateway_endpoint": "http://tést.example:8080"} - (gateway_dir / "metadata.json").write_bytes( - json.dumps(meta, ensure_ascii=False).encode("utf-8") - ) - - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) - monkeypatch.delenv("OPENSHELL_GATEWAY", raising=False) - - client = SandboxClient.from_active_cluster() - try: - assert client._cluster_name == gateway_name - assert client._endpoint == "tést.example:8080" - finally: - client.close() - - -# ---- Sandbox label / selector API tests ---- - - -def _make_sandbox_proto( - id_: str, - name: str, - labels: dict[str, str] | None = None, - phase: openshell_pb2.SandboxPhase = openshell_pb2.SANDBOX_PHASE_READY, - version: int = 0, - workspace: str = "default", -) -> openshell_pb2.Sandbox: - sandbox = openshell_pb2.Sandbox() - sandbox.metadata.id = id_ - sandbox.metadata.name = name - sandbox.metadata.workspace = workspace - for key, value in (labels or {}).items(): - sandbox.metadata.labels[key] = value - sandbox.status.phase = phase - sandbox.status.current_policy_version = version - return sandbox - - -def _make_workload_template_proto( - name: str, - *, - workspace: str = "default", -) -> openshell_pb2.SandboxWorkloadTemplate: - template = openshell_pb2.SandboxWorkloadTemplate() - template.metadata.name = name - template.metadata.workspace = workspace - template.spec.workload.image = f"ghcr.io/test/{name}:latest" - template.spec.workload.resources.cpu = "1" - template.spec.workload.resources.memory = "512Mi" - return template - - -class _FakeSandboxStub: - def __init__( - self, - listed: list[openshell_pb2.Sandbox] | None = None, - listed_pages: list[list[openshell_pb2.Sandbox]] | None = None, - ) -> None: - self.create_request: openshell_pb2.CreateSandboxRequest | None = None - self.list_request: openshell_pb2.ListSandboxesRequest | None = None - self.get_request: openshell_pb2.GetSandboxRequest | None = None - self.delete_request: openshell_pb2.DeleteSandboxRequest | None = None - self.stop_request: openshell_pb2.StopSandboxRequest | None = None - self.start_request: openshell_pb2.StartSandboxRequest | None = None - self.suspend_request: openshell_pb2.SuspendSandboxRequest | None = None - self.resume_request: openshell_pb2.ResumeSandboxRequest | None = None - self.create_template_request: ( - openshell_pb2.CreateSandboxTemplateRequest | None - ) = None - self.get_template_request: openshell_pb2.GetSandboxTemplateRequest | None = None - self.list_template_request: openshell_pb2.ListSandboxTemplatesRequest | None = ( - None - ) - self.delete_template_request: ( - openshell_pb2.DeleteSandboxTemplateRequest | None - ) = None - self._listed = listed or [] - self._listed_pages = listed_pages - self.list_requests: list[openshell_pb2.ListSandboxesRequest] = [] - self._templates: list[openshell_pb2.SandboxWorkloadTemplate] = [] - - def GetSandbox( - self, - request: openshell_pb2.GetSandboxRequest, - timeout: float | None = None, - ) -> Any: - self.get_request = request - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - _request_sandbox(request), - workspace=_request_workspace(request) or "default", - ) - ) - - def DeleteSandbox( - self, - request: openshell_pb2.DeleteSandboxRequest, - timeout: float | None = None, - ) -> Any: - self.delete_request = request - _ = timeout - return SimpleNamespace(outcome=1, sandbox_id="sb-1") - - def StopSandbox( - self, - request: openshell_pb2.StopSandboxRequest, - timeout: float | None = None, - ) -> Any: - self.stop_request = request - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - _request_sandbox(request), - phase=openshell_pb2.SANDBOX_PHASE_STOPPED, - workspace=_request_workspace(request) or "default", - ) - ) - - def StartSandbox( - self, - request: openshell_pb2.StartSandboxRequest, - timeout: float | None = None, - ) -> Any: - self.start_request = request - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - _request_sandbox(request), - phase=openshell_pb2.SANDBOX_PHASE_STARTING, - workspace=_request_workspace(request) or "default", - ) - ) - - def SuspendSandbox( - self, - request: openshell_pb2.SuspendSandboxRequest, - timeout: float | None = None, - ) -> Any: - self.suspend_request = request - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - _request_sandbox(request), - phase=openshell_pb2.SANDBOX_PHASE_SUSPENDING, - workspace=_request_workspace(request) or "default", - ) - ) - - def ResumeSandbox( - self, - request: openshell_pb2.ResumeSandboxRequest, - timeout: float | None = None, - ) -> Any: - self.resume_request = request - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - _request_sandbox(request), - phase=openshell_pb2.SANDBOX_PHASE_STARTING, - workspace=_request_workspace(request) or "default", - ) - ) - - def CreateSandbox( - self, - request: openshell_pb2.CreateSandboxRequest, - timeout: float | None = None, - ) -> Any: - self.create_request = request - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - request.name or "generated", - dict(request.labels), - workspace=_request_workspace(request) or "default", - ), - service_urls={ - exposure.service: f"https://{exposure.service}.example.test/" - for exposure in request.service_exposures - }, - ) - - def ListSandboxes( - self, - request: openshell_pb2.ListSandboxesRequest, - timeout: float | None = None, - ) -> Any: - self.list_request = request - self.list_requests.append(deepcopy(request)) - _ = timeout - if self._listed_pages is not None: - page = int(request.page_token or "0") - next_page_token = ( - str(page + 1) if page + 1 < len(self._listed_pages) else "" - ) - return SimpleNamespace( - sandboxes=list(self._listed_pages[page]), - next_page_token=next_page_token, - ) - return SimpleNamespace(sandboxes=list(self._listed)) - - def CreateSandboxTemplate( - self, - request: openshell_pb2.CreateSandboxTemplateRequest, - timeout: float | None = None, - ) -> Any: - self.create_template_request = request - _ = timeout - self._templates.append(request.template) - return SimpleNamespace(template=request.template) - - def GetSandboxTemplate( - self, - request: openshell_pb2.GetSandboxTemplateRequest, - timeout: float | None = None, - ) -> Any: - self.get_template_request = request - _ = timeout - return SimpleNamespace( - template=_make_workload_template_proto( - request.name, - workspace=_request_workspace(request) or "default", - ) - ) - - def ListSandboxTemplates( - self, - request: openshell_pb2.ListSandboxTemplatesRequest, - timeout: float | None = None, - ) -> Any: - self.list_template_request = request - _ = timeout - return SimpleNamespace(templates=list(self._templates)) - - def DeleteSandboxTemplate( - self, - request: openshell_pb2.DeleteSandboxTemplateRequest, - timeout: float | None = None, - ) -> Any: - self.delete_template_request = request - _ = timeout - return SimpleNamespace(outcome=1, sandbox_id="sb-1") - - -class _RecordingHighLevelClient: - """A stand-in for SandboxClient used to observe high-level forwarding.""" - - def __init__(self) -> None: - self.create_kwargs: dict[str, Any] | None = None - self.create_template_kwargs: dict[str, Any] | None = None - - def create_session( - self, - *, - workspace: str, - spec: Any = None, - name: str | None = None, - labels: Any = None, - ) -> Any: - self.create_kwargs = { - "workspace": workspace, - "spec": spec, - "name": name, - "labels": labels, - } - return SimpleNamespace(sandbox=SimpleNamespace(name=name or "generated")) - - def create_session_from_template( - self, - *, - workspace: str, - workload_template: str, - spec: Any = None, - name: str | None = None, - labels: Any = None, - ) -> Any: - self.create_template_kwargs = { - "workspace": workspace, - "workload_template": workload_template, - "spec": spec, - "name": name, - "labels": labels, - } - return SimpleNamespace(sandbox=SimpleNamespace(name=name or "generated")) - - def wait_ready( - self, name: str, *, workspace: str, timeout_seconds: float = 300.0 - ) -> SandboxRef: - _ = timeout_seconds - return SandboxRef( - id="sandbox-1", - name=name, - workspace=workspace, - status=SandboxStatusRef(phase=2, current_policy_version=0), - ) - - -def test_create_forwards_name_and_labels() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - ref = client.create( - workspace="default", name="job-1", labels={"aiq": "deep-research"} - ) - - assert stub.create_request is not None - assert stub.create_request.name == "job-1" - assert dict(stub.create_request.labels) == {"aiq": "deep-research"} - assert dict(ref.labels) == {"aiq": "deep-research"} - - -def test_create_forwards_service_exposures() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - ref = client.create( - workspace="default", - name="app-server", - service_exposures=[ - ServiceExposure(target_port=4500), - ServiceExposure( - service="metrics", - target_port=9090, - authorization_mode=ServiceAuthorizationMode.BEARER_PASSTHROUGH, - ), - ], - ) - - assert stub.create_request is not None - assert [ - (exposure.service, exposure.target_port, exposure.authorization_mode) - for exposure in stub.create_request.service_exposures - ] == [ - ("", 4500, openshell_pb2.SERVICE_AUTHORIZATION_MODE_STRIP), - ( - "metrics", - 9090, - openshell_pb2.SERVICE_AUTHORIZATION_MODE_BEARER_PASSTHROUGH, - ), - ] - assert dict(ref.service_urls) == { - "": "https://.example.test/", - "metrics": "https://metrics.example.test/", - } - - -def test_create_from_template_forwards_workload_template() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - spec = openshell_pb2.SandboxSpec( - providers=["github"], - command=["/opt/worker", "--serve"], - tty=True, - ) - - ref = client.create_from_template( - workspace="default", - workload_template="gpu-kata", - spec=spec, - name="job-1", - labels={"team": "runtime"}, - ) - - assert stub.create_request is not None - assert stub.create_request.name == "job-1" - assert stub.create_request.workload_template == "gpu-kata" - assert dict(stub.create_request.labels) == {"team": "runtime"} - assert list(stub.create_request.spec.providers) == ["github"] - assert list(stub.create_request.spec.command) == ["/opt/worker", "--serve"] - assert stub.create_request.spec.tty is True - assert dict(ref.labels) == {"team": "runtime"} - - -def test_create_from_template_rejects_empty_workload_template() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - with pytest.raises(SandboxError): - client.create_from_template(workspace="default", workload_template=" ") - - assert stub.create_request is None - - -def test_sandbox_template_create_builds_template_from_public_fields() -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - - created = client.create( - workspace="default", - name="gpu-kata", - image="ghcr.io/test/gpu-kata:latest", - labels={"team": "runtime"}, - annotations={"owner": "platform"}, - environment={"FEATURE_FLAG": "on"}, - cpu="1", - memory="512Mi", - gpu_count=2, - driver_config={"kubernetes": {"runtime_class_name": "kata"}}, - ) - - assert created.metadata.name == "gpu-kata" - assert stub.create_template_request is not None - assert _request_workspace(stub.create_template_request) == "default" - template = stub.create_template_request.template - assert template.metadata.name == "gpu-kata" - assert dict(template.metadata.labels) == {"team": "runtime"} - assert dict(template.metadata.annotations) == {"owner": "platform"} - assert template.spec.workload.image == "ghcr.io/test/gpu-kata:latest" - assert dict(template.spec.workload.environment) == {"FEATURE_FLAG": "on"} - assert template.spec.workload.resources.cpu == "1" - assert template.spec.workload.resources.memory == "512Mi" - assert template.spec.workload.resources.gpu.count == 2 - config = template.spec.driver_config["kubernetes"] - assert isinstance(config, Struct) - assert config["runtime_class_name"] == "kata" - - -def test_sandbox_template_create_materializes_default_workload() -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - - client.create(workspace="default", name="base") - - assert stub.create_template_request is not None - template = stub.create_template_request.template - assert template.HasField("spec") - assert template.spec.HasField("workload") - assert template.spec.workload.image == "" - - -def test_sandbox_template_create_materializes_workload_with_driver_config_only() -> ( - None -): - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - - client.create( - workspace="default", - name="kata-default-image", - driver_config={"kubernetes": {"runtime_class_name": "kata"}}, - ) - - assert stub.create_template_request is not None - template = stub.create_template_request.template - assert template.HasField("spec") - assert template.spec.HasField("workload") - assert template.spec.workload.image == "" - config = template.spec.driver_config["kubernetes"] - assert isinstance(config, Struct) - assert config["runtime_class_name"] == "kata" - - -def test_sandbox_template_create_rejects_missing_public_name() -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - - with pytest.raises(SandboxError): - client.create(workspace="default", image="ghcr.io/test/python:latest") - - assert stub.create_template_request is None - - -def test_sandbox_template_create_rejects_template_and_builder_fields() -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - template = _make_workload_template_proto("gpu-kata") - - with pytest.raises(SandboxError): - client.create(workspace="default", template=template, image="override") - - assert stub.create_template_request is None - - -@pytest.mark.parametrize( - "builder_kwargs", - ( - {"labels": {}}, - {"annotations": {}}, - {"environment": {}}, - {"driver_config": {}}, - ), -) -def test_sandbox_template_create_allows_template_and_empty_builder_mappings( - builder_kwargs: dict[str, Any], -) -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - template = _make_workload_template_proto("gpu-kata") - - created = client.create( - workspace="default", - template=template, - **builder_kwargs, - ) - - assert created.metadata.name == "gpu-kata" - assert stub.create_template_request is not None - assert stub.create_template_request.template.metadata.name == template.metadata.name - assert ( - stub.create_template_request.template.spec.workload.image - == template.spec.workload.image - ) - - -@pytest.mark.parametrize( - "builder_kwargs", - ( - {"labels": {"team": "runtime"}}, - {"annotations": {"owner": "platform"}}, - {"environment": {"FEATURE_FLAG": "on"}}, - {"driver_config": {"kubernetes": {"runtime_class_name": "kata"}}}, - ), -) -def test_sandbox_template_create_rejects_template_and_non_empty_builder_mappings( - builder_kwargs: dict[str, Any], -) -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - template = _make_workload_template_proto("gpu-kata") - - with pytest.raises(SandboxError): - client.create( - workspace="default", - template=template, - **builder_kwargs, - ) - - assert stub.create_template_request is None - - -def test_sandbox_template_create_rejects_non_positive_gpu_count() -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - - with pytest.raises(SandboxError): - client.create(workspace="default", name="gpu-kata", gpu_count=0) - - assert stub.create_template_request is None - - -def test_sandbox_template_client_crud_forwards_requests() -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - template = _make_workload_template_proto("gpu-kata") - template.spec.driver_config.update({"kubernetes": {"runtime_class_name": "kata"}}) - - created = client.create(workspace="default", template=template) - - assert created.metadata.name == "gpu-kata" - assert stub.create_template_request is not None - assert _request_workspace(stub.create_template_request) == "default" - assert ( - stub.create_template_request.template.spec.workload.image - == "ghcr.io/test/gpu-kata:latest" - ) - config = stub.create_template_request.template.spec.driver_config["kubernetes"] - assert isinstance(config, Struct) - assert config["runtime_class_name"] == "kata" - - got = client.get("gpu-kata", workspace="default") - assert got.metadata.name == "gpu-kata" - assert stub.get_template_request is not None - assert stub.get_template_request.name == "gpu-kata" - assert _request_workspace(stub.get_template_request) == "default" - - listed = client.list_all( - workspace="default", page_size=50, label_selector="team=runtime" - ) - assert len(listed) == 1 - assert stub.list_template_request is not None - assert _request_workspace(stub.list_template_request) == "default" - assert stub.list_template_request.page_size == 50 - assert stub.list_template_request.page_token == "" - assert stub.list_template_request.label_selector == "team=runtime" - assert not _request_selects_all_workspaces(stub.list_template_request) - - assert client.delete("gpu-kata", workspace="default").outcome == 1 - assert stub.delete_template_request is not None - assert stub.delete_template_request.name == "gpu-kata" - assert _request_workspace(stub.delete_template_request) == "default" - - -def test_sandbox_template_list_for_all_workspaces_selects_all() -> None: - stub = _FakeSandboxStub() - client = _template_client_with_fake_stub(stub) - - client.list_all_for_all_workspaces(page_size=100, label_selector="team=runtime") - - assert stub.list_template_request is not None - assert _request_selects_all_workspaces(stub.list_template_request) - assert _request_workspace(stub.list_template_request) is None - assert stub.list_template_request.page_size == 100 - assert stub.list_template_request.page_token == "" - assert stub.list_template_request.label_selector == "team=runtime" - - -def test_stop_and_start_forward_workspace_and_return_phase() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - stopped = client.stop("job-1", workspace="team-a") - assert stub.stop_request is not None - assert _request_sandbox(stub.stop_request) == "job-1" - assert _request_workspace(stub.stop_request) == "team-a" - assert stopped.phase == openshell_pb2.SANDBOX_PHASE_STOPPED - - starting = client.start("job-1", workspace="team-a") - assert stub.start_request is not None - assert _request_sandbox(stub.start_request) == "job-1" - assert _request_workspace(stub.start_request) == "team-a" - assert starting.phase == openshell_pb2.SANDBOX_PHASE_STARTING - - -def test_suspend_and_resume_forward_workspace_and_options() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - suspending = client.suspend("job-1", workspace="team-a") - assert stub.suspend_request is not None - assert _request_sandbox(stub.suspend_request) == "job-1" - assert _request_workspace(stub.suspend_request) == "team-a" - assert suspending.phase == openshell_pb2.SANDBOX_PHASE_SUSPENDING - - resumed = client.resume("job-1", workspace="team-a", restart_if_restore_fails=True) - assert stub.resume_request is not None - assert _request_sandbox(stub.resume_request) == "job-1" - assert _request_workspace(stub.resume_request) == "team-a" - assert stub.resume_request.restart_if_restore_fails - assert resumed.phase == openshell_pb2.SANDBOX_PHASE_STARTING - - client.resume("job-1", workspace="team-a") - assert not stub.resume_request.restart_if_restore_fails - - -def test_wait_ready_fails_fast_when_suspended() -> None: - class SuspendedStub(_FakeSandboxStub): - def GetSandbox( - self, - request: openshell_pb2.GetSandboxRequest, - timeout: float | None = None, - ) -> Any: - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - _request_sandbox(request), - phase=openshell_pb2.SANDBOX_PHASE_SUSPENDED, - workspace=_request_workspace(request) or "default", - ) - ) - - client = _client_with_fake_stub(SuspendedStub()) - with pytest.raises(SandboxError, match="is suspended"): - client.wait_ready("job-1", workspace="default", timeout_seconds=30) - suspended = client.wait_suspended("job-1", workspace="default", timeout_seconds=1) - assert suspended.phase == openshell_pb2.SANDBOX_PHASE_SUSPENDED - - -@pytest.mark.parametrize( - ("phase", "should_succeed"), - [ - (openshell_pb2.SANDBOX_PHASE_COMPLETED, True), - (openshell_pb2.SANDBOX_PHASE_ERROR, False), - ], -) -def test_wait_ready_handles_terminal_main_process_results( - phase: openshell_pb2.SandboxPhase, should_succeed: bool -) -> None: - class TerminalStub(_FakeSandboxStub): - def GetSandbox( - self, - request: openshell_pb2.GetSandboxRequest, - timeout: float | None = None, - ) -> Any: - _ = timeout - return SimpleNamespace( - sandbox=_make_sandbox_proto( - "sandbox-1", - _request_sandbox(request), - phase=phase, - workspace=_request_workspace(request) or "default", - ) - ) - - client = _client_with_fake_stub(TerminalStub()) - if should_succeed: - result = client.wait_ready("job-1", workspace="default", timeout_seconds=0.1) - assert result.phase == openshell_pb2.SANDBOX_PHASE_COMPLETED - else: - with pytest.raises(SandboxError, match="entered error phase"): - client.wait_ready("job-1", workspace="default", timeout_seconds=0.1) - - -def test_create_without_args_sends_empty_metadata() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - client.create(workspace="default") - - assert stub.create_request is not None - assert stub.create_request.name == "" - assert dict(stub.create_request.labels) == {} - assert _request_workspace(stub.create_request) == "default" - - -def test_create_copies_caller_labels() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - caller_labels = {"aiq": "deep-research"} - client.create(workspace="default", labels=caller_labels) - caller_labels["aiq"] = "mutated" - - assert stub.create_request is not None - assert dict(stub.create_request.labels) == {"aiq": "deep-research"} - - -def test_create_session_forwards_name_and_labels() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - session = client.create_session( - workspace="default", name="job-2", labels={"team": "aiq"} - ) - - assert stub.create_request is not None - assert stub.create_request.name == "job-2" - assert dict(stub.create_request.labels) == {"team": "aiq"} - assert session.sandbox.name == "job-2" - - -def test_list_forwards_label_selector() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - client.list_all(workspace="default", label_selector="aiq=deep-research") - - assert stub.list_request is not None - assert stub.list_request.label_selector == "aiq=deep-research" - assert _request_workspace(stub.list_request) == "default" - - -def test_list_without_selector_sends_empty_string() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - client.list_all(workspace="default") - - assert stub.list_request is not None - assert stub.list_request.label_selector == "" - - -def test_list_follows_continuation_tokens() -> None: - stub = _FakeSandboxStub( - listed_pages=[ - [_make_sandbox_proto("sandbox-1", "job-1")], - [_make_sandbox_proto("sandbox-2", "job-2")], - ] - ) - client = _client_with_fake_stub(stub) - - pager = client.list(workspace="default", page_size=1, label_selector="team=core") - - assert stub.list_requests == [] - first = next(pager) - assert [sandbox.name for sandbox in first.items] == ["job-1"] - assert first.next_page_token == "1" - second = next(pager) - assert [sandbox.name for sandbox in second.items] == ["job-2"] - assert second.next_page_token == "" - with pytest.raises(StopIteration): - next(pager) - assert len(stub.list_requests) == 2 - assert stub.list_requests[0].page_token == "" - assert stub.list_requests[1].page_token == "1" - assert stub.list_requests[1].label_selector == "team=core" - - -def test_list_passes_initial_page_token() -> None: - stub = _FakeSandboxStub( - listed_pages=[ - [_make_sandbox_proto("sandbox-1", "skipped")], - [_make_sandbox_proto("sandbox-2", "resumed")], - ] - ) - client = _client_with_fake_stub(stub) - - page = next(client.list(workspace="default", page_token="1")) - - assert [sandbox.name for sandbox in page.items] == ["resumed"] - assert stub.list_requests[0].page_token == "1" - - -def test_pager_retries_same_token_after_fetch_error() -> None: - tokens: list[str] = [] - - def fetch(token: str) -> Page[int]: - tokens.append(token) - if len(tokens) == 1: - raise RuntimeError("temporary failure") - return Page(items=[1], next_page_token="") - - pager = Pager(fetch, page_token="resume") - with pytest.raises(RuntimeError, match="temporary failure"): - next(pager) - - assert next(pager).items == [1] - assert tokens == ["resume", "resume"] - - -def test_pager_rejects_a_repeated_continuation_token() -> None: - pager = Pager( - lambda token: Page(items=[1], next_page_token=token), - page_token="resume", - ) - - with pytest.raises(SandboxError, match="repeated continuation token"): - next(pager) - - -def test_pager_bounds_consumed_token_count(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sandbox_module, "_PAGER_MAX_CONSUMED_TOKENS", 1) - requests: list[str] = [] - pager = Pager( - lambda token: ( - requests.append(token), - Page(items=[token], next_page_token="next"), - )[1], - page_token="first", - ) - - assert next(pager).items == ["first"] - with pytest.raises(SandboxError, match="token history limit exceeded"): - next(pager) - assert requests == ["first"] - - -def test_pager_bounds_consumed_token_bytes(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sandbox_module, "_PAGER_MAX_CONSUMED_TOKEN_BYTES", 1) - requests: list[str] = [] - pager = Pager( - lambda token: ( - requests.append(token), - Page(items=[token], next_page_token="next"), - )[1], - page_token="too-large", - ) - - with pytest.raises(SandboxError, match="token history limit exceeded"): - next(pager) - assert requests == [] - - -def test_list_ids_forwards_label_selector() -> None: - stub = _FakeSandboxStub(listed=[_make_sandbox_proto("sandbox-1", "job-1")]) - client = _client_with_fake_stub(stub) - - ids = client.list_ids(workspace="default", label_selector="aiq=deep-research") - - assert stub.list_request is not None - assert stub.list_request.label_selector == "aiq=deep-research" - assert ids == ["sandbox-1"] - - -def test_sandbox_ref_retains_gateway_labels() -> None: - proto = _make_sandbox_proto( - "sandbox-1", "job-1", {"aiq": "deep-research", "env": "dev"} - ) - - ref = _sandbox_ref(proto) - - assert dict(ref.labels) == {"aiq": "deep-research", "env": "dev"} - - -def test_sandbox_ref_exposes_host_identity_and_accepts_legacy_response() -> None: - proto = _make_sandbox_proto("sandbox-1", "job-1") - assert _sandbox_ref(proto).host_key_fingerprint is None - proto.host_key_fingerprint = "SHA256:expected" - assert _sandbox_ref(proto).host_key_fingerprint == "SHA256:expected" - - -def test_sandbox_ref_includes_main_process_result() -> None: - proto = _make_sandbox_proto("sandbox-1", "job-1") - proto.status.exit_code = 0 - proto.status.restart_count = 2 - proto.status.next_restart_time.FromMilliseconds(1_700_000_000_000) - proto.status.main_process_started_time.FromMilliseconds(1_699_999_000_000) - - status = _sandbox_ref(proto).status - - assert status.exit_code == 0 - assert status.restart_count == 2 - assert status.next_restart_at_ms == 1_700_000_000_000 - assert status.main_process_started_at_ms == 1_699_999_000_000 - - -def test_sandbox_ref_includes_conditions() -> None: - proto = _make_sandbox_proto("sandbox-1", "job-1") - - ready = proto.status.conditions.add() - ready.type = "Ready" - ready.status = "True" - ready.reason = "BackendReady" - ready.message = "Container is running" - ready.transition_time.FromMilliseconds(1_700_000_000_000) - - failed = proto.status.conditions.add() - failed.type = "Ready" - failed.status = "Unknown" - failed.reason = "InspectFailed" - failed.message = "Container inspect failed: connection refused" - - ref = _sandbox_ref(proto) - - assert ref.status.conditions == ( - SandboxConditionRef( - type="Ready", - status="True", - reason="BackendReady", - message="Container is running", - transition_time_ms=1_700_000_000_000, - ), - SandboxConditionRef( - type="Ready", - status="Unknown", - reason="InspectFailed", - message="Container inspect failed: connection refused", - transition_time_ms=None, - ), - ) - # Surfaces the same conditions through SandboxRef directly. - assert ref.conditions == ref.status.conditions - - -def test_sandbox_ref_conditions_default_to_empty() -> None: - ref = _sandbox_ref(_make_sandbox_proto("sandbox-1", "job-1")) - - assert ref.status.conditions == () - assert ref.conditions == () - - -def test_direct_sandbox_ref_construction_defaults_conditions() -> None: - ref = SandboxRef( - id="sandbox-1", - name="job-1", - workspace="default", - status=SandboxStatusRef(phase=2, current_policy_version=0), - ) - - assert ref.status.conditions == () - assert ref.conditions == () - - -def test_returned_labels_are_immutable() -> None: - proto = _make_sandbox_proto("sandbox-1", "job-1", {"aiq": "deep-research"}) - ref = _sandbox_ref(proto) - - with pytest.raises(TypeError): - ref.labels["mutated"] = "nope" # ty: ignore[invalid-assignment] - - -def test_direct_sandbox_ref_construction_defaults_labels() -> None: - ref = SandboxRef( - id="sandbox-1", - name="job-1", - workspace="default", - status=SandboxStatusRef(phase=2, current_policy_version=0), - ) - - assert dict(ref.labels) == {} - - -def test_sandbox_ref_stays_hashable_with_labels_excluded_from_identity() -> None: - ref_a = _sandbox_ref(_make_sandbox_proto("sandbox-1", "job-1", {"aiq": "a"})) - ref_b = _sandbox_ref(_make_sandbox_proto("sandbox-1", "job-1", {"aiq": "b"})) - - # Frozen dataclass must remain hashable despite the immutable labels field. - assert hash(ref_a) == hash(ref_b) - # Labels are excluded from identity: same (id, name, status) compares equal. - assert ref_a == ref_b - assert {ref_a, ref_b} == {ref_a} - - -def test_sandbox_ref_labels_support_standard_serialization() -> None: - ref = _sandbox_ref( - _make_sandbox_proto("sandbox-1", "job-1", {"aiq": "deep-research"}) - ) - - assert asdict(ref)["labels"] == {"aiq": "deep-research"} - assert dict(deepcopy(ref).labels) == {"aiq": "deep-research"} - assert dict(pickle.loads(pickle.dumps(ref)).labels) == {"aiq": "deep-research"} - - -def test_default_sandbox_ref_labels_support_standard_serialization() -> None: - ref = SandboxRef( - id="sandbox-1", - name="job-1", - workspace="default", - status=SandboxStatusRef(phase=2, current_policy_version=0), - ) - - assert asdict(ref)["labels"] == {} - assert dict(deepcopy(ref).labels) == {} - assert dict(pickle.loads(pickle.dumps(ref)).labels) == {} - - -def test_direct_sandbox_ref_copies_and_freezes_labels() -> None: - labels = {"aiq": "deep-research"} - ref = SandboxRef( - id="sandbox-1", - name="job-1", - workspace="default", - status=SandboxStatusRef(phase=2, current_policy_version=0), - labels=labels, - ) - labels["aiq"] = "mutated" - - assert dict(ref.labels) == {"aiq": "deep-research"} - with pytest.raises(TypeError): - ref.labels["mutated"] = "nope" # ty: ignore[invalid-assignment] - - -def test_high_level_creation_forwards_name_and_labels( - monkeypatch: pytest.MonkeyPatch, -) -> None: - recording = _RecordingHighLevelClient() - monkeypatch.setattr( - SandboxClient, - "from_active_cluster", - classmethod(lambda _cls, **_kwargs: recording), - ) - - sandbox = Sandbox( - workspace="staging", - name="job-1", - labels={"aiq": "deep-research"}, - delete_on_exit=False, - ) - sandbox.__enter__() - - assert recording.create_kwargs == { - "workspace": "staging", - "spec": None, - "name": "job-1", - "labels": {"aiq": "deep-research"}, - } - - -def test_high_level_template_creation_forwards_workload_template( - monkeypatch: pytest.MonkeyPatch, -) -> None: - recording = _RecordingHighLevelClient() - monkeypatch.setattr( - SandboxClient, - "from_active_cluster", - classmethod(lambda _cls, **_kwargs: recording), - ) - - spec = openshell_pb2.SandboxSpec( - providers=["github"], - command=["/opt/worker", "--serve"], - tty=True, - ) - sandbox = Sandbox( - workspace="staging", - workload_template="gpu-kata", - spec=spec, - name="job-1", - labels={"team": "runtime"}, - delete_on_exit=False, - ) - sandbox.__enter__() - - assert recording.create_template_kwargs == { - "workspace": "staging", - "workload_template": "gpu-kata", - "spec": spec, - "name": "job-1", - "labels": {"team": "runtime"}, - } - assert recording.create_template_kwargs is not None - forwarded_spec = recording.create_template_kwargs["spec"] - assert list(forwarded_spec.command) == ["/opt/worker", "--serve"] - assert forwarded_spec.tty is True - - -def test_high_level_attach_rejects_name() -> None: - sandbox = Sandbox(workspace="default", sandbox="existing-sandbox", name="job-1") - - with pytest.raises(SandboxError): - sandbox.__enter__() - - -def test_high_level_attach_rejects_labels() -> None: - ref = SandboxRef( - id="sandbox-1", - name="existing", - workspace="default", - status=SandboxStatusRef(phase=2, current_policy_version=0), - ) - sandbox = Sandbox(workspace="default", sandbox=ref, labels={"aiq": "deep-research"}) - - with pytest.raises(SandboxError): - sandbox.__enter__() - - -def test_high_level_attach_rejects_workload_template() -> None: - sandbox = Sandbox( - workspace="default", sandbox="existing-sandbox", workload_template="gpu-kata" - ) - - with pytest.raises(SandboxError): - sandbox.__enter__() - - -# --------------------------------------------------------------------------- -# Workspace support -# --------------------------------------------------------------------------- - - -def test_create_passes_workspace_to_proto() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - ref = client.create(workspace="staging", name="job-1") - - assert stub.create_request is not None - assert _request_workspace(stub.create_request) == "staging" - assert ref.workspace == "staging" - - -def test_get_passes_workspace_to_proto() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - ref = client.get("job-1", workspace="production") - - assert stub.get_request is not None - assert _request_workspace(stub.get_request) == "production" - assert ref.workspace == "production" - - -def test_delete_passes_workspace_to_proto() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - result = client.delete("job-1", workspace="staging") - - assert result.outcome == 1 - assert stub.delete_request is not None - assert _request_workspace(stub.delete_request) == "staging" - assert not stub.delete_request.allow_missing - - -@pytest.mark.parametrize("outcome", [0, 1, 2, 3, 99]) -def test_delete_preserves_outcome_and_identity(outcome: int) -> None: - class Stub: - def DeleteSandbox(self, request: Any, **_kwargs: Any) -> Any: - assert request.allow_missing - return openshell_pb2.DeleteSandboxResponse( - outcome=cast("openshell_pb2.DeletionOutcome", outcome), - sandbox_id="original-id", - ) - - result = _client_with_fake_stub(Stub()).delete( - "job", workspace="default", allow_missing=True - ) - assert int(result.outcome) == outcome - assert result.sandbox_id == "original-id" - if outcome == 99: - assert result.outcome not in ( - DeletionOutcome.COMPLETED, - DeletionOutcome.ALREADY_ABSENT, - ) - - -def test_list_for_all_workspaces_sets_flag() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - client.list_all_for_all_workspaces() - - assert stub.list_request is not None - assert _request_selects_all_workspaces(stub.list_request) - assert _request_workspace(stub.list_request) is None - - -def test_list_with_workspace_passes_workspace() -> None: - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - - client.list_all(workspace="staging") - - assert stub.list_request is not None - assert _request_workspace(stub.list_request) == "staging" - assert not _request_selects_all_workspaces(stub.list_request) - - -def test_sandbox_ref_includes_workspace_from_proto() -> None: - proto = _make_sandbox_proto("sandbox-1", "job-1", workspace="production") - - ref = _sandbox_ref(proto) - - assert ref.workspace == "production" - - -def test_sandbox_ref_includes_workload_template_provenance() -> None: - proto = _make_sandbox_proto("sandbox-1", "job-1") - proto.created_from_workload_template.name = "gpu-kata" - proto.created_from_workload_template.resource_version = "7" - - ref = _sandbox_ref(proto) - - assert ref.created_from_workload_template is not None - assert ref.created_from_workload_template.name == "gpu-kata" - assert ref.created_from_workload_template.resource_version == "7" - - -def test_sandbox_session_delete_passes_workspace() -> None: - from openshell.sandbox import SandboxSession - - stub = _FakeSandboxStub() - client = _client_with_fake_stub(stub) - ref = SandboxRef( - id="sandbox-1", - name="job-1", - workspace="staging", - status=SandboxStatusRef(phase=2, current_policy_version=0), - ) - session = SandboxSession(client, ref) - - session.delete() - - assert stub.delete_request is not None - assert _request_workspace(stub.delete_request) == "staging" - - -def test_sandbox_session_delete_omits_timeout_for_legacy_clients() -> None: - from openshell.sandbox import SandboxSession - - calls: list[tuple[str, str, bool]] = [] - - class LegacyClient: - def delete(self, name, *, workspace, allow_missing=False): - calls.append((name, workspace, allow_missing)) - - ref = SandboxRef( - id="sandbox-1", - name="job-1", - workspace="staging", - status=SandboxStatusRef(phase=2, current_policy_version=0), - ) - session = SandboxSession(cast("Any", LegacyClient()), ref) - - session.delete(allow_missing=True) - - assert calls == [("job-1", "staging", True)] diff --git a/scripts/update_license_headers.py b/scripts/update_license_headers.py index 13dd6f2416..f02ac251b0 100755 --- a/scripts/update_license_headers.py +++ b/scripts/update_license_headers.py @@ -75,7 +75,6 @@ ".venv", ".git", ".cache", - "python/openshell/_proto", } # Individual filenames to skip. diff --git a/tasks/python.toml b/tasks/python.toml index 740b546207..093e7414df 100644 --- a/tasks/python.toml +++ b/tasks/python.toml @@ -1,43 +1,25 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# Python development, build, lint, and format tasks - -["python:dev"] -description = "Install the Python SDK in development mode" -depends = ["python:proto"] -env = { SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL = "0.0.0" } -run = "uv sync --group dev" -hide = true +# Lint, format, and type-check tasks for the repository's Python scripts ["python:lint"] description = "Lint Python code with ruff" -depends = ["python:proto"] -env = { SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL = "0.0.0", UV_NO_SYNC = "1" } +env = { UV_NO_SYNC = "1" } run = "uv run ruff check {{vars.python_paths}}" hide = true ["python:format"] description = "Format Python code with ruff" -env = { SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL = "0.0.0" } run = "uv run ruff format {{vars.python_paths}}" hide = true ["python:format:check"] description = "Check Python formatting with ruff" -env = { SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL = "0.0.0" } run = "uv run ruff format --check {{vars.python_paths}}" hide = true ["python:typecheck"] description = "Type check Python code with ty" -depends = ["python:proto"] -env = { SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL = "0.0.0" } run = "uv run ty check --extra-search-path tasks/scripts --extra-search-path .agents/agents/labeler/bin {{vars.python_paths}}" hide = true - -["python:proto"] -description = "Generate Python protobuf stubs from .proto files" -env = { SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL = "0.0.0" } -run = "uv run --frozen python tasks/scripts/generate_python_proto.py" -hide = true diff --git a/tasks/scripts/check_frozen_paths_test.py b/tasks/scripts/check_frozen_paths_test.py index 698e20432c..1785ef6be2 100644 --- a/tasks/scripts/check_frozen_paths_test.py +++ b/tasks/scripts/check_frozen_paths_test.py @@ -43,20 +43,18 @@ def test_outside_and_prefix_lookalikes_pass(): assert v(("crates/openshell-gateway/src/docker.rs", "modified")) == [] -def test_python_sdk_group(): - assert c.violations( - [{"filename": "python/openshell/x.py", "status": "modified"}], - FREEZES["python-sdk"], - ) - assert v(("python/openshell/x.py", "modified")) == [] - - def test_group_selection(tmp_path): + config = tmp_path / "frozen-paths.toml" + config.write_text( + '[[freeze]]\nname = "a"\nmessage = "a moved"\npaths = ["a"]\n' + '[[freeze]]\nname = "b"\nmessage = "b moved"\npaths = ["b"]\n' + ) f = tmp_path / "f.json" - f.write_text(json.dumps([{"filename": "python/a.py", "status": "added"}])) - assert c.main(["--files-json", str(f), "--group", "desktop-drivers"]) == 0 - assert c.main(["--files-json", str(f), "--group", "python-sdk"]) == 1 - assert c.main(["--files-json", str(f)]) == 1 + f.write_text(json.dumps([{"filename": "b/x.py", "status": "added"}])) + args = ["--config", str(config), "--files-json", str(f)] + assert c.main([*args, "--group", "a"]) == 0 + assert c.main([*args, "--group", "b"]) == 1 + assert c.main(args) == 1 def test_cli_exit_codes(tmp_path): diff --git a/tasks/scripts/codex_compatibility_report.py b/tasks/scripts/codex_compatibility_report.py index 8b03d871e3..3e24e0a62a 100644 --- a/tasks/scripts/codex_compatibility_report.py +++ b/tasks/scripts/codex_compatibility_report.py @@ -10,7 +10,6 @@ SURFACES = ( "rust-sdk", - "python-sdk", "api-behavior", "cli", "configuration", diff --git a/tasks/scripts/generate_python_proto.py b/tasks/scripts/generate_python_proto.py deleted file mode 100644 index e0a1896d0d..0000000000 --- a/tasks/scripts/generate_python_proto.py +++ /dev/null @@ -1,72 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Generate Python protobuf stubs and make their imports package-relative.""" - -import argparse -import re -import subprocess -import sys -from pathlib import Path - -PROTO_FILES = [ - "proto/openshell.proto", - "proto/datamodel.proto", - "proto/options.proto", - "proto/sandbox.proto", - "proto/extension.proto", - "proto/credential_driver.proto", -] - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "--no-pyi", - action="store_true", - help=( - "Skip .pyi type stubs. Needed with protoc older than 3.20 " - "(e.g. Fedora's grpcio-tools 1.48), which has no --pyi_out." - ), - ) - args = parser.parse_args() - output_dir = Path("python/openshell/_proto") - - subprocess.run( - [ - sys.executable, - "-m", - "grpc_tools.protoc", - "-Iproto", - "--python_out=python/openshell/_proto", - *( - [] - if args.no_pyi - else [ - "--pyi_out=python/openshell/_proto", - "--mypy_grpc_out=generate_concrete_servicer_stubs:python/openshell/_proto", - ] - ), - "--grpc_python_out=python/openshell/_proto", - *PROTO_FILES, - ], - check=True, - ) - - # Rewrite only imports of our generated modules, leaving google.protobuf - # imports intact. The same rule covers runtime modules and type stubs. - modules = "|".join(re.escape(f"{Path(path).stem}_pb2") for path in PROTO_FILES) - pattern = rf"^import ({modules})( as \w+)?$" - suffixes = ["_pb2.py", "_pb2_grpc.py"] - if not args.no_pyi: - suffixes.extend(["_pb2.pyi", "_pb2_grpc.pyi"]) - for proto in PROTO_FILES: - for suffix in suffixes: - file_path = output_dir / f"{Path(proto).stem}{suffix}" - text = file_path.read_text() - text = re.sub(pattern, r"from . import \1\2", text, flags=re.MULTILINE) - file_path.write_text(text) - - -if __name__ == "__main__": - main() diff --git a/tasks/test.toml b/tasks/test.toml index c795f77cac..2a1a028ab1 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -7,7 +7,6 @@ description = "Run all tests (Rust + Python)" depends = [ "test:rust", - "test:python", "test:python-scripts", "test:sbom", "test:install-sh", @@ -190,13 +189,6 @@ description = "Test the release, RPM, E2E gateway config, and license header too run = "uv run --no-project --with pytest --with pyyaml pytest -o \"python_files=*_test.py\" tasks/scripts/release_formula_test.py tasks/scripts/release_tooling_test.py deploy/rpm/ e2e/configs/gateway/ scripts/update_license_headers_test.py" hide = true -["test:python"] -description = "Run Python tests" -depends = ["python:proto"] -env = { UV_NO_SYNC = "1" } -run = "uv run pytest python/" -hide = true - ["e2e:rust"] description = "Run Rust CLI e2e tests against a Docker-backed gateway" run = "e2e/rust/e2e-docker.sh" diff --git a/uv.lock b/uv.lock index 4fd26f5171..d84895489d 100644 --- a/uv.lock +++ b/uv.lock @@ -2,37 +2,6 @@ version = 1 revision = 3 requires-python = ">=3.11" -[[package]] -name = "anyio" -version = "4.14.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, -] - -[[package]] -name = "certifi" -version = "2026.10.19" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, -] - -[[package]] -name = "cloudpickle" -version = "3.1.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, -] - [[package]] name = "colorama" version = "0.4.6" @@ -42,269 +11,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] -[[package]] -name = "coverage" -version = "7.13.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ad/49/349848445b0e53660e258acbcc9b0d014895b6739237920886672240f84b/coverage-7.13.2.tar.gz", hash = "sha256:044c6951ec37146b72a50cc81ef02217d27d4c3640efd2640311393cbbf143d3", size = 826523, upload-time = "2026-01-25T13:00:04.889Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6c/01/abca50583a8975bb6e1c59eff67ed8e48bb127c07dad5c28d9e96ccc09ec/coverage-7.13.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:060ebf6f2c51aff5ba38e1f43a2095e087389b1c69d559fde6049a4b0001320e", size = 218971, upload-time = "2026-01-25T12:57:36.953Z" }, - { url = "https://files.pythonhosted.org/packages/eb/0e/b6489f344d99cd1e5b4d5e1be52dfd3f8a3dc5112aa6c33948da8cabad4e/coverage-7.13.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c1ea8ca9db5e7469cd364552985e15911548ea5b69c48a17291f0cac70484b2e", size = 219473, upload-time = "2026-01-25T12:57:38.934Z" }, - { url = "https://files.pythonhosted.org/packages/17/11/db2f414915a8e4ec53f60b17956c27f21fb68fcf20f8a455ce7c2ccec638/coverage-7.13.2-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:b780090d15fd58f07cf2011943e25a5f0c1c894384b13a216b6c86c8a8a7c508", size = 249896, upload-time = "2026-01-25T12:57:40.365Z" }, - { url = "https://files.pythonhosted.org/packages/80/06/0823fe93913663c017e508e8810c998c8ebd3ec2a5a85d2c3754297bdede/coverage-7.13.2-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:88a800258d83acb803c38175b4495d293656d5fac48659c953c18e5f539a274b", size = 251810, upload-time = "2026-01-25T12:57:42.045Z" }, - { url = "https://files.pythonhosted.org/packages/61/dc/b151c3cc41b28cdf7f0166c5fa1271cbc305a8ec0124cce4b04f74791a18/coverage-7.13.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6326e18e9a553e674d948536a04a80d850a5eeefe2aae2e6d7cf05d54046c01b", size = 253920, upload-time = "2026-01-25T12:57:44.026Z" }, - { url = "https://files.pythonhosted.org/packages/2d/35/e83de0556e54a4729a2b94ea816f74ce08732e81945024adee46851c2264/coverage-7.13.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:59562de3f797979e1ff07c587e2ac36ba60ca59d16c211eceaa579c266c5022f", size = 250025, upload-time = "2026-01-25T12:57:45.624Z" }, - { url = "https://files.pythonhosted.org/packages/39/67/af2eb9c3926ce3ea0d58a0d2516fcbdacf7a9fc9559fe63076beaf3f2596/coverage-7.13.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:27ba1ed6f66b0e2d61bfa78874dffd4f8c3a12f8e2b5410e515ab345ba7bc9c3", size = 251612, upload-time = "2026-01-25T12:57:47.713Z" }, - { url = "https://files.pythonhosted.org/packages/26/62/5be2e25f3d6c711d23b71296f8b44c978d4c8b4e5b26871abfc164297502/coverage-7.13.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:8be48da4d47cc68754ce643ea50b3234557cbefe47c2f120495e7bd0a2756f2b", size = 249670, upload-time = "2026-01-25T12:57:49.378Z" }, - { url = "https://files.pythonhosted.org/packages/b3/51/400d1b09a8344199f9b6a6fc1868005d766b7ea95e7882e494fa862ca69c/coverage-7.13.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:2a47a4223d3361b91176aedd9d4e05844ca67d7188456227b6bf5e436630c9a1", size = 249395, upload-time = "2026-01-25T12:57:50.86Z" }, - { url = "https://files.pythonhosted.org/packages/e0/36/f02234bc6e5230e2f0a63fd125d0a2093c73ef20fdf681c7af62a140e4e7/coverage-7.13.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c6f141b468740197d6bd38f2b26ade124363228cc3f9858bd9924ab059e00059", size = 250298, upload-time = "2026-01-25T12:57:52.287Z" }, - { url = "https://files.pythonhosted.org/packages/b0/06/713110d3dd3151b93611c9cbfc65c15b4156b44f927fced49ac0b20b32a4/coverage-7.13.2-cp311-cp311-win32.whl", hash = "sha256:89567798404af067604246e01a49ef907d112edf2b75ef814b1364d5ce267031", size = 221485, upload-time = "2026-01-25T12:57:53.876Z" }, - { url = "https://files.pythonhosted.org/packages/16/0c/3ae6255fa1ebcb7dec19c9a59e85ef5f34566d1265c70af5b2fc981da834/coverage-7.13.2-cp311-cp311-win_amd64.whl", hash = "sha256:21dd57941804ae2ac7e921771a5e21bbf9aabec317a041d164853ad0a96ce31e", size = 222421, upload-time = "2026-01-25T12:57:55.433Z" }, - { url = "https://files.pythonhosted.org/packages/b5/37/fabc3179af4d61d89ea47bd04333fec735cd5e8b59baad44fed9fc4170d7/coverage-7.13.2-cp311-cp311-win_arm64.whl", hash = "sha256:10758e0586c134a0bafa28f2d37dd2cdb5e4a90de25c0fc0c77dabbad46eca28", size = 221088, upload-time = "2026-01-25T12:57:57.41Z" }, - { url = "https://files.pythonhosted.org/packages/46/39/e92a35f7800222d3f7b2cbb7bbc3b65672ae8d501cb31801b2d2bd7acdf1/coverage-7.13.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f106b2af193f965d0d3234f3f83fc35278c7fb935dfbde56ae2da3dd2c03b84d", size = 219142, upload-time = "2026-01-25T12:58:00.448Z" }, - { url = "https://files.pythonhosted.org/packages/45/7a/8bf9e9309c4c996e65c52a7c5a112707ecdd9fbaf49e10b5a705a402bbb4/coverage-7.13.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:78f45d21dc4d5d6bd29323f0320089ef7eae16e4bef712dff79d184fa7330af3", size = 219503, upload-time = "2026-01-25T12:58:02.451Z" }, - { url = "https://files.pythonhosted.org/packages/87/93/17661e06b7b37580923f3f12406ac91d78aeed293fb6da0b69cc7957582f/coverage-7.13.2-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fae91dfecd816444c74531a9c3d6ded17a504767e97aa674d44f638107265b99", size = 251006, upload-time = "2026-01-25T12:58:04.059Z" }, - { url = "https://files.pythonhosted.org/packages/12/f0/f9e59fb8c310171497f379e25db060abef9fa605e09d63157eebec102676/coverage-7.13.2-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:264657171406c114787b441484de620e03d8f7202f113d62fcd3d9688baa3e6f", size = 253750, upload-time = "2026-01-25T12:58:05.574Z" }, - { url = "https://files.pythonhosted.org/packages/e5/b1/1935e31add2232663cf7edd8269548b122a7d100047ff93475dbaaae673e/coverage-7.13.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ae47d8dcd3ded0155afbb59c62bd8ab07ea0fd4902e1c40567439e6db9dcaf2f", size = 254862, upload-time = "2026-01-25T12:58:07.647Z" }, - { url = "https://files.pythonhosted.org/packages/af/59/b5e97071ec13df5f45da2b3391b6cdbec78ba20757bc92580a5b3d5fa53c/coverage-7.13.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8a0b33e9fd838220b007ce8f299114d406c1e8edb21336af4c97a26ecfd185aa", size = 251420, upload-time = "2026-01-25T12:58:09.309Z" }, - { url = "https://files.pythonhosted.org/packages/3f/75/9495932f87469d013dc515fb0ce1aac5fa97766f38f6b1a1deb1ee7b7f3a/coverage-7.13.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b3becbea7f3ce9a2d4d430f223ec15888e4deb31395840a79e916368d6004cce", size = 252786, upload-time = "2026-01-25T12:58:10.909Z" }, - { url = "https://files.pythonhosted.org/packages/6a/59/af550721f0eb62f46f7b8cb7e6f1860592189267b1c411a4e3a057caacee/coverage-7.13.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:f819c727a6e6eeb8711e4ce63d78c620f69630a2e9d53bc95ca5379f57b6ba94", size = 250928, upload-time = "2026-01-25T12:58:12.449Z" }, - { url = "https://files.pythonhosted.org/packages/9b/b1/21b4445709aae500be4ab43bbcfb4e53dc0811c3396dcb11bf9f23fd0226/coverage-7.13.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:4f7b71757a3ab19f7ba286e04c181004c1d61be921795ee8ba6970fd0ec91da5", size = 250496, upload-time = "2026-01-25T12:58:14.047Z" }, - { url = "https://files.pythonhosted.org/packages/ba/b1/0f5d89dfe0392990e4f3980adbde3eb34885bc1effb2dc369e0bf385e389/coverage-7.13.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b7fc50d2afd2e6b4f6f2f403b70103d280a8e0cb35320cbbe6debcda02a1030b", size = 252373, upload-time = "2026-01-25T12:58:15.976Z" }, - { url = "https://files.pythonhosted.org/packages/01/c9/0cf1a6a57a9968cc049a6b896693faa523c638a5314b1fc374eb2b2ac904/coverage-7.13.2-cp312-cp312-win32.whl", hash = "sha256:292250282cf9bcf206b543d7608bda17ca6fc151f4cbae949fc7e115112fbd41", size = 221696, upload-time = "2026-01-25T12:58:17.517Z" }, - { url = "https://files.pythonhosted.org/packages/4d/05/d7540bf983f09d32803911afed135524570f8c47bb394bf6206c1dc3a786/coverage-7.13.2-cp312-cp312-win_amd64.whl", hash = "sha256:eeea10169fac01549a7921d27a3e517194ae254b542102267bef7a93ed38c40e", size = 222504, upload-time = "2026-01-25T12:58:19.115Z" }, - { url = "https://files.pythonhosted.org/packages/15/8b/1a9f037a736ced0a12aacf6330cdaad5008081142a7070bc58b0f7930cbc/coverage-7.13.2-cp312-cp312-win_arm64.whl", hash = "sha256:2a5b567f0b635b592c917f96b9a9cb3dbd4c320d03f4bf94e9084e494f2e8894", size = 221120, upload-time = "2026-01-25T12:58:21.334Z" }, - { url = "https://files.pythonhosted.org/packages/a7/f0/3d3eac7568ab6096ff23791a526b0048a1ff3f49d0e236b2af6fb6558e88/coverage-7.13.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ed75de7d1217cf3b99365d110975f83af0528c849ef5180a12fd91b5064df9d6", size = 219168, upload-time = "2026-01-25T12:58:23.376Z" }, - { url = "https://files.pythonhosted.org/packages/a3/a6/f8b5cfeddbab95fdef4dcd682d82e5dcff7a112ced57a959f89537ee9995/coverage-7.13.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:97e596de8fa9bada4d88fde64a3f4d37f1b6131e4faa32bad7808abc79887ddc", size = 219537, upload-time = "2026-01-25T12:58:24.932Z" }, - { url = "https://files.pythonhosted.org/packages/7b/e6/8d8e6e0c516c838229d1e41cadcec91745f4b1031d4db17ce0043a0423b4/coverage-7.13.2-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:68c86173562ed4413345410c9480a8d64864ac5e54a5cda236748031e094229f", size = 250528, upload-time = "2026-01-25T12:58:26.567Z" }, - { url = "https://files.pythonhosted.org/packages/8e/78/befa6640f74092b86961f957f26504c8fba3d7da57cc2ab7407391870495/coverage-7.13.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:7be4d613638d678b2b3773b8f687537b284d7074695a43fe2fbbfc0e31ceaed1", size = 253132, upload-time = "2026-01-25T12:58:28.251Z" }, - { url = "https://files.pythonhosted.org/packages/9d/10/1630db1edd8ce675124a2ee0f7becc603d2bb7b345c2387b4b95c6907094/coverage-7.13.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d7f63ce526a96acd0e16c4af8b50b64334239550402fb1607ce6a584a6d62ce9", size = 254374, upload-time = "2026-01-25T12:58:30.294Z" }, - { url = "https://files.pythonhosted.org/packages/ed/1d/0d9381647b1e8e6d310ac4140be9c428a0277330991e0c35bdd751e338a4/coverage-7.13.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:406821f37f864f968e29ac14c3fccae0fec9fdeba48327f0341decf4daf92d7c", size = 250762, upload-time = "2026-01-25T12:58:32.036Z" }, - { url = "https://files.pythonhosted.org/packages/43/e4/5636dfc9a7c871ee8776af83ee33b4c26bc508ad6cee1e89b6419a366582/coverage-7.13.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ee68e5a4e3e5443623406b905db447dceddffee0dceb39f4e0cd9ec2a35004b5", size = 252502, upload-time = "2026-01-25T12:58:33.961Z" }, - { url = "https://files.pythonhosted.org/packages/02/2a/7ff2884d79d420cbb2d12fed6fff727b6d0ef27253140d3cdbbd03187ee0/coverage-7.13.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:2ee0e58cca0c17dd9c6c1cdde02bb705c7b3fbfa5f3b0b5afeda20d4ebff8ef4", size = 250463, upload-time = "2026-01-25T12:58:35.529Z" }, - { url = "https://files.pythonhosted.org/packages/91/c0/ba51087db645b6c7261570400fc62c89a16278763f36ba618dc8657a187b/coverage-7.13.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:6e5bbb5018bf76a56aabdb64246b5288d5ae1b7d0dd4d0534fe86df2c2992d1c", size = 250288, upload-time = "2026-01-25T12:58:37.226Z" }, - { url = "https://files.pythonhosted.org/packages/03/07/44e6f428551c4d9faf63ebcefe49b30e5c89d1be96f6a3abd86a52da9d15/coverage-7.13.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a55516c68ef3e08e134e818d5e308ffa6b1337cc8b092b69b24287bf07d38e31", size = 252063, upload-time = "2026-01-25T12:58:38.821Z" }, - { url = "https://files.pythonhosted.org/packages/c2/67/35b730ad7e1859dd57e834d1bc06080d22d2f87457d53f692fce3f24a5a9/coverage-7.13.2-cp313-cp313-win32.whl", hash = "sha256:5b20211c47a8abf4abc3319d8ce2464864fa9f30c5fcaf958a3eed92f4f1fef8", size = 221716, upload-time = "2026-01-25T12:58:40.484Z" }, - { url = "https://files.pythonhosted.org/packages/0d/82/e5fcf5a97c72f45fc14829237a6550bf49d0ab882ac90e04b12a69db76b4/coverage-7.13.2-cp313-cp313-win_amd64.whl", hash = "sha256:14f500232e521201cf031549fb1ebdfc0a40f401cf519157f76c397e586c3beb", size = 222522, upload-time = "2026-01-25T12:58:43.247Z" }, - { url = "https://files.pythonhosted.org/packages/b1/f1/25d7b2f946d239dd2d6644ca2cc060d24f97551e2af13b6c24c722ae5f97/coverage-7.13.2-cp313-cp313-win_arm64.whl", hash = "sha256:9779310cb5a9778a60c899f075a8514c89fa6d10131445c2207fc893e0b14557", size = 221145, upload-time = "2026-01-25T12:58:45Z" }, - { url = "https://files.pythonhosted.org/packages/9e/f7/080376c029c8f76fadfe43911d0daffa0cbdc9f9418a0eead70c56fb7f4b/coverage-7.13.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:e64fa5a1e41ce5df6b547cbc3d3699381c9e2c2c369c67837e716ed0f549d48e", size = 219861, upload-time = "2026-01-25T12:58:46.586Z" }, - { url = "https://files.pythonhosted.org/packages/42/11/0b5e315af5ab35f4c4a70e64d3314e4eec25eefc6dec13be3a7d5ffe8ac5/coverage-7.13.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:b01899e82a04085b6561eb233fd688474f57455e8ad35cd82286463ba06332b7", size = 220207, upload-time = "2026-01-25T12:58:48.277Z" }, - { url = "https://files.pythonhosted.org/packages/b2/0c/0874d0318fb1062117acbef06a09cf8b63f3060c22265adaad24b36306b7/coverage-7.13.2-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:838943bea48be0e2768b0cf7819544cdedc1bbb2f28427eabb6eb8c9eb2285d3", size = 261504, upload-time = "2026-01-25T12:58:49.904Z" }, - { url = "https://files.pythonhosted.org/packages/83/5e/1cd72c22ecb30751e43a72f40ba50fcef1b7e93e3ea823bd9feda8e51f9a/coverage-7.13.2-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:93d1d25ec2b27e90bcfef7012992d1f5121b51161b8bffcda756a816cf13c2c3", size = 263582, upload-time = "2026-01-25T12:58:51.582Z" }, - { url = "https://files.pythonhosted.org/packages/9b/da/8acf356707c7a42df4d0657020308e23e5a07397e81492640c186268497c/coverage-7.13.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93b57142f9621b0d12349c43fc7741fe578e4bc914c1e5a54142856cfc0bf421", size = 266008, upload-time = "2026-01-25T12:58:53.234Z" }, - { url = "https://files.pythonhosted.org/packages/41/41/ea1730af99960309423c6ea8d6a4f1fa5564b2d97bd1d29dda4b42611f04/coverage-7.13.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f06799ae1bdfff7ccb8665d75f8291c69110ba9585253de254688aa8a1ccc6c5", size = 260762, upload-time = "2026-01-25T12:58:55.372Z" }, - { url = "https://files.pythonhosted.org/packages/22/fa/02884d2080ba71db64fdc127b311db60e01fe6ba797d9c8363725e39f4d5/coverage-7.13.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:7f9405ab4f81d490811b1d91c7a20361135a2df4c170e7f0b747a794da5b7f23", size = 263571, upload-time = "2026-01-25T12:58:57.52Z" }, - { url = "https://files.pythonhosted.org/packages/d2/6b/4083aaaeba9b3112f55ac57c2ce7001dc4d8fa3fcc228a39f09cc84ede27/coverage-7.13.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:f9ab1d5b86f8fbc97a5b3cd6280a3fd85fef3b028689d8a2c00918f0d82c728c", size = 261200, upload-time = "2026-01-25T12:58:59.255Z" }, - { url = "https://files.pythonhosted.org/packages/e9/d2/aea92fa36d61955e8c416ede9cf9bf142aa196f3aea214bb67f85235a050/coverage-7.13.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:f674f59712d67e841525b99e5e2b595250e39b529c3bda14764e4f625a3fa01f", size = 260095, upload-time = "2026-01-25T12:59:01.066Z" }, - { url = "https://files.pythonhosted.org/packages/0d/ae/04ffe96a80f107ea21b22b2367175c621da920063260a1c22f9452fd7866/coverage-7.13.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c6cadac7b8ace1ba9144feb1ae3cb787a6065ba6d23ffc59a934b16406c26573", size = 262284, upload-time = "2026-01-25T12:59:02.802Z" }, - { url = "https://files.pythonhosted.org/packages/1c/7a/6f354dcd7dfc41297791d6fb4e0d618acb55810bde2c1fd14b3939e05c2b/coverage-7.13.2-cp313-cp313t-win32.whl", hash = "sha256:14ae4146465f8e6e6253eba0cccd57423e598a4cb925958b240c805300918343", size = 222389, upload-time = "2026-01-25T12:59:04.563Z" }, - { url = "https://files.pythonhosted.org/packages/8d/d5/080ad292a4a3d3daf411574be0a1f56d6dee2c4fdf6b005342be9fac807f/coverage-7.13.2-cp313-cp313t-win_amd64.whl", hash = "sha256:9074896edd705a05769e3de0eac0a8388484b503b68863dd06d5e473f874fd47", size = 223450, upload-time = "2026-01-25T12:59:06.677Z" }, - { url = "https://files.pythonhosted.org/packages/88/96/df576fbacc522e9fb8d1c4b7a7fc62eb734be56e2cba1d88d2eabe08ea3f/coverage-7.13.2-cp313-cp313t-win_arm64.whl", hash = "sha256:69e526e14f3f854eda573d3cf40cffd29a1a91c684743d904c33dbdcd0e0f3e7", size = 221707, upload-time = "2026-01-25T12:59:08.363Z" }, - { url = "https://files.pythonhosted.org/packages/55/53/1da9e51a0775634b04fcc11eb25c002fc58ee4f92ce2e8512f94ac5fc5bf/coverage-7.13.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:387a825f43d680e7310e6f325b2167dd093bc8ffd933b83e9aa0983cf6e0a2ef", size = 219213, upload-time = "2026-01-25T12:59:11.909Z" }, - { url = "https://files.pythonhosted.org/packages/46/35/b3caac3ebbd10230fea5a33012b27d19e999a17c9285c4228b4b2e35b7da/coverage-7.13.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:f0d7fea9d8e5d778cd5a9e8fc38308ad688f02040e883cdc13311ef2748cb40f", size = 219549, upload-time = "2026-01-25T12:59:13.638Z" }, - { url = "https://files.pythonhosted.org/packages/76/9c/e1cf7def1bdc72c1907e60703983a588f9558434a2ff94615747bd73c192/coverage-7.13.2-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:e080afb413be106c95c4ee96b4fffdc9e2fa56a8bbf90b5c0918e5c4449412f5", size = 250586, upload-time = "2026-01-25T12:59:15.808Z" }, - { url = "https://files.pythonhosted.org/packages/ba/49/f54ec02ed12be66c8d8897270505759e057b0c68564a65c429ccdd1f139e/coverage-7.13.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a7fc042ba3c7ce25b8a9f097eb0f32a5ce1ccdb639d9eec114e26def98e1f8a4", size = 253093, upload-time = "2026-01-25T12:59:17.491Z" }, - { url = "https://files.pythonhosted.org/packages/fb/5e/aaf86be3e181d907e23c0f61fccaeb38de8e6f6b47aed92bf57d8fc9c034/coverage-7.13.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d0ba505e021557f7f8173ee8cd6b926373d8653e5ff7581ae2efce1b11ef4c27", size = 254446, upload-time = "2026-01-25T12:59:19.752Z" }, - { url = "https://files.pythonhosted.org/packages/28/c8/a5fa01460e2d75b0c853b392080d6829d3ca8b5ab31e158fa0501bc7c708/coverage-7.13.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7de326f80e3451bd5cc7239ab46c73ddb658fe0b7649476bc7413572d36cd548", size = 250615, upload-time = "2026-01-25T12:59:21.928Z" }, - { url = "https://files.pythonhosted.org/packages/86/0b/6d56315a55f7062bb66410732c24879ccb2ec527ab6630246de5fe45a1df/coverage-7.13.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:abaea04f1e7e34841d4a7b343904a3f59481f62f9df39e2cd399d69a187a9660", size = 252452, upload-time = "2026-01-25T12:59:23.592Z" }, - { url = "https://files.pythonhosted.org/packages/30/19/9bc550363ebc6b0ea121977ee44d05ecd1e8bf79018b8444f1028701c563/coverage-7.13.2-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:9f93959ee0c604bccd8e0697be21de0887b1f73efcc3aa73a3ec0fd13feace92", size = 250418, upload-time = "2026-01-25T12:59:25.392Z" }, - { url = "https://files.pythonhosted.org/packages/1f/53/580530a31ca2f0cc6f07a8f2ab5460785b02bb11bdf815d4c4d37a4c5169/coverage-7.13.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:13fe81ead04e34e105bf1b3c9f9cdf32ce31736ee5d90a8d2de02b9d3e1bcb82", size = 250231, upload-time = "2026-01-25T12:59:27.888Z" }, - { url = "https://files.pythonhosted.org/packages/e2/42/dd9093f919dc3088cb472893651884bd675e3df3d38a43f9053656dca9a2/coverage-7.13.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d6d16b0f71120e365741bca2cb473ca6fe38930bc5431c5e850ba949f708f892", size = 251888, upload-time = "2026-01-25T12:59:29.636Z" }, - { url = "https://files.pythonhosted.org/packages/fa/a6/0af4053e6e819774626e133c3d6f70fae4d44884bfc4b126cb647baee8d3/coverage-7.13.2-cp314-cp314-win32.whl", hash = "sha256:9b2f4714bb7d99ba3790ee095b3b4ac94767e1347fe424278a0b10acb3ff04fe", size = 221968, upload-time = "2026-01-25T12:59:31.424Z" }, - { url = "https://files.pythonhosted.org/packages/c4/cc/5aff1e1f80d55862442855517bb8ad8ad3a68639441ff6287dde6a58558b/coverage-7.13.2-cp314-cp314-win_amd64.whl", hash = "sha256:e4121a90823a063d717a96e0a0529c727fb31ea889369a0ee3ec00ed99bf6859", size = 222783, upload-time = "2026-01-25T12:59:33.118Z" }, - { url = "https://files.pythonhosted.org/packages/de/20/09abafb24f84b3292cc658728803416c15b79f9ee5e68d25238a895b07d9/coverage-7.13.2-cp314-cp314-win_arm64.whl", hash = "sha256:6873f0271b4a15a33e7590f338d823f6f66f91ed147a03938d7ce26efd04eee6", size = 221348, upload-time = "2026-01-25T12:59:34.939Z" }, - { url = "https://files.pythonhosted.org/packages/b6/60/a3820c7232db63be060e4019017cd3426751c2699dab3c62819cdbcea387/coverage-7.13.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:f61d349f5b7cd95c34017f1927ee379bfbe9884300d74e07cf630ccf7a610c1b", size = 219950, upload-time = "2026-01-25T12:59:36.624Z" }, - { url = "https://files.pythonhosted.org/packages/fd/37/e4ef5975fdeb86b1e56db9a82f41b032e3d93a840ebaf4064f39e770d5c5/coverage-7.13.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a43d34ce714f4ca674c0d90beb760eb05aad906f2c47580ccee9da8fe8bfb417", size = 220209, upload-time = "2026-01-25T12:59:38.339Z" }, - { url = "https://files.pythonhosted.org/packages/54/df/d40e091d00c51adca1e251d3b60a8b464112efa3004949e96a74d7c19a64/coverage-7.13.2-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:bff1b04cb9d4900ce5c56c4942f047dc7efe57e2608cb7c3c8936e9970ccdbee", size = 261576, upload-time = "2026-01-25T12:59:40.446Z" }, - { url = "https://files.pythonhosted.org/packages/c5/44/5259c4bed54e3392e5c176121af9f71919d96dde853386e7730e705f3520/coverage-7.13.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6ae99e4560963ad8e163e819e5d77d413d331fd00566c1e0856aa252303552c1", size = 263704, upload-time = "2026-01-25T12:59:42.346Z" }, - { url = "https://files.pythonhosted.org/packages/16/bd/ae9f005827abcbe2c70157459ae86053971c9fa14617b63903abbdce26d9/coverage-7.13.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e79a8c7d461820257d9aa43716c4efc55366d7b292e46b5b37165be1d377405d", size = 266109, upload-time = "2026-01-25T12:59:44.073Z" }, - { url = "https://files.pythonhosted.org/packages/a2/c0/8e279c1c0f5b1eaa3ad9b0fb7a5637fc0379ea7d85a781c0fe0bb3cfc2ab/coverage-7.13.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:060ee84f6a769d40c492711911a76811b4befb6fba50abb450371abb720f5bd6", size = 260686, upload-time = "2026-01-25T12:59:45.804Z" }, - { url = "https://files.pythonhosted.org/packages/b2/47/3a8112627e9d863e7cddd72894171c929e94491a597811725befdcd76bce/coverage-7.13.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3bca209d001fd03ea2d978f8a4985093240a355c93078aee3f799852c23f561a", size = 263568, upload-time = "2026-01-25T12:59:47.929Z" }, - { url = "https://files.pythonhosted.org/packages/92/bc/7ea367d84afa3120afc3ce6de294fd2dcd33b51e2e7fbe4bbfd200f2cb8c/coverage-7.13.2-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:6b8092aa38d72f091db61ef83cb66076f18f02da3e1a75039a4f218629600e04", size = 261174, upload-time = "2026-01-25T12:59:49.717Z" }, - { url = "https://files.pythonhosted.org/packages/33/b7/f1092dcecb6637e31cc2db099581ee5c61a17647849bae6b8261a2b78430/coverage-7.13.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:4a3158dc2dcce5200d91ec28cd315c999eebff355437d2765840555d765a6e5f", size = 260017, upload-time = "2026-01-25T12:59:51.463Z" }, - { url = "https://files.pythonhosted.org/packages/2b/cd/f3d07d4b95fbe1a2ef0958c15da614f7e4f557720132de34d2dc3aa7e911/coverage-7.13.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3973f353b2d70bd9796cc12f532a05945232ccae966456c8ed7034cb96bbfd6f", size = 262337, upload-time = "2026-01-25T12:59:53.407Z" }, - { url = "https://files.pythonhosted.org/packages/e0/db/b0d5b2873a07cb1e06a55d998697c0a5a540dcefbf353774c99eb3874513/coverage-7.13.2-cp314-cp314t-win32.whl", hash = "sha256:79f6506a678a59d4ded048dc72f1859ebede8ec2b9a2d509ebe161f01c2879d3", size = 222749, upload-time = "2026-01-25T12:59:56.316Z" }, - { url = "https://files.pythonhosted.org/packages/e5/2f/838a5394c082ac57d85f57f6aba53093b30d9089781df72412126505716f/coverage-7.13.2-cp314-cp314t-win_amd64.whl", hash = "sha256:196bfeabdccc5a020a57d5a368c681e3a6ceb0447d153aeccc1ab4d70a5032ba", size = 223857, upload-time = "2026-01-25T12:59:58.201Z" }, - { url = "https://files.pythonhosted.org/packages/44/d4/b608243e76ead3a4298824b50922b89ef793e50069ce30316a65c1b4d7ef/coverage-7.13.2-cp314-cp314t-win_arm64.whl", hash = "sha256:69269ab58783e090bfbf5b916ab3d188126e22d6070bbfc93098fdd474ef937c", size = 221881, upload-time = "2026-01-25T13:00:00.449Z" }, - { url = "https://files.pythonhosted.org/packages/d2/db/d291e30fdf7ea617a335531e72294e0c723356d7fdde8fba00610a76bda9/coverage-7.13.2-py3-none-any.whl", hash = "sha256:40ce1ea1e25125556d8e76bd0b61500839a07944cc287ac21d5626f3e620cad5", size = 210943, upload-time = "2026-01-25T13:00:02.388Z" }, -] - -[package.optional-dependencies] -toml = [ - { name = "tomli", marker = "python_full_version <= '3.11'" }, -] - -[[package]] -name = "execnet" -version = "2.1.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" }, -] - -[[package]] -name = "googleapis-common-protos" -version = "1.75.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "protobuf" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8a/c5/4353a188e2c335aee33269e8b654af228278cca8e5f0b4b5f11e5d0e9adb/googleapis_common_protos-1.75.3.tar.gz", hash = "sha256:57c435ac2c68b108999b6db075d9053e4d7a936ba57b4a3d45667b1346f1738a", size = 153905, upload-time = "2026-09-03T22:31:21.869Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1a/7a/7d79170c6ce6f12e109df2b3879d6b934010cf4f99aea8de8b7e5408c174/googleapis_common_protos-1.75.3-py3-none-any.whl", hash = "sha256:a018d2bf098ca9fb6faa08d5bb780e2a2c2f73c566f069761331386c9596d3f2", size = 306984, upload-time = "2026-09-03T22:30:45.133Z" }, -] - -[[package]] -name = "grpcio" -version = "1.78.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/8a/3d098f35c143a89520e568e6539cc098fcd294495910e359889ce8741c84/grpcio-1.78.0.tar.gz", hash = "sha256:7382b95189546f375c174f53a5fa873cef91c4b8005faa05cc5b3beea9c4f1c5", size = 12852416, upload-time = "2026-02-06T09:57:18.093Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/86/c7/d0b780a29b0837bf4ca9580904dfb275c1fc321ded7897d620af7047ec57/grpcio-1.78.0-cp311-cp311-linux_armv7l.whl", hash = "sha256:2777b783f6c13b92bd7b716667452c329eefd646bfb3f2e9dabea2e05dbd34f6", size = 5951525, upload-time = "2026-02-06T09:55:01.989Z" }, - { url = "https://files.pythonhosted.org/packages/c5/b1/96920bf2ee61df85a9503cb6f733fe711c0ff321a5a697d791b075673281/grpcio-1.78.0-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:9dca934f24c732750389ce49d638069c3892ad065df86cb465b3fa3012b70c9e", size = 11830418, upload-time = "2026-02-06T09:55:04.462Z" }, - { url = "https://files.pythonhosted.org/packages/83/0c/7c1528f098aeb75a97de2bae18c530f56959fb7ad6c882db45d9884d6edc/grpcio-1.78.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:459ab414b35f4496138d0ecd735fed26f1318af5e52cb1efbc82a09f0d5aa911", size = 6524477, upload-time = "2026-02-06T09:55:07.111Z" }, - { url = "https://files.pythonhosted.org/packages/8d/52/e7c1f3688f949058e19a011c4e0dec973da3d0ae5e033909677f967ae1f4/grpcio-1.78.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:082653eecbdf290e6e3e2c276ab2c54b9e7c299e07f4221872380312d8cf395e", size = 7198266, upload-time = "2026-02-06T09:55:10.016Z" }, - { url = "https://files.pythonhosted.org/packages/e5/61/8ac32517c1e856677282c34f2e7812d6c328fa02b8f4067ab80e77fdc9c9/grpcio-1.78.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:85f93781028ec63f383f6bc90db785a016319c561cc11151fbb7b34e0d012303", size = 6730552, upload-time = "2026-02-06T09:55:12.207Z" }, - { url = "https://files.pythonhosted.org/packages/bd/98/b8ee0158199250220734f620b12e4a345955ac7329cfd908d0bf0fda77f0/grpcio-1.78.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f12857d24d98441af6a1d5c87442d624411db486f7ba12550b07788f74b67b04", size = 7304296, upload-time = "2026-02-06T09:55:15.044Z" }, - { url = "https://files.pythonhosted.org/packages/bd/0f/7b72762e0d8840b58032a56fdbd02b78fc645b9fa993d71abf04edbc54f4/grpcio-1.78.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5397fff416b79e4b284959642a4e95ac4b0f1ece82c9993658e0e477d40551ec", size = 8288298, upload-time = "2026-02-06T09:55:17.276Z" }, - { url = "https://files.pythonhosted.org/packages/24/ae/ae4ce56bc5bb5caa3a486d60f5f6083ac3469228faa734362487176c15c5/grpcio-1.78.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:fbe6e89c7ffb48518384068321621b2a69cab509f58e40e4399fdd378fa6d074", size = 7730953, upload-time = "2026-02-06T09:55:19.545Z" }, - { url = "https://files.pythonhosted.org/packages/b5/6e/8052e3a28eb6a820c372b2eb4b5e32d195c661e137d3eca94d534a4cfd8a/grpcio-1.78.0-cp311-cp311-win32.whl", hash = "sha256:6092beabe1966a3229f599d7088b38dfc8ffa1608b5b5cdda31e591e6500f856", size = 4076503, upload-time = "2026-02-06T09:55:21.521Z" }, - { url = "https://files.pythonhosted.org/packages/08/62/f22c98c5265dfad327251fa2f840b591b1df5f5e15d88b19c18c86965b27/grpcio-1.78.0-cp311-cp311-win_amd64.whl", hash = "sha256:1afa62af6e23f88629f2b29ec9e52ec7c65a7176c1e0a83292b93c76ca882558", size = 4799767, upload-time = "2026-02-06T09:55:24.107Z" }, - { url = "https://files.pythonhosted.org/packages/4e/f4/7384ed0178203d6074446b3c4f46c90a22ddf7ae0b3aee521627f54cfc2a/grpcio-1.78.0-cp312-cp312-linux_armv7l.whl", hash = "sha256:f9ab915a267fc47c7e88c387a3a28325b58c898e23d4995f765728f4e3dedb97", size = 5913985, upload-time = "2026-02-06T09:55:26.832Z" }, - { url = "https://files.pythonhosted.org/packages/81/ed/be1caa25f06594463f685b3790b320f18aea49b33166f4141bfdc2bfb236/grpcio-1.78.0-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:3f8904a8165ab21e07e58bf3e30a73f4dffc7a1e0dbc32d51c61b5360d26f43e", size = 11811853, upload-time = "2026-02-06T09:55:29.224Z" }, - { url = "https://files.pythonhosted.org/packages/24/a7/f06d151afc4e64b7e3cc3e872d331d011c279aaab02831e40a81c691fb65/grpcio-1.78.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:859b13906ce098c0b493af92142ad051bf64c7870fa58a123911c88606714996", size = 6475766, upload-time = "2026-02-06T09:55:31.825Z" }, - { url = "https://files.pythonhosted.org/packages/8a/a8/4482922da832ec0082d0f2cc3a10976d84a7424707f25780b82814aafc0a/grpcio-1.78.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:b2342d87af32790f934a79c3112641e7b27d63c261b8b4395350dad43eff1dc7", size = 7170027, upload-time = "2026-02-06T09:55:34.7Z" }, - { url = "https://files.pythonhosted.org/packages/54/bf/f4a3b9693e35d25b24b0b39fa46d7d8a3c439e0a3036c3451764678fec20/grpcio-1.78.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:12a771591ae40bc65ba67048fa52ef4f0e6db8279e595fd349f9dfddeef571f9", size = 6690766, upload-time = "2026-02-06T09:55:36.902Z" }, - { url = "https://files.pythonhosted.org/packages/c7/b9/521875265cc99fe5ad4c5a17010018085cae2810a928bf15ebe7d8bcd9cc/grpcio-1.78.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:185dea0d5260cbb2d224c507bf2a5444d5abbb1fa3594c1ed7e4c709d5eb8383", size = 7266161, upload-time = "2026-02-06T09:55:39.824Z" }, - { url = "https://files.pythonhosted.org/packages/05/86/296a82844fd40a4ad4a95f100b55044b4f817dece732bf686aea1a284147/grpcio-1.78.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:51b13f9aed9d59ee389ad666b8c2214cc87b5de258fa712f9ab05f922e3896c6", size = 8253303, upload-time = "2026-02-06T09:55:42.353Z" }, - { url = "https://files.pythonhosted.org/packages/f3/e4/ea3c0caf5468537f27ad5aab92b681ed7cc0ef5f8c9196d3fd42c8c2286b/grpcio-1.78.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fd5f135b1bd58ab088930b3c613455796dfa0393626a6972663ccdda5b4ac6ce", size = 7698222, upload-time = "2026-02-06T09:55:44.629Z" }, - { url = "https://files.pythonhosted.org/packages/d7/47/7f05f81e4bb6b831e93271fb12fd52ba7b319b5402cbc101d588f435df00/grpcio-1.78.0-cp312-cp312-win32.whl", hash = "sha256:94309f498bcc07e5a7d16089ab984d42ad96af1d94b5a4eb966a266d9fcabf68", size = 4066123, upload-time = "2026-02-06T09:55:47.644Z" }, - { url = "https://files.pythonhosted.org/packages/ad/e7/d6914822c88aa2974dbbd10903d801a28a19ce9cd8bad7e694cbbcf61528/grpcio-1.78.0-cp312-cp312-win_amd64.whl", hash = "sha256:9566fe4ababbb2610c39190791e5b829869351d14369603702e890ef3ad2d06e", size = 4797657, upload-time = "2026-02-06T09:55:49.86Z" }, - { url = "https://files.pythonhosted.org/packages/05/a9/8f75894993895f361ed8636cd9237f4ab39ef87fd30db17467235ed1c045/grpcio-1.78.0-cp313-cp313-linux_armv7l.whl", hash = "sha256:ce3a90455492bf8bfa38e56fbbe1dbd4f872a3d8eeaf7337dc3b1c8aa28c271b", size = 5920143, upload-time = "2026-02-06T09:55:52.035Z" }, - { url = "https://files.pythonhosted.org/packages/55/06/0b78408e938ac424100100fd081189451b472236e8a3a1f6500390dc4954/grpcio-1.78.0-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:2bf5e2e163b356978b23652c4818ce4759d40f4712ee9ec5a83c4be6f8c23a3a", size = 11803926, upload-time = "2026-02-06T09:55:55.494Z" }, - { url = "https://files.pythonhosted.org/packages/88/93/b59fe7832ff6ae3c78b813ea43dac60e295fa03606d14d89d2e0ec29f4f3/grpcio-1.78.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8f2ac84905d12918e4e55a16da17939eb63e433dc11b677267c35568aa63fc84", size = 6478628, upload-time = "2026-02-06T09:55:58.533Z" }, - { url = "https://files.pythonhosted.org/packages/ed/df/e67e3734527f9926b7d9c0dde6cd998d1d26850c3ed8eeec81297967ac67/grpcio-1.78.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:b58f37edab4a3881bc6c9bca52670610e0c9ca14e2ea3cf9debf185b870457fb", size = 7173574, upload-time = "2026-02-06T09:56:01.786Z" }, - { url = "https://files.pythonhosted.org/packages/a6/62/cc03fffb07bfba982a9ec097b164e8835546980aec25ecfa5f9c1a47e022/grpcio-1.78.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:735e38e176a88ce41840c21bb49098ab66177c64c82426e24e0082500cc68af5", size = 6692639, upload-time = "2026-02-06T09:56:04.529Z" }, - { url = "https://files.pythonhosted.org/packages/bf/9a/289c32e301b85bdb67d7ec68b752155e674ee3ba2173a1858f118e399ef3/grpcio-1.78.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2045397e63a7a0ee7957c25f7dbb36ddc110e0cfb418403d110c0a7a68a844e9", size = 7268838, upload-time = "2026-02-06T09:56:08.397Z" }, - { url = "https://files.pythonhosted.org/packages/0e/79/1be93f32add280461fa4773880196572563e9c8510861ac2da0ea0f892b6/grpcio-1.78.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:a9f136fbafe7ccf4ac7e8e0c28b31066e810be52d6e344ef954a3a70234e1702", size = 8251878, upload-time = "2026-02-06T09:56:10.914Z" }, - { url = "https://files.pythonhosted.org/packages/65/65/793f8e95296ab92e4164593674ae6291b204bb5f67f9d4a711489cd30ffa/grpcio-1.78.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:748b6138585379c737adc08aeffd21222abbda1a86a0dca2a39682feb9196c20", size = 7695412, upload-time = "2026-02-06T09:56:13.593Z" }, - { url = "https://files.pythonhosted.org/packages/1c/9f/1e233fe697ecc82845942c2822ed06bb522e70d6771c28d5528e4c50f6a4/grpcio-1.78.0-cp313-cp313-win32.whl", hash = "sha256:271c73e6e5676afe4fc52907686670c7cea22ab2310b76a59b678403ed40d670", size = 4064899, upload-time = "2026-02-06T09:56:15.601Z" }, - { url = "https://files.pythonhosted.org/packages/4d/27/d86b89e36de8a951501fb06a0f38df19853210f341d0b28f83f4aa0ffa08/grpcio-1.78.0-cp313-cp313-win_amd64.whl", hash = "sha256:f2d4e43ee362adfc05994ed479334d5a451ab7bc3f3fee1b796b8ca66895acb4", size = 4797393, upload-time = "2026-02-06T09:56:17.882Z" }, - { url = "https://files.pythonhosted.org/packages/29/f2/b56e43e3c968bfe822fa6ce5bca10d5c723aa40875b48791ce1029bb78c7/grpcio-1.78.0-cp314-cp314-linux_armv7l.whl", hash = "sha256:e87cbc002b6f440482b3519e36e1313eb5443e9e9e73d6a52d43bd2004fcfd8e", size = 5920591, upload-time = "2026-02-06T09:56:20.758Z" }, - { url = "https://files.pythonhosted.org/packages/5d/81/1f3b65bd30c334167bfa8b0d23300a44e2725ce39bba5b76a2460d85f745/grpcio-1.78.0-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:c41bc64626db62e72afec66b0c8a0da76491510015417c127bfc53b2fe6d7f7f", size = 11813685, upload-time = "2026-02-06T09:56:24.315Z" }, - { url = "https://files.pythonhosted.org/packages/0e/1c/bbe2f8216a5bd3036119c544d63c2e592bdf4a8ec6e4a1867592f4586b26/grpcio-1.78.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8dfffba826efcf366b1e3ccc37e67afe676f290e13a3b48d31a46739f80a8724", size = 6487803, upload-time = "2026-02-06T09:56:27.367Z" }, - { url = "https://files.pythonhosted.org/packages/16/5c/a6b2419723ea7ddce6308259a55e8e7593d88464ce8db9f4aa857aba96fa/grpcio-1.78.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:74be1268d1439eaaf552c698cdb11cd594f0c49295ae6bb72c34ee31abbe611b", size = 7173206, upload-time = "2026-02-06T09:56:29.876Z" }, - { url = "https://files.pythonhosted.org/packages/df/1e/b8801345629a415ea7e26c83d75eb5dbe91b07ffe5210cc517348a8d4218/grpcio-1.78.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:be63c88b32e6c0f1429f1398ca5c09bc64b0d80950c8bb7807d7d7fb36fb84c7", size = 6693826, upload-time = "2026-02-06T09:56:32.305Z" }, - { url = "https://files.pythonhosted.org/packages/34/84/0de28eac0377742679a510784f049738a80424b17287739fc47d63c2439e/grpcio-1.78.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:3c586ac70e855c721bda8f548d38c3ca66ac791dc49b66a8281a1f99db85e452", size = 7277897, upload-time = "2026-02-06T09:56:34.915Z" }, - { url = "https://files.pythonhosted.org/packages/ca/9c/ad8685cfe20559a9edb66f735afdcb2b7d3de69b13666fdfc542e1916ebd/grpcio-1.78.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:35eb275bf1751d2ffbd8f57cdbc46058e857cf3971041521b78b7db94bdaf127", size = 8252404, upload-time = "2026-02-06T09:56:37.553Z" }, - { url = "https://files.pythonhosted.org/packages/3c/05/33a7a4985586f27e1de4803887c417ec7ced145ebd069bc38a9607059e2b/grpcio-1.78.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:207db540302c884b8848036b80db352a832b99dfdf41db1eb554c2c2c7800f65", size = 7696837, upload-time = "2026-02-06T09:56:40.173Z" }, - { url = "https://files.pythonhosted.org/packages/73/77/7382241caf88729b106e49e7d18e3116216c778e6a7e833826eb96de22f7/grpcio-1.78.0-cp314-cp314-win32.whl", hash = "sha256:57bab6deef2f4f1ca76cc04565df38dc5713ae6c17de690721bdf30cb1e0545c", size = 4142439, upload-time = "2026-02-06T09:56:43.258Z" }, - { url = "https://files.pythonhosted.org/packages/48/b2/b096ccce418882fbfda4f7496f9357aaa9a5af1896a9a7f60d9f2b275a06/grpcio-1.78.0-cp314-cp314-win_amd64.whl", hash = "sha256:dce09d6116df20a96acfdbf85e4866258c3758180e8c49845d6ba8248b6d0bbb", size = 4929852, upload-time = "2026-02-06T09:56:45.885Z" }, -] - -[[package]] -name = "grpcio-tools" -version = "1.78.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "grpcio" }, - { name = "protobuf" }, - { name = "setuptools" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8b/d1/cbefe328653f746fd319c4377836a25ba64226e41c6a1d7d5cdbc87a459f/grpcio_tools-1.78.0.tar.gz", hash = "sha256:4b0dd86560274316e155d925158276f8564508193088bc43e20d3f5dff956b2b", size = 5393026, upload-time = "2026-02-06T09:59:59.53Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/75/78/280184d19242ed6762bf453c47a70b869b3c5c72a24dc5bf2bf43909faa3/grpcio_tools-1.78.0-cp311-cp311-linux_armv7l.whl", hash = "sha256:6a8b8b7b49f319d29dbcf507f62984fa382d1d10437d75c3f26db5f09c4ac0af", size = 2545904, upload-time = "2026-02-06T09:57:52.769Z" }, - { url = "https://files.pythonhosted.org/packages/5b/51/3c46dea5113f68fe879961cae62d34bb7a3c308a774301b45d614952ee98/grpcio_tools-1.78.0-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:d62cf3b68372b0c6d722a6165db41b976869811abeabc19c8522182978d8db10", size = 5709078, upload-time = "2026-02-06T09:57:56.389Z" }, - { url = "https://files.pythonhosted.org/packages/e0/2c/dc1ae9ec53182c96d56dfcbf3bcd3e55a8952ad508b188c75bf5fc8993d4/grpcio_tools-1.78.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fa9056742efeaf89d5fe14198af71e5cbc4fbf155d547b89507e19d6025906c6", size = 2591744, upload-time = "2026-02-06T09:57:58.341Z" }, - { url = "https://files.pythonhosted.org/packages/04/63/9b53fc9a9151dd24386785171a4191ee7cb5afb4d983b6a6a87408f41b28/grpcio_tools-1.78.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:e3191af125dcb705aa6bc3856ba81ba99b94121c1b6ebee152e66ea084672831", size = 2905113, upload-time = "2026-02-06T09:58:00.38Z" }, - { url = "https://files.pythonhosted.org/packages/96/b2/0ad8d789f3a2a00893131c140865605fa91671a6e6fcf9da659e1fabba10/grpcio_tools-1.78.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:283239ddbb67ae83fac111c61b25d8527a1dbd355b377cbc8383b79f1329944d", size = 2656436, upload-time = "2026-02-06T09:58:03.038Z" }, - { url = "https://files.pythonhosted.org/packages/09/4d/580f47ce2fc61b093ade747b378595f51b4f59972dd39949f7444b464a03/grpcio_tools-1.78.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ac977508c0db15301ef36d6c79769ec1a6cc4e3bc75735afca7fe7e360cead3a", size = 3106128, upload-time = "2026-02-06T09:58:05.064Z" }, - { url = "https://files.pythonhosted.org/packages/c9/29/d83b2d89f8d10e438bad36b1eb29356510fb97e81e6a608b22ae1890e8e6/grpcio_tools-1.78.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:4ff605e25652a0bd13aa8a73a09bc48669c68170902f5d2bf1468a57d5e78771", size = 3654953, upload-time = "2026-02-06T09:58:07.15Z" }, - { url = "https://files.pythonhosted.org/packages/08/71/917ce85633311e54fefd7e6eb1224fb780ef317a4d092766f5630c3fc419/grpcio_tools-1.78.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0197d7b561c79be78ab93d0fe2836c8def470683df594bae3ac89dd8e5c821b2", size = 3322630, upload-time = "2026-02-06T09:58:10.305Z" }, - { url = "https://files.pythonhosted.org/packages/b2/55/3fbf6b26ab46fc79e1e6f7f4e0993cf540263dad639290299fad374a0829/grpcio_tools-1.78.0-cp311-cp311-win32.whl", hash = "sha256:28f71f591f7f39555863ced84fcc209cbf4454e85ef957232f43271ee99af577", size = 993804, upload-time = "2026-02-06T09:58:13.698Z" }, - { url = "https://files.pythonhosted.org/packages/73/86/4affe006d9e1e9e1c6653d6aafe2f8b9188acb2b563cd8ed3a2c7c0e8aec/grpcio_tools-1.78.0-cp311-cp311-win_amd64.whl", hash = "sha256:5a6de495dabf86a3b40b9a7492994e1232b077af9d63080811838b781abbe4e8", size = 1158566, upload-time = "2026-02-06T09:58:15.721Z" }, - { url = "https://files.pythonhosted.org/packages/0c/ae/5b1fa5dd8d560a6925aa52de0de8731d319f121c276e35b9b2af7cc220a2/grpcio_tools-1.78.0-cp312-cp312-linux_armv7l.whl", hash = "sha256:9eb122da57d4cad7d339fc75483116f0113af99e8d2c67f3ef9cae7501d806e4", size = 2546823, upload-time = "2026-02-06T09:58:17.944Z" }, - { url = "https://files.pythonhosted.org/packages/a7/ed/d33ccf7fa701512efea7e7e23333b748848a123e9d3bbafde4e126784546/grpcio_tools-1.78.0-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:d0c501b8249940b886420e6935045c44cb818fa6f265f4c2b97d5cff9cb5e796", size = 5706776, upload-time = "2026-02-06T09:58:20.944Z" }, - { url = "https://files.pythonhosted.org/packages/c6/69/4285583f40b37af28277fc6b867d636e3b10e1b6a7ebd29391a856e1279b/grpcio_tools-1.78.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:77e5aa2d2a7268d55b1b113f958264681ef1994c970f69d48db7d4683d040f57", size = 2593972, upload-time = "2026-02-06T09:58:23.29Z" }, - { url = "https://files.pythonhosted.org/packages/d7/eb/ecc1885bd6b3147f0a1b7dff5565cab72f01c8f8aa458f682a1c77a9fb08/grpcio_tools-1.78.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:8e3c0b0e6ba5275322ba29a97bf890565a55f129f99a21b121145e9e93a22525", size = 2905531, upload-time = "2026-02-06T09:58:25.406Z" }, - { url = "https://files.pythonhosted.org/packages/ae/a9/511d0040ced66960ca10ba0f082d6b2d2ee6dd61837b1709636fdd8e23b4/grpcio_tools-1.78.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:975d4cb48694e20ebd78e1643e5f1cd94cdb6a3d38e677a8e84ae43665aa4790", size = 2656909, upload-time = "2026-02-06T09:58:28.022Z" }, - { url = "https://files.pythonhosted.org/packages/06/a3/3d2c707e7dee8df842c96fbb24feb2747e506e39f4a81b661def7fed107c/grpcio_tools-1.78.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:553ff18c5d52807dedecf25045ae70bad7a3dbba0b27a9a3cdd9bcf0a1b7baec", size = 3109778, upload-time = "2026-02-06T09:58:30.091Z" }, - { url = "https://files.pythonhosted.org/packages/1f/4b/646811ba241bf05da1f0dc6f25764f1c837f78f75b4485a4210c84b79eae/grpcio_tools-1.78.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:8c7f5e4af5a84d2e96c862b1a65e958a538237e268d5f8203a3a784340975b51", size = 3658763, upload-time = "2026-02-06T09:58:32.875Z" }, - { url = "https://files.pythonhosted.org/packages/45/de/0a5ef3b3e79d1011375f5580dfee3a9c1ccb96c5f5d1c74c8cee777a2483/grpcio_tools-1.78.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:96183e2b44afc3f9a761e9d0f985c3b44e03e8bb98e626241a6cbfb3b6f7e88f", size = 3325116, upload-time = "2026-02-06T09:58:34.894Z" }, - { url = "https://files.pythonhosted.org/packages/95/d2/6391b241ad571bc3e71d63f957c0b1860f0c47932d03c7f300028880f9b8/grpcio_tools-1.78.0-cp312-cp312-win32.whl", hash = "sha256:2250e8424c565a88573f7dc10659a0b92802e68c2a1d57e41872c9b88ccea7a6", size = 993493, upload-time = "2026-02-06T09:58:37.242Z" }, - { url = "https://files.pythonhosted.org/packages/7c/8f/7d0d3a39ecad76ccc136be28274daa660569b244fa7d7d0bbb24d68e5ece/grpcio_tools-1.78.0-cp312-cp312-win_amd64.whl", hash = "sha256:217d1fa29de14d9c567d616ead7cb0fef33cde36010edff5a9390b00d52e5094", size = 1158423, upload-time = "2026-02-06T09:58:40.072Z" }, - { url = "https://files.pythonhosted.org/packages/53/ce/17311fb77530420e2f441e916b347515133e83d21cd6cc77be04ce093d5b/grpcio_tools-1.78.0-cp313-cp313-linux_armv7l.whl", hash = "sha256:2d6de1cc23bdc1baafc23e201b1e48c617b8c1418b4d8e34cebf72141676e5fb", size = 2546284, upload-time = "2026-02-06T09:58:43.073Z" }, - { url = "https://files.pythonhosted.org/packages/1d/d3/79e101483115f0e78223397daef71751b75eba7e92a32060c10aae11ca64/grpcio_tools-1.78.0-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:2afeaad88040894c76656202ff832cb151bceb05c0e6907e539d129188b1e456", size = 5705653, upload-time = "2026-02-06T09:58:45.533Z" }, - { url = "https://files.pythonhosted.org/packages/8b/a7/52fa3ccb39ceeee6adc010056eadfbca8198651c113e418dafebbdf2b306/grpcio_tools-1.78.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:33cc593735c93c03d63efe7a8ba25f3c66f16c52f0651910712490244facad72", size = 2592788, upload-time = "2026-02-06T09:58:48.918Z" }, - { url = "https://files.pythonhosted.org/packages/68/08/682ff6bb548225513d73dc9403742d8975439d7469c673bc534b9bbc83a7/grpcio_tools-1.78.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:2921d7989c4d83b71f03130ab415fa4d66e6693b8b8a1fcbb7a1c67cff19b812", size = 2905157, upload-time = "2026-02-06T09:58:51.478Z" }, - { url = "https://files.pythonhosted.org/packages/b2/66/264f3836a96423b7018e5ada79d62576a6401f6da4e1f4975b18b2be1265/grpcio_tools-1.78.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e6a0df438e82c804c7b95e3f311c97c2f876dcc36376488d5b736b7bcf5a9b45", size = 2656166, upload-time = "2026-02-06T09:58:54.117Z" }, - { url = "https://files.pythonhosted.org/packages/f3/6b/f108276611522e03e98386b668cc7e575eff6952f2db9caa15b2a3b3e883/grpcio_tools-1.78.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e9c6070a9500798225191ef25d0055a15d2c01c9c8f2ee7b681fffa99c98c822", size = 3109110, upload-time = "2026-02-06T09:58:56.891Z" }, - { url = "https://files.pythonhosted.org/packages/6f/c7/cf048dbcd64b3396b3c860a2ffbcc67a8f8c87e736aaa74c2e505a7eee4c/grpcio_tools-1.78.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:394e8b57d85370a62e5b0a4d64c96fcf7568345c345d8590c821814d227ecf1d", size = 3657863, upload-time = "2026-02-06T09:58:59.176Z" }, - { url = "https://files.pythonhosted.org/packages/b6/37/e2736912c8fda57e2e57a66ea5e0bc8eb9a5fb7ded00e866ad22d50afb08/grpcio_tools-1.78.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a3ef700293ab375e111a2909d87434ed0a0b086adf0ce67a8d9cf12ea7765e63", size = 3324748, upload-time = "2026-02-06T09:59:01.242Z" }, - { url = "https://files.pythonhosted.org/packages/1c/5d/726abc75bb5bfc2841e88ea05896e42f51ca7c30cb56da5c5b63058b3867/grpcio_tools-1.78.0-cp313-cp313-win32.whl", hash = "sha256:6993b960fec43a8d840ee5dc20247ef206c1a19587ea49fe5e6cc3d2a09c1585", size = 993074, upload-time = "2026-02-06T09:59:03.085Z" }, - { url = "https://files.pythonhosted.org/packages/c5/68/91b400bb360faf9b177ffb5540ec1c4d06ca923691ddf0f79e2c9683f4da/grpcio_tools-1.78.0-cp313-cp313-win_amd64.whl", hash = "sha256:275ce3c2978842a8cf9dd88dce954e836e590cf7029649ad5d1145b779039ed5", size = 1158185, upload-time = "2026-02-06T09:59:05.036Z" }, - { url = "https://files.pythonhosted.org/packages/cf/5e/278f3831c8d56bae02e3acc570465648eccf0a6bbedcb1733789ac966803/grpcio_tools-1.78.0-cp314-cp314-linux_armv7l.whl", hash = "sha256:8b080d0d072e6032708a3a91731b808074d7ab02ca8fb9847b6a011fdce64cd9", size = 2546270, upload-time = "2026-02-06T09:59:07.426Z" }, - { url = "https://files.pythonhosted.org/packages/a3/d9/68582f2952b914b60dddc18a2e3f9c6f09af9372b6f6120d6cf3ec7f8b4e/grpcio_tools-1.78.0-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8c0ad8f8f133145cd7008b49cb611a5c6a9d89ab276c28afa17050516e801f79", size = 5705731, upload-time = "2026-02-06T09:59:09.856Z" }, - { url = "https://files.pythonhosted.org/packages/70/68/feb0f9a48818ee1df1e8b644069379a1e6ef5447b9b347c24e96fd258e5d/grpcio_tools-1.78.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2f8ea092a7de74c6359335d36f0674d939a3c7e1a550f4c2c9e80e0226de8fe4", size = 2593896, upload-time = "2026-02-06T09:59:12.23Z" }, - { url = "https://files.pythonhosted.org/packages/1f/08/a430d8d06e1b8d33f3e48d3f0cc28236723af2f35e37bd5c8db05df6c3aa/grpcio_tools-1.78.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:da422985e0cac822b41822f43429c19ecb27c81ffe3126d0b74e77edec452608", size = 2905298, upload-time = "2026-02-06T09:59:14.458Z" }, - { url = "https://files.pythonhosted.org/packages/71/0a/348c36a3eae101ca0c090c9c3bc96f2179adf59ee0c9262d11cdc7bfe7db/grpcio_tools-1.78.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4fab1faa3fbcb246263e68da7a8177d73772283f9db063fb8008517480888d26", size = 2656186, upload-time = "2026-02-06T09:59:16.949Z" }, - { url = "https://files.pythonhosted.org/packages/1d/3f/18219f331536fad4af6207ade04142292faa77b5cb4f4463787988963df8/grpcio_tools-1.78.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:dd9c094f73f734becae3f20f27d4944d3cd8fb68db7338ee6c58e62fc5c3d99f", size = 3109859, upload-time = "2026-02-06T09:59:19.202Z" }, - { url = "https://files.pythonhosted.org/packages/5b/d9/341ea20a44c8e5a3a18acc820b65014c2e3ea5b4f32a53d14864bcd236bc/grpcio_tools-1.78.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:2ed51ce6b833068f6c580b73193fc2ec16468e6bc18354bc2f83a58721195a58", size = 3657915, upload-time = "2026-02-06T09:59:21.839Z" }, - { url = "https://files.pythonhosted.org/packages/fb/f4/5978b0f91611a64371424c109dd0027b247e5b39260abad2eaee66b6aa37/grpcio_tools-1.78.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:05803a5cdafe77c8bdf36aa660ad7a6a1d9e49bc59ce45c1bade2a4698826599", size = 3324724, upload-time = "2026-02-06T09:59:24.402Z" }, - { url = "https://files.pythonhosted.org/packages/b2/80/96a324dba99cfbd20e291baf0b0ae719dbb62b76178c5ce6c788e7331cb1/grpcio_tools-1.78.0-cp314-cp314-win32.whl", hash = "sha256:f7c722e9ce6f11149ac5bddd5056e70aaccfd8168e74e9d34d8b8b588c3f5c7c", size = 1015505, upload-time = "2026-02-06T09:59:26.3Z" }, - { url = "https://files.pythonhosted.org/packages/3b/d1/909e6a05bfd44d46327dc4b8a78beb2bae4fb245ffab2772e350081aaf7e/grpcio_tools-1.78.0-cp314-cp314-win_amd64.whl", hash = "sha256:7d58ade518b546120ec8f0a8e006fc8076ae5df151250ebd7e82e9b5e152c229", size = 1190196, upload-time = "2026-02-06T09:59:28.359Z" }, -] - -[[package]] -name = "h11" -version = "0.16.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, -] - -[[package]] -name = "httpcore" -version = "1.0.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "h11" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, -] - -[[package]] -name = "httpx" -version = "0.28.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "certifi" }, - { name = "httpcore" }, - { name = "idna" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, -] - -[[package]] -name = "idna" -version = "3.17" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b9/28/99c51f664567218d824af024c0251650fb27e4ca066df188dab0769c5b91/idna-3.17.tar.gz", hash = "sha256:5eb0cb53bc467c12eadcf6de83163ad8527cec9416f44b9b61b19caedad2b87f", size = 196048, upload-time = "2026-05-28T14:32:38.55Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/de/a7/f76514cc40ad6234098ecdebda08732d75964776c51a42845b7da10649e2/idna-3.17-py3-none-any.whl", hash = "sha256:466e48829084efe2548012b855df21540b96f2e20e51bd124c851536556a592c", size = 65316, upload-time = "2026-05-28T14:32:37.035Z" }, -] - [[package]] name = "iniconfig" version = "2.3.0" @@ -315,69 +21,29 @@ wheels = [ ] [[package]] -name = "mypy-protobuf" -version = "5.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "protobuf" }, - { name = "types-protobuf" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/87/07/7ffb897eee5c01e816e037f51a6720bf1a0a8c17cca1a2382ae554f43044/mypy_protobuf-5.1.0.tar.gz", hash = "sha256:8493758852a9cdc075a11dbe96c6e37ea2feba5fd5f33ef7442b9a275322a94c", size = 37529, upload-time = "2026-04-28T15:56:40.356Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e8/ec/5ffcf8f5f53757e01afdece10c664e694ac60d2f17c2036811b85b842a5b/mypy_protobuf-5.1.0-py3-none-any.whl", hash = "sha256:d7031f563f806b8bcd448a3e86768bf0994c0af5b0017b344a4fbbba4191f43c", size = 26313, upload-time = "2026-04-28T15:56:39.096Z" }, -] - -[[package]] -name = "openshell" -source = { editable = "." } -dependencies = [ - { name = "cloudpickle" }, - { name = "googleapis-common-protos" }, - { name = "grpcio" }, - { name = "httpx" }, - { name = "protobuf" }, -] +name = "openshell-tooling" +version = "0.0.0" +source = { virtual = "." } [package.dev-dependencies] dev = [ - { name = "grpcio-tools" }, - { name = "mypy-protobuf" }, { name = "pyelftools" }, { name = "pytest" }, - { name = "pytest-asyncio" }, - { name = "pytest-cov" }, - { name = "pytest-xdist" }, { name = "pyyaml" }, { name = "ruff" }, { name = "ty" }, - { name = "types-grpcio" }, - { name = "types-protobuf" }, { name = "types-pyyaml" }, ] [package.metadata] -requires-dist = [ - { name = "cloudpickle", specifier = ">=3.0" }, - { name = "googleapis-common-protos", specifier = ">=1.63" }, - { name = "grpcio", specifier = ">=1.60" }, - { name = "httpx", specifier = ">=0.27" }, - { name = "protobuf", specifier = ">=4.25" }, -] [package.metadata.requires-dev] dev = [ - { name = "grpcio-tools", specifier = ">=1.60" }, - { name = "mypy-protobuf", specifier = ">=5.1" }, { name = "pyelftools", specifier = ">=0.30" }, { name = "pytest", specifier = ">=9.0.3" }, - { name = "pytest-asyncio", specifier = ">=0.23" }, - { name = "pytest-cov", specifier = ">=4.0" }, - { name = "pytest-xdist", specifier = ">=3.0" }, { name = "pyyaml", specifier = "==6.0.2" }, { name = "ruff", specifier = ">=0.4" }, { name = "ty", specifier = ">=0.0.94" }, - { name = "types-grpcio", specifier = ">=1.0.0.20251009" }, - { name = "types-protobuf", specifier = ">=6.32,<7" }, { name = "types-pyyaml", specifier = ">=6.0.12.20260518" }, ] @@ -399,21 +65,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] -[[package]] -name = "protobuf" -version = "6.33.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ba/25/7c72c307aafc96fa87062aa6291d9f7c94836e43214d43722e86037aac02/protobuf-6.33.5.tar.gz", hash = "sha256:6ddcac2a081f8b7b9642c09406bc6a4290128fce5f471cddd165960bb9119e5c", size = 444465, upload-time = "2026-01-29T21:51:33.494Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b1/79/af92d0a8369732b027e6d6084251dd8e782c685c72da161bd4a2e00fbabb/protobuf-6.33.5-cp310-abi3-win32.whl", hash = "sha256:d71b040839446bac0f4d162e758bea99c8251161dae9d0983a3b88dee345153b", size = 425769, upload-time = "2026-01-29T21:51:21.751Z" }, - { url = "https://files.pythonhosted.org/packages/55/75/bb9bc917d10e9ee13dee8607eb9ab963b7cf8be607c46e7862c748aa2af7/protobuf-6.33.5-cp310-abi3-win_amd64.whl", hash = "sha256:3093804752167bcab3998bec9f1048baae6e29505adaf1afd14a37bddede533c", size = 437118, upload-time = "2026-01-29T21:51:24.022Z" }, - { url = "https://files.pythonhosted.org/packages/a2/6b/e48dfc1191bc5b52950246275bf4089773e91cb5ba3592621723cdddca62/protobuf-6.33.5-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:a5cb85982d95d906df1e2210e58f8e4f1e3cdc088e52c921a041f9c9a0386de5", size = 427766, upload-time = "2026-01-29T21:51:25.413Z" }, - { url = "https://files.pythonhosted.org/packages/4e/b1/c79468184310de09d75095ed1314b839eb2f72df71097db9d1404a1b2717/protobuf-6.33.5-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:9b71e0281f36f179d00cbcb119cb19dec4d14a81393e5ea220f64b286173e190", size = 324638, upload-time = "2026-01-29T21:51:26.423Z" }, - { url = "https://files.pythonhosted.org/packages/c5/f5/65d838092fd01c44d16037953fd4c2cc851e783de9b8f02b27ec4ffd906f/protobuf-6.33.5-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:8afa18e1d6d20af15b417e728e9f60f3aa108ee76f23c3b2c07a2c3b546d3afd", size = 339411, upload-time = "2026-01-29T21:51:27.446Z" }, - { url = "https://files.pythonhosted.org/packages/9b/53/a9443aa3ca9ba8724fdfa02dd1887c1bcd8e89556b715cfbacca6b63dbec/protobuf-6.33.5-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:cbf16ba3350fb7b889fca858fb215967792dc125b35c7976ca4818bee3521cf0", size = 323465, upload-time = "2026-01-29T21:51:28.925Z" }, - { url = "https://files.pythonhosted.org/packages/57/bf/2086963c69bdac3d7cff1cc7ff79b8ce5ea0bec6797a017e1be338a46248/protobuf-6.33.5-py3-none-any.whl", hash = "sha256:69915a973dd0f60f31a08b8318b73eab2bd6a392c79184b3612226b0a3f8ec02", size = 170687, upload-time = "2026-01-29T21:51:32.557Z" }, -] - [[package]] name = "pyelftools" version = "0.32" @@ -448,46 +99,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" }, ] -[[package]] -name = "pytest-asyncio" -version = "1.3.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/90/2c/8af215c0f776415f3590cac4f9086ccefd6fd463befeae41cd4d3f193e5a/pytest_asyncio-1.3.0.tar.gz", hash = "sha256:d7f52f36d231b80ee124cd216ffb19369aa168fc10095013c6b014a34d3ee9e5", size = 50087, upload-time = "2025-11-10T16:07:47.256Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/35/f8b19922b6a25bc0880171a2f1a003eaeb93657475193ab516fd87cac9da/pytest_asyncio-1.3.0-py3-none-any.whl", hash = "sha256:611e26147c7f77640e6d0a92a38ed17c3e9848063698d5c93d5aa7aa11cebff5", size = 15075, upload-time = "2025-11-10T16:07:45.537Z" }, -] - -[[package]] -name = "pytest-cov" -version = "7.0.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "coverage", extra = ["toml"] }, - { name = "pluggy" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5e/f7/c933acc76f5208b3b00089573cf6a2bc26dc80a8aece8f52bb7d6b1855ca/pytest_cov-7.0.0.tar.gz", hash = "sha256:33c97eda2e049a0c5298e91f519302a1334c26ac65c1a483d6206fd458361af1", size = 54328, upload-time = "2025-09-09T10:57:02.113Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ee/49/1377b49de7d0c1ce41292161ea0f721913fa8722c19fb9c1e3aa0367eecb/pytest_cov-7.0.0-py3-none-any.whl", hash = "sha256:3b8e9558b16cc1479da72058bdecf8073661c7f57f7d3c5f22a1c23507f2d861", size = 22424, upload-time = "2025-09-09T10:57:00.695Z" }, -] - -[[package]] -name = "pytest-xdist" -version = "3.8.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "execnet" }, - { name = "pytest" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" }, -] - [[package]] name = "pyyaml" version = "6.0.2" @@ -549,69 +160,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9e/6a/40fee331a52339926a92e17ae748827270b288a35ef4a15c9c8f2ec54715/ruff-0.14.14-py3-none-win_arm64.whl", hash = "sha256:56e6981a98b13a32236a72a8da421d7839221fa308b223b9283312312e5ac76c", size = 10920448, upload-time = "2026-01-22T22:30:15.417Z" }, ] -[[package]] -name = "setuptools" -version = "84.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/73/eb/7e5f628ee2eb168fecbf8026de7856b2543d6d609cc85f086b9a91ac93d6/setuptools-84.1.0.tar.gz", hash = "sha256:23657205b63d4d31395ab917815247f694aafad28cd21316bf5fd45a51048ea0", size = 1171783, upload-time = "2026-10-19T20:11:43.489Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/18/02/b4bbb90f8f29e334898ff45c6d9b1fffaa6f378017052b3023a06262b5f7/setuptools-84.1.0-py3-none-any.whl", hash = "sha256:5231689c6ac8156cd155cfb98c3fd6fb252c3e7e9bd3d78b64d3c55f132624c9", size = 819380, upload-time = "2026-10-19T20:11:41.684Z" }, -] - -[[package]] -name = "tomli" -version = "2.4.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/22/de/48c59722572767841493b26183a0d1cc411d54fd759c5607c4590b6563a6/tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f", size = 17543, upload-time = "2026-03-25T20:22:03.828Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f4/11/db3d5885d8528263d8adc260bb2d28ebf1270b96e98f0e0268d32b8d9900/tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30", size = 154704, upload-time = "2026-03-25T20:21:10.473Z" }, - { url = "https://files.pythonhosted.org/packages/6d/f7/675db52c7e46064a9aa928885a9b20f4124ecb9bc2e1ce74c9106648d202/tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a", size = 149454, upload-time = "2026-03-25T20:21:12.036Z" }, - { url = "https://files.pythonhosted.org/packages/61/71/81c50943cf953efa35bce7646caab3cf457a7d8c030b27cfb40d7235f9ee/tomli-2.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076", size = 237561, upload-time = "2026-03-25T20:21:13.098Z" }, - { url = "https://files.pythonhosted.org/packages/48/c1/f41d9cb618acccca7df82aaf682f9b49013c9397212cb9f53219e3abac37/tomli-2.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9", size = 243824, upload-time = "2026-03-25T20:21:14.569Z" }, - { url = "https://files.pythonhosted.org/packages/22/e4/5a816ecdd1f8ca51fb756ef684b90f2780afc52fc67f987e3c61d800a46d/tomli-2.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c", size = 242227, upload-time = "2026-03-25T20:21:15.712Z" }, - { url = "https://files.pythonhosted.org/packages/6b/49/2b2a0ef529aa6eec245d25f0c703e020a73955ad7edf73e7f54ddc608aa5/tomli-2.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc", size = 247859, upload-time = "2026-03-25T20:21:17.001Z" }, - { url = "https://files.pythonhosted.org/packages/83/bd/6c1a630eaca337e1e78c5903104f831bda934c426f9231429396ce3c3467/tomli-2.4.1-cp311-cp311-win32.whl", hash = "sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049", size = 97204, upload-time = "2026-03-25T20:21:18.079Z" }, - { url = "https://files.pythonhosted.org/packages/42/59/71461df1a885647e10b6bb7802d0b8e66480c61f3f43079e0dcd315b3954/tomli-2.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e", size = 108084, upload-time = "2026-03-25T20:21:18.978Z" }, - { url = "https://files.pythonhosted.org/packages/b8/83/dceca96142499c069475b790e7913b1044c1a4337e700751f48ed723f883/tomli-2.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece", size = 95285, upload-time = "2026-03-25T20:21:20.309Z" }, - { url = "https://files.pythonhosted.org/packages/c1/ba/42f134a3fe2b370f555f44b1d72feebb94debcab01676bf918d0cb70e9aa/tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a", size = 155924, upload-time = "2026-03-25T20:21:21.626Z" }, - { url = "https://files.pythonhosted.org/packages/dc/c7/62d7a17c26487ade21c5422b646110f2162f1fcc95980ef7f63e73c68f14/tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085", size = 150018, upload-time = "2026-03-25T20:21:23.002Z" }, - { url = "https://files.pythonhosted.org/packages/5c/05/79d13d7c15f13bdef410bdd49a6485b1c37d28968314eabee452c22a7fda/tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9", size = 244948, upload-time = "2026-03-25T20:21:24.04Z" }, - { url = "https://files.pythonhosted.org/packages/10/90/d62ce007a1c80d0b2c93e02cab211224756240884751b94ca72df8a875ca/tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5", size = 253341, upload-time = "2026-03-25T20:21:25.177Z" }, - { url = "https://files.pythonhosted.org/packages/1a/7e/caf6496d60152ad4ed09282c1885cca4eea150bfd007da84aea07bcc0a3e/tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585", size = 248159, upload-time = "2026-03-25T20:21:26.364Z" }, - { url = "https://files.pythonhosted.org/packages/99/e7/c6f69c3120de34bbd882c6fba7975f3d7a746e9218e56ab46a1bc4b42552/tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1", size = 253290, upload-time = "2026-03-25T20:21:27.46Z" }, - { url = "https://files.pythonhosted.org/packages/d6/2f/4a3c322f22c5c66c4b836ec58211641a4067364f5dcdd7b974b4c5da300c/tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917", size = 98141, upload-time = "2026-03-25T20:21:28.492Z" }, - { url = "https://files.pythonhosted.org/packages/24/22/4daacd05391b92c55759d55eaee21e1dfaea86ce5c571f10083360adf534/tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9", size = 108847, upload-time = "2026-03-25T20:21:29.386Z" }, - { url = "https://files.pythonhosted.org/packages/68/fd/70e768887666ddd9e9f5d85129e84910f2db2796f9096aa02b721a53098d/tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257", size = 95088, upload-time = "2026-03-25T20:21:30.677Z" }, - { url = "https://files.pythonhosted.org/packages/07/06/b823a7e818c756d9a7123ba2cda7d07bc2dd32835648d1a7b7b7a05d848d/tomli-2.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54", size = 155866, upload-time = "2026-03-25T20:21:31.65Z" }, - { url = "https://files.pythonhosted.org/packages/14/6f/12645cf7f08e1a20c7eb8c297c6f11d31c1b50f316a7e7e1e1de6e2e7b7e/tomli-2.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a", size = 149887, upload-time = "2026-03-25T20:21:33.028Z" }, - { url = "https://files.pythonhosted.org/packages/5c/e0/90637574e5e7212c09099c67ad349b04ec4d6020324539297b634a0192b0/tomli-2.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897", size = 243704, upload-time = "2026-03-25T20:21:34.51Z" }, - { url = "https://files.pythonhosted.org/packages/10/8f/d3ddb16c5a4befdf31a23307f72828686ab2096f068eaf56631e136c1fdd/tomli-2.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f", size = 251628, upload-time = "2026-03-25T20:21:36.012Z" }, - { url = "https://files.pythonhosted.org/packages/e3/f1/dbeeb9116715abee2485bf0a12d07a8f31af94d71608c171c45f64c0469d/tomli-2.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d", size = 247180, upload-time = "2026-03-25T20:21:37.136Z" }, - { url = "https://files.pythonhosted.org/packages/d3/74/16336ffd19ed4da28a70959f92f506233bd7cfc2332b20bdb01591e8b1d1/tomli-2.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5", size = 251674, upload-time = "2026-03-25T20:21:38.298Z" }, - { url = "https://files.pythonhosted.org/packages/16/f9/229fa3434c590ddf6c0aa9af64d3af4b752540686cace29e6281e3458469/tomli-2.4.1-cp313-cp313-win32.whl", hash = "sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd", size = 97976, upload-time = "2026-03-25T20:21:39.316Z" }, - { url = "https://files.pythonhosted.org/packages/6a/1e/71dfd96bcc1c775420cb8befe7a9d35f2e5b1309798f009dca17b7708c1e/tomli-2.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36", size = 108755, upload-time = "2026-03-25T20:21:40.248Z" }, - { url = "https://files.pythonhosted.org/packages/83/7a/d34f422a021d62420b78f5c538e5b102f62bea616d1d75a13f0a88acb04a/tomli-2.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd", size = 95265, upload-time = "2026-03-25T20:21:41.219Z" }, - { url = "https://files.pythonhosted.org/packages/3c/fb/9a5c8d27dbab540869f7c1f8eb0abb3244189ce780ba9cd73f3770662072/tomli-2.4.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf", size = 155726, upload-time = "2026-03-25T20:21:42.23Z" }, - { url = "https://files.pythonhosted.org/packages/62/05/d2f816630cc771ad836af54f5001f47a6f611d2d39535364f148b6a92d6b/tomli-2.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac", size = 149859, upload-time = "2026-03-25T20:21:43.386Z" }, - { url = "https://files.pythonhosted.org/packages/ce/48/66341bdb858ad9bd0ceab5a86f90eddab127cf8b046418009f2125630ecb/tomli-2.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662", size = 244713, upload-time = "2026-03-25T20:21:44.474Z" }, - { url = "https://files.pythonhosted.org/packages/df/6d/c5fad00d82b3c7a3ab6189bd4b10e60466f22cfe8a08a9394185c8a8111c/tomli-2.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853", size = 252084, upload-time = "2026-03-25T20:21:45.62Z" }, - { url = "https://files.pythonhosted.org/packages/00/71/3a69e86f3eafe8c7a59d008d245888051005bd657760e96d5fbfb0b740c2/tomli-2.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15", size = 247973, upload-time = "2026-03-25T20:21:46.937Z" }, - { url = "https://files.pythonhosted.org/packages/67/50/361e986652847fec4bd5e4a0208752fbe64689c603c7ae5ea7cb16b1c0ca/tomli-2.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba", size = 256223, upload-time = "2026-03-25T20:21:48.467Z" }, - { url = "https://files.pythonhosted.org/packages/8c/9a/b4173689a9203472e5467217e0154b00e260621caa227b6fa01feab16998/tomli-2.4.1-cp314-cp314-win32.whl", hash = "sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6", size = 98973, upload-time = "2026-03-25T20:21:49.526Z" }, - { url = "https://files.pythonhosted.org/packages/14/58/640ac93bf230cd27d002462c9af0d837779f8773bc03dee06b5835208214/tomli-2.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7", size = 109082, upload-time = "2026-03-25T20:21:50.506Z" }, - { url = "https://files.pythonhosted.org/packages/d5/2f/702d5e05b227401c1068f0d386d79a589bb12bf64c3d2c72ce0631e3bc49/tomli-2.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232", size = 96490, upload-time = "2026-03-25T20:21:51.474Z" }, - { url = "https://files.pythonhosted.org/packages/45/4b/b877b05c8ba62927d9865dd980e34a755de541eb65fffba52b4cc495d4d2/tomli-2.4.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4", size = 164263, upload-time = "2026-03-25T20:21:52.543Z" }, - { url = "https://files.pythonhosted.org/packages/24/79/6ab420d37a270b89f7195dec5448f79400d9e9c1826df982f3f8e97b24fd/tomli-2.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c", size = 160736, upload-time = "2026-03-25T20:21:53.674Z" }, - { url = "https://files.pythonhosted.org/packages/02/e0/3630057d8eb170310785723ed5adcdfb7d50cb7e6455f85ba8a3deed642b/tomli-2.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d", size = 270717, upload-time = "2026-03-25T20:21:55.129Z" }, - { url = "https://files.pythonhosted.org/packages/7a/b4/1613716072e544d1a7891f548d8f9ec6ce2faf42ca65acae01d76ea06bb0/tomli-2.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41", size = 278461, upload-time = "2026-03-25T20:21:56.228Z" }, - { url = "https://files.pythonhosted.org/packages/05/38/30f541baf6a3f6df77b3df16b01ba319221389e2da59427e221ef417ac0c/tomli-2.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c", size = 274855, upload-time = "2026-03-25T20:21:57.653Z" }, - { url = "https://files.pythonhosted.org/packages/77/a3/ec9dd4fd2c38e98de34223b995a3b34813e6bdadf86c75314c928350ed14/tomli-2.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f", size = 283144, upload-time = "2026-03-25T20:21:59.089Z" }, - { url = "https://files.pythonhosted.org/packages/ef/be/605a6261cac79fba2ec0c9827e986e00323a1945700969b8ee0b30d85453/tomli-2.4.1-cp314-cp314t-win32.whl", hash = "sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8", size = 108683, upload-time = "2026-03-25T20:22:00.214Z" }, - { url = "https://files.pythonhosted.org/packages/12/64/da524626d3b9cc40c168a13da8335fe1c51be12c0a63685cc6db7308daae/tomli-2.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26", size = 121196, upload-time = "2026-03-25T20:22:01.169Z" }, - { url = "https://files.pythonhosted.org/packages/5a/cd/e80b62269fc78fc36c9af5a6b89c835baa8af28ff5ad28c7028d60860320/tomli-2.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396", size = 100393, upload-time = "2026-03-25T20:22:02.137Z" }, - { url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" }, -] - [[package]] name = "ty" version = "0.0.94" @@ -637,24 +185,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d7/d4/ac3a759556493230823abd31e149c95401f96b9cac36567bd403a8454ea3/ty-0.0.94-py3-none-win_arm64.whl", hash = "sha256:ce344353ccdc542cfcfd6abe1481cf23c005f483411ea79652b78ce0beae36f2", size = 13547398, upload-time = "2026-10-28T18:06:06.379Z" }, ] -[[package]] -name = "types-grpcio" -version = "1.85.0.20261028" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/6b/5248f1b10df2c02ffbd99f3c913259bf73cabd2bee0ca1c28d6f3e66c3f4/types_grpcio-1.85.0.20261028.tar.gz", hash = "sha256:4ea4f36a54cf9a62fcb09515f7305e89c01f4edca54b32de24f6b1204b84522c", size = 16127, upload-time = "2026-10-28T07:38:58.025Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/ee/e2b2f2d677478456869ca922c1d5bb68f64052c9dfd9ad6c2a91a1122269/types_grpcio-1.85.0.20261028-py3-none-any.whl", hash = "sha256:2c2684330ae57ab64ffb43183ac652e73d2609024e6076e3e9d2b8ae06816207", size = 16076, upload-time = "2026-10-28T07:38:57.193Z" }, -] - -[[package]] -name = "types-protobuf" -version = "6.32.1.20260221" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/5f/e2/9aa4a3b2469508bd7b4e2ae11cbedaf419222a09a1b94daffcd5efca4023/types_protobuf-6.32.1.20260221.tar.gz", hash = "sha256:6d5fb060a616bfb076cbb61b4b3c3969f5fc8bec5810f9a2f7e648ee5cbcbf6e", size = 64408, upload-time = "2026-02-21T03:55:13.916Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2e/e8/1fd38926f9cf031188fbc5a96694203ea6f24b0e34bd64a225ec6f6291ba/types_protobuf-6.32.1.20260221-py3-none-any.whl", hash = "sha256:da7cdd947975964a93c30bfbcc2c6841ee646b318d3816b033adc2c4eb6448e4", size = 77956, upload-time = "2026-02-21T03:55:12.894Z" }, -] - [[package]] name = "types-pyyaml" version = "6.0.12.20260518" @@ -663,12 +193,3 @@ sdist = { url = "https://files.pythonhosted.org/packages/b8/83/4a1afc3fbfcf5b8d4 wheels = [ { url = "https://files.pythonhosted.org/packages/06/a2/c01db32be2ae7d6a1689972f3c492b149ee4e164b12fdfd9f64b50888215/types_pyyaml-6.0.12.20260518-py3-none-any.whl", hash = "sha256:d2150f75a231c9fe9c7463bd29487d93e60bac90400287351384bc2284eba7cd", size = 20312, upload-time = "2026-05-18T06:01:57.368Z" }, ] - -[[package]] -name = "typing-extensions" -version = "4.15.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, -]