chore(sdk/go)!: remove the Go SDK, now at github.com/ai-openshell/sdk-go (#5461)

* chore(sdk/go)!: remove the Go SDK, now at github.com/ai-openshell/sdk-go

The Go SDK moved to github.com/ai-openshell/sdk-go (#5031), and the
final sdk/go tag carries the deprecation notice. Remove what is left of
it from this repository:

- sdk/go/, tasks/go.toml, and the Go toolchain and tools in mise.toml
  and mise.lock (nothing else here is written in Go)
- the Go entry, setup, and build steps in CodeQL, and sdk/go in the
  CodeQL config
- sdk-go-tag.yml and the tag-sdk-go job in release-publish.yml,
  including its needs entry and the expected-publisher check
- the Go SDK Freeze job in Branch Checks, which has nothing left to
  guard

docs/sdk/go.mdx now shows the new module path, pins the SDK version to
the gateway's, and keeps the migration steps from the old module that
were reviewed on #5245. README, CONTRIBUTING, AGENTS, TESTING, CI.md,
buf.yaml, and the Windows skill drop or redirect their sdk/go
references. Existing sdk/go/vX.Y.Z tags stay, so builds that use the
old module path keep working.

BREAKING CHANGE: github.com/NVIDIA/OpenShell/sdk/go is no longer
developed in this repository; use github.com/ai-openshell/sdk-go.

Signed-off-by: Roland Huß <rhuss@redhat.com>

* ci: drop the go-sdk compatibility surface

With sdk/go removed, the compatibility review has no Go SDK left to
review. Remove go-sdk from the required surfaces in the review prompt
and in the report validator, which rejects reviews that don't cover
exactly the listed surfaces, and drop Go from the CI.md descriptions of
the compatibility review, CodeQL, and the release publishers.

Signed-off-by: Roland Huß <rhuss@redhat.com>

---------

Signed-off-by: Roland Huß <rhuss@redhat.com>
This commit is contained in:
Roland Huss
2026-11-11 12:50:06 +00:00
committed by GitHub
parent f1ce693071
commit 9a2a6d0964
271 changed files with 45 additions and 77199 deletions
@@ -312,10 +312,9 @@ compatibility under emulation is not part of these tasks. The aggregate
commands above on an ARM64 host.
The repository-wide `mise run pre-commit` task is also supported on Windows.
Run `rust:lockfiles:check`, `sdk:ts:ci`, and `go:ci` through the Windows-aware
tasks when validating those surfaces. Do not count the Go
Windows ARM64 race-detector exclusion or POSIX permission-bit skips as security
coverage. SDK test dependencies must remain at their lockfile versions.
Run `rust:lockfiles:check` and `sdk:ts:ci` through the Windows-aware tasks
when validating those surfaces. Do not count POSIX permission-bit skips as
security coverage. SDK test dependencies must remain at their lockfile versions.
Its Rust check, Clippy, and test dependencies enter the same MSVC environment
for the native host target and use an inherited compiler wrapper when it is
available. Linux glibc
-1
View File
@@ -6,7 +6,6 @@ name: OpenShell Rust and SDKs
paths:
- crates
- examples
- sdk/go
- sdk/typescript/src
- python/openshell
+3 -12
View File
@@ -113,8 +113,9 @@ needed.
## Required surfaces
Account for every surface: `rust-sdk`, `python-sdk`, `go-sdk`, `typescript-sdk`,
`api-behavior`, `cli`, `configuration`, `policy`, `helm`, and `state`.
Account for every surface: `rust-sdk`, `python-sdk`, `typescript-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.
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
@@ -126,16 +127,6 @@ generated server-trait changes reachable through `raw::proto`, identifying
mock/server implementers as affected consumers and distinguishing them from
unaffected client callers.
For `go-sdk`, adopt the [Go struct-literal compatibility convention](https://go.dev/doc/go1compat):
adding fields to exported structs is additive when existing keyed literals remain
valid and omitted fields preserve existing behavior. Do not report a break solely
because unkeyed (positional) literals need updating, unless the baseline explicitly
guarantees that construction form. Still inspect existing field names and types,
zero-value behavior, comparability (equality and map keys), and serialization
contracts; a field addition can break those independently. Follow the
[Go module compatibility guidance](https://go.dev/blog/module-compatibility#maintaining-struct-compatibility)
for these limits. This exception applies only to Go struct-field additions.
Check exported signatures/types, generated and handwritten SDK behavior,
serialization and error contracts, command flags and documented machine-readable
output, config/default semantics, policy formats, chart values, and persisted
-33
View File
@@ -608,39 +608,6 @@ jobs:
- name: Test release qualification summary
run: mise run test:qualification-summary
sdk-go-freeze:
# The Go SDK moved to ai-openshell/sdk-go (#5031). Its directory stays only
# until the final deprecated sdk/go tag exists, so PRs must not add or change
# files in it. Deleting files is allowed (the removal PR), and so are the
# moved notice and the deprecation comment in README.md and go.mod.
# Merge queue runs skip this job; the PR already passed it on its mirror.
name: Go SDK Freeze
needs: pr_metadata
if: needs.pr_metadata.outputs.should_run == 'true' && github.event_name == 'push'
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 sdk/go
env:
BASE_SHA: ${{ needs.pr_metadata.outputs.base_sha }}
run: |
set -euo pipefail
changed=$(git diff --name-only --diff-filter=d "${BASE_SHA}...HEAD" -- \
sdk/go ':!sdk/go/README.md' ':!sdk/go/go.mod')
if [ -z "$changed" ]; then
echo "No added or changed files under sdk/go."
exit 0
fi
echo "::error title=Go SDK moved::The Go SDK moved to https://github.com/ai-openshell/sdk-go. Drop the sdk/go changes from this PR and open SDK changes there. Regenerated bindings are not needed here; sdk-go regenerates them from core releases."
echo "Changed files under sdk/go:"
echo "$changed"
exit 1
python-sdk-freeze:
# The Python SDK moved to ai-openshell/sdk-python (#5287), which imported it
# at v0.1.7. Its files stay only until core removes them, so PRs must not
-14
View File
@@ -40,8 +40,6 @@ jobs:
include:
- language: rust
build-mode: none
- language: go
build-mode: manual
- language: python
build-mode: none
- language: javascript-typescript
@@ -53,13 +51,6 @@ jobs:
ref: ${{ inputs.candidate_ref && format('refs/tags/{0}', inputs.candidate_ref) || '' }}
persist-credentials: false
- name: Set up Go
if: matrix.language == 'go'
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: sdk/go/go.mod
cache-dependency-path: sdk/go/go.sum
- name: Initialize CodeQL
uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
with:
@@ -67,11 +58,6 @@ jobs:
build-mode: ${{ matrix.build-mode }}
config-file: ./.github/codeql/codeql-config.yml
- name: Build Go SDK
if: matrix.language == 'go'
working-directory: sdk/go
run: go build ./...
- name: Analyze
id: analyze
uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
+1 -13
View File
@@ -543,17 +543,6 @@ jobs:
npm-version: ${{ inputs.npm-version }}
make-latest: ${{ inputs.make-latest }}
tag-sdk-go:
name: Tag Go SDK
needs: release
if: ${{ !inputs.is-prerelease }}
permissions:
contents: write
uses: ./.github/workflows/sdk-go-tag.yml
with:
version: ${{ inputs.semver }}
source-sha: ${{ inputs.source-sha }}
# GitHub treats skipped jobs as passing, so a publisher that never ran would
# leave the run green. Fail when any publisher expected for this release kind
# did not succeed, so callers' failure notifications fire.
@@ -567,7 +556,6 @@ jobs:
- publish-snap
- publish-prerelease-snap
- publish-sdk-typescript
- tag-sdk-go
if: always()
runs-on: ubuntu-latest
timeout-minutes: 2
@@ -583,7 +571,7 @@ jobs:
if [[ "${IS_PRERELEASE}" == "true" ]]; then
expected+=(publish-prerelease-snap)
else
expected+=(publish-sdk-typescript tag-sdk-go)
expected+=(publish-sdk-typescript)
if [[ "${MAKE_LATEST}" == "true" ]]; then
expected+=(publish-snap)
fi
-58
View File
@@ -1,58 +0,0 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Go resolves submodule versions from directory-prefixed tags, so the SDK at
# sdk/go needs its own sdk/go/vX.Y.Z tag to show up as a release on pkg.go.dev.
name: Tag Go SDK
on:
workflow_call:
inputs:
version:
required: true
type: string
source-sha:
required: true
type: string
workflow_dispatch:
inputs:
version:
description: Release version without the v prefix, e.g. 0.1.6
required: true
type: string
source-sha:
description: Commit the stable tag points to
required: true
type: string
permissions:
contents: write
jobs:
tag:
name: Tag Go SDK
runs-on: ubuntu-latest
timeout-minutes: 5
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ inputs.version }}
SOURCE_SHA: ${{ inputs.source-sha }}
steps:
- name: Create Go SDK tag
shell: bash
run: |
set -euo pipefail
tag="sdk/go/v${VERSION}"
# Lightweight tag, so the ref points at the commit directly.
if ! existing=$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/tags/${tag}" --jq .object.sha 2>/dev/null); then
gh api "repos/${GITHUB_REPOSITORY}/git/refs" -f ref="refs/tags/${tag}" -f sha="${SOURCE_SHA}"
elif [[ "${existing}" != "${SOURCE_SHA}" ]]; then
echo "${tag} already exists at ${existing}, expected ${SOURCE_SHA}" >&2
exit 1
fi
# pkg.go.dev picks up versions the Go module proxy has fetched.
- name: Request version from Go module proxy
continue-on-error: true
shell: bash
run: curl --fail --silent --show-error --max-time 60 "https://proxy.golang.org/github.com/!n!v!i!d!i!a/!open!shell/sdk/go/@v/v${VERSION}.info"
+2 -3
View File
@@ -196,10 +196,9 @@ Follow `CONTRIBUTING.md` and `create-github-pr`. Authors without target-reposito
- Sign off on each commit for DCO compliance. Use the `--signoff` option to `git commit` to add the `Signed-off-by` footer to ensure the user's configured email address is used.
- Never mention Claude or any AI agent in commits, PR descriptions, or issues (no author attribution, no Co-Authored-By, no "Generated with" footers)
## Go SDK (`sdk/go/`)
## Go SDK
- The Go SDK moved to [ai-openshell/sdk-go](https://github.com/ai-openshell/sdk-go) (module `github.com/ai-openshell/sdk-go`). Open SDK changes there.
- `sdk/go/` is frozen until it is removed; Branch Checks fails PRs that change it. Proto changes do not need regenerated Go bindings.
- 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/`)
+5 -6
View File
@@ -94,8 +94,8 @@ qualification. Branch checks compare the prospective merge tree with its target,
using workflow-revision review tooling and the target's tag-derived train policy.
Release qualification reviews the cumulative diff from the previous reachable
stable release to the exact candidate commit, using the same tag-derived
patch/minor policy as the protobuf check. It reviews public Rust, Python, Go,
and TypeScript SDKs, API behavior, CLI contracts, configuration, policy, Helm,
patch/minor policy as the protobuf check. It reviews public Rust, Python, and
TypeScript SDKs, API behavior, CLI contracts, configuration, policy, Helm,
and persisted state.
Both Codex workflows share the `codex-release-review` concurrency group with
`queue: max`, so only one review runs at a time and up to 100 pending reviews
@@ -245,7 +245,7 @@ scanners upload results directly:
warn-only mode. A preflight turns an unavailable GitHub Dependency Graph into
a warning, so the workflow remains neutral until the repository feature is
available.
- `CodeQL` analyzes product Rust code, examples, and the Go, Python, and
- `CodeQL` analyzes product Rust code, examples, and the Python and
TypeScript SDKs. Rust `cfg(test)` blocks, Rust integration-test targets, and
E2E test code are excluded. It runs nightly on `main`, remains manually
dispatchable for diagnostics, uploads results to Code Scanning, and retains
@@ -707,7 +707,7 @@ The bot's full administrator documentation is internal to NVIDIA. The only comma
| `.github/workflows/e2e-label-help.yml` | When a `test:e2e*` label is applied, posts a PR comment telling the maintainer the next manual step (re-run an existing workflow run, or `/ok to test <SHA>` to refresh the mirror). |
| `.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 Go, Python, and TypeScript SDKs and retains SARIF artifacts. |
| `.github/workflows/codeql.yml` | Runs nightly informational CodeQL analysis on `main` for Rust and the Python and TypeScript SDKs 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. |
@@ -726,13 +726,12 @@ Each step that publishes to an external registry, store, or site lives in its ow
| `.github/workflows/release-auto-tag.yml` | Weekdays at 14:00 Europe/Zurich, tags the next `-pre.N` on `main` when commits landed since the latest one, then dispatches Pre-release. It skips when the train has no `-pre.1` or its version is already stable, so push each train's `-pre.1` tag by hand. |
| `.github/workflows/release-prerelease.yml` | Pre-release orchestrator, triggered by prerelease tag pushes or dispatched by Release Auto-Tag or manually. A tagless dispatch creates the next candidate on its branch; explicit tags select existing candidates. Builds, then publishes and qualifies in parallel. Qualification failure fails the run and sends the failure notification; published artifacts remain available. |
| `.github/workflows/release-build.yml` | Shared version computation, binary and image builds, and package builds. Validates that the tag matches the caller's release kind. |
| `.github/workflows/release-publish.yml` | Shared artifact assembly, OCI image tags and Helm chart publication, and package publication. Stable releases also publish release-labeled public schemas to Buf (`BUF_TOKEN` required) and GitHub Releases, and call the snap, npm, and Go SDK publishers. The Python SDK is released from [ai-openshell/sdk-python](https://github.com/ai-openshell/sdk-python), so no GitHub Release carries a wheel. |
| `.github/workflows/release-publish.yml` | Shared artifact assembly, OCI image tags and Helm chart publication, and package publication. Stable releases also publish release-labeled public schemas to Buf (`BUF_TOKEN` required) and GitHub Releases, and call the snap and npm publishers. The Python SDK is released from [ai-openshell/sdk-python](https://github.com/ai-openshell/sdk-python), so no GitHub Release carries a wheel. |
| `.github/workflows/release-notes.yml` | Shared prompt-driven release notes generation through Inference Hub, used by prerelease previews, notes-only previews, and stable releases. Stable releases reuse the promoted prerelease's preview when available. |
| `.github/workflows/release-qualification.yml` | Reusable qualification suites and result aggregation. Runs security scans, conformance and feature integration, Docker and VM E2E, protobuf compatibility, and advisory compatibility review. |
| `.github/workflows/snap-package.yml` | Builds snap and component artifacts for Release Dev, Release, and Pre-release without Store credentials or publication. |
| `.github/workflows/snap-publish.yml` | Uploads existing snap and component artifacts directly to a Store channel without rebuilding. Release Dev uses `latest/edge`, Pre-release uses `latest/beta`, and Release uses `latest/stable` for the stable rebuild. Uploads queue per channel and architecture, so tagged beta and stable jobs recheck repository tags after earlier publication finishes and before updating their floating channels. Manual dispatch uploads the `snap-linux-*` artifacts from `artifact-run-id`. |
| `.github/workflows/sdk-typescript-publish.yml` | Publishes the TypeScript SDK to GitHub Packages. Called by stable Release; manual dispatch publishes a given tag and npm version. |
| `.github/workflows/sdk-go-tag.yml` | Creates the `sdk/go/vX.Y.Z` tag and asks the Go module proxy to fetch it. Called by stable Release; manual dispatch tags a given version and commit. |
| `.github/workflows/release-canary.yml` | Smoke-tests published dev artifacts in the `macos`, `ubuntu-deb`, `ubuntu-snap-system-docker`, `fedora`, and `kubernetes` (kind + Helm) jobs. Each job reaches its gateway and creates, exercises, and deletes a sandbox. The `ubuntu-snap-system-docker` job verifies a compatible system Docker lifecycle, while `ubuntu-snap-docker-preflight` tests fail-fast behavior when Docker is absent or supplied by the Docker snap. The positive snap lane also runs a local policy containment check with the packaged prover. It runs automatically after `Release Dev` succeeds and supports manual dispatch (`gh workflow run release-canary.yml --ref <branch>`). See the `test-release-canary` skill for the playbook and local kind reproduction. |
## Required status contexts
-1
View File
@@ -383,7 +383,6 @@ These are the primary `mise` tasks for day-to-day development:
| `crates/openshell-policy-schema/` | Canonical authored policy DTOs and bounded YAML/JSON parser |
| `crates/openshell-prover-cli/` | Standalone local policy boundary checker |
| `python/` | Python SDK (frozen, moved to ai-openshell/sdk-python) |
| `sdk/go/` | Go SDK (types, gRPC clients, converters) |
| `sdk/typescript/` | TypeScript SDK (Connect client and generated protobuf bindings) |
| `proto/` | Protocol buffer definitions and [public API conventions](proto/README.md) |
| `tasks/` | `mise` task definitions and build scripts |
+1 -1
View File
@@ -74,7 +74,7 @@ SDKs connect applications to an OpenShell gateway. They do not install the CLI.
|---|---|---|
| Python | `uv add openshell` | [README](python/openshell/) |
| TypeScript | `npm install @nvidia/openshell-sdk` (GitHub Packages) | [README](sdk/typescript/README.md) |
| Go | `go get github.com/NVIDIA/OpenShell/sdk/go@latest` | [README](sdk/go/README.md) |
| 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/NVIDIA/OpenShell --tag <release-tag>` | [Installation and usage](docs/sdk/rust.mdx) |
## Community
+1 -2
View File
@@ -124,8 +124,7 @@ plugin through its Windows `.cmd` launcher, and installs the matching locked
ARM64 Rolldown binding when Node itself is ARM64. The helper preserves lockfile
resolution; it must not upgrade unrelated test dependencies.
`mise run --skip-tools go:ci` retains race detection except on Windows ARM64,
where Go does not support it. Windows token-file tests explicitly skip POSIX
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.
+3 -3
View File
@@ -3,9 +3,9 @@
# Repo-level buf workspace. Declares public and storage modules so buf generate,
# buf lint, buf breaking, and the editor LSP all resolve imports the same way.
# Code generation lives with each consumer (see sdk/go/buf.gen.yaml,
# sdk/typescript/buf.gen.yaml); this file owns the module boundaries and proto
# validation policy.
# Code generation lives with each consumer (see sdk/typescript/buf.gen.yaml;
# the Go SDK in ai-openshell/sdk-go generates from a release tag); this file
# owns the module boundaries and proto validation policy.
version: v2
modules:
- path: proto
+26 -7
View File
@@ -10,14 +10,18 @@ position: 1
Use the Go SDK to manage OpenShell resources from Go applications, operators,
and controllers. Its typed subclients follow familiar Kubernetes client
patterns. Use the SDK and gateway from the same OpenShell release when possible.
patterns. The SDK is developed in
[ai-openshell/sdk-go](https://github.com/ai-openshell/sdk-go), which also has
the full [SDK documentation](https://ai-openshell.github.io/sdk-go/).
## Install the SDK
The SDK requires Go 1.25.13 or later. Add it to your Go module:
The SDK requires Go 1.26 or later. SDK releases follow OpenShell releases,
so SDK `vX.Y.Z` works with a gateway from OpenShell `vX.Y.Z`. Add the version
that matches your gateway to your Go module:
```shell
go get github.com/NVIDIA/OpenShell/sdk/go@latest
go get github.com/ai-openshell/sdk-go@vX.Y.Z
```
## Connect to a Gateway
@@ -34,7 +38,7 @@ import (
"log"
"time"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
v1 "github.com/ai-openshell/sdk-go/openshell/v1"
)
func main() {
@@ -70,7 +74,7 @@ client, err := v1.NewClient(v1.Config{
Omit `CAFile` to use system roots. For renewable OIDC service credentials, use
`oidc.NewClientCredentialsAuth` from
`github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc`.
`github.com/ai-openshell/sdk-go/openshell/v1/oidc`.
## Discover the Active Gateway
@@ -95,7 +99,6 @@ sandbox, err := client.Sandboxes().Create(
Image: "registry.example.com/team/python-agent:1.0",
},
},
nil,
)
if err != nil {
log.Fatal(err)
@@ -126,8 +129,24 @@ The root client also exposes subclients for providers, services, files, SSH,
TCP forwarding, policy, configuration, templates, and workspaces. List methods
return lazy pagers so callers choose when to fetch the next page.
## Migrate from `github.com/NVIDIA/OpenShell/sdk/go`
The SDK used to live in this repository as `github.com/NVIDIA/OpenShell/sdk/go`.
That module is deprecated and gets no further changes, including dependency and
security updates. As of the move, packages and APIs are the same; only the
module path is new. Rewrite the imports, then fetch the SDK version that
matches your gateway:
```shell
grep -rlZ --include='*.go' --include=go.mod 'github.com/NVIDIA/OpenShell/sdk/go' . | xargs -0 perl -pi -e 's#github.com/NVIDIA/OpenShell/sdk/go#github.com/ai-openshell/sdk-go#g'
go get github.com/ai-openshell/sdk-go@vX.Y.Z && go mod tidy
```
Existing builds keep working: the old module's tags stay published, and the
latest one carries the deprecation notice that `go get` and pkg.go.dev show.
## Next Steps
- Review [Gateway Authentication](/how-it-works/gateways/authentication) before connecting a service to a production gateway.
- Review [API Errors](/sdk/api-errors) for the gateway error model.
- Browse the [Go package reference](https://pkg.go.dev/github.com/NVIDIA/OpenShell/sdk/go/openshell/v1) for all exported types and methods.
- Browse the [Go package reference](https://pkg.go.dev/github.com/ai-openshell/sdk-go/openshell/v1) for all exported types and methods.
-40
View File
@@ -259,46 +259,6 @@ checksum = "sha256:83a7d5955c7ac96ede5d896ac9ede5f7ecce9ece0e95d9e47acd766b09e2e
url = "https://github.com/rust-secure-code/cargo-auditable/releases/download/v0.7.5/cargo-auditable-x86_64-pc-windows-msvc.zip"
url_api = "https://api.github.com/repos/rust-secure-code/cargo-auditable/releases/assets/426566657"
[[tools.go]]
version = "1.26.7"
backend = "core:go"
[tools.go."platforms.linux-arm64"]
checksum = "sha256:5a4ec883379d51ee9ce1040d5e87f8d35e20387574dd8c947feb01eabc3c1b37"
url = "https://dl.google.com/go/go1.26.7.linux-arm64.tar.gz"
[tools.go."platforms.linux-x64"]
checksum = "sha256:ffb5f8de10c62550dfddab66b36b57030721e0a44a3218e9e1181d7b59f121ca"
url = "https://dl.google.com/go/go1.26.7.linux-amd64.tar.gz"
[tools.go."platforms.macos-arm64"]
checksum = "sha256:020a1e8224811be75163e920bc77e0926a1390a6aeea19bdcf23f74b9d749f6d"
url = "https://dl.google.com/go/go1.26.7.darwin-arm64.tar.gz"
[tools.go."platforms.windows-arm64"]
checksum = "sha256:6f1b08de9e2dd94f69c52e524ab6834737275253291e8fd7f1c12ed4eceeda89"
url = "https://dl.google.com/go/go1.26.7.windows-arm64.zip"
[tools.go."platforms.windows-x64"]
checksum = "sha256:f4f534a486e4bc3387fa18f08208f2f854b7aaea8a08f2a2d829a914a05abb11"
url = "https://dl.google.com/go/go1.26.7.windows-amd64.zip"
[[tools."go:github.com/golangci/golangci-lint/v2/cmd/golangci-lint"]]
version = "2.12.2"
backend = "go:github.com/golangci/golangci-lint/v2/cmd/golangci-lint"
[[tools."go:golang.org/x/tools/cmd/goimports"]]
version = "0.48.0"
backend = "go:golang.org/x/tools/cmd/goimports"
[[tools."go:google.golang.org/grpc/cmd/protoc-gen-go-grpc"]]
version = "1.6.2"
backend = "go:google.golang.org/grpc/cmd/protoc-gen-go-grpc"
[[tools."go:google.golang.org/protobuf/cmd/protoc-gen-go"]]
version = "1.36.11"
backend = "go:google.golang.org/protobuf/cmd/protoc-gen-go"
[[tools.helm]]
version = "4.2.0"
backend = "aqua:helm/helm"
-5
View File
@@ -25,11 +25,6 @@ node = "24.15.0"
kubectl = { version = "1.36.1", version_prefix = "v" }
uv = "0.10.12"
protoc = "29.6"
go = "1.26.7"
"go:github.com/golangci/golangci-lint/v2/cmd/golangci-lint" = "2.12"
"go:google.golang.org/protobuf/cmd/protoc-gen-go" = "1.36.11"
"go:google.golang.org/grpc/cmd/protoc-gen-go-grpc" = "1.6.2"
"go:golang.org/x/tools/cmd/goimports" = "0.48.0"
buf = "1.72.0"
helm = { version = "4.2.0", version_prefix = "v" }
helm-docs = "1.14.2"
-43
View File
@@ -1,43 +0,0 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
version: "2"
run:
timeout: 5m
linters:
enable:
- govet
- errcheck
- staticcheck
- unused
- ineffassign
- revive
- goheader
exclusions:
rules:
- path: "proto/"
linters:
- goheader
- revive
linters-settings:
goheader:
template: |-
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
revive:
rules:
- name: blank-imports
- name: exported
- name: var-naming
- name: indent-error-flow
- name: range
- name: error-return
- name: error-naming
- name: error-strings
- name: receiver-naming
- name: increment-decrement
- name: superfluous-else
- name: unreachable-code
-18
View File
@@ -1,18 +0,0 @@
# OpenShell SDK for Go (moved)
> [!IMPORTANT]
> The Go SDK moved to **[ai-openshell/sdk-go](https://github.com/ai-openshell/sdk-go)**.
> The module path is now `github.com/ai-openshell/sdk-go`.
This directory is frozen and will be removed from NVIDIA/OpenShell. Its last tagged version, `github.com/NVIDIA/OpenShell/sdk/go`, is marked deprecated and gets no further changes. Open issues and pull requests for the SDK in [ai-openshell/sdk-go](https://github.com/ai-openshell/sdk-go).
## Migrating
Packages and APIs are unchanged; only the module path is new. Rewrite the imports, then fetch the new module:
```shell
grep -rl --include='*.go' --include=go.mod 'github.com/NVIDIA/OpenShell/sdk/go' . | xargs perl -pi -e 's#github.com/NVIDIA/OpenShell/sdk/go#github.com/ai-openshell/sdk-go#g'
go get github.com/ai-openshell/sdk-go@latest && go mod tidy
```
SDK releases follow core releases, so SDK `vX.Y.Z` works with core `vX.Y.Z`. The move is tracked in [#5031](https://github.com/NVIDIA/OpenShell/issues/5031).
-32
View File
@@ -1,32 +0,0 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Code generation for the Go SDK. buf compiles the proto module with its own
# compiler and runs protoc-gen-go / protoc-gen-go-grpc from mise-managed
# binaries. The public SDK entry points are declared here; imported schemas
# are included automatically, so their canonical dependency closure is
# generated without duplicating a filename list in the generation scripts.
version: v2
inputs:
- proto_file: proto/openshell.proto
plugins:
- local: protoc-gen-go
out: sdk/go
include_imports: true
opt:
- module=github.com/NVIDIA/OpenShell/sdk/go
- Mopenshell.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1
- Mdatamodel.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1
- Msandbox.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1
- Moptions.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/optionsv1
- local: protoc-gen-go-grpc
out: sdk/go
include_imports: true
opt:
- module=github.com/NVIDIA/OpenShell/sdk/go
- Mopenshell.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1
- Mdatamodel.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1
- Msandbox.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1
- Moptions.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/optionsv1
-23
View File
@@ -1,23 +0,0 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
[book]
title = "OpenShell Go SDK"
authors = ["NVIDIA Corporation"]
language = "en"
src = "src"
[build]
build-dir = "book"
create-missing = false
[output.html]
default-theme = "ayu"
preferred-dark-theme = "navy"
additional-css = ["theme/custom.css"]
git-repository-url = "https://github.com/NVIDIA/OpenShell/sdk/go"
edit-url-template = "https://github.com/NVIDIA/OpenShell/sdk/go/edit/main/docs/src/{path}"
[output.html.search]
enable = true
limit-results = 20
-38
View File
@@ -1,38 +0,0 @@
# Summary
[Introduction](introduction.md)
# Getting Started
- [Quick Start](getting-started.md)
# Architecture
- [Overview](architecture.md)
# API Reference
- [Overview](api/overview.md)
- [Client](api/client.md)
- [Sandboxes](api/sandboxes.md)
- [Sandbox Templates](api/sandbox-templates.md)
- [Exec](api/exec.md)
- [Providers](api/providers.md)
- [Profiles](api/profiles.md)
- [Refresh](api/refresh.md)
- [Services](api/services.md)
- [Files](api/files.md)
- [Health](api/health.md)
- [SSH](api/ssh.md)
- [TCP](api/tcp.md)
- [Config](api/config.md)
- [Policy](api/policy.md)
- [Gateway](api/gateway.md)
- [OIDC](api/oidc.md)
- [Edge](api/edge.md)
- [Fake](api/fake.md)
# Guides
- [Error Handling](error-handling.md)
- [Testing](testing.md)
-79
View File
@@ -1,79 +0,0 @@
# Client
Constructor: `v1.NewClient(config)`
`Client` is the root entry point for SDK operations. It provides typed accessors
for each resource domain and manages the underlying gRPC connection. The
`ClientInterface` covers the stable core accessors; additive helpers such as
`SandboxTemplates()` are available on the concrete client.
## Methods
| Accessor | Returns | Description |
|----------|---------|-------------|
| `Sandboxes()` | `SandboxInterface` | Sandbox lifecycle management |
| `SandboxTemplates()` | `SandboxTemplateInterface` | Reusable sandbox template management |
| `Providers()` | `ProviderInterface` | Provider CRUD and idempotent ensure |
| `Services()` | `ServiceInterface` | Service exposure and management |
| `Exec()` | `ExecInterface` | Command execution (run, stream, interactive) |
| `Files()` | `FileInterface` | File upload and download |
| `Health()` | `HealthInterface` | Gateway health checking |
| `SSH()` | `SSHInterface` | SSH session and tunnel management |
| `TCP()` | `TCPInterface` | TCP port forwarding |
| `Config()` | `ConfigInterface` | Sandbox and gateway configuration |
| `Policy()` | `PolicyInterface` | Draft policy review workflow |
| `Close()` | `error` | Close the gRPC connection |
Sub-client hierarchy: `Providers()` has two nested accessors:
- `client.Providers().Profiles()` returns `ProfileInterface`
- `client.Providers().Refresh()` returns `RefreshInterface`
## Creating a Client
```go
import v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: v1.StaticToken("my-token"),
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
```
## Configuration
The `Config` struct controls connection behavior:
```go
type Config struct {
Address string // Gateway address (host:port)
TLS *TLSConfig // TLS settings (nil uses system defaults)
Auth AuthProvider // Authentication provider
Timeout time.Duration // Default timeout for all operations (0 = no timeout)
RetryPolicy *RetryPolicy // Retry configuration (nil = no automatic retries)
Logger Logger // Custom logger (nil = no logging)
}
```
Authentication providers:
- `v1.StaticToken(token)` provides a fixed bearer token
- `v1.NoAuth()` skips authentication (for local development)
## Testing
For unit tests, use the fake client instead of a real connection:
```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
client := fake.NewClient()
defer client.Close()
```
The fake client implements the full `ClientInterface` with in-memory stores.
See [Testing](../testing.md) for details.
See also: [Getting Started](../getting-started.md), [Architecture](../architecture.md)
-52
View File
@@ -1,52 +0,0 @@
# Config
Accessor: `client.Config()`
Retrieve and update configuration for sandboxes and the gateway.
## GetSandbox
Retrieve the current configuration for a specific sandbox.
```go
config, err := client.Config().GetSandbox(ctx, "default", "sandbox-123")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sandbox config: policy_version=%d, revision=%d\n",
config.PolicyVersion, config.ConfigRevision)
```
## GetGateway
Retrieve the gateway-level configuration.
```go
config, err := client.Config().GetGateway(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Gateway settings revision: %d\n", config.SettingsRevision)
```
## Update
Apply a configuration update. The update is validated before being applied.
```go
result, err := client.Config().Update(ctx, "default", &v1.ConfigUpdate{
Name: "sandbox-123",
SettingKey: "idle_timeout",
SettingValue: &v1.SettingValue{
Type: v1.SettingValueString,
StringVal: "30m",
},
})
if err != nil {
// See [Error Handling](../error-handling.md) for validation errors
log.Fatal(err)
}
fmt.Printf("Config updated: revision=%d\n", result.SettingsRevision)
```
See also: [Error Handling](../error-handling.md)
-91
View File
@@ -1,91 +0,0 @@
# Edge
Package: `openshell/v1/edge`
The edge package provides utilities for connecting to OpenShell gateways
through edge proxies such as Cloudflare Access. It includes auth wrappers
for edge proxy headers and a WebSocket tunnel proxy for gRPC transport
through HTTP/1.1-only proxies.
## Cloudflare Access
Wrap any `AuthProvider` with Cloudflare Access headers
(`cf-access-jwt-assertion` and `CF_Authorization` cookie):
```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/edge"
base := v1.StaticToken("my-gateway-token")
auth, err := edge.CloudflareAccess(base, os.Getenv("CF_ACCESS_TOKEN"))
if err != nil {
log.Fatal(err)
}
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: auth,
})
```
CloudflareAccess composes with any auth provider, including `RefreshableToken`
for automatic token refresh:
```go
tokenSource := oauth2Config.TokenSource(ctx, initialToken)
refreshAuth, err := v1.RefreshableToken(tokenSource)
if err != nil {
log.Fatal(err)
}
auth, err := edge.CloudflareAccess(refreshAuth, cfToken)
```
## WebSocket Tunnel
`TunnelProxy` bridges gRPC connections over a WebSocket tunnel for edge
proxies that reject standard HTTP/2 POST requests. The tunnel carries
its own edge token for proxy authentication, independent of the
application-level auth provider.
```go
tunnel, err := edge.NewTunnelProxy(
"wss://gateway.example.com/ws",
os.Getenv("CF_ACCESS_TOKEN"),
)
if err != nil {
log.Fatal(err)
}
defer tunnel.Close()
auth := v1.StaticToken("my-gateway-token")
client, err := v1.NewClient(v1.Config{
Address: tunnel.Addr(),
Auth: auth,
TLS: &v1.TLSConfig{Insecure: true}, // local tunnel
})
```
## Functions
| Function | Description |
|----------|-------------|
| `CloudflareAccess(base, edgeToken)` | Wrap an AuthProvider with Cloudflare Access headers |
| `NewTunnelProxy(url, edgeToken, opts...)` | Create a WebSocket tunnel proxy for gRPC-over-HTTP/1.1 |
## TunnelProxy Methods
| Method | Description |
|--------|-------------|
| `Addr()` | Local listener address for gRPC client to dial |
| `Close()` | Gracefully drain in-flight connections and shut down |
## TunnelOption
| Constructor | Effect |
|-------------|--------|
| `WithTunnelTLS(cfg)` | Configure TLS for the WebSocket connection |
| `WithTunnelLogger(l)` | Set a logger for tunnel events |
| `WithCloseTimeout(d)` | Override the graceful shutdown timeout (default 5s) |
## Thread Safety
All exported functions and methods are safe for concurrent use.
`Close` is idempotent and safe to call multiple times.
-175
View File
@@ -1,175 +0,0 @@
# Exec
Accessor: `client.Exec()`
Execute commands in a sandbox with three modes: one-shot (`Run`), streaming
(`Stream`), or interactive terminal (`Interactive`).
## Run
Execute a command and collect all output into a single result.
```go
result, err := client.Exec().Run(ctx, "default", "sbx-123", []string{"ls", "-la"})
if err != nil {
log.Fatal(err)
}
fmt.Println("Exit code:", result.ExitCode)
fmt.Println("Stdout:", result.Stdout)
fmt.Println("Stderr:", result.Stderr)
```
The SDK collects all streamed events, assembles stdout/stderr, and returns a single `ExecResult`.
`ExecResult` contains the complete output after the command finishes:
| Field | Type | Description |
|------------|--------|------------------------------|
| `Stdout` | string | Captured standard output |
| `Stderr` | string | Captured standard error |
| `ExitCode` | int | Process exit code |
## Stream
Execute a command and process output chunks as they arrive.
```go
stream, err := client.Exec().Stream(ctx, "default", "sbx-123", []string{"tail", "-f", "/var/log/app.log"})
if err != nil {
log.Fatal(err)
}
defer stream.Close()
for {
chunk, err := stream.Next()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if chunk.Stream == v1.StreamStdout {
fmt.Print(string(chunk.Data))
}
}
exitCode, err := stream.ExitCode()
if err != nil {
log.Fatal(err)
}
fmt.Println("Exited with:", exitCode)
```
## Interactive
Open a bidirectional terminal session with a command.
```go
session, err := client.Exec().Interactive(ctx, "default", "sbx-123", []string{"/bin/bash"}, 80, 24)
if err != nil {
log.Fatal(err)
}
defer session.Close()
// Send input
_, err = session.Write([]byte("echo hello\n"))
if err != nil {
log.Fatal(err)
}
// Read output
buf := make([]byte, 4096)
n, err := session.Read(buf)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(buf[:n]))
// Handle terminal resize
if err := session.Resize(120, 40); err != nil {
log.Fatal(err)
}
// Get exit code after session ends
exitCode, err := session.ExitCode()
if err != nil {
log.Fatal(err)
}
fmt.Println("Exited with:", exitCode)
```
The SDK wraps the bidirectional stream as an `InteractiveSession` with `Read`/`Write`/`Resize` methods.
## ExecStream
`ExecStream` provides an iterator interface over command output chunks. Call `Next()` repeatedly to receive output as it is produced. When the command finishes, `Next()` returns `io.EOF`.
```go
type ExecStream interface {
Next() (*ExecChunk, error)
ExitCode() (int, error)
Close() error
}
```
| Method | Description |
|------------|----------------------------------------------------------------|
| `Next` | Returns the next output chunk. Returns `io.EOF` when done. |
| `ExitCode` | Returns the process exit code. Call after `Next` returns `io.EOF`. |
| `Close` | Releases the underlying stream resources. |
## InteractiveSession
`InteractiveSession` implements `io.Reader` and `io.Writer` for bidirectional communication with a running process. Use it for terminal emulation, REPL interaction, or any command that requires ongoing input.
```go
type InteractiveSession interface {
Read(p []byte) (int, error)
Write(p []byte) (int, error)
Resize(cols, rows uint32) error
ExitCode() (int, error)
Close() error
}
```
| Method | Description |
|------------|---------------------------------------------------------------------|
| `Read` | Reads output from the process into the provided buffer. |
| `Write` | Sends input to the process. |
| `Resize` | Updates the terminal dimensions (columns and rows). |
| `ExitCode` | Waits for final gRPC status; returns any observed exit code alongside a later stream error. |
| `Close` | Aborts the RPC and releases resources. |
SDK sessions also implement the optional `InteractiveSessionControl` interface,
which embeds `InteractiveSession` and adds `CloseWrite() error` and `Cancel() error`.
Existing custom implementations only need the original methods above.
Call `CloseInteractiveInput(session)` to end stdin and resize input without
cancelling output. It invokes `CloseWrite()` when supported; otherwise it returns
`ErrorUnimplemented` without closing the session. Call `CancelInteractive(session)`
to invoke `Cancel()` when supported, falling back to `Close()` for legacy sessions.
The SDK's close and cancel methods are idempotent.
Drain `Read` concurrently with waiting for `ExitCode`; bounded output buffers can
otherwise prevent completion. After input closure, writes and resizes return
`io.ErrClosedPipe`. Request EOF is not equivalent to a terminal Ctrl-D keystroke.
## ExecChunk
Each chunk from `ExecStream.Next()` carries a segment of process output along with which stream it came from.
```go
type ExecChunk struct {
Data []byte
Stream StreamType
}
```
| Field | Type | Description |
|----------|------------|---------------------------------------------------|
| `Data` | `[]byte` | Raw output bytes from the process. |
| `Stream` | StreamType | Either `StreamStdout` or `StreamStderr`. |
See also: [Error Handling](../error-handling.md), [Testing](../testing.md)
-122
View File
@@ -1,122 +0,0 @@
# Fake
Package: `openshell/v1/fake`
The fake package provides an in-memory fake implementation of all SDK
client interfaces for use in consumer test suites. It follows the
`client-go/kubernetes/fake` pattern: in-memory stores, watch event
broadcasting, and matching `StatusError` codes for equivalent error
conditions (`NotFound`, `AlreadyExists`, `Unavailable`, `Unimplemented`).
## Quick Start
```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
func TestSandboxLifecycle(t *testing.T) {
client := fake.NewClient()
defer client.Close()
ctx := context.Background()
sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
require.NoError(t, err)
assert.Equal(t, types.SandboxProvisioning, sb.Status.Phase)
sb, err = client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
require.NoError(t, err)
assert.Equal(t, types.SandboxReady, sb.Status.Phase)
deletion, err := client.Sandboxes().Delete(ctx, "default", "my-sandbox")
require.NoError(t, err)
assert.Equal(t, v1.DeletionCompleted, deletion.Outcome)
}
```
## Creating a Client
```go
func NewClient(opts ...ClientOption) *Client
```
Returns a fake client implementing `v1.ClientInterface` with all
sub-clients wired up. Default health result is healthy. Use options
to customize initial state:
```go
client := fake.NewClient(
fake.WithHealthResult(&types.HealthResult{Healthy: false}),
fake.WithCurrentUser(&types.CurrentUser{Subject: "test-user"}),
fake.WithGatewayInfo(&types.GatewayInfo{Version: "1.0.0"}),
)
```
## Pre-populating State
Seed objects directly into the fake stores for test setup:
```go
client := fake.NewClient()
client.AddSandbox("default", &types.Sandbox{
Name: "pre-existing",
Status: types.SandboxStatus{Phase: types.SandboxReady},
})
client.AddSandboxTemplate("default", &types.SandboxWorkloadTemplate{
Name: "gpu-kata",
Spec: types.SandboxWorkloadTemplateSpec{
Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"},
},
})
client.AddProvider("default", &types.Provider{
Name: "my-provider",
Spec: types.ProviderSpec{Type: "docker"},
})
client.AddWorkspace(&types.Workspace{Name: "staging"})
client.AddMember("staging", &types.WorkspaceMember{
PrincipalSubject: "subject-123",
Role: types.WorkspaceRoleAdmin,
})
```
All `Add*` methods deep-copy their arguments; mutating the input after
insertion does not affect the stored object.
## Sub-Client Coverage
The fake client implements every stable accessor in `v1.ClientInterface` plus
additive concrete-client accessors such as `SandboxTemplates()`:
| Accessor | Interface | Behavior |
|----------|-----------|----------|
| `Sandboxes()` | `SandboxInterface` | Full CRUD, Watch, WaitReady |
| `SandboxTemplates()` | `SandboxTemplateInterface` | Full CRUD |
| `Providers()` | `ProviderInterface` | Full CRUD, Ensure |
| `Workspaces()` | `WorkspaceInterface` | Full CRUD, Members |
| `Health()` | `HealthInterface` | Configurable result |
| `Policy()` | `PolicyInterface` | List, GetStatus (draft ops return Unimplemented) |
| `Exec()` | `ExecInterface` | Returns Unimplemented |
| `Files()` | `FileInterface` | Returns Unimplemented |
| `Services()` | `ServiceInterface` | Returns Unimplemented |
| `SSH()` | `SSHInterface` | Input validation, then Unimplemented |
| `TCP()` | `TCPInterface` | Input validation, then Unimplemented |
| `Config()` | `ConfigInterface` | Returns Unimplemented |
## ClientOption
| Constructor | Effect |
|-------------|--------|
| `WithHealthResult(r)` | Set the health check return value |
| `WithCurrentUser(u)` | Set the current user return value |
| `WithGatewayInfo(i)` | Set the gateway info return value |
## Thread Safety
All operations are safe for concurrent use from multiple goroutines.
`Close` is idempotent and causes all subsequent operations to return
`Unavailable`.
See also: [Testing Guide](../testing.md)
-36
View File
@@ -1,36 +0,0 @@
# Files
Accessor: `client.Files()`
`FileInterface` reserves the upload and download API while keeping sandbox lookup
and SSH-session lifecycle behavior stable. The standalone SDK does not currently
ship an SSH file-transfer transport, so both operations return
`v1.ErrTransportNotAvailable` before performing local validation or gateway RPCs.
## Upload
Detect transport availability programmatically:
```go
err := client.Files().Upload(ctx, "default", "sandbox-123", "./data/config.yaml", "/app/config.yaml")
if errors.Is(err, v1.ErrTransportNotAvailable) {
// Use another transfer mechanism until an SSH transport is available.
} else if err != nil {
log.Fatal(err)
}
```
## Download
`Download` has the same capability gate:
```go
err := client.Files().Download(ctx, "default", "sandbox-123", "/app/output.log", "./output.log")
if errors.Is(err, v1.ErrTransportNotAvailable) {
// Use another transfer mechanism until an SSH transport is available.
} else if err != nil {
log.Fatal(err)
}
```
See also: [Error Handling](../error-handling.md), [Testing](../testing.md)
-188
View File
@@ -1,188 +0,0 @@
# Gateway
Package: `openshell/v1/gateway`
The gateway package reads on-disk gateway configurations created by the
OpenShell Rust CLI and constructs fully wired SDK clients. It eliminates
the boilerplate of locating config files, parsing metadata, loading
tokens, and wiring auth providers.
## Quick Start
```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
// Connect to a named gateway
client, err := gateway.NewClient("prod")
if err != nil {
log.Fatal(err)
}
defer client.Close()
```
## Functions
| Function | Description |
|----------|-------------|
| `NewClient(name, opts...)` | Create a fully wired SDK client from gateway config |
| `LoadConfig(name)` | Parse gateway config without connecting |
| `ListGateways()` | Enumerate all available gateways |
### NewClient
```go
func NewClient(name string, opts ...ClientOption) (*v1.Client, error)
```
Creates a fully configured SDK client for the named gateway. If `name`
is empty, the active gateway (set via `openshell gateway use`) is used.
The function resolves the gateway directory, parses `metadata.json`,
loads tokens lazily, maps the auth mode to an SDK auth provider, and
applies any `ClientOption` values before delegating to `v1.NewClient`.
```go
// Named gateway
client, err := gateway.NewClient("prod")
// Active gateway
client, err := gateway.NewClient("")
// With options
client, err := gateway.NewClient("staging",
gateway.WithTimeout(10 * time.Second),
gateway.WithLogger(myLogger),
)
```
**Errors**: `ErrGatewayNotFound`, `ErrConfigParse`,
`ErrUnsupportedAuthMode`, `ErrInvalidGatewayName`, `ErrNoActiveGateway`
### LoadConfig
```go
func LoadConfig(name string) (*Config, error)
```
Parses gateway configuration without creating a client connection.
Returns a frozen snapshot; changes to on-disk files after the call
are not reflected.
```go
cfg, err := gateway.LoadConfig("staging")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Endpoint: %s, Auth: %s\n", cfg.Endpoint, cfg.AuthMode)
```
### ListGateways
```go
func ListGateways() ([]Info, error)
```
Enumerates all available gateways from user and system directories.
User gateways appear first. Duplicate names resolve to user precedence.
Returns an empty slice (not an error) when no gateways are configured.
```go
gateways, err := gateway.ListGateways()
for _, gw := range gateways {
fmt.Printf("%s (active=%v, source=%s)\n", gw.Name, gw.Active, gw.Source)
}
```
## Types
### Config
```go
type Config struct {
Name string // Validated gateway name
Endpoint string // Host:port of the gateway
AuthMode AuthMode // Resolved auth mode
Source ConfigSource // User or System origin
Dir string // Absolute path to gateway config directory
}
```
### Info
```go
type Info struct {
Name string // Gateway name from directory listing
Active bool // Whether this is the active gateway
Source ConfigSource // User or System origin
}
```
### AuthMode
| Value | Constant | SDK AuthProvider |
|-------|----------|-----------------|
| `""` or `"none"` | `AuthModeNone` | `v1.NoAuth()` |
| `"plaintext"` | `AuthModePlaintext` | `v1.NoAuth()` + insecure TLS |
| `"cloudflare_jwt"` | `AuthModeCloudflareJWT` | Lazy edge token auth |
| `"oidc"` | `AuthModeOIDC` | `v1.RefreshableToken` that reads `oidc_token.json` near expiry and fails once the token has expired |
| `"mtls"` | `AuthModeMTLS` | Unsupported (use `WithAuth`) |
### ClientOption
| Constructor | Effect |
|-------------|--------|
| `WithLogger(l)` | Set logger on the SDK client |
| `WithTimeout(d)` | Set connection timeout |
| `WithTLS(cfg)` | Override TLS settings from gateway config |
| `WithAuth(provider)` | Override auto-resolved auth provider |
| `WithRetryPolicy(p)` | Set retry policy |
## Error Handling
All errors support `errors.Is` for classification:
```go
client, err := gateway.NewClient("my-gateway")
if errors.Is(err, gateway.ErrGatewayNotFound) {
fmt.Println("Gateway not configured. Run: openshell gateway add my-gateway")
}
```
Tokens load lazily, so `NewClient` does not return `ErrTokenLoad`. For `oidc`
gateways, a missing, malformed, or expired `oidc_token.json` surfaces on RPCs as
an error for which `v1.IsUnauthenticated(err)` is true, and its message includes
``run `openshell gateway login <name>` ``.
| Error | Meaning |
|-------|---------|
| `ErrGatewayNotFound` | No gateway directory in user or system paths |
| `ErrConfigParse` | metadata.json missing or malformed |
| `ErrTokenLoad` | Token file missing, unreadable, malformed, or expired; RPCs report it as Unauthenticated |
| `ErrUnsupportedAuthMode` | Unrecognized auth_mode value |
| `ErrInvalidGatewayName` | Name fails validation |
| `ErrNoActiveGateway` | No active gateway configured |
## On-Disk Layout
The package reads gateway metadata from these locations:
```
$XDG_CONFIG_HOME/openshell/ (user, default: ~/.config/openshell/)
├── active_gateway # Plain text: active gateway name
└── gateways/
└── <name>/
├── metadata.json # {"endpoint":"...","auth_mode":"...","name":"..."}
├── edge_token # Cloudflare edge JWT (plaintext)
├── cf_token # Legacy edge token (fallback)
└── oidc_token.json # OIDC token bundle
/etc/openshell/gateways/ (system, fallback)
```
User gateways take precedence over system gateways with the same name.
## Thread Safety
All exported functions (`NewClient`, `LoadConfig`, `ListGateways`) are
safe for concurrent use from multiple goroutines. Token loading uses
internal synchronization.
-32
View File
@@ -1,32 +0,0 @@
# Health
Accessor: `client.Health()`
Check the health status of the connected OpenShell gateway.
## Check
Perform a health check against the gateway. Returns the overall status and
component-level details.
```go
result, err := client.Health().Check(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Gateway healthy: %v\n", result.Healthy)
```
This is useful for readiness probes or verifying connectivity before executing
other operations.
```go
// Quick connectivity check before starting work
if result, err := client.Health().Check(ctx); err != nil {
log.Fatalf("Gateway unreachable: %v", err)
} else if !result.Healthy {
log.Fatal("Gateway is not healthy")
}
```
See also: [Error Handling](../error-handling.md)
-173
View File
@@ -1,173 +0,0 @@
# OIDC Login
Package: `openshell/v1/oidc`
The oidc package provides OIDC authentication for OpenShell gateways.
It supports four OAuth2 flows: browser-based authorization code with
PKCE, keyboard fallback, device code (RFC 8628), and client credentials.
## Quick Start
```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc"
// Gateway-aware login (reads OIDC config from gateway metadata)
token, err := oidc.Login(ctx, "my-gateway")
if err != nil {
log.Fatal(err)
}
```
## Functions
| Function | Description |
|----------|-------------|
| `Login(ctx, gatewayName, opts...)` | Interactive login via browser or keyboard flow |
| `DeviceLogin(ctx, opts...)` | Device authorization grant (RFC 8628) |
| `ClientCredentials(ctx, opts...)` | Non-interactive client credentials grant |
### Login
```go
func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth2.Token, error)
```
Performs an interactive OIDC login. When `gatewayName` is provided, the
OIDC issuer and client ID are read from the gateway's `metadata.json`.
The default flow opens a browser for authorization code exchange with
PKCE. If the provider does not support PKCE (S256), the flow proceeds
without it.
Tokens are persisted to the gateway's config directory as
`oidc_token.json`, in the same format as `openshell gateway login`, so CLI
commands against that gateway can use them. Subsequent calls reuse the stored
token only when it is valid and was issued for the gateway's issuer and client
ID; otherwise `Login` runs the flow again and rewrites the file.
For standalone use (no gateway), pass an empty `gatewayName` with
`WithIssuer` and `WithClientID`. Combine with `WithInMemory` to skip
disk persistence.
### DeviceLogin
```go
func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error)
```
Performs an OAuth2 device authorization grant (RFC 8628). The flow
requests a device code and user code from the provider, displays them
via `WithDisplayFunc` (or stdout), and polls the token endpoint until
the user completes authorization.
Requires `WithIssuer` and `WithClientID`, or `WithGateway`.
### ClientCredentials
```go
func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error)
```
Performs a non-interactive OAuth2 client credentials grant. Requires
`WithIssuer`, `WithClientID`, and `WithClientSecret` (or `WithGateway`
combined with `WithClientSecret`). The client secret is never included
in error messages.
### NewClientCredentialsAuth
```go
func NewClientCredentialsAuth(opts ...LoginOption) (types.AuthProvider, error)
```
Returns a lazy renewable auth provider for `v1.Config.Auth` or
`gateway.WithAuth`. It caches access tokens in memory, renews within 30 seconds
of expiry, coalesces concurrent exchanges, and fails closed if renewal fails.
Use `WithClientSecretProvider` when the application rotates secret material.
## Options
| Option | Description |
|--------|-------------|
| `WithIssuer(url)` | OIDC provider issuer URL |
| `WithClientID(id)` | OAuth2 client ID |
| `WithClientSecret(secret)` | OAuth2 client secret (for client credentials) |
| `WithClientSecretProvider(provider)` | Resolve the client secret for each exchange |
| `WithAudience(audience)` | Optional OAuth2 resource-server audience |
| `WithScopes(scopes...)` | Custom scopes (client credentials has no implicit scopes) |
| `WithCallbackPort(port)` | Fixed port for localhost callback (default: tries 8000, then 18000) |
| `WithTimeout(d)` | Auth flow timeout (default: 2 minutes) |
| `WithKeyboardFlow()` | Use keyboard flow instead of browser |
| `WithInMemory()` | Skip token persistence to disk |
| `WithDisplayFunc(fn)` | Custom display for device code flow |
| `WithGateway(name)` | Resolve OIDC config from gateway metadata |
## Error Handling
The package defines sentinel errors for `errors.Is()` matching:
| Error | Description |
|-------|-------------|
| `ErrDiscovery` | OIDC discovery document fetch failed |
| `ErrAuthCode` | Authorization code exchange failed |
| `ErrDeviceCode` | Device code flow failed |
| `ErrClientCredentials` | Client credentials exchange failed |
| `ErrTimeout` | Authentication flow timed out |
| `ErrCallbackServer` | Localhost callback server failed |
| `ErrTokenPersist` | Token read/write failed |
| `ErrOIDCConfig` | Missing or invalid OIDC configuration |
```go
token, err := oidc.Login(ctx, "my-gateway")
if errors.Is(err, oidc.ErrDiscovery) {
// Provider unreachable
}
if errors.Is(err, oidc.ErrTimeout) {
// User did not complete login in time
}
```
## Gateway Integration
When a gateway's `metadata.json` contains `oidc_issuer` and
`oidc_client_id` fields, `Login` and `DeviceLogin` can resolve
configuration automatically:
```go
// Login reads OIDC config from the gateway
token, err := oidc.Login(ctx, "my-gateway")
// Then use the token with the SDK client
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: v1.StaticToken(token.AccessToken),
})
```
## Flows
### Browser Flow (default)
1. Discovers OIDC endpoints from issuer
2. Generates PKCE code verifier and S256 challenge
3. Opens browser to authorization URL
4. Starts localhost callback server to receive the auth code
5. Exchanges code for tokens with PKCE verification
6. Persists tokens to disk
### Keyboard Flow
Same as browser flow, but prints the authorization URL for the user to
copy manually. The user pastes the authorization code back into the
terminal. Use `WithKeyboardFlow()` to enable.
### Device Code Flow (RFC 8628)
1. Requests a device code and user code from the provider
2. Displays the verification URL and user code
3. Polls the token endpoint at the provider's requested interval
4. Handles `slow_down` responses by increasing the poll interval
### Client Credentials Flow
1. Discovers OIDC endpoints from issuer
2. Exchanges client ID and secret for an access token
3. No user interaction required
-65
View File
@@ -1,65 +0,0 @@
# API Overview
The OpenShell Go SDK exposes typed interfaces through the sub-client pattern.
You access each interface through a typed accessor on the concrete `Client`.
## Interface Summary
### Top-Level Interfaces
| Interface | Accessor | Description |
|-----------|----------|-------------|
| [SandboxInterface](sandboxes.md) | `client.Sandboxes()` | Create, manage, and watch sandbox lifecycle |
| [SandboxTemplateInterface](sandbox-templates.md) | `client.SandboxTemplates()` | Manage reusable sandbox templates |
| [ExecInterface](exec.md) | `client.Exec()` | Run commands, stream output, interactive sessions |
| [ProviderInterface](providers.md) | `client.Providers()` | Manage compute providers and their lifecycle |
| [ServiceInterface](services.md) | `client.Services()` | Expose and manage HTTP services inside sandboxes |
| [FileInterface](files.md) | `client.Files()` | Upload and download files to/from sandboxes |
| [HealthInterface](health.md) | `client.Health()` | Check gateway health status |
| [SSHInterface](ssh.md) | `client.SSH()` | Create SSH sessions and tunnels to sandboxes |
| [TCPInterface](tcp.md) | `client.TCP()` | Forward TCP connections to sandbox ports |
| [ConfigInterface](config.md) | `client.Config()` | Read and update sandbox and gateway configuration |
| [PolicyInterface](policy.md) | `client.Policy()` | Manage draft policy recommendations |
### Convenience Packages
| Package | Entry Point | Description |
|---------|-------------|-------------|
| [gateway](gateway.md) | `gateway.NewClient(name)` | Read CLI gateway configs and auto-wire clients |
### Provider Sub-Interfaces
These are accessed through `client.Providers()`:
| Interface | Accessor | Description |
|-----------|----------|-------------|
| [ProfileInterface](profiles.md) | `client.Providers().Profiles()` | Manage provider type profiles |
| [RefreshInterface](refresh.md) | `client.Providers().Refresh()` | Configure credential refresh strategies |
## Interfaces
Each interface has a reference page with method signatures and usage examples:
- **[Sandboxes](sandboxes.md)**: Create sandboxes, wait for readiness, watch state changes, manage providers, retrieve logs.
- **[Sandbox Templates](sandbox-templates.md)**: Create reusable workload templates and launch sandboxes from them.
- **[Exec](exec.md)**: Execute commands with one-shot, streaming, or interactive modes.
- **[Providers](providers.md)**: Register and manage compute providers. Includes sub-clients for profiles and credential refresh.
- **[Services](services.md)**: Expose and manage HTTP services inside sandboxes.
- **[Files](files.md)**: Upload and download files to/from sandboxes.
- **[Health](health.md)**: Check gateway health status.
- **[SSH](ssh.md)**: Create SSH sessions and tunnels to sandboxes.
- **[TCP](tcp.md)**: Forward TCP connections to sandbox ports.
- **[Config](config.md)**: Read and update sandbox and gateway configuration.
- **[Policy](policy.md)**: Manage draft policy recommendations.
- **[Profiles](profiles.md)**: Manage provider type profiles (via `client.Providers().Profiles()`).
- **[Refresh](refresh.md)**: Configure credential refresh strategies (via `client.Providers().Refresh()`).
## Common Patterns
SDK methods follow these conventions:
- Network operations take `context.Context`; list constructors return a pager,
and each `NextPage` call accepts the request context
- Methods that can fail return `(result, error)`
- List methods accept variadic options and `ListAll` is the explicit exhaustive path
- Errors from the gateway carry a `StatusError` with a typed code (see [Error Handling](../error-handling.md))
-128
View File
@@ -1,128 +0,0 @@
# Policy
Accessor: `client.Policy()`
Manage network policies for sandboxes through a draft-based workflow. Policies
go through a draft, review, and approval cycle before being applied.
## GetDraft
Retrieve the current draft policy for a sandbox.
```go
draft, err := client.Policy().GetDraft(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
for _, chunk := range draft.Chunks {
fmt.Printf("Chunk %s: rule=%s, status=%s, confidence=%.1f\n",
chunk.ID, chunk.RuleName, chunk.Status, chunk.Confidence)
}
```
## ApproveAllDraftChunks
Approve all pending chunks in a single operation.
```go
result, err := client.Policy().ApproveAllDraftChunks(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Approved %d chunks (skipped %d), policy version: %d\n",
result.ChunksApproved, result.ChunksSkipped, result.PolicyVersion)
```
## GetStatus
Check the current policy enforcement status for a sandbox.
```go
status, err := client.Policy().GetStatus(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Active version: %d, revision status: %s\n",
status.ActiveVersion, status.Revision.Status)
```
## List
`List` returns a lazy pager over policy revisions for one sandbox. Use
`ListAll` to collect every page.
```go
revisions, err := client.Policy().ListAll(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
for _, rev := range revisions {
fmt.Printf("Version %d: %s (status: %s)\n",
rev.Version, rev.CreatedAt, rev.Status)
}
```
## RejectDraftChunk
Reject a specific draft chunk, providing a reason.
```go
err := client.Policy().RejectDraftChunk(ctx, "default", "my-sandbox", "chunk-abc", "Too permissive")
if err != nil {
log.Fatal(err)
}
```
## EditDraftChunk
Modify the proposed rule in a draft chunk before approval.
```go
err := client.Policy().EditDraftChunk(ctx, "default", "my-sandbox", "chunk-abc", &v1.NetworkPolicyRule{
Name: "allow-api",
Endpoints: []v1.PolicyNetworkEndpoint{{
Host: "api.example.com",
Port: 443,
Protocol: "tcp",
}},
})
if err != nil {
log.Fatal(err)
}
```
## Append allow or deny rules
Use `client.Config().Update` with `AddAllowRules` or `AddDenyRules` to append request matchers to an existing base-policy endpoint. Both operations require an `L7RuleTarget` naming the rule, host, every affected port, and every binary governed by that rule. The gateway rejects missing scope or a scope that differs from the current policy without applying the merge batch.
```go
result, err := client.Config().Update(ctx, "default", &v1.ConfigUpdate{
Name: "my-sandbox",
MergeOperations: []v1.PolicyMergeOperation{{
AddAllowRules: &v1.AddAllowRules{
Target: &v1.L7RuleTarget{
RuleName: "api",
Host: "api.example.com",
Ports: []uint32{443, 8443},
Binaries: []v1.PolicyNetworkBinary{
{Path: "/usr/bin/curl"},
{Path: "/usr/bin/wget"},
},
},
Rules: []v1.L7Rule{{
Allow: &v1.L7Allow{Method: "POST", Path: "/admin"},
}},
},
}},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Policy version: %d\n", result.Version)
```
This example explicitly permits both binaries to make the new request on both ports. For a rule that permits any binary, set `AnyBinary: true` and omit `Binaries`. Omitting both fields is invalid; the SDK never infers any-binary permission.
`Target.Path` selects the existing endpoint path and is separate from the appended request matcher's path. Leave it `nil` when the rule, host, and ports identify a unique endpoint. To choose an endpoint with a specific path, pass a pointer to that path; a pointer to an empty string selects an endpoint without a path selector. Use `AddDenyRules` with the same target shape and a `DenyRules` payload to append deny matchers.
See also: [Error Handling](../error-handling.md), [Testing](../testing.md)
-86
View File
@@ -1,86 +0,0 @@
# Profiles
Accessor: `client.Providers().Profiles()`
Manage provider profiles for AI model providers. Profiles define connection details,
credentials, and model mappings for providers like OpenAI, Anthropic, or custom endpoints.
## List
`List` returns a lazy pager over visible provider profiles. Use `ListAll` to
collect every page.
```go
profiles, err := client.Providers().Profiles().ListAll(ctx, "default")
if err != nil {
log.Fatal(err)
}
for _, p := range profiles {
fmt.Printf("Profile: %s (%s)\n", p.ID, p.DisplayName)
}
```
## Import
Import one or more provider profiles from configuration items.
```go
result, err := client.Providers().Profiles().Import(ctx, "default", []v1.ProfileImportItem{
{
Profile: v1.ProviderProfile{
DisplayName: "OpenAI",
Category: v1.ProfileCategoryInference,
},
Source: "manual",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Imported: %v\n", result.Imported)
```
## Update
Update a profile using optimistic concurrency control via the resource version.
```go
profile, err := client.Providers().Profiles().Get(ctx, "default", "profile-id")
if err != nil {
log.Fatal(err)
}
profile.DisplayName = "Updated Provider"
result, err := client.Providers().Profiles().Update(
ctx, "default",
profile.ID,
profile.ResourceVersion,
v1.ProfileImportItem{Profile: *profile, Source: "manual"},
)
if err != nil {
// See [Error Handling](../error-handling.md) for conflict errors
log.Fatal(err)
}
```
## Lint
Validate profile configurations without persisting them. Useful for pre-flight checks.
```go
items := []v1.ProfileImportItem{
{
Profile: v1.ProviderProfile{DisplayName: "Test"},
Source: "manual",
},
}
result, err := client.Providers().Profiles().Lint(ctx, "default", items)
if err != nil {
log.Fatal(err)
}
for _, d := range result.Diagnostics {
fmt.Printf("[%s] %s: %s\n", d.Severity, d.Field, d.Message)
}
```
See also: [Error Handling](../error-handling.md), [Testing](../testing.md)
-161
View File
@@ -1,161 +0,0 @@
# Providers
Accessor: `client.Providers()`
Register and manage compute providers (AI inference endpoints). Exposes
sub-clients for [Profiles](profiles.md) and [Refresh](refresh.md).
## Create
Register a new provider with the gateway.
```go
provider, err := client.Providers().Create(ctx, "default", &v1.Provider{
Name: "my-openai",
Type: "openai",
Spec: v1.ProviderSpec{
Credentials: map[string]string{
"api_key": "sk-...",
},
Config: map[string]string{
"base_url": "https://api.openai.com/v1",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Created provider:", provider.Name)
```
## Get
Fetch a provider by name.
```go
provider, err := client.Providers().Get(ctx, "default", "my-openai")
if err != nil {
log.Fatal(err)
}
fmt.Println("Provider type:", provider.Type)
```
## List
`List` returns a lazy pager over registered providers. `ListAll` follows every
continuation token; `PageSize` controls each request.
```go
// List all providers
providers, err := client.Providers().ListAll(ctx, "default")
if err != nil {
log.Fatal(err)
}
for _, p := range providers {
fmt.Println(p.Name, p.Type)
}
// With a smaller page size
providers, err = client.Providers().ListAll(ctx, "default", v1.ListOptions{
PageSize: 10,
})
// Platform Admin only: list across all workspaces
allProviders, err := client.Providers().ListAll(ctx, "", v1.ListOptions{
AllWorkspaces: true,
})
```
## Update
Update an existing provider's configuration or credentials.
```go
provider, err := client.Providers().Get(ctx, "default", "my-openai")
if err != nil {
log.Fatal(err)
}
provider.Spec.Credentials["api_key"] = "sk-new-key"
updated, err := client.Providers().Update(ctx, "default", provider)
if err != nil {
log.Fatal(err)
}
fmt.Println("Updated provider:", updated.Name)
```
## Delete
Remove a provider by name.
```go
deletion, err := client.Providers().Delete(ctx, "default", "my-openai")
if err != nil {
log.Fatal(err)
}
```
## Ensure
Create or update a provider in a single idempotent call. If a provider with the given name exists, it is updated; otherwise a new one is created. This is the recommended way to register providers because it avoids "already exists" errors when re-registering.
```go
provider, err := client.Providers().Ensure(ctx, "default", &v1.Provider{
Name: "my-openai",
Type: "openai",
Spec: v1.ProviderSpec{
Credentials: map[string]string{
"api_key": "sk-...",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Provider ready:", provider.Name)
```
Ensure is an SDK-level convenience. It calls `GetProvider` first, then either `CreateProvider` or `UpdateProvider` depending on whether the provider already exists.
## Sub-Clients
The `ProviderInterface` exposes two sub-client accessors for related operations. These are pure client-side accessors with no corresponding gRPC call.
### Profiles
`client.Providers().Profiles()` returns a [ProfileInterface](profiles.md) for managing provider type profiles. Profiles define templates and defaults for different provider types.
### Refresh
`client.Providers().Refresh()` returns a [RefreshInterface](refresh.md) for configuring credential refresh strategies. Use it to set up automatic credential rotation for providers with expiring credentials.
## Provider
The `Provider` type represents a registered compute provider.
| Field | Type | Description |
|-------------------|------------------------|--------------------------------------------|
| `ID` | string | Server-assigned unique identifier |
| `Name` | string | User-chosen name (unique per gateway) |
| `Type` | string | Provider type (e.g., `"openai"`, `"azure"`) |
| `CreatedAt` | time.Time | Timestamp of creation |
| `Labels` | map[string]string | Key-value metadata labels |
| `ResourceVersion` | uint64 | Optimistic concurrency version |
| `Spec` | ProviderSpec | Configuration and credentials |
## ProviderSpec
`ProviderSpec` holds provider-specific configuration and credentials.
| Field | Type | Description |
|------------------------|---------------------------|-------------------------------------------------|
| `Credentials` | map[string]string | Authentication credentials (e.g., API keys) |
| `Config` | map[string]string | Provider-specific configuration values |
| `CredentialExpiresAt` | map[string]time.Time | Expiration timestamps for credentials |
The curated Go API uses a zero `time.Time` value to clear an expiration during
an update. Consequently, it cannot represent the protobuf minimum timestamp
(`0001-01-01T00:00:00Z`) in this map. Use the raw protobuf API if that exact
timestamp is required. Other pointer-based timestamp fields preserve it.
See also: [Profiles](profiles.md), [Refresh](refresh.md), [Error Handling](../error-handling.md), [Testing](../testing.md)
-57
View File
@@ -1,57 +0,0 @@
# Refresh
Accessor: `client.Providers().Refresh()`
Manage credential refresh schedules for provider profiles. Configure automatic
rotation of API keys and monitor refresh status.
## GetStatus
Check the refresh status for a specific provider credential.
```go
statuses, err := client.Providers().Refresh().GetStatus(ctx, "default", "openai", "default")
if err != nil {
log.Fatal(err)
}
for _, s := range statuses {
fmt.Printf("Key: %s, Last refresh: %s, Next: %s\n",
s.CredentialKey, s.LastRefreshAt, s.NextRefreshAt)
}
```
## Configure
Set up automatic credential refresh with a defined strategy and material.
```go
status, err := client.Providers().Refresh().Configure(ctx, "default", &v1.RefreshConfig{
Provider: "openai",
CredentialKey: "default",
Strategy: v1.RefreshStrategyOAuth2ClientCredentials,
Material: map[string]string{
"client_id": "my-client-id",
"client_secret": "my-client-secret",
"token_url": "https://oauth.example.com/token",
},
SecretMaterialKeys: []string{"client_secret"},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Refresh configured, next rotation: %s\n", status.NextRefreshAt)
```
## Rotate
Manually trigger an immediate credential rotation.
```go
status, err := client.Providers().Refresh().Rotate(ctx, "default", "openai", "default")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Rotated successfully at %s\n", status.LastRefreshAt)
```
See also: [Error Handling](../error-handling.md), [Profiles](profiles.md)
-127
View File
@@ -1,127 +0,0 @@
# Sandbox Templates
Accessor: `client.SandboxTemplates()`
Manage reusable, workspace-scoped sandbox workload templates. Templates own the
portable workload shape and optional driver-specific config. Sandbox creation
can reference a template by name while supplying only governance fields such as
providers or policy.
The Go SDK names the reusable resource `SandboxWorkloadTemplate` because
`SandboxTemplate` already represents the legacy inline compute template inside
`SandboxSpec`.
## Create
Creates a reusable template in a workspace.
```go
gpuCount := uint32(1)
template, err := client.SandboxTemplates().Create(ctx, "default", &v1.SandboxWorkloadTemplate{
Name: "gpu-kata",
Labels: map[string]string{
"team": "platform",
},
Spec: v1.SandboxWorkloadTemplateSpec{
Workload: &v1.SandboxWorkloadConfig{
Image: "nvcr.io/nvidia/openshell:latest",
Environment: map[string]string{
"NVIDIA_VISIBLE_DEVICES": "all",
},
Resources: &v1.SandboxResources{
CPU: "2",
Memory: "8Gi",
GPU: &v1.SandboxGPURequirements{Count: &gpuCount},
},
},
DriverConfig: map[string]any{
"kubernetes": map[string]any{
"pod": map[string]any{
"runtime_class_name": "kata",
},
},
},
DesiredServiceLevel: &v1.SandboxServiceLevel{
Startup: &v1.SandboxStartup{
ReadyWithin: 45 * time.Second,
MaxBurst: 2,
},
},
},
})
```
Set `GPU: &v1.SandboxGPURequirements{}` to request the active driver's default
GPU assignment without specifying a count.
## Create a Sandbox From a Template
Use `CreateSandboxFromTemplate` to create a sandbox from a named reusable
template without changing the legacy `Sandboxes()` interface.
```go
sb, err := client.CreateSandboxFromTemplate(
ctx,
"default",
"training-run",
"gpu-kata",
&v1.SandboxSpec{
Providers: []string{"openai"},
Policy: policy,
},
v1.WithLabels(map[string]string{"job": "training"}),
)
```
When creating from a template, the spec should only include governance fields:
`Providers`, `Policy`, `Command`, and `TTY`. Workload fields such as image,
environment, CPU, memory, GPU, and driver config come from the template.
## Get
Retrieves a template by name.
```go
template, err := client.SandboxTemplates().Get(ctx, "default", "gpu-kata")
fmt.Println(template.Spec.Workload.Image)
```
## List
`List` returns a lazy pager over matching templates in one workspace or across
all workspaces. Use `ListAll` to follow every continuation token automatically.
```go
templates, err := client.SandboxTemplates().ListAll(ctx, "default", v1.ListOptions{
PageSize: 50,
})
allTemplates, err := client.SandboxTemplates().ListAll(ctx, "", v1.ListOptions{
AllWorkspaces: true,
})
```
## Delete
Deletes a template by name. Existing sandboxes created from the template are not
deleted.
```go
deletion, err := client.SandboxTemplates().Delete(ctx, "default", "gpu-kata")
```
## Fake Client
The fake client includes the same template sub-client and can be pre-populated
for tests.
```go
client := fake.NewClient()
client.AddSandboxTemplate("default", &types.SandboxWorkloadTemplate{
Name: "gpu-kata",
Spec: types.SandboxWorkloadTemplateSpec{
Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"},
},
})
```
-304
View File
@@ -1,304 +0,0 @@
# Sandboxes
Accessor: `client.Sandboxes()`
Manage sandbox lifecycle: create, inspect, delete, attach/detach providers,
wait for readiness, watch state changes, and retrieve logs.
## Create
Creates a new sandbox with the given name and spec.
```go
sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{
Template: &v1.SandboxTemplate{
Image: "nvcr.io/nvidia/openshell:latest",
},
Providers: []string{"openai"},
}, v1.WithLabels(map[string]string{
"team": "platform",
}), v1.WithServiceExposures(v1.ServiceExposure{TargetPort: 8080}))
fmt.Println(sb.ServiceURLs[""])
```
Create-time service exposures register loopback HTTP endpoints with the
sandbox. Leave `Service` empty for the unnamed endpoint or set it to create a
named endpoint. Routing begins when the sandbox is ready.
`ServiceURLs` returns the routed URLs keyed by service name; the empty key is
the unnamed endpoint.
Set `GPU: true` to request the active driver's default GPU assignment. Set
`GPUCount` when the sandbox needs a specific GPU count; a non-nil `GPUCount`
also implies `GPU`.
## Create From Template
Creates a new sandbox from a reusable sandbox workload template. The template
provides workload fields such as image, environment, resources, and driver
config. The create request supplies governance fields such as providers,
policy, command, and TTY.
```go
sb, err := client.CreateSandboxFromTemplate(ctx,
"default",
"my-sandbox",
"gpu-kata",
&v1.SandboxSpec{
Providers: []string{"openai"},
Policy: policy,
},
v1.WithLabels(map[string]string{"team": "platform"}),
)
```
See [Sandbox Templates](sandbox-templates.md) for template CRUD.
## Get
Retrieves a sandbox by name.
```go
sb, err := client.Sandboxes().Get(ctx, "default", "my-sandbox")
fmt.Println(sb.Status.Phase) // "Ready", "Provisioning", etc.
```
### Tool server connections
`sb.Status.EndpointStatuses` shows each configured tool server endpoint and its last accepted network result in one record. A sandbox can be `Ready` while a tool server connection fails; endpoint results do not change lifecycle readiness. OpenShell currently observes endpoints configured for MCP over HTTP.
```go
for _, endpoint := range sb.Status.EndpointStatuses {
fmt.Printf("%s:%v%s: %s, reported %s\n",
endpoint.Host, endpoint.Ports, endpoint.Path,
endpoint.LastResult, endpoint.LastReportedAt)
}
```
`LastResult` is a typed `v1.EndpointResult`. For example, `v1.EndpointTransportFailed` means the transport failed before an HTTP response arrived. `v1.EndpointHTTPResponseReceived` means the server returned an HTTP status below 400; its body can still contain a tool error. Neither result establishes current availability.
OpenShell observes real traffic passively and does not expire idle observations. Keep `LastReportedAt` visible when displaying a result: it records when the gateway accepted the observation, not when the request happened. Retained evidence can be accepted after a reset. `v1.EndpointNoObservedExchange` has an empty timestamp and retains the configured address, so the endpoint remains identifiable before traffic is observed or after evidence is invalidated.
`LastFailure` explains a `v1.EndpointCredentialUnavailable` result when the supervisor classified the cause, and is `nil` otherwise. Each later observation replaces or clears it. `Code` and `Stage` come from closed sets, `Provider` and `CredentialKey` name the configured credential, and no field carries remote text. `RequestID` matches the `x-openshell-request-id` header the workload received, so you can correlate the refused request.
```go
for _, endpoint := range sb.Status.EndpointStatuses {
if f := endpoint.LastFailure; f != nil && f.Domain == v1.EndpointFailureDomainTokenGrant {
fmt.Printf("%s/%s: %s at %s (request %s)\n",
f.Provider, f.CredentialKey, f.Code, f.Stage, f.RequestID)
if f.RecoveryAction == v1.RefreshRecoveryActionReauthorize {
// Ask the user to replace the provider's OAuth grant.
}
}
}
```
### Token grant failures
`sb.Status.LastTokenGrantFailure` gives the latest classified grant refusal for any destination, including REST requests without an MCP inventory entry. It carries `DestinationHost`, `DestinationPort`, and the same bounded `EndpointFailure` as endpoint status.
```go
if observation := sb.Status.LastTokenGrantFailure; observation != nil && observation.Failure != nil {
f := observation.Failure
fmt.Printf("%s (port %d): %s, recovery %s, request %s\n",
observation.DestinationHost, observation.DestinationPort,
f.Code, f.RecoveryAction, f.RequestID)
}
```
Check `RequestID` against the refused response before acting: a newer failure can replace this record. A successful grant for the same destination, provider, and credential clears it; a failure before credential selection clears on the next successful grant to that destination. Policy, provider, and supervisor-session resets also clear it. `nil` means no retained cause. This is one latest observation, not a request history or a server health check.
## List
`List` constructs a lazy pager; `NextPage` fetches one page at a time.
`PageSize` controls each request, and `ListAll` explicitly exhausts the pager.
```go
// List all sandboxes
sandboxes, err := client.Sandboxes().ListAll(ctx, "default")
// Process one page at a time
pages, err := client.Sandboxes().List("default", v1.ListOptions{PageSize: 10})
page, err := pages.NextPage(ctx)
// With a page size and label filtering
sandboxes, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{
PageSize: 10,
LabelSelector: "team=platform",
})
// Platform Admin only: list across all workspaces
allSandboxes, err := client.Sandboxes().ListAll(ctx, "", v1.ListOptions{
AllWorkspaces: true,
})
```
## Delete
Deletes a sandbox by name.
```go
deletion, err := client.Sandboxes().Delete(ctx, "default", "my-sandbox", v1.DeleteOptions{AllowMissing: true})
```
Missing targets return `NotFound` unless `AllowMissing` is true. Inspect
`deletion.Outcome`: `DeletionAccepted` means cleanup is pending, while
`DeletionCompleted` and `DeletionAlreadyAbsent` establish logical completion.
Unknown values do not establish completion. `deletion.SandboxID` identifies the
original sandbox; do not confuse a same-name replacement with that target.
Allowing absence does not make a retry safe if names can be reused.
## AttachProvider
Attaches a provider to a sandbox. The `expectedResourceVersion` enables optimistic concurrency control: pass the sandbox's current `ResourceVersion` to ensure no other client has modified it since your last read.
```go
sb, _ := client.Sandboxes().Get(ctx, "default", "my-sandbox")
result, err := client.Sandboxes().AttachProvider(ctx,
"default", "my-sandbox",
"openai",
sb.ResourceVersion,
)
fmt.Println(result.Attached) // true if newly attached
```
## DetachProvider
Detaches a provider from a sandbox. Uses the same optimistic concurrency pattern as `AttachProvider`.
```go
sb, _ := client.Sandboxes().Get(ctx, "default", "my-sandbox")
result, err := client.Sandboxes().DetachProvider(ctx,
"default", "my-sandbox",
"openai",
sb.ResourceVersion,
)
fmt.Println(result.Detached) // true if actually detached
```
## ListProviders
Lists all providers currently attached to a sandbox.
```go
providers, err := client.Sandboxes().ListProviders(ctx, "default", "my-sandbox")
for _, p := range providers {
fmt.Printf("provider: %s (type: %s)\n", p.Name, p.Type)
}
```
## WaitReady
Blocks until the sandbox reaches the `Ready` phase, returning the final sandbox state. Under the hood, WaitReady polls via `Get` at a configurable interval (default 500ms). Use context cancellation or deadlines to set a timeout.
If the sandbox enters the `Error` phase, WaitReady returns immediately with a `StatusError`.
```go
// Wait with a 30-second timeout
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
sb, err := client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
fmt.Println(sb.Status.Phase) // "Ready"
// Custom poll interval
sb, err := client.Sandboxes().WaitReady(ctx, "default", "my-sandbox", v1.WaitOptions{
PollInterval: 2 * time.Second,
})
```
There is no dedicated WaitReady RPC. The SDK implements this by polling `GetSandbox` until the sandbox phase is `Ready` or `Error`.
## Watch
Opens a server-streaming connection to observe sandbox state changes in real time. Returns a `WatchInterface[*Sandbox]` that delivers events through a channel.
The `WatchInterface[T]` provides:
- `ResultChan() <-chan Event[T]` returns the channel of events
- `Stop()` closes the stream and the channel
Each `Event[T]` carries:
- `Type`: one of `EventAdded`, `EventModified`, `EventDeleted`, or `EventError`
- `Object`: the `*Sandbox` at that point in time (`nil` for `EventError`)
```go
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
defer watcher.Stop()
for event := range watcher.ResultChan() {
switch event.Type {
case v1.EventModified:
fmt.Printf("phase: %s\n", event.Object.Status.Phase)
case v1.EventDeleted:
fmt.Println("sandbox deleted")
return
case v1.EventError:
fmt.Println("watch error")
return
}
}
```
Setting `StopOnTerminal: true` causes the watcher to close automatically once the sandbox reaches a terminal phase (`Ready` or `Error`). This is useful for provisioning flows where you only care about the outcome.
```go
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox", v1.WatchOptions{
StopOnTerminal: true,
})
if err != nil {
log.Fatal(err)
}
for event := range watcher.ResultChan() {
fmt.Printf("phase: %s\n", event.Object.Status.Phase)
}
// Channel closes after Ready or Error
```
## GetLogs
Retrieves log entries from a sandbox. The sandbox is looked up by name (the SDK resolves the name to an internal ID automatically). Use functional options to filter results.
**Available options:**
| Option | Description |
|--------|-------------|
| `WithLogLines(n uint32)` | Maximum number of log lines to return |
| `WithLogSince(t time.Time)` | Only include entries at or after this time |
| `WithLogSources(sources ...string)` | Filter by source (e.g., `"gateway"`, `"sandbox"`) |
| `WithLogMinLevel(level string)` | Minimum log level (e.g., `"WARN"`, `"ERROR"`) |
```go
// Get the last 50 log lines
result, err := client.Sandboxes().GetLogs(ctx, "default", "my-sandbox",
v1.WithLogLines(50),
)
for _, line := range result.Lines {
fmt.Printf("[%s] %s: %s\n", line.Level, line.Source, line.Message)
}
// Filter by source and level since a specific time
result, err := client.Sandboxes().GetLogs(ctx, "default", "my-sandbox",
v1.WithLogSources("gateway"),
v1.WithLogMinLevel("WARN"),
v1.WithLogSince(time.Now().Add(-1*time.Hour)),
)
```
The `LogResult` contains:
- `Lines []LogLine`: log entries in chronological order
- `BufferTotal uint32`: total number of lines available in the server's buffer
Each `LogLine` has `Timestamp`, `Level`, `Target`, `Message`, `Source`, and `Fields` (structured key-value data).
See also: [Error Handling](../error-handling.md), [Testing](../testing.md)
-53
View File
@@ -1,53 +0,0 @@
# Services
Accessor: `client.Services()`
Expose, inspect, and manage network services attached to sandboxes. Services provide
external access to ports running inside a sandbox via managed endpoints.
## Expose
Expose a port from a sandbox as a named service endpoint. Set `domain` to `true`
to assign a DNS-routable domain name to the service.
```go
endpoint, err := client.Services().Expose(ctx, "default", "my-sandbox", "web", 8080, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Service available at: %s\n", endpoint.URL)
```
## List
`List` returns a lazy pager over exposed services. Use `ListAll` to collect
every page.
```go
services, err := client.Services().ListAll(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
for _, svc := range services {
fmt.Printf(" %s -> port %d (%s)\n", svc.Name, svc.TargetPort, svc.URL)
}
// Platform Admin only: list services across all workspaces
allServices, err := client.Services().ListAll(ctx, "", "", v1.ListOptions{
AllWorkspaces: true,
})
```
## Delete
Remove an exposed service. The underlying sandbox port remains accessible
internally but is no longer reachable through the service endpoint.
```go
deletion, err := client.Services().Delete(ctx, "default", "my-sandbox", "web")
if err != nil {
log.Fatal(err)
}
```
See also: [Error Handling](../error-handling.md), [Testing](../testing.md)
-55
View File
@@ -1,55 +0,0 @@
# SSH
Accessor: `client.SSH()`
Create and manage SSH sessions for sandboxes. Supports direct SSH access and
TCP tunneling through SSH connections.
## CreateSession
Create a new SSH session for a sandbox. Returns connection details including
host, port, and authentication credentials.
```go
session, err := client.SSH().CreateSession(ctx, "default", "sandbox-123")
if err != nil {
log.Fatal(err)
}
fmt.Printf("SSH via %s://%s:%d\n", session.GatewayScheme, session.GatewayHost, session.GatewayPort)
```
## RevokeSession
Revoke an active SSH session, immediately terminating any connections using it.
```go
deletion, err := client.SSH().RevokeSession(ctx, "default", session.Token)
if err != nil {
log.Fatal(err)
}
if deletion.Outcome == v1.DeletionCompleted {
fmt.Println("Session revoked")
}
```
## Tunnel
Create an SSH tunnel that provides a bidirectional stream to a port inside a
sandbox. This combines SSH session creation with TCP forwarding into a single
operation, returning an `io.ReadWriteCloser` for the tunnel.
```go
tunnel, err := client.SSH().Tunnel(ctx, "default", "my-sandbox", 8080)
if err != nil {
log.Fatal(err)
}
defer tunnel.Close()
// Use the tunnel as a regular io.ReadWriteCloser
_, err = tunnel.Write([]byte("GET / HTTP/1.0\r\n\r\n"))
if err != nil {
log.Fatal(err)
}
```
See also: [TCP Forwarding](tcp.md), [Error Handling](../error-handling.md)
-60
View File
@@ -1,60 +0,0 @@
# TCP
Accessor: `client.TCP()`
Forward TCP connections to sandbox ports using bidirectional gRPC streaming.
## Forward
Open a bidirectional TCP forwarding stream to a specific port inside a sandbox.
Returns an `io.ReadWriteCloser` that proxies data between the caller and the
sandbox port over gRPC streaming.
```go
conn, err := client.TCP().Forward(ctx, "default", "sandbox-123", 8080)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Exchange protocol bytes with the service through the tunnel.
_, err = conn.Write([]byte("ping\n"))
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Response: %s\n", buf[:n])
```
## Listen
Bind a local address that forwards every connection to a sandbox port. The
returned `ForwardListener` owns its accept loop and all bridge goroutines; it is
a lifecycle handle with `Addr` and `Close`, not a `net.Listener`.
```go
forward, err := client.TCP().Listen(ctx, "default", "sandbox-123", 8080, 0)
if err != nil {
log.Fatal(err)
}
defer forward.Close()
conn, err := net.Dial("tcp", forward.Addr().String())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
```
Do not pass `ForwardListener` to `http.Serve`. Dial its address with the client
for the protocol exposed by the sandbox service.
TCP forwarding is lower-level than [SSH tunneling](ssh.md). Use TCP forwarding
when you need direct port access without SSH session overhead.
See also: [SSH Tunneling](ssh.md), [Error Handling](../error-handling.md)
-139
View File
@@ -1,139 +0,0 @@
# Architecture
This page explains how the OpenShell Go SDK is structured internally. Understanding the design helps you navigate the API surface and write idiomatic code.
## Client Hierarchy
The SDK follows the Kubernetes client-go sub-client pattern. A single `Client` provides typed accessors for each API domain:
```text
Client
├── Sandboxes() → SandboxInterface
├── Exec() → ExecInterface
├── Providers() → ProviderInterface
│ ├── Profiles() → ProfileInterface
│ └── Refresh() → RefreshInterface
├── Services() → ServiceInterface
├── Files() → FileInterface
├── Health() → HealthInterface
├── SSH() → SSHInterface
├── TCP() → TCPInterface
├── Config() → ConfigInterface
└── Policy() → PolicyInterface
```
Each accessor returns an interface. You work with the interface, not the concrete implementation. This makes the sub-clients easy to mock and test.
## Creating a Client
All interaction starts with `NewClient`:
```go
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: v1.StaticToken("my-token"),
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
```
The `Config` struct controls:
| Field | Purpose |
|-------|---------|
| `Address` | Gateway host and port |
| `Auth` | Authentication provider (`StaticToken`, `NoAuth`, or custom) |
| `TLS` | TLS settings (CA cert, skip verify, client certs) |
| `Retry` | Retry policy for transient failures |
## Proto Isolation
The SDK never exposes protobuf-generated types in its public API. Instead, it defines its own Go types (in `openshell/v1/`) and converts to/from proto at the gRPC boundary.
This means:
- Your code imports `openshell/v1`, not `proto/openshellv1`
- You work with plain Go structs, not proto messages
- Proto schema changes in upstream OpenShell do not break your code (the SDK adapts internally)
- You can use standard Go patterns (json.Marshal, fmt.Sprintf, reflect) on SDK types without proto constraints
The conversion layer lives in `openshell/v1/internal/converter/` and is not part of the public API.
## Sub-Client Pattern
Each sub-client groups methods for a specific API domain. For example, `SandboxInterface` provides `Create`, `Get`, `List`, `Delete`, `WaitReady`, `Watch`, and more.
Sub-clients are cheap to access. They are created once when the `Client` is initialized and reuse the same underlying gRPC connection:
```go
// These return the same sub-client instance every time
sandboxes := client.Sandboxes()
exec := client.Exec()
```
Some sub-clients have their own sub-clients. `ProviderInterface` exposes `Profiles()` and `Refresh()`:
```go
profiles, err := client.Providers().Profiles().ListAll(ctx, "default")
status, err := client.Providers().Refresh().GetStatus(ctx, "default", "openai", "api-key")
```
## Functional Options
Many SDK entry points accept variadic option parameters that configure the call:
```go
auth, err := v1.RefreshableToken(tokenSource,
v1.WithLeeway(30*time.Second),
v1.WithLogger(logger),
)
```
Options are applied in the order they are passed, so later options override earlier ones when they set the same field. **Nil options are silently ignored at every entry point.** You can safely build option lists conditionally without filtering out nil entries:
```go
opts := []v1.RefreshOption{
v1.WithLeeway(30 * time.Second),
maybeLogger(), // may return nil
}
auth, err := v1.RefreshableToken(tokenSource, opts...)
```
## gRPC Layer
Underneath, the SDK communicates with the OpenShell gateway over gRPC. The single `OpenShell` service in `proto/openshell.proto` defines all RPCs. The SDK maps each interface method to one or more RPCs:
| Pattern | Example |
|---------|---------|
| Unary RPC | `Create`, `Get`, `Delete` |
| Server-streaming RPC | `Watch`, `Stream`, `GetLogs` |
| Client-streaming RPC | File uploads |
| Bidirectional streaming | `Interactive`, `Forward` |
The gRPC connection is managed by the `Client`. Calling `client.Close()` cleanly shuts down all active streams and the underlying connection.
## Error Model
All SDK methods return standard Go errors. Errors from the gateway carry a `StatusError` with a typed error code. Use the `Is*` functions to classify errors:
```go
_, err := client.Sandboxes().Get(ctx, "default", "missing")
if v1.IsNotFound(err) {
// sandbox does not exist
}
```
See the [Error Handling](error-handling.md) guide for the complete list of error checks and retry patterns.
## Fake Client
For testing, the SDK provides `openshell/v1/fake` with an in-memory implementation of `ClientInterface`. The fake client supports fixture seeding, watch events, and health simulation:
```go
fc := fake.NewClient()
fc.AddSandbox(&v1.Sandbox{Name: "test-sb", Status: v1.SandboxStatus{Phase: v1.SandboxReady}})
```
See the [Testing](testing.md) guide for complete examples.
-202
View File
@@ -1,202 +0,0 @@
# Error Handling
Gateway status failures and SDK validation failures use `*v1.StatusError`, which carries a machine-readable `Code` and a human-readable `Message`. Local I/O, transport setup, and sentinel errors may use other Go error types. The SDK provides predicate functions for classified status errors.
## StatusError
When an operation returns a classified status error, inspect it directly or use the convenience predicates below. Use `errors.Is` for documented sentinel errors such as `ErrTransportNotAvailable`.
```go
var se *v1.StatusError
if errors.As(err, &se) {
fmt.Printf("code: %s, message: %s\n", se.Code, se.Message)
// se.ErrorInfo and se.FieldViolations contain optional structured details.
}
```
| Field | Type | Description |
|-----------|-------------------|--------------------------------------|
| `Code` | `ErrorCode` | Machine-readable error classification |
| `Message` | `string` | Human-readable error description |
| `GRPCCode` | `int32` | Original gRPC code before SDK classification |
| `FieldViolations` | `[]FieldViolation` | Rejected request fields and descriptions |
| `ErrorInfo` | `*ErrorInfo` | Server reason, domain, and metadata |
| `RetryDelay` | `*time.Duration` | Suggested minimum delay for an otherwise safe retry |
| `Cause` | `error` | Original gRPC error, including unknown details |
Use `status.FromError(err)` to inspect the complete gRPC status through the SDK's
error wrapper. A delay does not prove that a timed-out mutation was not applied.
## Predicate Functions
Use these top-level functions to check error types. They work with wrapped errors via `errors.As`.
| Function | ErrorCode | When it fires |
|----------------------|----------------------|-------------------------------------------------|
| `v1.IsNotFound` | `ErrorNotFound` | Resource does not exist (sandbox, provider, etc.) |
| `v1.IsAlreadyExists` | `ErrorAlreadyExists` | Resource with that name already exists |
| `v1.IsConflict` | `ErrorConflict` | Optimistic concurrency violation or invalid state transition |
| `v1.IsUnavailable` | `ErrorUnavailable` | Gateway is unreachable or client is closed |
| `v1.IsUnimplemented` | `ErrorUnimplemented` | Operation not supported by the gateway version |
| `v1.IsPermissionDenied` | `ErrorPermissionDenied` | Insufficient permissions |
| `v1.IsInvalidArgument` | `ErrorInvalidArgument` | Invalid request parameters |
| `v1.IsDeadlineExceeded` | `ErrorDeadlineExceeded` | Operation timed out |
| `v1.IsCancelled` | `ErrorCancelled` | Operation was cancelled (context cancellation) |
For `ErrorInternal` (server-side errors), no convenience predicate exists. Match it directly via the `Code` field:
```go
var se *v1.StatusError
if errors.As(err, &se) && se.Code == v1.ErrorInternal {
fmt.Println("Internal server error:", se.Message)
}
```
## Common Patterns
### Not Found
Handle missing resources gracefully:
```go
sb, err := client.Sandboxes().Get(ctx, "default", "my-sandbox")
if v1.IsNotFound(err) {
fmt.Println("Sandbox does not exist, creating...")
sb, err = client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
}
if err != nil {
log.Fatal(err)
}
```
### Already Exists
Guard against duplicate creation:
```go
_, err := client.Providers().Create(ctx, "default", &v1.Provider{
Name: "openai",
Type: "openai",
})
if v1.IsAlreadyExists(err) {
fmt.Println("Provider already registered, skipping")
} else if err != nil {
log.Fatal(err)
}
```
Alternatively, use `Ensure` for idempotent registration:
```go
// Create-or-update in a single call
provider, err := client.Providers().Ensure(ctx, "default", &v1.Provider{
Name: "openai",
Type: "openai",
})
```
### Conflict (Optimistic Concurrency)
When two clients modify the same resource concurrently, the second write receives a conflict error. Retry by re-reading the resource:
```go
sb, _ := client.Sandboxes().Get(ctx, "default", "my-sandbox")
result, err := client.Sandboxes().AttachProvider(ctx,
"default", "my-sandbox", "openai", sb.ResourceVersion,
)
if v1.IsConflict(err) {
// Another client modified the sandbox — re-read and retry
sb, _ = client.Sandboxes().Get(ctx, "default", "my-sandbox")
result, err = client.Sandboxes().AttachProvider(ctx,
"default", "my-sandbox", "openai", sb.ResourceVersion,
)
}
if err != nil {
log.Fatal(err)
}
```
### Unavailable
Handle gateway connectivity issues:
```go
sb, err := client.Sandboxes().Get(ctx, "default", "my-sandbox")
if v1.IsUnavailable(err) {
fmt.Println("Gateway is not reachable, check connection")
// Implement retry with backoff
}
```
### Unimplemented
Detect unsupported operations gracefully:
```go
_, err := client.Sandboxes().GetLogs(ctx, "default", "my-sandbox")
if v1.IsUnimplemented(err) {
fmt.Println("Log retrieval not supported by this gateway version")
}
```
## Retry with Backoff
For transient errors like `Unavailable` or `DeadlineExceeded`, use exponential backoff only when the operation is idempotent or carries an idempotency/concurrency token. A timeout does not prove that a mutating request was not applied.
```go
func withRetry(ctx context.Context, maxAttempts int, fn func() error) error {
backoff := 100 * time.Millisecond
for attempt := 0; attempt < maxAttempts; attempt++ {
err := fn()
if err == nil {
return nil
}
// Only retry transient errors
if !v1.IsUnavailable(err) && !v1.IsDeadlineExceeded(err) {
return err
}
// Add jitter to prevent thundering herd after outages
jitter := time.Duration(rand.Int63n(int64(backoff) / 2))
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoff + jitter):
backoff *= 2
}
}
return fmt.Errorf("exhausted %d retry attempts", maxAttempts)
}
```
Usage:
```go
var sb *v1.Sandbox
err := withRetry(ctx, 3, func() error {
var e error
sb, e = client.Sandboxes().Get(ctx, "default", "my-sandbox")
return e
})
```
## Context Cancellation
All SDK methods accept a `context.Context`. Use context deadlines and cancellation to control timeouts:
```go
// 5-second timeout for a single call
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
sb, err := client.Sandboxes().Get(ctx, "default", "my-sandbox")
if v1.IsDeadlineExceeded(err) {
fmt.Println("Request timed out")
}
```
See also: [Testing](testing.md) for how the fake client returns the same error codes.
-123
View File
@@ -1,123 +0,0 @@
# Quick Start
This guide walks you through installing the OpenShell Go SDK, connecting to a gateway, creating a sandbox, running a command, and cleaning up. You should be up and running in under 5 minutes.
## Prerequisites
- Go 1.25.13 or later
- Access to an OpenShell gateway (address and authentication token)
## Installation
Add the SDK to your Go module:
```bash
go get github.com/NVIDIA/OpenShell/sdk/go@latest
```
## Connect to the Gateway
Create a client by providing the gateway address and authentication credentials:
```go
package main
import (
"context"
"fmt"
"log"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
)
func main() {
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: v1.StaticToken("my-token"),
})
if err != nil {
log.Fatal(err)
}
defer client.Close()
```
For production use, load the token from an environment variable instead of hardcoding it:
`v1.StaticToken(os.Getenv("OPENSHELL_TOKEN"))`
The `Config` struct accepts optional fields for TLS configuration and retry policies. For development against a local gateway without TLS, use `v1.NoAuth()` and set TLS to skip verification.
## Check Gateway Health
Verify the gateway is reachable:
```go
ctx := context.Background()
health, err := client.Health().Check(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Gateway healthy: %v\n", health.Healthy)
```
## Create a Sandbox
Create a sandbox with a Python image:
```go
sandbox, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{
Template: &v1.SandboxTemplate{Image: "python:3.12"},
Environment: map[string]string{"LANG": "en_US.UTF-8"},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created sandbox: %s\n", sandbox.Name)
```
## Wait for the Sandbox to be Ready
Sandboxes take a moment to provision. Use `WaitReady` to block until the sandbox is ready to accept commands:
```go
sandbox, err = client.Sandboxes().WaitReady(ctx, "default", sandbox.Name)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sandbox is ready (phase: %s)\n", sandbox.Status.Phase)
```
## Run a Command
Execute a command inside the sandbox:
```go
result, err := client.Exec().Run(ctx, "default", sandbox.Name, []string{"echo", "hello from OpenShell"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Output: %s", result.Stdout)
fmt.Printf("Exit code: %d\n", result.ExitCode)
```
For long-running commands, use `Stream` to receive output incrementally, or `Interactive` for terminal-like sessions.
## Clean Up
Delete the sandbox when you are done:
```go
deletion, err := client.Sandboxes().Delete(ctx, "default", sandbox.Name)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deletion outcome: %v\n", deletion.Outcome)
}
```
## Next Steps
- Browse the [API Overview](api/overview.md) to see all available interfaces
- Learn about [Error Handling](error-handling.md) for production code
- Set up [Testing](testing.md) with the fake client for your test suites
- Explore the [Architecture](architecture.md) to understand the SDK design
-34
View File
@@ -1,34 +0,0 @@
# OpenShell Go SDK
The OpenShell Go SDK provides an idiomatic Go client for the OpenShell gateway API. It wraps the underlying gRPC protocol behind typed interfaces, making it straightforward to manage sandboxes, execute commands, handle providers, and more.
## Key Features
- **Sub-client pattern**: A single `Client` provides typed accessors for each API domain (Sandboxes, SandboxTemplates, Exec, Providers, Files, Health, SSH, TCP, Config, Policy, Services)
- **Clean types**: SDK types are self-contained, so your code works with idiomatic Go types without extra dependencies
- **Fake client for testing**: An in-memory implementation of the full `ClientInterface` for testing without a live gateway
- **Watch and streaming**: First-class support for watching sandbox state changes and streaming command output
- **Typed error handling**: Functions like `IsNotFound`, `IsAlreadyExists`, and `IsConflict` for precise error classification
## Where to Start
If you are new to the SDK, the [Quick Start](getting-started.md) guide walks you through installation, connecting to a gateway, creating your first sandbox, running a command, and cleaning up.
For a deeper understanding of how the SDK is structured, see the [Architecture](architecture.md) overview.
## API Reference
Every SDK interface has a dedicated reference page with method signatures and code examples.
Browse the full [API Overview](api/overview.md) to see all 13 interfaces at a glance.
## Guides
- [Error Handling](error-handling.md): StatusError, typed error checks, retry patterns
- [Testing](testing.md): Fake client usage, fixture seeding, watch event testing
## Related Projects
- [**OpenShell**](https://github.com/NVIDIA/OpenShell) (by NVIDIA): The upstream project that defines the gateway API and sandbox runtime this SDK wraps.
- [**openshell-sdk-go**](https://github.com/NVIDIA/OpenShell/sdk/go): This SDK's source repository on GitHub.
- [**pkg.go.dev**](https://pkg.go.dev/github.com/NVIDIA/OpenShell/sdk/go/openshell/v1): Go package documentation with type signatures and godoc.
-184
View File
@@ -1,184 +0,0 @@
# Testing
The SDK ships a `fake` package that provides an in-memory implementation of all client interfaces. Use it in your test suites to exercise SDK interactions without a real gateway.
```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
```
The fake client follows the same pattern as `k8s.io/client-go/kubernetes/fake`: it maintains in-memory stores, supports watch event broadcasting, and returns the same `StatusError` codes as the real client.
## Creating a Fake Client
```go
func TestMyOperator(t *testing.T) {
client := fake.NewClient()
defer client.Close()
ctx := context.Background()
// Use client exactly like the real SDK
sb, err := client.Sandboxes().Create(ctx, "default", "test-sandbox", &v1.SandboxSpec{})
require.NoError(t, err)
assert.Equal(t, "Provisioning", string(sb.Status.Phase))
}
```
The returned `*fake.Client` satisfies `v1.ClientInterface`, so you can pass it anywhere your code accepts the interface.
## Fixture Seeding
Pre-populate the fake client with existing resources before your test runs. Seeded resources are available immediately via `Get` and `List` without going through `Create`.
### AddSandbox
```go
client := fake.NewClient()
// Pre-seed a sandbox that already exists
client.AddSandbox(&types.Sandbox{
Name: "existing-sandbox",
Status: types.SandboxStatus{
Phase: types.SandboxReady,
},
ResourceVersion: 5,
})
// Now Get returns it immediately
sb, err := client.Sandboxes().Get(ctx, "default", "existing-sandbox")
// sb.Status.Phase == "Ready"
```
### AddProvider
```go
client := fake.NewClient()
// Pre-seed a provider
client.AddProvider(&types.Provider{
Name: "my-openai",
Type: "openai",
Spec: types.ProviderSpec{
Credentials: map[string]string{
"api_key": "sk-test-key",
},
},
})
// List returns the seeded provider
providers, _ := client.Providers().ListAll(ctx, "default")
// len(providers) == 1
```
## Sandbox Lifecycle
The fake client implements the full sandbox lifecycle. Created sandboxes start in the `Provisioning` phase. Calling `WaitReady` transitions them to `Ready` synchronously.
```go
client := fake.NewClient()
ctx := context.Background()
// Create starts in Provisioning
sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
assert.Equal(t, types.SandboxProvisioning, sb.Status.Phase)
// WaitReady transitions to Ready (synchronous in fake)
sb, err = client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
assert.Equal(t, types.SandboxReady, sb.Status.Phase)
// Delete removes the sandbox
_, err = client.Sandboxes().Delete(ctx, "default", "my-sandbox")
assert.NoError(t, err)
// Get after delete returns NotFound
_, err = client.Sandboxes().Get(ctx, "default", "my-sandbox")
assert.True(t, v1.IsNotFound(err))
```
## Watch Events
The fake client broadcasts watch events when resources change. Use watchers to test event-driven code.
```go
client := fake.NewClient()
ctx := context.Background()
// Start watching before making changes
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox")
require.NoError(t, err)
defer watcher.Stop()
// Create a sandbox — triggers an ADDED event
client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
// Read the event from the channel
event := <-watcher.ResultChan()
assert.Equal(t, types.EventAdded, event.Type)
assert.Equal(t, "my-sandbox", event.Object.Name)
```
### StopOnTerminal
Setting `StopOnTerminal: true` causes the watcher to close automatically when the sandbox reaches a terminal phase (`Ready` or `Error`).
```go
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox", v1.WatchOptions{
StopOnTerminal: true,
})
require.NoError(t, err)
// Create and transition to Ready
client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
// Drain events — channel closes after the Ready event
var events []types.Event[*types.Sandbox]
for ev := range watcher.ResultChan() {
events = append(events, ev)
}
// Channel is now closed
```
## Health Simulation
Use `WithHealthResult` to simulate an unhealthy or degraded gateway.
```go
// Default: healthy gateway
client := fake.NewClient()
result, _ := client.Health().Check(ctx)
// result.Healthy == true, result.Version == "fake"
// Simulate unhealthy gateway
client = fake.NewClient(fake.WithHealthResult(&types.HealthResult{
Healthy: false,
Version: "1.2.3",
}))
result, _ = client.Health().Check(ctx)
// result.Healthy == false
```
## Error Behavior
The fake client returns the same `StatusError` codes as the real client:
| Scenario | Error Code |
|----------|------------|
| `Get` for a non-existent resource | `ErrorNotFound` |
| `Create` with a duplicate name | `ErrorAlreadyExists` |
| Any call after `Close()` | `ErrorUnavailable` |
| Unimplemented operations (e.g., `GetLogs`) | `ErrorUnimplemented` |
```go
client := fake.NewClient()
client.Close()
_, err := client.Sandboxes().Get(ctx, "default", "anything")
assert.True(t, v1.IsUnavailable(err))
```
## Concurrency
All fake client operations are safe for concurrent use. The internal stores use mutex-based synchronization. This means you can safely use the fake client from multiple goroutines in parallel tests.
See also: [Error Handling](error-handling.md), [API Reference](api/overview.md)
-184
View File
@@ -1,184 +0,0 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/* OpenShell Go SDK - Custom Typography
*
* Font: Inter from Google Fonts CDN
* Base size: 18px, line-height: 1.7
* Max content width: 800px
*/
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
:root {
--content-max-width: none;
}
/* Base typography */
body,
.content,
.sidebar {
font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
.content {
font-size: 18px;
line-height: 1.7;
max-width: none;
padding: 0 4em;
}
/* Headings */
.content h1 {
font-size: 2em;
font-weight: 700;
margin-top: 1.5em;
margin-bottom: 0.5em;
line-height: 1.2;
}
.content h2 {
font-size: 1.5em;
font-weight: 600;
margin-top: 1.8em;
margin-bottom: 0.4em;
line-height: 1.3;
border-bottom: 1px solid var(--sidebar-separator);
padding-bottom: 0.3em;
}
.content h3 {
font-size: 1.25em;
font-weight: 600;
margin-top: 1.5em;
margin-bottom: 0.3em;
line-height: 1.4;
}
.content h4 {
font-size: 1.1em;
font-weight: 600;
margin-top: 1.2em;
margin-bottom: 0.3em;
}
/* Paragraphs */
.content p {
margin-bottom: 1em;
}
/* Code blocks */
.content pre {
font-size: 15px;
line-height: 1.5;
padding: 0;
border-radius: 6px;
margin: 1em 0;
overflow-x: auto;
max-width: 100%;
}
.content code {
font-size: 0.875em;
padding: 0.15em 0.35em;
border-radius: 3px;
}
.content pre > code,
.content pre > code.hljs {
font-size: 16px;
padding: 1em 1em !important;
display: block;
}
/* Tables */
.content table {
font-size: 16px;
width: 100%;
margin: 1em 0;
border-collapse: collapse;
}
.content th {
font-weight: 600;
text-align: left;
padding: 0.6em 1em;
border-bottom: 2px solid var(--sidebar-separator);
}
.content td {
padding: 0.5em 1em;
border-bottom: 1px solid var(--sidebar-separator);
}
/* Sidebar adjustments */
.sidebar .sidebar-scrollbox {
font-size: 17px;
}
/* Hide chapter numbers (mdBook 0.5.x uses <strong> inside links) */
.sidebar ol.chapter li.chapter-item a > strong {
display: none;
}
/* Main sidebar items */
.sidebar ol.chapter li.chapter-item {
line-height: 1.7;
margin: 0;
padding: 0;
padding-left: 1em;
}
/* On-this-page sub-navigation */
.sidebar .on-this-page li {
line-height: 1.8;
margin: 0;
padding: 0;
}
.sidebar .on-this-page {
margin-top: 0.3em;
}
.sidebar .on-this-page ol.section {
padding-left: 1em;
margin: 0;
}
/* Section headers: clear visual break */
.sidebar ol.chapter li.part-title {
margin-top: 1.2em;
margin-bottom: 0.4em;
padding-bottom: 0.2em;
font-weight: 700;
font-size: 1.15em;
letter-spacing: 0.03em;
opacity: 0.9;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
/* Lists */
.content li {
margin-bottom: 0.3em;
}
/* Navigation arrows: smaller, less intrusive */
.nav-chapters {
font-size: 2em;
max-width: 40px;
opacity: 0.4;
}
.nav-chapters:hover {
opacity: 0.8;
}
/* Blockquotes */
.content blockquote {
margin: 1em 0;
padding: 0.5em 1.2em;
border-left: 4px solid var(--sidebar-separator);
font-style: normal;
}
-23
View File
@@ -1,23 +0,0 @@
// Deprecated: this module moved to github.com/ai-openshell/sdk-go.
module github.com/NVIDIA/OpenShell/sdk/go
go 1.25.13
require (
github.com/coder/websocket v1.8.15
github.com/stretchr/testify v1.11.1
golang.org/x/oauth2 v0.36.0
golang.org/x/sync v0.22.0
google.golang.org/grpc v1.83.2
google.golang.org/protobuf v1.36.11
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
-54
View File
@@ -1,54 +0,0 @@
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-154
View File
@@ -1,154 +0,0 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
[tools]
go = "1.25.14"
buf = "1.72.0"
"go:github.com/golangci/golangci-lint/v2/cmd/golangci-lint" = "2.12"
"go:google.golang.org/protobuf/cmd/protoc-gen-go" = "1.36.11"
"go:google.golang.org/grpc/cmd/protoc-gen-go-grpc" = "1.6.2"
[tasks.test]
description = "Run unit tests with coverage"
run = "go test -coverprofile=coverage.out -coverpkg=./openshell/... -race ./..."
[tasks."test:integration"]
description = "Run integration tests"
run = "go test -tags=integration -race ./..."
[tasks.lint]
description = "Run linter"
run = "golangci-lint run ./..."
[tasks.fmt]
description = "Format code"
run = "goimports -w . && go fmt ./..."
[tasks.build]
description = "Build all packages"
run = "go build ./..."
[tasks.ci]
description = "Run full CI pipeline"
depends = ["lint", "build", "test", "proto:check", "docs:check"]
[tasks."docs:check"]
description = "Verify every public package has a docs page"
run = """
#!/usr/bin/env bash
set -euo pipefail
DOCS_DIR="docs/src/api"
SUMMARY="docs/src/SUMMARY.md"
MISSING=0
# Find all public packages with a doc.go (excluding internal, proto, types)
for docfile in openshell/v1/*/doc.go; do
pkg=$(basename "$(dirname "$docfile")")
# Skip internal packages and types (no user-facing docs needed)
case "$pkg" in
internal|types) continue ;;
esac
# Check for matching docs page
if [ ! -f "$DOCS_DIR/$pkg.md" ]; then
echo "MISSING: $DOCS_DIR/$pkg.md (package openshell/v1/$pkg has doc.go but no docs page)"
MISSING=$((MISSING + 1))
fi
# Check for SUMMARY.md entry
if ! grep -q "api/$pkg.md" "$SUMMARY" 2>/dev/null; then
echo "MISSING: SUMMARY.md entry for api/$pkg.md"
MISSING=$((MISSING + 1))
fi
done
if [ "$MISSING" -gt 0 ]; then
echo ""
echo "ERROR: $MISSING documentation gaps found."
echo "Every public package with doc.go needs a docs/src/api/<pkg>.md page"
echo "and a SUMMARY.md entry. See Constitution XIII."
exit 1
fi
echo "Docs check passed: all public packages have documentation."
"""
[tasks."proto:gen"]
description = "Generate Go bindings from proto files using buf"
run = """
#!/usr/bin/env bash
set -euo pipefail
SDK_ROOT=$(pwd -P)
REPO_ROOT=$(cd ../.. && pwd -P)
for tool in buf protoc-gen-go protoc-gen-go-grpc; do
if ! command -v "$tool" &>/dev/null; then
echo "ERROR: $tool not found. Run 'mise install' to install it."
exit 1
fi
done
if find proto -maxdepth 1 -name '*.proto' -print -quit | grep -q .; then
echo "ERROR: sdk/go/proto must contain generated bindings only."
echo "Proto sources belong in the repository root proto/ directory."
exit 1
fi
# Clean previous output before regeneration
find proto -name '*.pb.go' -delete 2>/dev/null || true
find proto -mindepth 1 -type d -empty -delete 2>/dev/null || true
(cd "$REPO_ROOT" && buf generate --template "$SDK_ROOT/buf.gen.yaml")
echo "Proto generation complete."
echo "Generated packages:"
for pkg_dir in proto/*/; do
count=$(find "$pkg_dir" -maxdepth 1 -name '*.go' | wc -l | tr -d ' ')
echo " $pkg_dir: $count files"
done
"""
[tasks."proto:check"]
description = "Verify generated proto files are up to date"
run = """
#!/usr/bin/env bash
set -euo pipefail
SDK_ROOT=$(pwd -P)
REPO_ROOT=$(cd ../.. && pwd -P)
for tool in buf protoc-gen-go protoc-gen-go-grpc; do
if ! command -v "$tool" &>/dev/null; then
echo "ERROR: $tool not found. Run 'mise install' to install it."
exit 1
fi
done
WORK_DIR=$(mktemp -d)
trap 'rm -rf "$WORK_DIR"' EXIT
if find proto -maxdepth 1 -name '*.proto' -print -quit | grep -q .; then
echo "ERROR: sdk/go/proto contains copied proto sources."
echo "Proto sources belong in the repository root proto/ directory."
exit 1
fi
# Generate to temp directory with adjusted output path
CHECK_TEMPLATE=$(sed 's|out: sdk/go|out: '"$WORK_DIR"'|' buf.gen.yaml)
(cd "$REPO_ROOT" && buf generate --template "$CHECK_TEMPLATE")
DIFF_OUTPUT=$(diff -r "$WORK_DIR/proto" "$SDK_ROOT/proto" 2>&1) || true
if [ -n "$DIFF_OUTPUT" ]; then
echo "ERROR: Generated proto files are out of date."
echo "Run 'mise run proto:gen' to regenerate."
echo ""
echo "$DIFF_OUTPUT"
exit 1
fi
echo "Proto check passed: generated files are up to date."
"""
-48
View File
@@ -1,48 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// AuthProvider supplies per-RPC credentials. It implements the
// grpc credentials.PerRPCCredentials interface.
type AuthProvider = types.AuthProvider
type noAuth struct{}
// NoAuth returns an AuthProvider that sends no credentials.
func NoAuth() AuthProvider {
return &noAuth{}
}
func (n *noAuth) GetRequestMetadata(_ context.Context, _ ...string) (map[string]string, error) {
return nil, nil
}
func (n *noAuth) RequireTransportSecurity() bool {
return false
}
type staticToken struct {
token string
}
// StaticToken returns an AuthProvider that sends a fixed Bearer token.
func StaticToken(token string) AuthProvider {
return &staticToken{token: token}
}
func (s *staticToken) GetRequestMetadata(_ context.Context, _ ...string) (map[string]string, error) {
return map[string]string{
"authorization": "Bearer " + s.token,
}, nil
}
func (s *staticToken) RequireTransportSecurity() bool {
return true
}
-80
View File
@@ -1,80 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"errors"
"maps"
"strings"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// extraHeadersAuth wraps a base AuthProvider with additional static headers
// that are merged into every GetRequestMetadata call. Extra headers take
// precedence over base headers on key collision (case-insensitive).
type extraHeadersAuth struct {
base types.AuthProvider
headers map[string]string // keys already lowercase, empty values filtered out
}
// WithExtraHeaders wraps base with additional per-RPC headers. Keys are
// normalized to lowercase per HTTP/2 (RFC 9113). Empty-string values are
// silently dropped. The headers map is deep-copied at construction time,
// so later mutations to the caller's map have no effect.
//
// Returns an error if base is nil or if headers is nil, empty, or contains
// only empty-string values.
func WithExtraHeaders(base AuthProvider, headers map[string]string) (AuthProvider, error) {
if base == nil {
return nil, errors.New("base auth provider must not be nil")
}
if len(headers) == 0 {
return nil, errors.New("headers must not be nil or empty")
}
// Deep-copy and normalize: lowercase keys, skip empty values.
normalized := make(map[string]string, len(headers))
for k, v := range headers {
if v == "" {
continue
}
normalized[strings.ToLower(k)] = v
}
if len(normalized) == 0 {
return nil, errors.New("headers must contain at least one non-empty value")
}
return &extraHeadersAuth{
base: base,
headers: normalized,
}, nil
}
// GetRequestMetadata merges base metadata with extra headers. Extra headers
// win on key collision because they are applied after the base metadata.
func (e *extraHeadersAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
baseMD, err := e.base.GetRequestMetadata(ctx, uri...)
if err != nil {
return nil, err
}
// Start with base metadata (may be nil for NoAuth).
// Normalize base keys to lowercase for case-insensitive collision.
merged := make(map[string]string, len(baseMD)+len(e.headers))
for k, v := range baseMD {
merged[strings.ToLower(k)] = v
}
// Extra headers overwrite base on collision.
maps.Copy(merged, e.headers)
return merged, nil
}
// RequireTransportSecurity delegates to the base auth provider.
func (e *extraHeadersAuth) RequireTransportSecurity() bool {
return e.base.RequireTransportSecurity()
}
-177
View File
@@ -1,177 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWithExtraHeaders_NilBase(t *testing.T) {
_, err := WithExtraHeaders(nil, map[string]string{"x-key": "val"})
require.Error(t, err)
assert.Contains(t, err.Error(), "base")
}
func TestWithExtraHeaders_NilHeaders(t *testing.T) {
_, err := WithExtraHeaders(NoAuth(), nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "headers")
}
func TestWithExtraHeaders_EmptyHeaders(t *testing.T) {
_, err := WithExtraHeaders(NoAuth(), map[string]string{})
require.Error(t, err)
assert.Contains(t, err.Error(), "headers")
}
func TestWithExtraHeaders_AllEmptyValues(t *testing.T) {
// All values are empty strings, so after filtering, headers map is empty.
_, err := WithExtraHeaders(NoAuth(), map[string]string{"x-key": ""})
require.Error(t, err)
assert.Contains(t, err.Error(), "headers")
}
func TestWithExtraHeaders_MergesWithBase(t *testing.T) {
base := StaticToken("my-token")
auth, err := WithExtraHeaders(base, map[string]string{
"x-proxy-key": "proxy-secret",
"x-tenant-id": "acme-corp",
})
require.NoError(t, err)
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer my-token", md["authorization"])
assert.Equal(t, "proxy-secret", md["x-proxy-key"])
assert.Equal(t, "acme-corp", md["x-tenant-id"])
}
func TestWithExtraHeaders_ExtraPrecedenceOnCollision(t *testing.T) {
base := StaticToken("my-token")
auth, err := WithExtraHeaders(base, map[string]string{
"authorization": "Custom override-token",
})
require.NoError(t, err)
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
// Extra header wins over base.
assert.Equal(t, "Custom override-token", md["authorization"])
}
func TestWithExtraHeaders_CaseInsensitiveCollision(t *testing.T) {
base := StaticToken("my-token")
// "Authorization" with uppercase should still override "authorization".
auth, err := WithExtraHeaders(base, map[string]string{
"Authorization": "Custom override-token",
})
require.NoError(t, err)
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Custom override-token", md["authorization"])
}
func TestWithExtraHeaders_EmptyValueSkipped(t *testing.T) {
base := StaticToken("my-token")
auth, err := WithExtraHeaders(base, map[string]string{
"x-proxy-key": "proxy-secret",
"x-empty": "", // Should be silently skipped.
})
require.NoError(t, err)
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "proxy-secret", md["x-proxy-key"])
_, hasEmpty := md["x-empty"]
assert.False(t, hasEmpty, "empty-string header values should be skipped")
}
func TestWithExtraHeaders_RequireTransportSecurity_Delegates(t *testing.T) {
tests := []struct {
name string
base AuthProvider
expected bool
}{
{
name: "delegates to NoAuth (false)",
base: NoAuth(),
expected: false,
},
{
name: "delegates to StaticToken (true)",
base: StaticToken("tok"),
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
auth, err := WithExtraHeaders(tt.base, map[string]string{"x-key": "val"})
require.NoError(t, err)
assert.Equal(t, tt.expected, auth.RequireTransportSecurity())
})
}
}
func TestWithExtraHeaders_WithNoAuth(t *testing.T) {
auth, err := WithExtraHeaders(NoAuth(), map[string]string{
"x-proxy-key": "proxy-secret",
})
require.NoError(t, err)
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
// NoAuth returns nil metadata, extra headers should still appear.
assert.Equal(t, "proxy-secret", md["x-proxy-key"])
}
func TestWithExtraHeaders_BaseError_Propagated(t *testing.T) {
base := &errAuth{err: errors.New("auth failure")}
auth, err := WithExtraHeaders(base, map[string]string{"x-key": "val"})
require.NoError(t, err)
_, err = auth.GetRequestMetadata(context.Background())
require.Error(t, err)
assert.Contains(t, err.Error(), "auth failure")
}
func TestWithExtraHeaders_DeepCopiesHeaders(t *testing.T) {
original := map[string]string{
"x-key": "original-value",
}
auth, err := WithExtraHeaders(NoAuth(), original)
require.NoError(t, err)
// Mutate the original map after construction.
original["x-key"] = "mutated-value"
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
// The wrapper should use the value at construction time, not the mutated value.
assert.Equal(t, "original-value", md["x-key"])
}
// errAuth is a test helper that always returns an error.
type errAuth struct {
err error
}
func (e *errAuth) GetRequestMetadata(_ context.Context, _ ...string) (map[string]string, error) {
return nil, e.err
}
func (e *errAuth) RequireTransportSecurity() bool {
return false
}
-183
View File
@@ -1,183 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"errors"
"sync"
"time"
"golang.org/x/oauth2"
"golang.org/x/sync/singleflight"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
const (
defaultLeeway = 10 * time.Second
initialBackoff = 1 * time.Second
maxBackoff = 30 * time.Second
)
var errNilTokenSource = errors.New("openshell: TokenSource must not be nil")
// RefreshOption configures the behavior of RefreshableToken.
type RefreshOption func(*refreshConfig)
type refreshConfig struct {
leeway time.Duration
logger types.Logger
}
func defaultRefreshConfig() refreshConfig {
return refreshConfig{
leeway: defaultLeeway,
}
}
// WithLeeway sets the duration before token expiry at which a proactive
// refresh is triggered. Default is 10 seconds.
func WithLeeway(d time.Duration) RefreshOption {
return func(c *refreshConfig) {
if d < 0 {
d = 0
}
c.leeway = d
}
}
// WithLogger sets the logger used for stale-token fallback warnings.
// When not set, warnings are silently dropped.
func WithLogger(l types.Logger) RefreshOption {
return func(c *refreshConfig) {
c.logger = l
}
}
type refreshableAuth struct {
source oauth2.TokenSource
mu sync.Mutex
group singleflight.Group
tok *oauth2.Token
leeway time.Duration
logger types.Logger
nextRetry time.Time
backoff time.Duration
lastErr error
}
// usableCached reports whether the cached token has not yet expired.
// Callers must hold r.mu.
func (r *refreshableAuth) usableCached() bool {
return r.tok != nil && (r.tok.Expiry.IsZero() || time.Now().Before(r.tok.Expiry))
}
func (r *refreshableAuth) isTokenValid() bool {
if r.tok == nil {
return false
}
if r.tok.Expiry.IsZero() {
return true
}
return time.Now().Before(r.tok.Expiry.Add(-r.leeway))
}
func (r *refreshableAuth) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error) {
r.mu.Lock()
if r.isTokenValid() {
tok := r.tok.AccessToken
r.mu.Unlock()
return map[string]string{"authorization": "Bearer " + tok}, nil
}
if !r.nextRetry.IsZero() && time.Now().Before(r.nextRetry) {
if r.usableCached() {
tok := r.tok.AccessToken
r.mu.Unlock()
return map[string]string{"authorization": "Bearer " + tok}, nil
}
err := r.lastErr
r.mu.Unlock()
return nil, err
}
r.mu.Unlock()
resultCh := r.group.DoChan("refresh", func() (any, error) {
return r.source.Token()
})
var val any
var err error
select {
case <-ctx.Done():
return nil, ctx.Err()
case result := <-resultCh:
val = result.Val
err = result.Err
}
r.mu.Lock()
defer r.mu.Unlock()
if err != nil {
if r.nextRetry.IsZero() || !time.Now().Before(r.nextRetry) {
bo := r.backoff
if bo == 0 {
bo = initialBackoff
} else {
bo *= 2
if bo > maxBackoff {
bo = maxBackoff
}
}
r.backoff = bo
r.nextRetry = time.Now().Add(bo)
}
r.lastErr = err
if r.usableCached() {
if r.logger != nil {
r.logger.Error(err, "token refresh failed, using cached token")
}
return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, nil
}
return nil, err
}
tok, ok := val.(*oauth2.Token)
if !ok || tok == nil {
return nil, errors.New("openshell: token source returned nil token without error")
}
r.tok = tok
r.backoff = 0
r.nextRetry = time.Time{}
r.lastErr = nil
return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, nil
}
func (r *refreshableAuth) RequireTransportSecurity() bool {
return true
}
// RefreshableToken returns an AuthProvider that caches tokens from src
// and refreshes them before expiry. Concurrent callers share a single
// in-flight refresh via singleflight. Failed refreshes trigger exponential
// backoff (1s, 2s, 4s, ..., 30s cap) to avoid amplifying token endpoint outages.
// After a failed refresh, the cached token is used only until it expires;
// after that, requests fail with the last refresh error.
func RefreshableToken(src oauth2.TokenSource, opts ...RefreshOption) (AuthProvider, error) {
if src == nil {
return nil, errNilTokenSource
}
cfg := defaultRefreshConfig()
options.Apply(&cfg, opts)
return &refreshableAuth{
source: src,
leeway: cfg.leeway,
logger: cfg.logger,
}, nil
}
-571
View File
@@ -1,571 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
)
// mockTokenSource implements oauth2.TokenSource for testing.
type mockTokenSource struct {
mu sync.Mutex
tokenFunc func() (*oauth2.Token, error)
callCount int
}
func (m *mockTokenSource) Token() (*oauth2.Token, error) {
m.mu.Lock()
m.callCount++
m.mu.Unlock()
return m.tokenFunc()
}
func (m *mockTokenSource) calls() int {
m.mu.Lock()
defer m.mu.Unlock()
return m.callCount
}
// --- Phase 2 tests: constructor validation ---
func TestRefreshableToken_NilSource(t *testing.T) {
_, err := RefreshableToken(nil)
require.Error(t, err)
assert.Equal(t, "openshell: TokenSource must not be nil", err.Error())
}
func TestRefreshableToken_ValidSource(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "tok", Expiry: time.Now().Add(time.Hour)}, nil
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
assert.NotNil(t, provider)
}
func TestGetRequestMetadata_ReturnsWhenContextCanceledDuringRefresh(t *testing.T) {
release := make(chan struct{})
t.Cleanup(func() { close(release) })
src := &mockTokenSource{tokenFunc: func() (*oauth2.Token, error) {
<-release
return &oauth2.Token{AccessToken: "late-token"}, nil
}}
provider, err := RefreshableToken(src)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
cancel()
started := time.Now()
_, err = provider.GetRequestMetadata(ctx)
require.ErrorIs(t, err, context.Canceled)
assert.Less(t, time.Since(started), time.Second)
}
// --- Phase 3 / US1 tests: automatic token refresh ---
func TestGetRequestMetadata_FirstCallFetchesToken(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "fresh-token", Expiry: time.Now().Add(time.Hour)}, nil
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer fresh-token", md["authorization"])
assert.Equal(t, 1, src.calls())
}
func TestGetRequestMetadata_CachedTokenNoExtraCall(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "cached-token", Expiry: time.Now().Add(time.Hour)}, nil
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer cached-token", md["authorization"])
assert.Equal(t, 1, src.calls(), "second call should use cache, not invoke TokenSource")
}
func TestGetRequestMetadata_RefreshesExpiredToken(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
if n == 1 {
return &oauth2.Token{AccessToken: "old", Expiry: time.Now().Add(-time.Minute)}, nil
}
return &oauth2.Token{AccessToken: "new", Expiry: time.Now().Add(time.Hour)}, nil
},
}
provider, err := RefreshableToken(src, WithLeeway(0))
require.NoError(t, err)
// First call gets the expired token, which is immediately stale.
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer old", md["authorization"])
// Second call should trigger a refresh since the cached token is expired.
md, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer new", md["authorization"])
assert.Equal(t, 2, src.calls())
}
func TestGetRequestMetadata_ConcurrentSingleFlight(t *testing.T) {
var fetchCount atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
fetchCount.Add(1)
time.Sleep(100 * time.Millisecond)
return &oauth2.Token{AccessToken: "shared-token", Expiry: time.Now().Add(time.Hour)}, nil
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
const goroutines = 20
var wg sync.WaitGroup
wg.Add(goroutines)
ready := make(chan struct{})
results := make([]string, goroutines)
errs := make([]error, goroutines)
for i := range goroutines {
go func(idx int) {
defer wg.Done()
<-ready
md, e := provider.GetRequestMetadata(context.Background())
errs[idx] = e
if md != nil {
results[idx] = md["authorization"]
}
}(i)
}
close(ready)
wg.Wait()
for i := range goroutines {
require.NoError(t, errs[i], "goroutine %d failed", i)
assert.Equal(t, "Bearer shared-token", results[i], "goroutine %d got wrong token", i)
}
assert.Equal(t, int32(1), fetchCount.Load(), "expected exactly 1 TokenSource.Token() call, got %d", fetchCount.Load())
}
func TestRefreshableAuth_RequireTransportSecurity(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "t"}, nil
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
assert.True(t, provider.RequireTransportSecurity())
}
// --- Phase 4 / US2 tests: graceful degradation ---
func TestGetRequestMetadata_RefreshFailureReturnsStaleCachedToken(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
if n == 1 {
return &oauth2.Token{AccessToken: "stale", Expiry: time.Now().Add(5 * time.Second)}, nil
}
return nil, fmt.Errorf("idp unavailable")
},
}
provider, err := RefreshableToken(src) // default 10s leeway
require.NoError(t, err)
// First call succeeds with a token inside the leeway window.
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
// Second call: refresh fails, should return the unexpired stale token.
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer stale", md["authorization"])
}
func TestGetRequestMetadata_RefreshFailureWithExpiredCachedTokenReturnsError(t *testing.T) {
errIDP := errors.New("idp unavailable")
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
if n == 1 {
return &oauth2.Token{AccessToken: "expired", Expiry: time.Now().Add(-time.Minute)}, nil
}
return nil, errIDP
},
}
logger := &captureLogger{}
provider, err := RefreshableToken(src, WithLeeway(0), WithLogger(logger))
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
md, err := provider.GetRequestMetadata(context.Background())
require.ErrorIs(t, err, errIDP)
assert.Nil(t, md)
assert.Empty(t, logger.errors)
// During backoff, the same error is returned without calling the source.
md, err = provider.GetRequestMetadata(context.Background())
require.ErrorIs(t, err, errIDP)
assert.Nil(t, md)
assert.Equal(t, 2, src.calls())
}
func TestGetRequestMetadata_RefreshFailureLogsWarning(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
if n == 1 {
return &oauth2.Token{AccessToken: "stale", Expiry: time.Now().Add(5 * time.Second)}, nil
}
return nil, fmt.Errorf("idp unavailable")
},
}
logger := &captureLogger{}
provider, err := RefreshableToken(src, WithLogger(logger))
require.NoError(t, err)
_, _ = provider.GetRequestMetadata(context.Background())
_, _ = provider.GetRequestMetadata(context.Background())
require.Len(t, logger.errors, 1)
assert.Contains(t, logger.errors[0].msg, "token refresh failed")
}
func TestGetRequestMetadata_RefreshFailureNoCachedTokenReturnsError(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return nil, fmt.Errorf("idp unavailable")
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.Error(t, err)
assert.Contains(t, err.Error(), "idp unavailable")
}
func TestGetRequestMetadata_RefreshFailureNoLoggerNoPanic(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
if n == 1 {
return &oauth2.Token{AccessToken: "stale", Expiry: time.Now().Add(5 * time.Second)}, nil
}
return nil, fmt.Errorf("idp unavailable")
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
_, _ = provider.GetRequestMetadata(context.Background())
assert.NotPanics(t, func() {
_, _ = provider.GetRequestMetadata(context.Background())
})
}
// --- Phase 5 / US3 tests: configurable leeway ---
func TestGetRequestMetadata_DefaultLeewayTriggersRefresh(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
return &oauth2.Token{
AccessToken: fmt.Sprintf("token-%d", n),
Expiry: time.Now().Add(5 * time.Second), // within default 10s leeway
}, nil
},
}
provider, err := RefreshableToken(src) // default 10s leeway
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
// Token expires in 5s, which is within 10s leeway, so next call should refresh.
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer token-2", md["authorization"])
assert.Equal(t, 2, src.calls())
}
func TestGetRequestMetadata_CustomLeewayTriggersRefresh(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
return &oauth2.Token{
AccessToken: fmt.Sprintf("token-%d", n),
Expiry: time.Now().Add(25 * time.Second), // within custom 30s leeway
}, nil
},
}
provider, err := RefreshableToken(src, WithLeeway(30*time.Second))
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
// Token expires in 25s, which is within 30s leeway, so next call should refresh.
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer token-2", md["authorization"])
assert.Equal(t, 2, src.calls())
}
func TestGetRequestMetadata_ZeroExpiryNeverRefreshes(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "forever-token"}, nil // zero Expiry
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
// Call multiple times; should never refresh since expiry is zero.
for range 10 {
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
}
assert.Equal(t, 1, src.calls(), "zero-expiry token should never be refreshed")
}
// --- Backoff tests ---
func TestGetRequestMetadata_BackoffSkipsRefreshDuringWindow(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
if n == 1 {
return &oauth2.Token{AccessToken: "stale", Expiry: time.Now().Add(5 * time.Second)}, nil
}
return nil, fmt.Errorf("idp down")
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
beforeCount := src.calls()
require.Equal(t, 2, beforeCount)
ra := provider.(*refreshableAuth)
ra.mu.Lock()
ra.nextRetry = time.Now().Add(time.Minute)
ra.mu.Unlock()
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer stale", md["authorization"])
assert.Equal(t, beforeCount, src.calls(), "should not call Token() during backoff window")
}
func TestGetRequestMetadata_BackoffWithoutCachedTokenReturnsLastError(t *testing.T) {
errIDP := errors.New("idp down")
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return nil, errIDP
},
}
provider, err := RefreshableToken(src)
require.NoError(t, err)
_, err = provider.GetRequestMetadata(context.Background())
require.ErrorIs(t, err, errIDP)
_, err = provider.GetRequestMetadata(context.Background())
require.ErrorIs(t, err, errIDP)
assert.Equal(t, 1, src.calls(), "should not call Token() during backoff window")
}
func TestGetRequestMetadata_BackoffResetsOnSuccess(t *testing.T) {
var callNum atomic.Int32
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
n := callNum.Add(1)
switch n {
case 1:
return &oauth2.Token{AccessToken: "initial", Expiry: time.Now().Add(-time.Second)}, nil
case 2:
return nil, fmt.Errorf("fail once")
default:
return &oauth2.Token{AccessToken: "recovered", Expiry: time.Now().Add(time.Hour)}, nil
}
},
}
provider, err := RefreshableToken(src, WithLeeway(0))
require.NoError(t, err)
_, _ = provider.GetRequestMetadata(context.Background())
_, _ = provider.GetRequestMetadata(context.Background())
ra := provider.(*refreshableAuth)
ra.mu.Lock()
ra.nextRetry = time.Time{}
ra.mu.Unlock()
md, err := provider.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer recovered", md["authorization"])
ra.mu.Lock()
assert.Equal(t, time.Duration(0), ra.backoff, "backoff should reset after success")
assert.True(t, ra.nextRetry.IsZero(), "nextRetry should be zero after success")
ra.mu.Unlock()
}
func TestGetRequestMetadata_BackoffCapsAt30s(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return nil, fmt.Errorf("always fail")
},
}
provider, err := RefreshableToken(src, WithLeeway(0))
require.NoError(t, err)
ra := provider.(*refreshableAuth)
for range 10 {
ra.mu.Lock()
ra.nextRetry = time.Time{}
ra.mu.Unlock()
_, _ = provider.GetRequestMetadata(context.Background())
}
ra.mu.Lock()
assert.Equal(t, maxBackoff, ra.backoff, "backoff should cap at maxBackoff")
ra.mu.Unlock()
}
func TestGetRequestMetadata_ConcurrentFailureBackoffNotOverIncremented(t *testing.T) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
time.Sleep(10 * time.Millisecond)
return nil, fmt.Errorf("idp down")
},
}
provider, err := RefreshableToken(src, WithLeeway(0))
require.NoError(t, err)
const goroutines = 20
var wg sync.WaitGroup
wg.Add(goroutines)
ready := make(chan struct{})
for range goroutines {
go func() {
defer wg.Done()
<-ready
_, _ = provider.GetRequestMetadata(context.Background())
}()
}
close(ready)
wg.Wait()
ra := provider.(*refreshableAuth)
ra.mu.Lock()
assert.Equal(t, initialBackoff, ra.backoff,
"a single coalesced failure should set backoff to initialBackoff, not escalate")
ra.mu.Unlock()
assert.Equal(t, 1, src.calls(), "singleflight should coalesce to 1 call")
}
// --- benchmarks ---
func BenchmarkGetRequestMetadata_CachedToken(b *testing.B) {
src := &mockTokenSource{
tokenFunc: func() (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "bench-token", Expiry: time.Now().Add(time.Hour)}, nil
},
}
provider, err := RefreshableToken(src)
require.NoError(b, err)
// Prime the cache.
_, err = provider.GetRequestMetadata(context.Background())
require.NoError(b, err)
b.ResetTimer()
b.ReportAllocs()
for range b.N {
_, _ = provider.GetRequestMetadata(context.Background())
}
}
// --- helpers ---
type logEntry struct {
err error
msg string
}
type captureLogger struct {
mu sync.Mutex
debugs []string
infos []string
errors []logEntry
}
func (l *captureLogger) Debug(msg string, _ ...any) {
l.mu.Lock()
defer l.mu.Unlock()
l.debugs = append(l.debugs, msg)
}
func (l *captureLogger) Info(msg string, _ ...any) {
l.mu.Lock()
defer l.mu.Unlock()
l.infos = append(l.infos, msg)
}
func (l *captureLogger) Error(err error, msg string, _ ...any) {
l.mu.Lock()
defer l.mu.Unlock()
l.errors = append(l.errors, logEntry{err: err, msg: msg})
}
-36
View File
@@ -1,36 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNoAuth_GetRequestMetadata(t *testing.T) {
auth := NoAuth()
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Empty(t, md)
}
func TestNoAuth_RequireTransportSecurity(t *testing.T) {
auth := NoAuth()
assert.False(t, auth.RequireTransportSecurity())
}
func TestStaticToken_GetRequestMetadata(t *testing.T) {
auth := StaticToken("my-secret-token")
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "Bearer my-secret-token", md["authorization"])
}
func TestStaticToken_RequireTransportSecurity(t *testing.T) {
auth := StaticToken("token")
assert.True(t, auth.RequireTransportSecurity())
}
-171
View File
@@ -1,171 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"sync"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
internalgrpc "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/grpc"
"google.golang.org/grpc"
)
// Config holds all settings needed to create a Client.
type Config = types.Config
// ClientInterface defines the top-level SDK surface.
type ClientInterface interface {
Sandboxes() SandboxInterface
SandboxTemplates() SandboxTemplateInterface
CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, opts ...CreateOption) (*Sandbox, error)
SandboxSuspendResume() SandboxSuspendResumeInterface
Providers() ProviderInterface
Services() ServiceInterface
Exec() ExecInterface
Files() FileInterface
Health() HealthInterface
SSH() SSHInterface
TCP() TCPInterface
Config() ConfigInterface
Policy() PolicyInterface
Workspaces() WorkspaceInterface
Close() error
}
// SandboxInterface is defined in sandbox.go
// ProviderInterface is defined in provider.go
// ExecInterface is defined in exec.go
// FileInterface is defined in file.go
// Client implements ClientInterface. It holds a gRPC connection and provides
// sub-client accessors following the Kubernetes client-go pattern.
type Client struct {
conn *grpc.ClientConn
config Config
closeOnce sync.Once
closeErr error
sandboxes SandboxInterface
templateCreate SandboxTemplateCreateInterface
suspendResume SandboxSuspendResumeInterface
templates SandboxTemplateInterface
providers ProviderInterface
services ServiceInterface
exec ExecInterface
files FileInterface
health HealthInterface
ssh SSHInterface
tcp TCPInterface
cfg ConfigInterface
policy PolicyInterface
workspaces WorkspaceInterface
}
// NewClient creates a new SDK client connected to the given gateway.
func NewClient(cfg Config) (*Client, error) {
if cfg.Address == "" {
return nil, &StatusError{Code: ErrorInvalidArgument, Message: "address must not be empty"}
}
if cfg.Auth == nil {
cfg.Auth = NoAuth()
}
var tlsParams *internalgrpc.TLSParams
if cfg.TLS != nil {
tlsParams = &internalgrpc.TLSParams{
CertFile: cfg.TLS.CertFile,
KeyFile: cfg.TLS.KeyFile,
CAFile: cfg.TLS.CAFile,
Insecure: cfg.TLS.Insecure,
}
}
conn, err := internalgrpc.NewConnection(cfg.Address, tlsParams, cfg.Auth)
if err != nil {
return nil, err
}
c := &Client{
conn: conn,
config: cfg,
}
sandboxes := newSandboxClient(conn)
c.sandboxes = sandboxes
c.templateCreate = sandboxes
c.suspendResume = sandboxes
c.templates = newSandboxTemplateClient(conn)
c.providers = newProviderClient(conn)
c.services = newServiceClient(conn)
c.exec = newExecClient(conn, c.sandboxes)
c.files = newFileClient(conn, c.sandboxes)
c.health = newHealthClient(conn)
c.ssh = newSSHClient(conn, c.sandboxes)
c.tcp = newTCPClient(conn, c.sandboxes, c.ssh)
c.cfg = newConfigClient(conn, c.sandboxes)
c.policy = newPolicyClient(conn)
c.workspaces = newWorkspaceClient(conn)
return c, nil
}
// Sandboxes returns the sandbox sub-client.
func (c *Client) Sandboxes() SandboxInterface { return c.sandboxes }
// SandboxTemplates returns the reusable sandbox template sub-client.
func (c *Client) SandboxTemplates() SandboxTemplateInterface { return c.templates }
// CreateSandboxFromTemplate creates a sandbox from a named workload template
// without changing the legacy Sandboxes() interface.
func (c *Client) CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, opts ...CreateOption) (*Sandbox, error) {
return c.templateCreate.CreateFromTemplate(ctx, workspace, name, templateName, spec, opts...)
}
// SandboxSuspendResume returns the sandbox suspend and resume sub-client.
func (c *Client) SandboxSuspendResume() SandboxSuspendResumeInterface { return c.suspendResume }
// Providers returns the provider sub-client.
func (c *Client) Providers() ProviderInterface { return c.providers }
// Services returns the service sub-client.
func (c *Client) Services() ServiceInterface { return c.services }
// Exec returns the exec sub-client.
func (c *Client) Exec() ExecInterface { return c.exec }
// Files returns the file sub-client.
func (c *Client) Files() FileInterface { return c.files }
// Health returns the health sub-client.
func (c *Client) Health() HealthInterface { return c.health }
// SSH returns the SSH session sub-client.
func (c *Client) SSH() SSHInterface { return c.ssh }
// TCP returns the TCP port forwarding sub-client.
func (c *Client) TCP() TCPInterface { return c.tcp }
// Config returns the configuration sub-client.
func (c *Client) Config() ConfigInterface { return c.cfg }
// Policy returns the policy management sub-client.
func (c *Client) Policy() PolicyInterface { return c.policy }
// Workspaces returns the workspace management sub-client.
func (c *Client) Workspaces() WorkspaceInterface { return c.workspaces }
// Close closes the underlying gRPC connection. Safe to call multiple times.
func (c *Client) Close() error {
c.closeOnce.Do(func() {
c.closeErr = c.conn.Close()
})
return c.closeErr
}
-67
View File
@@ -1,67 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewClient_EmptyAddress(t *testing.T) {
_, err := NewClient(Config{Address: ""})
require.Error(t, err)
assert.Contains(t, err.Error(), "address")
}
func TestNewClient_ValidConfig(t *testing.T) {
client, err := NewClient(Config{
Address: "localhost:50051",
Auth: NoAuth(),
TLS: &TLSConfig{Insecure: true},
})
require.NoError(t, err)
require.NotNil(t, client)
assert.NotNil(t, client.Sandboxes())
assert.NotNil(t, client.Providers())
assert.NotNil(t, client.Exec())
assert.NotNil(t, client.Files())
assert.NotNil(t, client.Health())
assert.NotNil(t, client.Services())
assert.NotNil(t, client.SSH())
assert.NotNil(t, client.TCP())
assert.NotNil(t, client.Config())
assert.NotNil(t, client.Policy())
assert.NotNil(t, client.Workspaces())
err = client.Close()
assert.NoError(t, err)
}
func TestClient_CloseIdempotent(t *testing.T) {
client, err := NewClient(Config{
Address: "localhost:50051",
Auth: NoAuth(),
TLS: &TLSConfig{Insecure: true},
})
require.NoError(t, err)
err = client.Close()
assert.NoError(t, err)
err = client.Close()
assert.NoError(t, err)
}
func TestNewClient_DefaultAuth(t *testing.T) {
client, err := NewClient(Config{
Address: "localhost:50051",
TLS: &TLSConfig{Insecure: true},
})
require.NoError(t, err)
require.NotNil(t, client)
_ = client.Close()
}
-67
View File
@@ -1,67 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// SandboxConfig represents the full configuration state of a sandbox.
type SandboxConfig = types.SandboxConfig
// GatewayConfig represents gateway-global settings.
type GatewayConfig = types.GatewayConfig
// ConfigUpdate represents a configuration mutation request.
type ConfigUpdate = types.ConfigUpdate
// ConfigUpdateResult holds the result of a configuration update operation.
type ConfigUpdateResult = types.ConfigUpdateResult
// SettingValue is a typed setting value (string, bool, int64, or bytes).
type SettingValue = types.SettingValue
// SettingValueType identifies which typed field of a SettingValue is active.
type SettingValueType = types.SettingValueType
// EffectiveSetting is a setting value paired with its resolved scope.
type EffectiveSetting = types.EffectiveSetting
// SettingScope indicates whether a setting is sandbox or global.
type SettingScope = types.SettingScope
// PolicySource indicates the source of a policy payload.
type PolicySource = types.PolicySource
// SettingValueType constants re-exported from types package.
const (
SettingValueString = types.SettingValueString
SettingValueBool = types.SettingValueBool
SettingValueInt = types.SettingValueInt
SettingValueBytes = types.SettingValueBytes
)
// SettingScope constants re-exported from types package.
const (
SettingScopeUnspecified = types.SettingScopeUnspecified
SettingScopeSandbox = types.SettingScopeSandbox
SettingScopeGlobal = types.SettingScopeGlobal
)
// PolicySource constants re-exported from types package.
const (
PolicySourceUnspecified = types.PolicySourceUnspecified
PolicySourceSandbox = types.PolicySourceSandbox
PolicySourceGlobal = types.PolicySourceGlobal
)
// ConfigInterface defines operations for reading and updating gateway and
// sandbox configuration.
type ConfigInterface interface {
GetSandbox(ctx context.Context, workspace, sandboxName string) (*SandboxConfig, error)
GetGateway(ctx context.Context) (*GatewayConfig, error)
Update(ctx context.Context, workspace string, update *ConfigUpdate) (*ConfigUpdateResult, error)
}
-68
View File
@@ -1,68 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"google.golang.org/grpc"
)
type configClient struct {
client pb.OpenShellClient
sandboxes SandboxInterface
}
func newConfigClient(conn grpc.ClientConnInterface, sandboxes SandboxInterface) *configClient {
return &configClient{client: pb.NewOpenShellClient(conn), sandboxes: sandboxes}
}
func (c *configClient) GetSandbox(ctx context.Context, workspace, sandboxName string) (*SandboxConfig, error) {
if sandboxName == "" {
return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
if _, err := c.sandboxes.Get(ctx, workspace, sandboxName); err != nil {
return nil, err
}
resp, err := c.client.GetSandboxConfig(ctx, &sbv1.GetSandboxConfigRequest{
Name: sandboxName,
WorkspaceScope: namedWorkspaceScope(workspace),
})
if err != nil {
return nil, converter.FromGRPCError(err)
}
return converter.SandboxConfigFromProto(resp), nil
}
func (c *configClient) GetGateway(ctx context.Context) (*GatewayConfig, error) {
resp, err := c.client.GetGatewayConfig(ctx, &sbv1.GetGatewayConfigRequest{})
if err != nil {
return nil, converter.FromGRPCError(err)
}
return converter.GatewayConfigFromProto(resp), nil
}
func (c *configClient) Update(ctx context.Context, workspace string, update *ConfigUpdate) (*ConfigUpdateResult, error) {
if update == nil {
return nil, &StatusError{
Code: ErrorInvalidArgument,
Message: "update must not be nil",
}
}
req, convErr := converter.ConfigUpdateToProto(update)
if convErr != nil {
return nil, &StatusError{Code: ErrorInvalidArgument, Message: convErr.Error()}
}
if !req.GetGlobal() {
req.WorkspaceScope = namedWorkspaceScope(workspace)
}
resp, err := c.client.UpdateConfig(ctx, req)
if err != nil {
return nil, converter.FromGRPCError(err)
}
return converter.ConfigUpdateResultFromProto(resp), nil
}
-645
View File
@@ -1,645 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"net"
"sync"
"testing"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
)
// --- Mock server for Config RPCs ---
type mockConfigServer struct {
pb.UnimplementedOpenShellServer
mu sync.Mutex
// Canned responses.
sandboxResp *sbv1.GetSandboxConfigResponse
gatewayResp *sbv1.GetGatewayConfigResponse
updateResp *pb.UpdateConfigResponse
// Recorded requests.
lastSandboxReq *sbv1.GetSandboxConfigRequest
lastGatewayReq *sbv1.GetGatewayConfigRequest
lastUpdateReq *pb.UpdateConfigRequest
// Inject errors.
sandboxErr error
gatewayErr error
updateErr error
}
func newMockConfigServer() *mockConfigServer {
return &mockConfigServer{}
}
func (s *mockConfigServer) GetSandboxConfig(_ context.Context, req *sbv1.GetSandboxConfigRequest) (*sbv1.GetSandboxConfigResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.lastSandboxReq = req
if s.sandboxErr != nil {
return nil, s.sandboxErr
}
return s.sandboxResp, nil
}
func (s *mockConfigServer) GetGatewayConfig(_ context.Context, req *sbv1.GetGatewayConfigRequest) (*sbv1.GetGatewayConfigResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.lastGatewayReq = req
if s.gatewayErr != nil {
return nil, s.gatewayErr
}
return s.gatewayResp, nil
}
func (s *mockConfigServer) UpdateConfig(_ context.Context, req *pb.UpdateConfigRequest) (*pb.UpdateConfigResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.lastUpdateReq = req
if s.updateErr != nil {
return nil, s.updateErr
}
return s.updateResp, nil
}
// --- Test setup ---
func setupConfigTest(t *testing.T, mock *mockConfigServer) (*configClient, func()) {
t.Helper()
lis := bufconn.Listen(bufSize)
srv := grpc.NewServer()
pb.RegisterOpenShellServer(srv, mock)
go func() { _ = srv.Serve(lis) }()
conn, err := grpc.NewClient("passthrough:///bufconn",
grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) {
return lis.Dial()
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
return newConfigClient(conn, &stubSandboxResolver{}), func() {
_ = conn.Close()
srv.Stop()
}
}
// --- GetSandbox tests ---
func TestConfigGetSandbox(t *testing.T) {
mock := newMockConfigServer()
mock.sandboxResp = &sbv1.GetSandboxConfigResponse{
Policy: &sbv1.SandboxPolicy{
Version: 4,
Filesystem: &sbv1.FilesystemPolicy{
ReadOnly: []string{"/etc"},
},
},
Version: 3,
PolicyHash: "sha256:deadbeef",
ConfigRevision: 42,
PolicySource: sbv1.PolicySource_POLICY_SOURCE_SANDBOX,
GlobalPolicyVersion: 1,
ProviderEnvRevision: 7,
Settings: map[string]*sbv1.EffectiveSetting{
"max_tokens": {
Value: &sbv1.SettingValue{
Value: &sbv1.SettingValue_IntValue{IntValue: 4096},
},
Scope: sbv1.SettingScope_SETTING_SCOPE_SANDBOX,
},
"debug": {
Value: &sbv1.SettingValue{
Value: &sbv1.SettingValue_BoolValue{BoolValue: true},
},
Scope: sbv1.SettingScope_SETTING_SCOPE_GLOBAL,
},
},
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
sc, err := client.GetSandbox(context.Background(), "default", "my-sandbox")
require.NoError(t, err)
require.NotNil(t, sc)
// Verify request was forwarded with resolved ID (stubSandboxResolver returns "sb-<name>").
mock.mu.Lock()
assert.Equal(t, "my-sandbox", mock.lastSandboxReq.GetName())
mock.mu.Unlock()
// Scalar fields.
assert.Equal(t, uint32(3), sc.PolicyVersion)
assert.Equal(t, "sha256:deadbeef", sc.PolicyHash)
assert.Equal(t, uint64(42), sc.ConfigRevision)
assert.Equal(t, PolicySource("sandbox"), sc.PolicySource)
assert.Equal(t, uint32(1), sc.GlobalPolicyVersion)
assert.Equal(t, uint64(7), sc.ProviderEnvRevision)
// Typed SandboxPolicy.
require.NotNil(t, sc.Policy)
assert.Equal(t, uint32(4), sc.Policy.Version)
require.NotNil(t, sc.Policy.Filesystem)
assert.Equal(t, []string{"/etc"}, sc.Policy.Filesystem.ReadOnly)
// Settings map.
require.Len(t, sc.Settings, 2)
maxTok := sc.Settings["max_tokens"]
assert.Equal(t, SettingValueType("int"), maxTok.Value.Type)
assert.Equal(t, int64(4096), maxTok.Value.IntVal)
assert.Equal(t, SettingScope("sandbox"), maxTok.Scope)
debug := sc.Settings["debug"]
assert.Equal(t, SettingValueType("bool"), debug.Value.Type)
assert.True(t, debug.Value.BoolVal)
assert.Equal(t, SettingScope("global"), debug.Scope)
}
func TestConfigGetSandbox_DeepCopy(t *testing.T) {
mock := newMockConfigServer()
mock.sandboxResp = &sbv1.GetSandboxConfigResponse{
Version: 1,
Settings: map[string]*sbv1.EffectiveSetting{
"key": {
Value: &sbv1.SettingValue{
Value: &sbv1.SettingValue_BytesValue{BytesValue: []byte("original")},
},
Scope: sbv1.SettingScope_SETTING_SCOPE_SANDBOX,
},
},
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
sc, err := client.GetSandbox(context.Background(), "default", "sb1")
require.NoError(t, err)
// Mutate the returned setting — should not affect future calls.
sc.Settings["key"] = EffectiveSetting{}
sc2, err := client.GetSandbox(context.Background(), "default", "sb1")
require.NoError(t, err)
// The server still returns the original value — verifies we're not
// sharing references between calls.
require.Contains(t, sc2.Settings, "key")
assert.Equal(t, []byte("original"), sc2.Settings["key"].Value.BytesVal)
}
func TestConfigGetSandbox_Error(t *testing.T) {
mock := newMockConfigServer()
mock.sandboxErr = status.Errorf(codes.Unavailable, "server unavailable")
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
sc, err := client.GetSandbox(context.Background(), "default", "my-sandbox")
assert.Nil(t, sc)
require.Error(t, err)
assert.True(t, IsUnavailable(err))
}
// --- Name-to-ID resolution tests ---
func TestConfigGetSandbox_UsesName(t *testing.T) {
mock := newMockConfigServer()
mock.sandboxResp = &sbv1.GetSandboxConfigResponse{Version: 1}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
sc, err := client.GetSandbox(context.Background(), "default", "my-sandbox")
require.NoError(t, err)
require.NotNil(t, sc)
// stubSandboxResolver returns ID "sb-<name>" — verify the proto has the resolved ID, not the name.
mock.mu.Lock()
assert.Equal(t, "my-sandbox", mock.lastSandboxReq.GetName())
mock.mu.Unlock()
}
func TestConfigGetSandbox_ResolutionError(t *testing.T) {
mock := newMockConfigServer()
lis := bufconn.Listen(bufSize)
srv := grpc.NewServer()
pb.RegisterOpenShellServer(srv, mock)
go func() { _ = srv.Serve(lis) }()
conn, err := grpc.NewClient("passthrough:///bufconn",
grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) {
return lis.Dial()
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
defer func() {
_ = conn.Close()
srv.Stop()
}()
resolver := &stubSandboxResolver{
getErr: &StatusError{Code: ErrorNotFound, Message: "sandbox not found"},
}
client := newConfigClient(conn, resolver)
sc, err := client.GetSandbox(context.Background(), "default", "nonexistent")
assert.Nil(t, sc)
require.Error(t, err)
assert.True(t, IsNotFound(err))
}
// --- GetGateway tests ---
func TestConfigGetGateway(t *testing.T) {
mock := newMockConfigServer()
mock.gatewayResp = &sbv1.GetGatewayConfigResponse{
SettingsRevision: 99,
Settings: map[string]*sbv1.SettingValue{
"rate_limit": {
Value: &sbv1.SettingValue_IntValue{IntValue: 1000},
},
"motd": {
Value: &sbv1.SettingValue_StringValue{StringValue: "welcome"},
},
},
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
gc, err := client.GetGateway(context.Background())
require.NoError(t, err)
require.NotNil(t, gc)
assert.Equal(t, uint64(99), gc.SettingsRevision)
require.Len(t, gc.Settings, 2)
rl := gc.Settings["rate_limit"]
assert.Equal(t, SettingValueType("int"), rl.Type)
assert.Equal(t, int64(1000), rl.IntVal)
motd := gc.Settings["motd"]
assert.Equal(t, SettingValueType("string"), motd.Type)
assert.Equal(t, "welcome", motd.StringVal)
}
func TestConfigGetGateway_Error(t *testing.T) {
mock := newMockConfigServer()
mock.gatewayErr = status.Errorf(codes.Internal, "internal error")
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
gc, err := client.GetGateway(context.Background())
assert.Nil(t, gc)
require.Error(t, err)
var se *StatusError
require.ErrorAs(t, err, &se)
assert.Equal(t, ErrorInternal, se.Code)
}
// --- Update tests ---
func TestConfigUpdate_SandboxScope(t *testing.T) {
mock := newMockConfigServer()
mock.updateResp = &pb.UpdateConfigResponse{
Version: 5,
PolicyHash: "sha256:cafe",
SettingsRevision: 10,
Deleted: false,
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
update := &ConfigUpdate{
Name: "my-sandbox",
SettingKey: "max_tokens",
SettingValue: &SettingValue{
Type: SettingValueInt,
IntVal: 8192,
},
ExpectedResourceVersion: 4,
}
result, err := client.Update(context.Background(), "default", update)
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, uint32(5), result.Version)
assert.Equal(t, "sha256:cafe", result.PolicyHash)
assert.Equal(t, uint64(10), result.SettingsRevision)
assert.False(t, result.Deleted)
// Verify request was correctly converted.
mock.mu.Lock()
req := mock.lastUpdateReq
mock.mu.Unlock()
require.NotNil(t, req)
assert.Equal(t, "my-sandbox", req.GetSandbox())
assert.Equal(t, "max_tokens", req.GetSettingKey())
assert.False(t, req.GetGlobal())
assert.Equal(t, uint64(4), req.GetExpectedResourceVersion())
assert.Equal(t, int64(8192), req.GetSettingValue().GetIntValue())
}
func TestConfigUpdate_GlobalScope(t *testing.T) {
mock := newMockConfigServer()
mock.updateResp = &pb.UpdateConfigResponse{
SettingsRevision: 20,
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
update := &ConfigUpdate{
Global: true,
SettingKey: "global_flag",
SettingValue: &SettingValue{
Type: SettingValueBool,
BoolVal: true,
},
}
result, err := client.Update(context.Background(), "default", update)
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, uint64(20), result.SettingsRevision)
mock.mu.Lock()
req := mock.lastUpdateReq
mock.mu.Unlock()
assert.True(t, req.GetGlobal())
assert.Empty(t, req.GetSandbox())
}
func TestConfigUpdate_DeleteSetting(t *testing.T) {
mock := newMockConfigServer()
mock.updateResp = &pb.UpdateConfigResponse{
SettingsRevision: 15,
Deleted: true,
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
update := &ConfigUpdate{
Name: "my-sandbox",
SettingKey: "deprecated_key",
DeleteSetting: true,
}
result, err := client.Update(context.Background(), "default", update)
require.NoError(t, err)
require.NotNil(t, result)
assert.True(t, result.Deleted)
assert.Equal(t, uint64(15), result.SettingsRevision)
mock.mu.Lock()
req := mock.lastUpdateReq
mock.mu.Unlock()
assert.True(t, req.GetDeleteSetting())
}
func TestConfigUpdate_WithPolicy(t *testing.T) {
mock := newMockConfigServer()
mock.updateResp = &pb.UpdateConfigResponse{
Version: 2,
PolicyHash: "sha256:newpolicy",
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
update := &ConfigUpdate{
Name: "my-sandbox",
Policy: &types.SandboxPolicy{
Version: 5,
Filesystem: &types.FilesystemPolicy{
ReadOnly: []string{"/usr"},
},
},
}
result, err := client.Update(context.Background(), "default", update)
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, uint32(2), result.Version)
// Verify the typed policy was converted and sent as proto.
mock.mu.Lock()
req := mock.lastUpdateReq
mock.mu.Unlock()
require.NotNil(t, req.GetPolicy())
assert.Equal(t, uint32(5), req.GetPolicy().GetVersion())
require.NotNil(t, req.GetPolicy().GetFilesystem())
assert.Equal(t, []string{"/usr"}, req.GetPolicy().GetFilesystem().GetReadOnly())
}
func TestConfigUpdate_RejectsUnrepresentableMiddlewareConfigBeforeRPC(t *testing.T) {
mock := newMockConfigServer()
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
_, err := client.Update(context.Background(), "default", &ConfigUpdate{Policy: &SandboxPolicy{
NetworkMiddlewares: map[string]types.NetworkMiddlewareConfig{
"audit": {Config: map[string]any{"invalid": make(chan int)}},
},
}})
require.Error(t, err)
assert.True(t, IsInvalidArgument(err))
mock.mu.Lock()
defer mock.mu.Unlock()
assert.Nil(t, mock.lastUpdateReq)
}
func TestConfigUpdate_Error(t *testing.T) {
mock := newMockConfigServer()
mock.updateErr = status.Errorf(codes.FailedPrecondition, "version mismatch")
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
update := &ConfigUpdate{
Name: "my-sandbox",
SettingKey: "key",
ExpectedResourceVersion: 99,
}
result, err := client.Update(context.Background(), "default", update)
assert.Nil(t, result)
require.Error(t, err)
var se *StatusError
require.ErrorAs(t, err, &se)
assert.Equal(t, ErrorConflict, se.Code)
}
func TestConfigUpdate_NilUpdate(t *testing.T) {
mock := newMockConfigServer()
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
result, err := client.Update(context.Background(), "default", nil)
assert.Nil(t, result)
require.Error(t, err)
assert.True(t, IsInvalidArgument(err))
}
func TestConfigUpdate_MergeOperationsAccepted(t *testing.T) {
mock := newMockConfigServer()
mock.updateResp = &pb.UpdateConfigResponse{
Version: 3,
PolicyHash: "abc123",
}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
update := &ConfigUpdate{
Name: "my-sandbox",
MergeOperations: []types.PolicyMergeOperation{{RemoveRule: &types.RemoveNetworkRule{RuleName: "test"}}},
}
result, err := client.Update(context.Background(), "default", update)
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, uint32(3), result.Version)
assert.Equal(t, "abc123", result.PolicyHash)
// Verify the merge operations were serialized in the proto request
mock.mu.Lock()
req := mock.lastUpdateReq
mock.mu.Unlock()
require.NotNil(t, req)
assert.NotEmpty(t, req.GetMergeOperations(), "MergeOperations should be serialized to proto")
}
func TestConfigUpdate_L7TargetScopeSurvivesTransport(t *testing.T) {
mock := newMockConfigServer()
mock.updateResp = &pb.UpdateConfigResponse{Version: 3}
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
path := ""
_, err := client.Update(context.Background(), "default", &ConfigUpdate{
Name: "my-sandbox",
MergeOperations: []PolicyMergeOperation{
{AddAllowRules: &AddAllowRules{
Target: &L7RuleTarget{
RuleName: "api", Host: "api.example.com",
Ports: []uint32{443, 8443},
Path: &path,
Binaries: []PolicyNetworkBinary{{Path: "/usr/bin/curl"}, {Path: "/usr/bin/wget"}},
},
Rules: []L7Rule{{Allow: &L7Allow{Method: "POST", Path: "/admin"}}},
}},
{AddDenyRules: &AddDenyRules{
Target: &L7RuleTarget{
RuleName: "public-api", Host: "public.example.com",
Ports: []uint32{443},
AnyBinary: true,
},
DenyRules: []L7DenyRule{{Method: "DELETE", Path: "/admin"}},
}},
},
})
require.NoError(t, err)
mock.mu.Lock()
req := mock.lastUpdateReq
mock.mu.Unlock()
require.NotNil(t, req)
require.Len(t, req.GetMergeOperations(), 2)
allow := req.GetMergeOperations()[0].GetAddAllowRules()
require.NotNil(t, allow)
allowTarget := allow.GetTarget()
require.NotNil(t, allowTarget)
assert.Equal(t, "api", allowTarget.GetRuleName())
assert.Equal(t, "api.example.com", allowTarget.GetHost())
assert.Equal(t, []uint32{443, 8443}, allowTarget.GetPorts())
require.NotNil(t, allowTarget.Path, "empty endpoint path must survive protobuf encoding")
assert.Empty(t, *allowTarget.Path)
require.Len(t, allowTarget.GetBinaries(), 2)
assert.Equal(t, "/usr/bin/curl", allowTarget.GetBinaries()[0].GetPath())
assert.Equal(t, "/usr/bin/wget", allowTarget.GetBinaries()[1].GetPath())
assert.False(t, allowTarget.GetAnyBinary())
require.Len(t, allow.GetRules(), 1)
assert.Equal(t, "POST", allow.GetRules()[0].GetAllow().GetMethod())
assert.Equal(t, "/admin", allow.GetRules()[0].GetAllow().GetPath())
deny := req.GetMergeOperations()[1].GetAddDenyRules()
require.NotNil(t, deny)
denyTarget := deny.GetTarget()
require.NotNil(t, denyTarget)
assert.Equal(t, "public-api", denyTarget.GetRuleName())
assert.Equal(t, "public.example.com", denyTarget.GetHost())
assert.Equal(t, []uint32{443}, denyTarget.GetPorts())
assert.Nil(t, denyTarget.Path)
assert.Empty(t, denyTarget.GetBinaries())
assert.True(t, denyTarget.GetAnyBinary())
require.Len(t, deny.GetDenyRules(), 1)
assert.Equal(t, "DELETE", deny.GetDenyRules()[0].GetMethod())
assert.Equal(t, "/admin", deny.GetDenyRules()[0].GetPath())
}
func TestConfigUpdate_ErrorConflict(t *testing.T) {
mock := newMockConfigServer()
mock.updateErr = status.Error(codes.Aborted, "resource version conflict")
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
update := &ConfigUpdate{
Name: "my-sandbox",
ExpectedResourceVersion: 5,
}
result, err := client.Update(context.Background(), "default", update)
assert.Nil(t, result)
require.Error(t, err)
assert.True(t, IsConflict(err))
}
func TestConfigGetSandbox_EmptySandboxName(t *testing.T) {
mock := newMockConfigServer()
client, cleanup := setupConfigTest(t, mock)
defer cleanup()
cfg, err := client.GetSandbox(context.Background(), "default", "")
assert.Nil(t, cfg)
require.Error(t, err)
assert.True(t, IsInvalidArgument(err))
}
-20
View File
@@ -1,20 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import "context"
func contextError(err error) error {
if err == nil {
return nil
}
switch err {
case context.DeadlineExceeded:
return &StatusError{Code: ErrorDeadlineExceeded, Message: err.Error(), Cause: err}
case context.Canceled:
return &StatusError{Code: ErrorCancelled, Message: err.Error(), Cause: err}
default:
return &StatusError{Code: ErrorInternal, Message: err.Error(), Cause: err}
}
}
@@ -1,49 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestContextError_Nil(t *testing.T) {
result := contextError(nil)
assert.Nil(t, result)
}
func TestContextError_DeadlineExceeded(t *testing.T) {
result := contextError(context.DeadlineExceeded)
require.Error(t, result)
var se *StatusError
require.True(t, errors.As(result, &se))
assert.Equal(t, ErrorDeadlineExceeded, se.Code)
assert.True(t, errors.Is(result, context.DeadlineExceeded))
}
func TestContextError_Canceled(t *testing.T) {
result := contextError(context.Canceled)
require.Error(t, result)
var se *StatusError
require.True(t, errors.As(result, &se))
assert.Equal(t, ErrorCancelled, se.Code)
assert.True(t, errors.Is(result, context.Canceled))
}
func TestContextError_Default(t *testing.T) {
orig := errors.New("unexpected context error")
result := contextError(orig)
require.Error(t, result)
var se *StatusError
require.True(t, errors.As(result, &se))
assert.Equal(t, ErrorInternal, se.Code)
assert.True(t, errors.Is(result, orig))
}
-466
View File
@@ -1,466 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// Package v1 provides a Go SDK for interacting with OpenShell servers.
//
// The SDK follows the Kubernetes client-go sub-client pattern: a single Client
// provides typed accessors for each resource domain (Sandboxes, Providers, Exec,
// Files, Health, Services, SSH, TCP, Config, Policy, and Workspaces). Network
// operations accept a context.Context and return idiomatic Go types.
// Proto-generated types never appear in the public API.
//
// # Quick Start
//
// client, err := v1.NewClient(v1.Config{
// Address: "gateway.example.com:443",
// Auth: v1.StaticToken("my-token"),
// })
// if err != nil {
// log.Fatal(err)
// }
// defer client.Close()
//
// # Sandbox Lifecycle
//
// sandbox, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{
// Template: &v1.SandboxTemplate{Image: "python:3.12"},
// Environment: map[string]string{"LANG": "en_US.UTF-8"},
// })
// if err != nil {
// log.Fatal(err)
// }
//
// sandbox, err = client.Sandboxes().WaitReady(ctx, "default", sandbox.Name)
// if err != nil {
// log.Fatal(err)
// }
//
// # Pagination
//
// List methods construct a lazy Pager without issuing an RPC. Each NextPage
// call fetches one page; ListAll is the explicit exhaustive convenience.
//
// pages, err := client.Sandboxes().List("default", v1.ListOptions{PageSize: 100})
// if err != nil {
// log.Fatal(err)
// }
// for {
// page, err := pages.NextPage(ctx)
// if err != nil {
// log.Fatal(err)
// }
// if page == nil {
// break
// }
// for _, sandbox := range page.Items {
// fmt.Println(sandbox.Name)
// }
// }
//
// # Command Execution
//
// result, err := client.Exec().Run(ctx, "default", sandbox.Name, []string{"echo", "hello"}, v1.ExecOptions{})
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(string(result.Stdout)) // "hello\n"
//
// # Error Handling
//
// _, err = client.Sandboxes().Get(ctx, "default", "missing")
// if v1.IsNotFound(err) {
// // handle not found
// }
//
// # Watching
//
// watcher, err := client.Sandboxes().Watch(ctx, "default", sandbox.Name)
// if err != nil {
// log.Fatal(err)
// }
// defer watcher.Stop()
// for event := range watcher.ResultChan() {
// fmt.Printf("%s: %s\n", event.Type, event.Object.Name)
// }
//
// # Watching with StopOnTerminal
//
// Use StopOnTerminal to auto-close the watcher when the sandbox reaches a
// terminal phase (Ready or Error):
//
// watcher, err := client.Sandboxes().Watch(ctx, "default", sandbox.Name,
// v1.WatchOptions{StopOnTerminal: true},
// )
// if err != nil {
// log.Fatal(err)
// }
// for event := range watcher.ResultChan() {
// fmt.Printf("phase: %s\n", event.Object.Status.Phase)
// }
// // channel closes automatically after Ready or Error
//
// # Service Exposure
//
// Expose an HTTP service running inside a sandbox and retrieve its public URL:
//
// endpoint, err := client.Services().Expose(ctx, "default", "my-sandbox", "api", 8080, true)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Service URL: %s\n", endpoint.URL)
//
// endpoints, err := client.Services().ListAll(ctx, "default", "my-sandbox")
// if err != nil {
// log.Fatal(err)
// }
// for _, ep := range endpoints {
// fmt.Printf(" %s → port %d (URL: %s)\n", ep.Name, ep.TargetPort, ep.URL)
// }
//
// # Provider Profiles
//
// List available provider profiles and import new ones:
//
// profiles, err := client.Providers().Profiles().ListAll(ctx, "default")
// if err != nil {
// log.Fatal(err)
// }
// for _, p := range profiles {
// fmt.Printf("%s (%s): %s\n", p.DisplayName, p.Category, p.Description)
// }
//
// result, err := client.Providers().Profiles().Import(ctx, "default", []v1.ProfileImportItem{
// {Source: "openai-profile.yaml", Profile: v1.ProviderProfile{
// DisplayName: "OpenAI",
// Category: v1.ProfileCategoryInference,
// }},
// })
// if err != nil {
// log.Fatal(err)
// }
// for _, d := range result.Diagnostics {
// fmt.Printf("[%s] %s: %s\n", d.Severity, d.Field, d.Message)
// }
//
// # Credential Refresh
//
// Configure gateway-owned credential refresh for a provider:
//
// status, err := client.Providers().Refresh().Configure(ctx, "default", &v1.RefreshConfig{
// Provider: "openai",
// CredentialKey: "api-key",
// Strategy: v1.RefreshStrategyOAuth2ClientCredentials,
// Material: map[string]string{"client_id": "xxx", "client_secret": "yyy"},
// })
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Refresh status: %s (next: %s)\n", status.Status, status.NextRefreshAt)
//
// # Token Refresh
//
// Use RefreshableToken for automatic OAuth2 token caching and refresh.
// Concurrent callers share a single refresh call:
//
// tokenSource := oauth2Config.TokenSource(ctx, initialToken)
// auth, err := v1.RefreshableToken(tokenSource,
// v1.WithLeeway(30*time.Second),
// )
// if err != nil {
// log.Fatal(err)
// }
// client, err := v1.NewClient(v1.Config{
// Address: "gateway.example.com:443",
// Auth: auth,
// })
// if err != nil {
// log.Fatal(err)
// }
// defer client.Close()
//
// # Extra Headers
//
// Use WithExtraHeaders to attach additional per-RPC headers to any auth
// provider. This is useful for edge proxies, API gateways, or any middleware
// that requires custom headers alongside standard authentication:
//
// base := v1.StaticToken("my-token")
// auth, err := v1.WithExtraHeaders(base, map[string]string{
// "x-proxy-key": "proxy-secret",
// "x-tenant-id": "acme-corp",
// })
// if err != nil {
// log.Fatal(err)
// }
// client, err := v1.NewClient(v1.Config{
// Address: "gateway.example.com:443",
// Auth: auth,
// })
// if err != nil {
// log.Fatal(err)
// }
// defer client.Close()
//
// Keys are normalized to lowercase (per HTTP/2 RFC 9113). On key collision,
// extra headers take precedence over base auth headers. Empty-string values
// are silently dropped. WithExtraHeaders composes with any AuthProvider,
// including RefreshableToken:
//
// tokenSource := oauth2Config.TokenSource(ctx, initialToken)
// refreshAuth, err := v1.RefreshableToken(tokenSource)
// if err != nil {
// log.Fatal(err)
// }
// auth, err := v1.WithExtraHeaders(refreshAuth, map[string]string{
// "x-proxy-key": "proxy-secret",
// })
//
// # SSH Session Management
//
// Create an SSH session for a sandbox by its canonical name in a workspace and
// use the returned connection details.
//
// session, err := client.SSH().CreateSession(ctx, "default", sandbox.Name)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("SSH to %s:%d (scheme: %s)\n",
// session.GatewayHost, session.GatewayPort, session.GatewayScheme)
// fmt.Printf("Host key: %s\n", session.HostKeyFingerprint)
// // Use session.Token to authenticate the SSH connection.
//
// deletion, err := client.SSH().RevokeSession(ctx, "default", session.Token)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Revocation outcome: %v\n", deletion.Outcome)
//
// # TCP Port Forwarding
//
// Forward a local connection to a port inside a sandbox:
//
// conn, err := client.TCP().Forward(ctx, "default", "my-sandbox", 5432)
// if err != nil {
// log.Fatal(err)
// }
// defer conn.Close()
//
// // conn implements io.ReadWriteCloser, use it like a net.Conn.
// _, err = conn.Write([]byte("PING\n"))
// if err != nil {
// log.Fatal(err)
// }
// buf := make([]byte, 1024)
// n, err := conn.Read(buf)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Response: %s\n", buf[:n])
//
// Use WithForwardServiceID to tag the forwarding session with a service
// identifier for audit logging:
//
// conn, err := client.TCP().Forward(ctx, "default", "my-sandbox", 5432,
// v1.WithForwardServiceID("billing-db"),
// )
//
// # SSH Tunneling
//
// Create an SSH tunnel to a sandbox port in a single call. Tunnel combines
// session creation, TCP forwarding with an SSH relay target, and automatic
// session cleanup into one operation:
//
// tunnel, err := client.SSH().Tunnel(ctx, "default", "my-sandbox", 22)
// if err != nil {
// log.Fatal(err)
// }
// defer tunnel.Close()
//
// // tunnel implements io.ReadWriteCloser. The underlying SSH session
// // is automatically revoked when Close is called.
// _, err = tunnel.Write([]byte("SSH-2.0-client\r\n"))
// if err != nil {
// log.Fatal(err)
// }
// buf := make([]byte, 256)
// n, err := tunnel.Read(buf)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Server banner: %s\n", buf[:n])
//
// Use WithTunnelServiceID to associate a service identifier with the tunnel:
//
// tunnel, err := client.SSH().Tunnel(ctx, "default", "my-sandbox", 22,
// v1.WithTunnelServiceID("dev-ssh"),
// )
//
// # Sandbox Policy
//
// Set an initial security policy when creating a sandbox:
//
// sandbox, err := client.Sandboxes().Create(ctx, "default", "secure-sandbox", &v1.SandboxSpec{
// Template: &v1.SandboxTemplate{Image: "python:3.12"},
// Policy: &v1.SandboxPolicy{
// Version: 1,
// Filesystem: &v1.FilesystemPolicy{
// IncludeWorkdir: true,
// ReadOnly: []string{"/usr", "/lib"},
// },
// Process: &v1.ProcessPolicy{
// RunAsUser: "sandbox",
// RunAsGroup: "sandbox",
// },
// NetworkPolicies: map[string]v1.NetworkPolicyRule{
// "allow-api": {
// Name: "allow-api",
// Endpoints: []v1.PolicyNetworkEndpoint{
// {Host: "api.example.com", Port: 443, Protocol: "tcp"},
// },
// },
// },
// },
// })
//
// Replace the full policy at runtime via configuration update:
//
// result, err := client.Config().Update(ctx, "default", &v1.ConfigUpdate{
// Name: "secure-sandbox",
// Policy: &v1.SandboxPolicy{
// Version: 2,
// NetworkPolicies: map[string]v1.NetworkPolicyRule{
// "allow-all": {Name: "allow-all"},
// },
// },
// })
//
// Read a policy back from revision history:
//
// revisions, err := client.Policy().ListAll(ctx, "default", "my-sandbox")
// if err != nil {
// log.Fatal(err)
// }
// for _, rev := range revisions {
// if rev.Policy != nil {
// fmt.Printf("v%d: %d network rules\n", rev.Version, len(rev.Policy.NetworkPolicies))
// }
// }
//
// # Global Policy
//
// List gateway-global policy revisions (no sandbox name or workspace needed):
//
// revisions, err := client.Policy().ListAll(ctx, "", "", v1.WithListGlobal(true))
// if err != nil {
// log.Fatal(err)
// }
// for _, rev := range revisions {
// fmt.Printf("Global v%d: %s\n", rev.Version, rev.Status)
// }
//
// Get the status of a specific global policy version:
//
// status, err := client.Policy().GetStatus(ctx, "", "",
// v1.WithStatusGlobal(true), v1.WithVersion(3),
// )
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Version %d status: %s\n", status.Revision.Version, status.Revision.Status)
//
// # Workspace Management
//
// Create and manage workspaces for multi-tenant resource isolation:
//
// ws, err := client.Workspaces().Create(ctx, "team-alpha", map[string]string{
// "team": "alpha",
// "env": "production",
// })
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Workspace %s created (phase: %s)\n", ws.Name, ws.Phase)
//
// workspaces, err := client.Workspaces().ListAll(ctx)
// if err != nil {
// log.Fatal(err)
// }
// for _, w := range workspaces {
// fmt.Printf(" %s (phase: %s)\n", w.Name, w.Phase)
// }
//
// # Workspace Members
//
// Manage workspace membership with role-based access:
//
// member, err := client.Workspaces().AddMember(ctx, "team-alpha",
// "alice@example.com", v1.WorkspaceRoleAdmin)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Added %s as %s\n", member.PrincipalSubject, member.Role)
//
// members, err := client.Workspaces().ListAllMembers(ctx, "team-alpha")
// if err != nil {
// log.Fatal(err)
// }
// for _, m := range members {
// fmt.Printf(" %s (%s)\n", m.PrincipalSubject, m.Role)
// }
//
// # Gateway Info
//
// Query gateway metadata and compute driver capabilities:
//
// info, err := client.Health().GetGatewayInfo(ctx)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Gateway %s (status: %s)\n", info.Version, info.Status)
// for _, d := range info.ComputeDrivers {
// fmt.Printf(" Driver: %s %s\n", d.DriverName, d.DriverVersion)
// }
//
// # Current User
//
// Determine the identity of the authenticated caller:
//
// user, err := client.Health().GetCurrentUser(ctx)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Logged in as %s (%s)\n", user.DisplayName, user.Subject)
// fmt.Printf("Roles: %v, Scopes: %v\n", user.Roles, user.Scopes)
//
// # Configuration Management
//
// Read sandbox and gateway configuration, and update settings:
//
// sbCfg, err := client.Config().GetSandbox(ctx, "default", "my-sandbox")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Config revision: %d\n", sbCfg.ConfigRevision)
// for name, setting := range sbCfg.Settings {
// fmt.Printf(" %s = %v (scope: %s)\n", name, setting.Value, setting.Scope)
// }
//
// gwCfg, err := client.Config().GetGateway(ctx)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Gateway settings revision: %d\n", gwCfg.SettingsRevision)
//
// result, err := client.Config().Update(ctx, "default", &v1.ConfigUpdate{
// Name: "my-sandbox",
// SettingKey: "max_tokens",
// SettingValue: &v1.SettingValue{
// Type: v1.SettingValueInt,
// IntVal: 8192,
// },
// })
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("New settings revision: %d\n", result.SettingsRevision)
package v1
-29
View File
@@ -1,29 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package edge
import (
"errors"
"fmt"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
)
// CloudflareAccess returns an AuthProvider that adds Cloudflare Access
// headers to every RPC. It sets:
// - cf-access-jwt-assertion: the edge JWT token
// - cookie: CF_Authorization=<token>
//
// The edgeToken authenticates with the Cloudflare Access edge proxy.
// Returns an error if baseAuth is nil or edgeToken is empty.
func CloudflareAccess(baseAuth v1.AuthProvider, edgeToken string) (v1.AuthProvider, error) {
if edgeToken == "" {
return nil, errors.New("edge token must not be empty")
}
return v1.WithExtraHeaders(baseAuth, map[string]string{
"cf-access-jwt-assertion": edgeToken,
"cookie": fmt.Sprintf("CF_Authorization=%s", edgeToken),
})
}
@@ -1,88 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package edge
import (
"context"
"testing"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCloudflareAccess_ValidToken(t *testing.T) {
base := v1.StaticToken("my-token")
auth, err := CloudflareAccess(base, "cf-edge-jwt-xxx")
require.NoError(t, err)
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
// Base auth header preserved.
assert.Equal(t, "Bearer my-token", md["authorization"])
// Cloudflare-specific headers present.
assert.Equal(t, "cf-edge-jwt-xxx", md["cf-access-jwt-assertion"])
assert.Equal(t, "CF_Authorization=cf-edge-jwt-xxx", md["cookie"])
}
func TestCloudflareAccess_EmptyToken(t *testing.T) {
base := v1.StaticToken("my-token")
_, err := CloudflareAccess(base, "")
require.Error(t, err)
assert.Contains(t, err.Error(), "edge token")
}
func TestCloudflareAccess_NilBase(t *testing.T) {
_, err := CloudflareAccess(nil, "cf-edge-jwt-xxx")
require.Error(t, err)
assert.Contains(t, err.Error(), "base")
}
func TestCloudflareAccess_WithNoAuth(t *testing.T) {
auth, err := CloudflareAccess(v1.NoAuth(), "cf-edge-jwt-xxx")
require.NoError(t, err)
md, err := auth.GetRequestMetadata(context.Background())
require.NoError(t, err)
// NoAuth provides no base metadata; only CF headers should appear.
assert.Equal(t, "cf-edge-jwt-xxx", md["cf-access-jwt-assertion"])
assert.Equal(t, "CF_Authorization=cf-edge-jwt-xxx", md["cookie"])
}
func TestCloudflareAccess_RequireTransportSecurity_Delegates(t *testing.T) {
tests := []struct {
name string
base v1.AuthProvider
expected bool
}{
{
name: "delegates to NoAuth (false)",
base: v1.NoAuth(),
expected: false,
},
{
name: "delegates to StaticToken (true)",
base: v1.StaticToken("tok"),
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
auth, err := CloudflareAccess(tt.base, "cf-edge-jwt-xxx")
require.NoError(t, err)
assert.Equal(t, tt.expected, auth.RequireTransportSecurity())
})
}
}
func TestCloudflareAccess_TokenNotInError(t *testing.T) {
// Verify the error for empty token does not leak actual token values.
_, err := CloudflareAccess(v1.StaticToken("s3cr3t-val"), "")
require.Error(t, err)
// The error should mention the parameter name, not any token value.
assert.NotContains(t, err.Error(), "s3cr3t-val")
}
-88
View File
@@ -1,88 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// Package edge provides utilities for connecting to OpenShell gateways
// through edge proxies such as Cloudflare Access. It includes convenience
// constructors for common edge auth patterns and a WebSocket tunnel proxy
// for gRPC transport through HTTP/1.1-only proxies.
//
// # Cloudflare Access
//
// CloudflareAccess wraps any AuthProvider with the headers required by
// Cloudflare Access (cf-access-jwt-assertion and CF_Authorization cookie).
// The edge token is typically a service token or application token obtained
// from Cloudflare:
//
// base := v1.StaticToken("my-gateway-token")
// auth, err := edge.CloudflareAccess(base, os.Getenv("CF_ACCESS_TOKEN"))
// if err != nil {
// log.Fatal(err)
// }
// client, err := v1.NewClient(v1.Config{
// Address: "gateway.example.com:443",
// Auth: auth,
// })
// if err != nil {
// log.Fatal(err)
// }
// defer client.Close()
//
// CloudflareAccess composes with any auth provider, including RefreshableToken
// for automatic token refresh:
//
// tokenSource := oauth2Config.TokenSource(ctx, initialToken)
// refreshAuth, err := v1.RefreshableToken(tokenSource)
// if err != nil {
// log.Fatal(err)
// }
// auth, err := edge.CloudflareAccess(refreshAuth, cfToken)
// if err != nil {
// log.Fatal(err)
// }
//
// # WebSocket Tunnel
//
// TunnelProxy bridges gRPC connections over a WebSocket tunnel for edge
// proxies that reject standard HTTP/2 POST requests. The tunnel carries
// its own edge token for proxy authentication, independent of the
// application-level auth provider.
//
// Create a tunnel proxy pointed at the gateway, then dial the proxy's
// local address from the gRPC client:
//
// tunnel, err := edge.NewTunnelProxy(
// "wss://gateway.example.com/ws",
// os.Getenv("CF_ACCESS_TOKEN"),
// )
// if err != nil {
// log.Fatal(err)
// }
// defer tunnel.Close()
//
// auth := v1.StaticToken("my-gateway-token")
// client, err := v1.NewClient(v1.Config{
// Address: tunnel.Addr(),
// Auth: auth,
// TLS: &v1.TLSConfig{Insecure: true}, // local tunnel
// })
// if err != nil {
// log.Fatal(err)
// }
// defer client.Close()
//
// Use functional options to configure TLS, logging, and close timeout:
//
// tunnel, err := edge.NewTunnelProxy(
// "wss://gateway.example.com/ws",
// cfToken,
// edge.WithTunnelTLS(&tls.Config{RootCAs: customCertPool}),
// edge.WithTunnelLogger(myLogger),
// edge.WithCloseTimeout(10*time.Second),
// )
//
// Close drains in-flight connections gracefully. If draining exceeds the
// configured timeout (default 5 seconds), remaining connections are
// force-closed:
//
// err := tunnel.Close() // safe to call multiple times
package edge
@@ -1,23 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package edge
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
func TestTunnelOption_NilIgnored(t *testing.T) {
cfg := tunnelConfig{closeTimeout: defaultCloseTimeout}
options.Apply(&cfg, []TunnelOption{
WithTunnelLogger(nil),
nil,
WithCloseTimeout(10 * time.Second),
})
assert.Equal(t, 10*time.Second, cfg.closeTimeout)
}
-294
View File
@@ -1,294 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package edge
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"sync"
"time"
"github.com/coder/websocket"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
const defaultCloseTimeout = 5 * time.Second
// tunnelConfig holds configuration set by TunnelOption functions.
type tunnelConfig struct {
logger types.Logger
tlsConfig *tls.Config
closeTimeout time.Duration
}
// TunnelOption configures TunnelProxy behavior.
type TunnelOption func(*tunnelConfig)
// WithTunnelLogger sets the structured logger for tunnel events.
func WithTunnelLogger(l types.Logger) TunnelOption {
return func(c *tunnelConfig) {
c.logger = l
}
}
// WithTunnelTLS sets TLS configuration for the WebSocket connection (wss://).
func WithTunnelTLS(cfg *tls.Config) TunnelOption {
return func(c *tunnelConfig) {
c.tlsConfig = cfg
}
}
// WithCloseTimeout sets the maximum time Close waits for in-flight
// connections to drain before force-closing. Default is 5 seconds.
func WithCloseTimeout(d time.Duration) TunnelOption {
return func(c *tunnelConfig) {
c.closeTimeout = d
}
}
// TunnelProxy bridges gRPC connections over a WebSocket tunnel.
// The gRPC client dials TunnelProxy.Addr() instead of the remote gateway.
// Each accepted connection spawns a goroutine that dials the gateway over
// WebSocket and copies data bidirectionally.
type TunnelProxy struct {
listener net.Listener
gatewayURL string
edgeToken string
logger types.Logger
closeTimeout time.Duration
httpClient *http.Client
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
mu sync.Mutex
closing bool
closeOnce sync.Once
closeErr error
}
// NewTunnelProxy creates a tunnel proxy that forwards TCP connections
// through a WebSocket connection to gatewayURL. The edgeToken authenticates
// with the edge proxy via Cloudflare Access headers on the WebSocket
// handshake.
//
// Returns error if gatewayURL is empty or invalid, or if edgeToken is empty.
func NewTunnelProxy(gatewayURL, edgeToken string, opts ...TunnelOption) (*TunnelProxy, error) {
if gatewayURL == "" {
return nil, errors.New("gateway URL must not be empty")
}
if edgeToken == "" {
return nil, errors.New("edge token must not be empty")
}
// Validate the URL parses correctly.
u, err := url.Parse(gatewayURL)
if err != nil {
return nil, fmt.Errorf("invalid gateway URL: %w", err)
}
if u.Scheme != "ws" && u.Scheme != "wss" {
return nil, fmt.Errorf("gateway URL must use ws:// or wss:// scheme, got %q", u.Scheme)
}
if u.Host == "" {
return nil, errors.New("gateway URL must include a host")
}
if u.Scheme == "ws" && !isLoopbackHost(u.Hostname()) {
return nil, errors.New("gateway URL with an edge token must use wss:// (ws:// is allowed only for loopback hosts)")
}
cfg := tunnelConfig{
closeTimeout: defaultCloseTimeout,
}
options.Apply(&cfg, opts)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, fmt.Errorf("listen: %w", err)
}
ctx, cancel := context.WithCancel(context.Background())
var httpClient *http.Client
if cfg.tlsConfig != nil {
httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: cfg.tlsConfig,
},
}
}
tp := &TunnelProxy{
listener: listener,
gatewayURL: gatewayURL,
edgeToken: edgeToken,
logger: cfg.logger,
closeTimeout: cfg.closeTimeout,
httpClient: httpClient,
ctx: ctx,
cancel: cancel,
}
// Start the accept loop.
tp.wg.Add(1)
go tp.acceptLoop()
return tp, nil
}
func isLoopbackHost(host string) bool {
if host == "localhost" {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// Addr returns the local address the gRPC client should dial.
func (tp *TunnelProxy) Addr() string {
return tp.listener.Addr().String()
}
// Close drains in-flight connections (up to the configured timeout,
// default 5s) then force-closes any remaining connections. All goroutines
// are cleaned up. Safe to call multiple times; the second and subsequent
// calls return immediately.
func (tp *TunnelProxy) Close() error {
tp.closeOnce.Do(func() {
tp.mu.Lock()
tp.closing = true
tp.mu.Unlock()
// Stop accepting new connections.
tp.closeErr = tp.listener.Close()
// Wait for in-flight connections to drain, with a timeout.
done := make(chan struct{})
go func() {
tp.wg.Wait()
close(done)
}()
select {
case <-done:
// All goroutines drained cleanly.
case <-time.After(tp.closeTimeout):
// Timeout reached; cancel all bridge contexts to force-close.
if tp.logger != nil {
tp.logger.Info("tunnel close timeout reached, force-closing")
}
tp.cancel()
<-done
}
// Always cancel to release the context tree.
tp.cancel()
})
return tp.closeErr
}
// acceptLoop runs in a goroutine. It accepts local TCP connections and
// spawns a bridge goroutine for each one.
func (tp *TunnelProxy) acceptLoop() {
defer tp.wg.Done()
for {
conn, err := tp.listener.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
if tp.logger != nil {
tp.logger.Error(err, "tunnel accept error")
}
time.Sleep(10 * time.Millisecond)
continue
}
tp.mu.Lock()
if tp.closing {
tp.mu.Unlock()
_ = conn.Close()
return
}
tp.wg.Add(1)
tp.mu.Unlock()
if tp.logger != nil {
tp.logger.Debug("tunnel connection accepted", "remote", conn.RemoteAddr().String())
}
go tp.bridge(conn)
}
}
// bridge dials the gateway over WebSocket and copies data bidirectionally
// between the local TCP connection and the WebSocket connection.
func (tp *TunnelProxy) bridge(local net.Conn) {
defer tp.wg.Done()
defer func() { _ = local.Close() }()
ctx, cancel := context.WithCancel(tp.ctx)
defer cancel()
// Build WebSocket dial options with edge auth headers.
dialOpts := &websocket.DialOptions{
HTTPHeader: http.Header{
"cf-access-jwt-assertion": []string{tp.edgeToken},
"cookie": []string{fmt.Sprintf("CF_Authorization=%s", tp.edgeToken)},
},
}
if tp.httpClient != nil {
dialOpts.HTTPClient = tp.httpClient
}
dialCtx, dialCancel := context.WithTimeout(ctx, 10*time.Second)
defer dialCancel()
wsConn, _, err := websocket.Dial(dialCtx, tp.gatewayURL, dialOpts)
if err != nil {
if tp.logger != nil {
tp.logger.Error(err, "tunnel websocket dial failed")
}
return
}
defer func() { _ = wsConn.CloseNow() }()
// Set a generous read limit for gRPC frames.
wsConn.SetReadLimit(64 * 1024 * 1024) // 64 MiB
// Convert the WebSocket connection to a net.Conn for bidirectional I/O.
remote := websocket.NetConn(ctx, wsConn, websocket.MessageBinary)
// Bidirectional copy.
done := make(chan struct{}, 2)
// Local -> Remote (WebSocket)
go func() {
_, _ = io.Copy(remote, local)
done <- struct{}{}
}()
// Remote (WebSocket) -> Local
go func() {
_, _ = io.Copy(local, remote)
done <- struct{}{}
}()
// Wait for one direction to finish, then tear down both.
<-done
cancel()
_ = local.Close()
<-done
if tp.logger != nil {
tp.logger.Debug("tunnel bridge closed")
}
}
-500
View File
@@ -1,500 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package edge
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"runtime"
"slices"
"sync"
"testing"
"time"
"github.com/coder/websocket"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// echoWSHandler accepts a WebSocket connection and echoes every binary
// message back to the sender until the client disconnects.
func echoWSHandler(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
InsecureSkipVerify: true,
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer func() { _ = conn.CloseNow() }()
ctx := r.Context()
for {
typ, data, err := conn.Read(ctx)
if err != nil {
return
}
if err := conn.Write(ctx, typ, data); err != nil {
return
}
}
}
// startEchoServer starts an HTTP test server that upgrades connections to
// WebSocket and echoes binary messages. Returns the server and its ws:// URL.
func startEchoServer(t *testing.T) (*httptest.Server, string) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(echoWSHandler))
t.Cleanup(srv.Close)
// Convert http://host:port to ws://host:port.
wsURL := "ws" + srv.URL[len("http"):]
return srv, wsURL
}
// startTLSEchoServer starts a TLS HTTP test server. Returns the server,
// its wss:// URL, and a tls.Config that trusts the server's certificate.
func startTLSEchoServer(t *testing.T) (*httptest.Server, string, *tls.Config) {
t.Helper()
srv := httptest.NewTLSServer(http.HandlerFunc(echoWSHandler))
t.Cleanup(srv.Close)
wssURL := "wss" + srv.URL[len("https"):]
certPool := x509.NewCertPool()
certPool.AddCert(srv.Certificate())
tlsCfg := &tls.Config{
RootCAs: certPool,
}
return srv, wssURL, tlsCfg
}
// testLogger captures log messages for assertions.
type testLogger struct {
mu sync.Mutex
messages []string
}
func (l *testLogger) Debug(msg string, _ ...any) {
l.mu.Lock()
defer l.mu.Unlock()
l.messages = append(l.messages, "DEBUG: "+msg)
}
func (l *testLogger) Info(msg string, _ ...any) {
l.mu.Lock()
defer l.mu.Unlock()
l.messages = append(l.messages, "INFO: "+msg)
}
func (l *testLogger) Error(_ error, msg string, _ ...any) {
l.mu.Lock()
defer l.mu.Unlock()
l.messages = append(l.messages, "ERROR: "+msg)
}
func (l *testLogger) Messages() []string {
l.mu.Lock()
defer l.mu.Unlock()
cp := make([]string, len(l.messages))
copy(cp, l.messages)
return cp
}
// --- Test: NewTunnelProxy creation ---
func TestNewTunnelProxy_ValidURL(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "edge-token-123")
require.NoError(t, err)
require.NotNil(t, tp)
defer func() { _ = tp.Close() }()
// Addr() must return a non-empty, dialable address.
addr := tp.Addr()
assert.NotEmpty(t, addr)
// Verify the address is dialable.
conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
require.NoError(t, err)
_ = conn.Close()
}
func TestNewTunnelProxy_EmptyURL(t *testing.T) {
_, err := NewTunnelProxy("", "edge-token-123")
require.Error(t, err)
assert.Contains(t, err.Error(), "gateway URL")
}
func TestNewTunnelProxy_InvalidURL(t *testing.T) {
_, err := NewTunnelProxy("://bad-url", "edge-token-123")
require.Error(t, err)
}
func TestNewTunnelProxy_WrongScheme(t *testing.T) {
_, err := NewTunnelProxy("http://gateway.example.com", "edge-token-123")
require.Error(t, err)
assert.Contains(t, err.Error(), "ws:// or wss://")
}
func TestNewTunnelProxy_RejectsCredentialBearingRemoteWS(t *testing.T) {
_, err := NewTunnelProxy("ws://gateway.example.com/tunnel", "edge-token-123")
require.Error(t, err)
assert.Contains(t, err.Error(), "wss://")
}
func TestNewTunnelProxy_EmptyHost(t *testing.T) {
_, err := NewTunnelProxy("ws://", "edge-token-123")
require.Error(t, err)
assert.Contains(t, err.Error(), "must include a host")
}
func TestNewTunnelProxy_EmptyEdgeToken(t *testing.T) {
_, wsURL := startEchoServer(t)
_, err := NewTunnelProxy(wsURL, "")
require.Error(t, err)
assert.Contains(t, err.Error(), "edge token")
}
func TestNewTunnelProxy_TokenNotInError(t *testing.T) {
// Verify error messages do not leak the edge token.
_, err := NewTunnelProxy("", "super-secret-token-abc")
require.Error(t, err)
assert.NotContains(t, err.Error(), "super-secret-token-abc")
}
// --- Test: Addr ---
func TestTunnelProxy_Addr_Dialable(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "tok")
require.NoError(t, err)
defer func() { _ = tp.Close() }()
addr := tp.Addr()
host, port, err := net.SplitHostPort(addr)
require.NoError(t, err)
assert.NotEmpty(t, host)
assert.NotEmpty(t, port)
}
// --- Test: Close on unused proxy ---
func TestTunnelProxy_Close_Unused(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "tok")
require.NoError(t, err)
// Close immediately without any connections should return nil.
err = tp.Close()
assert.NoError(t, err)
}
// --- Test: Close drains in-flight connections ---
func TestTunnelProxy_Close_DrainsInFlight(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "tok", WithCloseTimeout(5*time.Second))
require.NoError(t, err)
// Establish a connection through the tunnel.
conn, err := net.DialTimeout("tcp", tp.Addr(), 2*time.Second)
require.NoError(t, err)
// Send data through the tunnel and verify echo.
testData := []byte("hello tunnel")
_, err = conn.Write(testData)
require.NoError(t, err)
// Give the tunnel time to relay.
time.Sleep(100 * time.Millisecond)
// Close the client connection first so the bridge goroutine can drain.
_ = conn.Close()
// Now close the tunnel; should drain cleanly.
err = tp.Close()
assert.NoError(t, err)
}
// --- Test: Close force-closes after timeout ---
func TestTunnelProxy_Close_ForceClosesAfterTimeout(t *testing.T) {
// Use a slow handler that holds connections open.
slowHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wsConn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
InsecureSkipVerify: true,
})
if err != nil {
return
}
defer func() { _ = wsConn.CloseNow() }()
// Hold the connection open for a long time.
ctx := r.Context()
select {
case <-ctx.Done():
case <-time.After(30 * time.Second):
}
})
srv := httptest.NewServer(slowHandler)
defer srv.Close()
wsURL := "ws" + srv.URL[len("http"):]
// Use a very short close timeout and a logger to verify timeout logging.
logger := &testLogger{}
tp, err := NewTunnelProxy(wsURL, "tok", WithCloseTimeout(200*time.Millisecond), WithTunnelLogger(logger))
require.NoError(t, err)
// Establish a connection that will be held open by the slow handler.
conn, err := net.DialTimeout("tcp", tp.Addr(), 2*time.Second)
require.NoError(t, err)
defer func() { _ = conn.Close() }()
// Write something to trigger the WebSocket dial.
_, _ = conn.Write([]byte("trigger"))
// Give the tunnel time to establish the bridge.
time.Sleep(100 * time.Millisecond)
// Close should force-close after the short timeout, not hang.
start := time.Now()
err = tp.Close()
elapsed := time.Since(start)
// Should complete within a reasonable time (timeout + margin).
assert.Less(t, elapsed, 2*time.Second, "Close should not hang beyond timeout")
// err may or may not be nil depending on force-close; we don't assert on it.
_ = err
// Verify the timeout was logged.
msgs := logger.Messages()
assert.True(t, slices.Contains(msgs, "INFO: tunnel close timeout reached, force-closing"),
"expected timeout log message, got: %v", msgs)
}
// --- Test: Concurrent Close is safe ---
func TestTunnelProxy_Close_ConcurrentSafe(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "tok")
require.NoError(t, err)
// Call Close concurrently from multiple goroutines.
var wg sync.WaitGroup
errs := make([]error, 10)
for i := range errs {
wg.Add(1)
go func(idx int) {
defer wg.Done()
errs[idx] = tp.Close()
}(i)
}
wg.Wait()
// All calls should succeed without panic.
for _, e := range errs {
assert.NoError(t, e)
}
}
// --- Test: Goroutine cleanup ---
func TestTunnelProxy_GoroutineCleanup(t *testing.T) {
_, wsURL := startEchoServer(t)
// Record baseline goroutine count.
runtime.GC()
time.Sleep(50 * time.Millisecond)
baseline := runtime.NumGoroutine()
tp, err := NewTunnelProxy(wsURL, "tok")
require.NoError(t, err)
// Open several connections.
conns := make([]net.Conn, 5)
for i := range conns {
c, err := net.DialTimeout("tcp", tp.Addr(), 2*time.Second)
require.NoError(t, err)
_, _ = fmt.Fprintf(c, "msg-%d", i)
conns[i] = c
}
// Let bridges establish.
time.Sleep(100 * time.Millisecond)
// Close all client connections.
for _, c := range conns {
_ = c.Close()
}
// Close the tunnel.
err = tp.Close()
require.NoError(t, err)
// Wait for goroutines to wind down.
time.Sleep(200 * time.Millisecond)
runtime.GC()
// Goroutine count should return to near baseline.
// Allow a small margin for runtime goroutines.
final := runtime.NumGoroutine()
assert.LessOrEqual(t, final, baseline+3,
"goroutine leak: baseline=%d, final=%d", baseline, final)
}
// --- Test: Concurrent streams ---
func TestTunnelProxy_ConcurrentStreams(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "tok")
require.NoError(t, err)
defer func() { _ = tp.Close() }()
const streamCount = 10
var wg sync.WaitGroup
errs := make(chan error, streamCount)
for i := range streamCount {
wg.Add(1)
go func(idx int) {
defer wg.Done()
conn, err := net.DialTimeout("tcp", tp.Addr(), 2*time.Second)
if err != nil {
errs <- fmt.Errorf("stream %d dial: %w", idx, err)
return
}
defer func() { _ = conn.Close() }()
msg := fmt.Sprintf("stream-%d-data", idx)
_, err = conn.Write([]byte(msg))
if err != nil {
errs <- fmt.Errorf("stream %d write: %w", idx, err)
return
}
// Read echo response.
buf := make([]byte, len(msg))
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
n, err := io.ReadFull(conn, buf)
if err != nil {
errs <- fmt.Errorf("stream %d read: %w (got %d bytes)", idx, err, n)
return
}
if string(buf) != msg {
errs <- fmt.Errorf("stream %d: expected %q, got %q", idx, msg, string(buf))
}
}(i)
}
wg.Wait()
close(errs)
for err := range errs {
t.Error(err)
}
}
// --- Test: TLS option ---
func TestTunnelProxy_TLSOption(t *testing.T) {
_, wssURL, tlsCfg := startTLSEchoServer(t)
tp, err := NewTunnelProxy(wssURL, "tok", WithTunnelTLS(tlsCfg))
require.NoError(t, err)
defer func() { _ = tp.Close() }()
// Verify we can communicate through the TLS tunnel.
conn, err := net.DialTimeout("tcp", tp.Addr(), 2*time.Second)
require.NoError(t, err)
defer func() { _ = conn.Close() }()
msg := []byte("tls-echo-test")
_, err = conn.Write(msg)
require.NoError(t, err)
buf := make([]byte, len(msg))
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
_, err = io.ReadFull(conn, buf)
require.NoError(t, err)
assert.Equal(t, msg, buf)
}
// --- Test: Logger option ---
func TestTunnelProxy_LoggerOption(t *testing.T) {
_, wsURL := startEchoServer(t)
logger := &testLogger{}
tp, err := NewTunnelProxy(wsURL, "tok", WithTunnelLogger(logger))
require.NoError(t, err)
// Open a connection to trigger log events.
conn, err := net.DialTimeout("tcp", tp.Addr(), 2*time.Second)
require.NoError(t, err)
_, _ = conn.Write([]byte("log-test"))
// Give the tunnel time to process.
time.Sleep(200 * time.Millisecond)
_ = conn.Close()
err = tp.Close()
require.NoError(t, err)
// Logger should have received at least one message.
msgs := logger.Messages()
assert.NotEmpty(t, msgs, "logger should receive log events")
}
// --- Test: WithCloseTimeout option ---
func TestWithCloseTimeout(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "tok", WithCloseTimeout(10*time.Second))
require.NoError(t, err)
defer func() { _ = tp.Close() }()
// We can't directly inspect the config, but creation should succeed.
assert.NotNil(t, tp)
}
// --- Test: Data flows through the tunnel ---
func TestTunnelProxy_DataRoundTrip(t *testing.T) {
_, wsURL := startEchoServer(t)
tp, err := NewTunnelProxy(wsURL, "tok")
require.NoError(t, err)
defer func() { _ = tp.Close() }()
conn, err := net.DialTimeout("tcp", tp.Addr(), 2*time.Second)
require.NoError(t, err)
defer func() { _ = conn.Close() }()
// Send data and verify round-trip through the WebSocket echo server.
msg := []byte("round-trip-payload-12345")
_, err = conn.Write(msg)
require.NoError(t, err)
buf := make([]byte, len(msg))
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
_, err = io.ReadFull(conn, buf)
require.NoError(t, err)
assert.Equal(t, msg, buf)
}
-66
View File
@@ -1,66 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// ErrorCode classifies SDK errors by their gRPC origin.
type ErrorCode = types.ErrorCode
// ErrorCode values for classifying gRPC errors.
const (
ErrorNotFound = types.ErrorNotFound
ErrorAlreadyExists = types.ErrorAlreadyExists
ErrorUnavailable = types.ErrorUnavailable
ErrorPermissionDenied = types.ErrorPermissionDenied
ErrorInvalidArgument = types.ErrorInvalidArgument
ErrorDeadlineExceeded = types.ErrorDeadlineExceeded
ErrorCancelled = types.ErrorCancelled
ErrorInternal = types.ErrorInternal
ErrorUnimplemented = types.ErrorUnimplemented
ErrorConflict = types.ErrorConflict
ErrorUnauthenticated = types.ErrorUnauthenticated
)
// StatusError is the typed error returned by all SDK operations.
type StatusError = types.StatusError
// FieldViolation identifies an invalid request field.
type FieldViolation = types.FieldViolation
// ErrorInfo describes a server failure using a stable reason within a domain.
type ErrorInfo = types.ErrorInfo
// IsNotFound returns true if the error indicates a resource was not found.
func IsNotFound(err error) bool { return types.IsNotFound(err) }
// IsAlreadyExists returns true if the error indicates a resource already exists.
func IsAlreadyExists(err error) bool { return types.IsAlreadyExists(err) }
// IsUnavailable returns true if the error indicates the service is unavailable.
func IsUnavailable(err error) bool { return types.IsUnavailable(err) }
// IsPermissionDenied returns true if the error indicates insufficient permissions.
func IsPermissionDenied(err error) bool { return types.IsPermissionDenied(err) }
// IsInvalidArgument returns true if the error indicates an invalid argument.
func IsInvalidArgument(err error) bool { return types.IsInvalidArgument(err) }
// IsDeadlineExceeded returns true if the error indicates a deadline was exceeded.
func IsDeadlineExceeded(err error) bool { return types.IsDeadlineExceeded(err) }
// IsCancelled returns true if the error indicates the operation was cancelled.
func IsCancelled(err error) bool { return types.IsCancelled(err) }
// IsUnimplemented returns true if the error indicates the operation is not implemented.
func IsUnimplemented(err error) bool { return types.IsUnimplemented(err) }
// IsConflict returns true if the error indicates a conflict, such as
// optimistic concurrency or an invalid state transition.
func IsConflict(err error) bool { return types.IsConflict(err) }
// IsUnauthenticated returns true if the error indicates invalid or missing credentials.
func IsUnauthenticated(err error) bool { return types.IsUnauthenticated(err) }
-127
View File
@@ -1,127 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStatusError_Error(t *testing.T) {
err := &StatusError{
Code: ErrorNotFound,
Message: "sandbox not found",
}
s := err.Error()
assert.Contains(t, s, "NotFound")
assert.Contains(t, s, "sandbox not found")
}
func TestStatusError_ErrorWithCause(t *testing.T) {
cause := errors.New("underlying error")
err := &StatusError{
Code: ErrorInvalidArgument,
Message: "bad name",
Cause: cause,
}
s := err.Error()
assert.Contains(t, s, "InvalidArgument")
assert.Contains(t, s, "bad name")
assert.Equal(t, cause, errors.Unwrap(err))
}
func TestIsNotFound(t *testing.T) {
err := &StatusError{Code: ErrorNotFound, Message: "not found"}
assert.True(t, IsNotFound(err))
assert.False(t, IsAlreadyExists(err))
}
func TestIsAlreadyExists(t *testing.T) {
err := &StatusError{Code: ErrorAlreadyExists, Message: "exists"}
assert.True(t, IsAlreadyExists(err))
assert.False(t, IsNotFound(err))
}
func TestIsUnavailable(t *testing.T) {
err := &StatusError{Code: ErrorUnavailable, Message: "down"}
assert.True(t, IsUnavailable(err))
}
func TestIsPermissionDenied(t *testing.T) {
err := &StatusError{Code: ErrorPermissionDenied, Message: "denied"}
assert.True(t, IsPermissionDenied(err))
}
func TestIsInvalidArgument(t *testing.T) {
err := &StatusError{Code: ErrorInvalidArgument, Message: "invalid"}
assert.True(t, IsInvalidArgument(err))
}
func TestIsDeadlineExceeded(t *testing.T) {
err := &StatusError{Code: ErrorDeadlineExceeded, Message: "timeout"}
assert.True(t, IsDeadlineExceeded(err))
}
func TestIsCancelled(t *testing.T) {
err := &StatusError{Code: ErrorCancelled, Message: "cancelled"}
assert.True(t, IsCancelled(err))
}
func TestIsConflict(t *testing.T) {
err := &StatusError{Code: ErrorConflict, Message: "version conflict"}
assert.True(t, IsConflict(err))
assert.False(t, IsNotFound(err))
}
func TestIsHelpers_NonStatusError(t *testing.T) {
err := errors.New("plain error")
assert.False(t, IsNotFound(err))
assert.False(t, IsAlreadyExists(err))
assert.False(t, IsUnavailable(err))
assert.False(t, IsPermissionDenied(err))
assert.False(t, IsInvalidArgument(err))
assert.False(t, IsDeadlineExceeded(err))
assert.False(t, IsCancelled(err))
assert.False(t, IsConflict(err))
}
func TestIsHelpers_NilError(t *testing.T) {
assert.False(t, IsNotFound(nil))
assert.False(t, IsConflict(nil))
}
func TestStatusError_WrappedError(t *testing.T) {
inner := &StatusError{Code: ErrorNotFound, Message: "not found"}
wrapped := fmt.Errorf("operation failed: %w", inner)
assert.True(t, IsNotFound(wrapped))
var se *StatusError
require.True(t, errors.As(wrapped, &se))
assert.Equal(t, ErrorNotFound, se.Code)
}
func TestErrorCode_String(t *testing.T) {
tests := []struct {
code ErrorCode
want string
}{
{ErrorNotFound, "NotFound"},
{ErrorAlreadyExists, "AlreadyExists"},
{ErrorUnavailable, "Unavailable"},
{ErrorPermissionDenied, "PermissionDenied"},
{ErrorInvalidArgument, "InvalidArgument"},
{ErrorDeadlineExceeded, "DeadlineExceeded"},
{ErrorCancelled, "Cancelled"},
{ErrorInternal, "Internal"},
{ErrorUnimplemented, "Unimplemented"},
{ErrorConflict, "Conflict"},
}
for _, tt := range tests {
assert.Equal(t, tt.want, tt.code.String())
}
}
-155
View File
@@ -1,155 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1_test
import (
"context"
"fmt"
"log"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// ExampleNewClient_addSandbox demonstrates pre-seeding a fake client with
// a sandbox fixture.
func ExampleNewClient_addSandbox() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
// Pre-seed a sandbox that already exists in Ready state
client.AddSandbox("default", &types.Sandbox{
Name: "pre-existing",
Status: types.SandboxStatus{
Phase: types.SandboxReady,
},
ResourceVersion: 5,
})
ctx := context.Background()
sb, err := client.Sandboxes().Get(ctx, "default", "pre-existing")
if err != nil {
log.Fatal(err)
}
fmt.Println("Name:", sb.Name)
fmt.Println("Phase:", sb.Status.Phase)
// Output:
// Name: pre-existing
// Phase: Ready
}
// ExampleNewClient_addProvider demonstrates pre-seeding a fake client with
// a provider fixture.
func ExampleNewClient_addProvider() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
// Pre-seed a provider
client.AddProvider("default", &types.Provider{
Name: "seeded-provider",
Type: "openai",
})
ctx := context.Background()
providers, err := client.Providers().ListAll(ctx, "default")
if err != nil {
log.Fatal(err)
}
fmt.Println("Count:", len(providers))
fmt.Println("Name:", providers[0].Name)
// Output:
// Count: 1
// Name: seeded-provider
}
// ExampleNewClient_withHealthResult demonstrates configuring the fake
// health sub-client to return a custom result.
func ExampleNewClient_withHealthResult() {
client := fake.NewClient(fake.WithHealthResult(&types.HealthResult{
Healthy: false,
Version: "1.2.3",
}))
defer client.Close() //nolint:errcheck
ctx := context.Background()
result, err := client.Health().Check(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Healthy:", result.Healthy)
fmt.Println("Version:", result.Version)
// Output:
// Healthy: false
// Version: 1.2.3
}
// ExampleNewClient_watchEvents demonstrates watching for sandbox events
// using the fake client.
func ExampleNewClient_watchEvents() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Start watching before creating
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
defer watcher.Stop()
// Create triggers an ADDED event
_, err = client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
if err != nil {
log.Fatal(err)
}
event := <-watcher.ResultChan()
fmt.Println("Type:", event.Type)
fmt.Println("Name:", event.Object.Name)
// Output:
// Type: ADDED
// Name: my-sandbox
}
// ExampleNewClient_stopOnTerminal demonstrates the StopOnTerminal watch
// option that automatically closes the watcher when a sandbox reaches a
// terminal phase.
func ExampleNewClient_stopOnTerminal() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Watch with StopOnTerminal
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox", v1.WatchOptions{
StopOnTerminal: true,
})
if err != nil {
log.Fatal(err)
}
// Create and transition to Ready
_, err = client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
if err != nil {
log.Fatal(err)
}
_, err = client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
// Drain events, channel closes after terminal phase
var count int
for range watcher.ResultChan() {
count++
}
fmt.Println("Events received:", count)
// Output:
// Events received: 2
}
-184
View File
@@ -1,184 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1_test
import (
"context"
"fmt"
"log"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
)
// ExampleClient_Sandboxes demonstrates the sandbox lifecycle: create a sandbox,
// wait for it to become ready, and then clean up.
func ExampleClient_Sandboxes() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Create a sandbox
sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
if err != nil {
log.Fatal(err)
}
fmt.Println("Phase after create:", sb.Status.Phase)
// Wait for the sandbox to become ready
sb, err = client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
if err != nil {
log.Fatal(err)
}
fmt.Println("Phase after wait:", sb.Status.Phase)
// Clean up
if _, err := client.Sandboxes().Delete(ctx, "default", "my-sandbox"); err != nil {
log.Fatal(err)
}
fmt.Println("Deleted")
// Output:
// Phase after create: Provisioning
// Phase after wait: Ready
// Deleted
}
// ExampleClient_Providers demonstrates registering and listing providers.
func ExampleClient_Providers() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Register a provider
_, err := client.Providers().Create(ctx, "default", &v1.Provider{
Name: "my-openai",
Type: "openai",
})
if err != nil {
log.Fatal(err)
}
// List all providers
providers, err := client.Providers().ListAll(ctx, "default")
if err != nil {
log.Fatal(err)
}
fmt.Println("Count:", len(providers))
fmt.Println("Name:", providers[0].Name)
// Output:
// Count: 1
// Name: my-openai
}
// ExampleClient_Health demonstrates checking gateway health.
func ExampleClient_Health() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
result, err := client.Health().Check(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Healthy:", result.Healthy)
// Output:
// Healthy: true
}
// ExampleClient_Exec demonstrates running a command in a sandbox.
// The fake client returns Unimplemented for exec operations, so this
// example shows the call pattern and error handling.
func ExampleClient_Exec() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
_, err := client.Exec().Run(ctx, "default", "my-sandbox", []string{"echo", "hello"})
if v1.IsUnimplemented(err) {
fmt.Println("Exec requires a real gateway")
}
// Output:
// Exec requires a real gateway
}
// ExampleClient_TCP demonstrates binding a local port to a sandbox port.
// The returned handle accepts and tunnels connections internally.
//
// The fake client returns Unimplemented for Listen, so this example shows
// the call pattern and error handling rather than a live tunnel.
func ExampleClient_TCP() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Bind local port 0 (OS-assigned) to sandbox port 8080.
ln, err := client.TCP().Listen(ctx, "default", "my-sandbox", 8080, 0)
if v1.IsUnimplemented(err) {
fmt.Println("Listen requires a real gateway")
}
if ln != nil {
// In production, dial ln.Addr() with the protocol client that should
// connect to the sandbox service. No Accept loop is required.
defer ln.Close() //nolint:errcheck
}
// Output:
// Listen requires a real gateway
}
// ExampleIsNotFound demonstrates handling a not-found error.
func ExampleIsNotFound() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
_, err := client.Sandboxes().Get(ctx, "default", "nonexistent")
if v1.IsNotFound(err) {
fmt.Println("Sandbox not found")
}
// Output:
// Sandbox not found
}
// ExampleIsAlreadyExists demonstrates handling a duplicate-creation error.
func ExampleIsAlreadyExists() {
client := fake.NewClient()
defer client.Close() //nolint:errcheck
ctx := context.Background()
// Create a sandbox
_, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
if err != nil {
log.Fatal(err)
}
// Try to create the same sandbox again
_, err = client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{})
if v1.IsAlreadyExists(err) {
fmt.Println("Sandbox already exists")
}
// Output:
// Sandbox already exists
}
// ExampleIsUnavailable demonstrates detecting a closed client.
func ExampleIsUnavailable() {
client := fake.NewClient()
_ = client.Close()
ctx := context.Background()
_, err := client.Sandboxes().Get(ctx, "default", "any")
if v1.IsUnavailable(err) {
fmt.Println("Client is closed")
}
// Output:
// Client is closed
}
-70
View File
@@ -1,70 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// ExecResult holds the collected output of a completed command execution.
type ExecResult = types.ExecResult
// ExecChunk represents a single chunk of output from a streaming command execution.
type ExecChunk = types.ExecChunk
// ExecStream provides an iterator interface over streaming command output.
type ExecStream interface {
Next() (*ExecChunk, error)
ExitCode() (int, error)
Close() error
}
// InteractiveSession provides bidirectional I/O for interactive command execution.
type InteractiveSession interface {
Read(p []byte) (int, error)
Write(p []byte) (int, error)
Resize(cols, rows uint32) error
// ExitCode waits for final stream completion. An observed exit code is
// returned alongside any later transport error. Drain Read concurrently.
ExitCode() (int, error)
Close() error
}
// InteractiveSessionControl adds optional input closure and cancellation to
// InteractiveSession without requiring existing implementations to add methods.
// Sessions returned by this SDK implement both interfaces.
type InteractiveSessionControl interface {
InteractiveSession
// CloseWrite ends stdin and resize input without cancelling output.
CloseWrite() error
// Cancel aborts the RPC. Close retains the same full-close behavior.
Cancel() error
}
// CloseInteractiveInput ends input while preserving output when supported.
// Unsupported sessions return ErrorUnimplemented and are left open.
func CloseInteractiveInput(session InteractiveSession) error {
if closer, ok := session.(interface{ CloseWrite() error }); ok {
return closer.CloseWrite()
}
return &StatusError{Code: ErrorUnimplemented, Message: "interactive session does not support closing input independently"}
}
// CancelInteractive aborts a session, falling back to the original Close contract.
func CancelInteractive(session InteractiveSession) error {
if canceler, ok := session.(interface{ Cancel() error }); ok {
return canceler.Cancel()
}
return session.Close()
}
// ExecInterface defines command execution operations on sandboxes.
// Methods accept a sandbox name and resolve it to an ID internally.
type ExecInterface interface {
Run(ctx context.Context, workspace, sandboxName string, command []string, opts ...ExecOptions) (*ExecResult, error)
Stream(ctx context.Context, workspace, sandboxName string, command []string, opts ...ExecOptions) (ExecStream, error)
Interactive(ctx context.Context, workspace, sandboxName string, command []string, cols, rows uint32, opts ...ExecOptions) (InteractiveSession, error)
}
-341
View File
@@ -1,341 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"io"
"sync"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
type execClient struct {
client pb.OpenShellClient
sandboxes SandboxInterface
}
func newExecClient(conn grpc.ClientConnInterface, sandboxes SandboxInterface) *execClient {
return &execClient{client: pb.NewOpenShellClient(conn), sandboxes: sandboxes}
}
func (e *execClient) Run(ctx context.Context, workspace, sandboxName string, command []string, opts ...ExecOptions) (*ExecResult, error) {
if sandboxName == "" {
return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
owner, err := sandboxOwner(ctx, e.sandboxes, workspace, sandboxName)
if err != nil {
return nil, err
}
var opt *ExecOptions
if len(opts) > 0 {
opt = &opts[0]
}
req := converter.ExecRequestToProto(sandboxName, command, opt)
req.WorkspaceScope = namedWorkspaceScope(workspace)
stream, err := openRouted(ctx, owner, func(ctx context.Context) (grpc.ServerStreamingClient[pb.ExecSandboxEvent], error) {
return e.client.ExecSandbox(ctx, req)
})
if err != nil {
return nil, converter.FromGRPCError(err)
}
var events []*pb.ExecSandboxEvent
for {
ev, recvErr := stream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
return nil, converter.FromGRPCError(recvErr)
}
events = append(events, ev)
}
return converter.ExecResultFromEvents(events)
}
func (e *execClient) Stream(ctx context.Context, workspace, sandboxName string, command []string, opts ...ExecOptions) (ExecStream, error) {
if sandboxName == "" {
return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
owner, err := sandboxOwner(ctx, e.sandboxes, workspace, sandboxName)
if err != nil {
return nil, err
}
var opt *ExecOptions
if len(opts) > 0 {
opt = &opts[0]
}
req := converter.ExecRequestToProto(sandboxName, command, opt)
req.WorkspaceScope = namedWorkspaceScope(workspace)
streamCtx, cancel := context.WithCancel(ctx)
stream, err := openRouted(streamCtx, owner, func(ctx context.Context) (grpc.ServerStreamingClient[pb.ExecSandboxEvent], error) {
return e.client.ExecSandbox(ctx, req)
})
if err != nil {
cancel()
return nil, converter.FromGRPCError(err)
}
return &execStream{stream: stream, cancel: cancel}, nil
}
func (e *execClient) Interactive(ctx context.Context, workspace, sandboxName string, command []string, cols, rows uint32, opts ...ExecOptions) (InteractiveSession, error) {
if sandboxName == "" {
return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
owner, err := sandboxOwner(ctx, e.sandboxes, workspace, sandboxName)
if err != nil {
return nil, err
}
var opt *ExecOptions
if len(opts) > 0 {
opt = &opts[0]
}
startReq := converter.ExecInteractiveRequestToProto(sandboxName, command, cols, rows, opt)
startReq.WorkspaceScope = namedWorkspaceScope(workspace)
streamCtx, cancel := context.WithCancel(ctx)
start := &pb.ExecSandboxInput{Payload: &pb.ExecSandboxInput_Start{Start: startReq}}
stream, err := openBidiRouted(streamCtx, owner, start, e.client.ExecSandboxInteractive)
if err != nil {
cancel()
return nil, converter.FromGRPCError(err)
}
return newInteractiveSession(streamCtx, cancel, stream), nil
}
// execStream wraps a server-streaming RPC into the ExecStream interface.
type execStream struct {
stream grpc.ServerStreamingClient[pb.ExecSandboxEvent]
cancel context.CancelFunc
exitCode int
exited bool
hasExit bool
}
func (s *execStream) Next() (*ExecChunk, error) {
if s.exited {
return nil, io.EOF
}
ev, err := s.stream.Recv()
if err == io.EOF {
return nil, io.EOF
}
if err != nil {
return nil, converter.FromGRPCError(err)
}
chunk, code, convErr := converter.ExecChunkFromEvent(ev)
if convErr != nil {
return nil, convErr
}
if chunk != nil {
return chunk, nil
}
// nil chunk with no error means exit event
s.exitCode = code
s.exited = true
s.hasExit = true
return nil, io.EOF
}
func (s *execStream) ExitCode() (int, error) {
if !s.exited {
for {
_, err := s.Next()
if err == io.EOF {
break
}
if err != nil {
return -1, err
}
}
}
if !s.hasExit {
return -1, &StatusError{Code: ErrorInternal, Message: "stream ended without exit event"}
}
return s.exitCode, nil
}
func (s *execStream) Close() error {
if s.cancel != nil {
s.cancel()
}
return nil
}
// interactiveSession wraps a bidirectional streaming RPC into the InteractiveSession interface.
// A background goroutine owns the Recv loop and routes events to dataCh (for Read)
// and publishes the final exit/status through done, preventing concurrent Recv calls.
type interactiveSession struct {
stream grpc.BidiStreamingClient[pb.ExecSandboxInput, pb.ExecSandboxEvent]
cancel context.CancelFunc
sendMu sync.Mutex
inputClosed bool
inputCloseErr error
closeOnce sync.Once
closeErr error
dataCh chan []byte
done chan struct{}
errOnce sync.Once
err error
buf []byte
exitCode int
hasExitCode bool
}
func newInteractiveSession(ctx context.Context, cancel context.CancelFunc, stream grpc.BidiStreamingClient[pb.ExecSandboxInput, pb.ExecSandboxEvent]) *interactiveSession {
s := &interactiveSession{
stream: stream,
cancel: cancel,
dataCh: make(chan []byte, 64),
done: make(chan struct{}),
}
go s.readLoop(ctx)
return s
}
func (s *interactiveSession) setErr(err error) {
s.errOnce.Do(func() { s.err = err })
}
func (s *interactiveSession) readLoop(ctx context.Context) {
defer s.cancel()
defer close(s.dataCh)
defer close(s.done)
for {
ev, err := s.stream.Recv()
if err != nil {
if err != io.EOF {
s.setErr(converter.FromGRPCError(err))
} else if ctx.Err() != nil {
s.setErr(converter.FromGRPCError(status.FromContextError(ctx.Err()).Err()))
} else if !s.hasExitCode {
s.setErr(&StatusError{Code: ErrorInternal, Message: "stream ended without exit event"})
}
return
}
if s.hasExitCode {
s.setErr(&StatusError{Code: ErrorInternal, Message: "received event after exit"})
return
}
chunk, code, convErr := converter.ExecChunkFromEvent(ev)
if convErr != nil {
s.setErr(convErr)
return
}
// nil chunk with no error means exit event
if chunk == nil {
s.exitCode = code
s.hasExitCode = true
continue
}
select {
case s.dataCh <- chunk.Data:
case <-ctx.Done():
s.setErr(converter.FromGRPCError(status.FromContextError(ctx.Err()).Err()))
return
}
}
}
func (s *interactiveSession) Read(p []byte) (int, error) {
if len(s.buf) > 0 {
n := copy(p, s.buf)
s.buf = s.buf[n:]
return n, nil
}
data, ok := <-s.dataCh
if !ok {
if s.err != nil {
return 0, s.err
}
return 0, io.EOF
}
n := copy(p, data)
if n < len(data) {
s.buf = append(s.buf, data[n:]...)
}
return n, nil
}
func (s *interactiveSession) Write(p []byte) (int, error) {
s.sendMu.Lock()
defer s.sendMu.Unlock()
if s.inputClosed {
return 0, io.ErrClosedPipe
}
err := s.stream.Send(&pb.ExecSandboxInput{
Payload: &pb.ExecSandboxInput_Stdin{Stdin: p},
})
if err != nil {
return 0, converter.FromGRPCError(err)
}
return len(p), nil
}
func (s *interactiveSession) Resize(cols, rows uint32) error {
s.sendMu.Lock()
defer s.sendMu.Unlock()
if s.inputClosed {
return io.ErrClosedPipe
}
err := s.stream.Send(&pb.ExecSandboxInput{
Payload: &pb.ExecSandboxInput_Resize{
Resize: &pb.ExecSandboxWindowResize{
Cols: cols,
Rows: rows,
},
},
})
if err != nil {
return converter.FromGRPCError(err)
}
return nil
}
func (s *interactiveSession) ExitCode() (int, error) {
<-s.done
if s.hasExitCode {
return s.exitCode, s.err
}
return -1, s.err
}
func (s *interactiveSession) CloseWrite() error {
s.sendMu.Lock()
defer s.sendMu.Unlock()
if !s.inputClosed {
s.inputClosed = true
s.inputCloseErr = s.stream.CloseSend()
}
return s.inputCloseErr
}
func (s *interactiveSession) Cancel() error {
s.closeOnce.Do(func() {
// Cancel before taking sendMu so a blocked Write can release it.
s.cancel()
s.closeErr = s.CloseWrite()
<-s.done
})
return s.closeErr
}
func (s *interactiveSession) Close() error {
return s.Cancel()
}
-764
View File
@@ -1,764 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"context"
"io"
"net"
"sync"
"testing"
"time"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
)
// stubSandboxResolver implements SandboxInterface for testing name-to-ID resolution.
// Get returns a Sandbox with ID = "sb-" + name. All other methods panic.
type stubSandboxResolver struct {
getErr error // if non-nil, Get returns this error
}
func (r *stubSandboxResolver) Get(_ context.Context, _, name string) (*Sandbox, error) {
if r.getErr != nil {
return nil, r.getErr
}
return &Sandbox{ID: "sb-" + name, Name: name}, nil
}
func (r *stubSandboxResolver) Create(context.Context, string, string, *SandboxSpec, ...CreateOption) (*Sandbox, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) List(string, ...ListOptions) (*Pager[*Sandbox], error) {
panic("not implemented")
}
func (r *stubSandboxResolver) ListAll(context.Context, string, ...ListOptions) ([]*Sandbox, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) Delete(context.Context, string, string, ...DeleteOptions) (*DeletionResult, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) AttachProvider(context.Context, string, string, string, uint64) (*AttachProviderResult, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) DetachProvider(context.Context, string, string, string, uint64) (*DetachProviderResult, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) ListProviders(string, string, ...ListOptions) (*Pager[*Provider], error) {
panic("not implemented")
}
func (r *stubSandboxResolver) ListAllProviders(context.Context, string, string, ...ListOptions) ([]*Provider, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) WaitReady(context.Context, string, string, ...WaitOptions) (*Sandbox, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) Watch(context.Context, string, string, ...WatchOptions) (WatchInterface[*Sandbox], error) {
panic("not implemented")
}
func (r *stubSandboxResolver) GetLogs(context.Context, string, string, ...LogOption) (*LogResult, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) Stop(context.Context, string, string) (*Sandbox, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) Start(context.Context, string, string) (*Sandbox, error) {
panic("not implemented")
}
func (r *stubSandboxResolver) WaitStopped(context.Context, string, string, ...WaitOptions) (*Sandbox, error) {
panic("not implemented")
}
type mockExecServer struct {
pb.UnimplementedOpenShellServer
mu sync.Mutex
execEvents []*pb.ExecSandboxEvent
execErr error
lastExecRequest *pb.ExecSandboxRequest
interactiveEvents []*pb.ExecSandboxEvent
interactiveErr error
interactiveWaitInput bool
interactiveBlock bool
interactiveWaitEOF bool
interactiveFinalErr error
receivedInputs []*pb.ExecSandboxInput
}
func newMockExecServer() *mockExecServer {
return &mockExecServer{}
}
func (s *mockExecServer) ExecSandbox(req *pb.ExecSandboxRequest, stream grpc.ServerStreamingServer[pb.ExecSandboxEvent]) error {
s.mu.Lock()
s.lastExecRequest = req
events := make([]*pb.ExecSandboxEvent, len(s.execEvents))
copy(events, s.execEvents)
execErr := s.execErr
s.mu.Unlock()
if execErr != nil {
return execErr
}
for _, ev := range events {
if err := stream.Send(ev); err != nil {
return err
}
}
return nil
}
func (s *mockExecServer) ExecSandboxInteractive(stream grpc.BidiStreamingServer[pb.ExecSandboxInput, pb.ExecSandboxEvent]) error {
s.mu.Lock()
interactiveErr := s.interactiveErr
interactiveBlock := s.interactiveBlock
waitEOF := s.interactiveWaitEOF
finalErr := s.interactiveFinalErr
events := make([]*pb.ExecSandboxEvent, len(s.interactiveEvents))
copy(events, s.interactiveEvents)
s.mu.Unlock()
if interactiveErr != nil {
return interactiveErr
}
// Read the start message
startMsg, err := stream.Recv()
if err != nil {
return err
}
s.mu.Lock()
s.receivedInputs = append(s.receivedInputs, startMsg)
s.mu.Unlock()
if interactiveBlock {
<-stream.Context().Done()
return stream.Context().Err()
}
if waitEOF {
for {
_, recvErr := stream.Recv()
if recvErr == io.EOF {
break
}
if recvErr != nil {
return recvErr
}
}
}
s.mu.Lock()
waitInput := s.interactiveWaitInput
s.mu.Unlock()
if waitInput {
msg, recvErr := stream.Recv()
if recvErr != nil {
return recvErr
}
s.mu.Lock()
s.receivedInputs = append(s.receivedInputs, msg)
s.mu.Unlock()
}
// Read subsequent messages until client closes, collecting them
go func() {
for {
msg, recvErr := stream.Recv()
if recvErr != nil {
return
}
s.mu.Lock()
s.receivedInputs = append(s.receivedInputs, msg)
s.mu.Unlock()
}
}()
// Send canned events
for _, ev := range events {
if err := stream.Send(ev); err != nil {
return err
}
}
return finalErr
}
func setupExecTest(t *testing.T, mock *mockExecServer) (*execClient, func()) {
t.Helper()
lis := bufconn.Listen(bufSize)
srv := grpc.NewServer()
pb.RegisterOpenShellServer(srv, mock)
go func() { _ = srv.Serve(lis) }()
conn, err := grpc.NewClient("passthrough:///bufconn",
grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) {
return lis.Dial()
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
return newExecClient(conn, &stubSandboxResolver{}), func() {
_ = conn.Close()
srv.Stop()
}
}
// --- T043: Run and Stream tests ---
func TestExecRun(t *testing.T) {
mock := newMockExecServer()
mock.execEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("hello ")}}},
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("world\n")}}},
{Payload: &pb.ExecSandboxEvent_Stderr{Stderr: &pb.ExecSandboxStderr{Data: []byte("warn\n")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
result, err := client.Run(context.Background(), "default", "test-sandbox", []string{"echo", "hello", "world"})
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, 0, result.ExitCode)
assert.Equal(t, []byte("hello world\n"), result.Stdout)
assert.Equal(t, []byte("warn\n"), result.Stderr)
}
func TestExecRun_WithOptions(t *testing.T) {
mock := newMockExecServer()
mock.execEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
opts := ExecOptions{
Env: map[string]string{"FOO": "bar"},
WorkDir: "/tmp",
}
result, err := client.Run(context.Background(), "default", "test-sandbox", []string{"ls"}, opts)
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, 0, result.ExitCode)
mock.mu.Lock()
defer mock.mu.Unlock()
assert.Equal(t, "test-sandbox", mock.lastExecRequest.GetSandbox())
assert.Equal(t, []string{"ls"}, mock.lastExecRequest.GetCommand())
assert.Equal(t, "/tmp", mock.lastExecRequest.GetWorkdir())
assert.Equal(t, map[string]string{"FOO": "bar"}, mock.lastExecRequest.GetEnvironment())
}
func TestExecRun_NonZeroExit(t *testing.T) {
mock := newMockExecServer()
mock.execEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stderr{Stderr: &pb.ExecSandboxStderr{Data: []byte("fail\n")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 1}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
result, err := client.Run(context.Background(), "default", "test-sandbox", []string{"false"})
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, 1, result.ExitCode)
assert.Empty(t, result.Stdout)
assert.Equal(t, []byte("fail\n"), result.Stderr)
}
func TestExecRun_ServerError(t *testing.T) {
mock := newMockExecServer()
mock.execErr = status.Error(codes.NotFound, "sandbox not found")
client, cleanup := setupExecTest(t, mock)
defer cleanup()
_, err := client.Run(context.Background(), "default", "missing-sandbox", []string{"ls"})
require.Error(t, err)
assert.True(t, IsNotFound(err))
}
func TestExecStream(t *testing.T) {
mock := newMockExecServer()
mock.execEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("line1\n")}}},
{Payload: &pb.ExecSandboxEvent_Stderr{Stderr: &pb.ExecSandboxStderr{Data: []byte("err1\n")}}},
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("line2\n")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 42}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
stream, err := client.Stream(context.Background(), "default", "test-sandbox", []string{"cat"})
require.NoError(t, err)
require.NotNil(t, stream)
defer func() { _ = stream.Close() }()
chunk1, err := stream.Next()
require.NoError(t, err)
assert.Equal(t, StreamStdout, chunk1.Stream)
assert.Equal(t, []byte("line1\n"), chunk1.Data)
chunk2, err := stream.Next()
require.NoError(t, err)
assert.Equal(t, StreamStderr, chunk2.Stream)
assert.Equal(t, []byte("err1\n"), chunk2.Data)
chunk3, err := stream.Next()
require.NoError(t, err)
assert.Equal(t, StreamStdout, chunk3.Stream)
assert.Equal(t, []byte("line2\n"), chunk3.Data)
// Next call after exit should return io.EOF
_, err = stream.Next()
assert.ErrorIs(t, err, io.EOF)
exitCode, err := stream.ExitCode()
require.NoError(t, err)
assert.Equal(t, 42, exitCode)
}
func TestExecStream_ServerError(t *testing.T) {
mock := newMockExecServer()
mock.execErr = status.Error(codes.Internal, "internal error")
client, cleanup := setupExecTest(t, mock)
defer cleanup()
stream, err := client.Stream(context.Background(), "default", "test-sandbox", []string{"ls"})
if err != nil {
var se *StatusError
require.ErrorAs(t, err, &se)
assert.Equal(t, ErrorInternal, se.Code)
return
}
_, err = stream.Next()
require.Error(t, err)
}
func TestExecStream_EmptyOutput(t *testing.T) {
mock := newMockExecServer()
mock.execEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
stream, err := client.Stream(context.Background(), "default", "test-sandbox", []string{"true"})
require.NoError(t, err)
defer func() { _ = stream.Close() }()
_, err = stream.Next()
assert.ErrorIs(t, err, io.EOF)
exitCode, err := stream.ExitCode()
require.NoError(t, err)
assert.Equal(t, 0, exitCode)
}
// --- T044: Interactive session tests ---
func TestExecInteractive(t *testing.T) {
mock := newMockExecServer()
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("$ ")}}},
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("output\n")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "test-sandbox", []string{"/bin/bash"}, 80, 24)
require.NoError(t, err)
require.NotNil(t, session)
defer func() { _ = session.Close() }()
// Read output
buf := make([]byte, 1024)
n, err := session.Read(buf)
require.NoError(t, err)
assert.Equal(t, "$ ", string(buf[:n]))
// Verify start message was received
mock.mu.Lock()
require.GreaterOrEqual(t, len(mock.receivedInputs), 1)
startInput := mock.receivedInputs[0]
mock.mu.Unlock()
startReq := startInput.GetStart()
require.NotNil(t, startReq)
assert.Equal(t, "test-sandbox", startReq.GetSandbox())
assert.Equal(t, []string{"/bin/bash"}, startReq.GetCommand())
assert.True(t, startReq.GetTty())
assert.Equal(t, uint32(80), startReq.GetCols())
assert.Equal(t, uint32(24), startReq.GetRows())
}
func TestExecInteractive_CloseCancelsReceiveStream(t *testing.T) {
mock := newMockExecServer()
mock.interactiveBlock = true
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "test-sandbox", []string{"/bin/sh"}, 80, 24)
require.NoError(t, err)
closed := make(chan error, 1)
go func() { closed <- session.Close() }()
select {
case err := <-closed:
require.NoError(t, err)
case <-time.After(time.Second):
t.Fatal("InteractiveSession.Close did not cancel the receive stream")
}
}
func TestExecInteractive_CloseWriteDrainsOutput(t *testing.T) {
mock := newMockExecServer()
mock.interactiveWaitEOF = true
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("after EOF")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 7}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
session, err := client.Interactive(ctx, "default", "test-sandbox", []string{"cat"}, 0, 0)
require.NoError(t, err)
defer func() { _ = session.Close() }()
require.Implements(t, (*InteractiveSessionControl)(nil), session)
require.NoError(t, CloseInteractiveInput(session))
require.NoError(t, CloseInteractiveInput(session))
_, err = session.Write([]byte("late"))
require.ErrorIs(t, err, io.ErrClosedPipe)
require.ErrorIs(t, session.Resize(80, 24), io.ErrClosedPipe)
output, err := io.ReadAll(session)
require.NoError(t, err)
require.Equal(t, "after EOF", string(output))
code, err := session.ExitCode()
require.NoError(t, err)
require.Equal(t, 7, code)
}
func TestExecInteractive_RetainsExitOnTerminalFailure(t *testing.T) {
for _, finalErr := range []error{status.Error(codes.Unavailable, "connection lost"), status.Error(codes.Canceled, "cancelled")} {
t.Run(status.Code(finalErr).String(), func(t *testing.T) {
mock := newMockExecServer()
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 7}}},
}
mock.interactiveFinalErr = finalErr
client, cleanup := setupExecTest(t, mock)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
session, err := client.Interactive(ctx, "default", "test-sandbox", []string{"true"}, 0, 0)
require.NoError(t, err)
defer func() { _ = session.Close() }()
code, err := session.ExitCode()
require.Error(t, err)
require.Equal(t, 7, code)
var sdkErr *StatusError
require.ErrorAs(t, err, &sdkErr)
require.Equal(t, status.Code(finalErr), status.Code(sdkErr.Cause))
codeAgain, errAgain := session.ExitCode()
require.Equal(t, code, codeAgain)
require.Equal(t, err, errAgain)
})
}
}
func TestExecInteractive_RejectsEventsAfterExit(t *testing.T) {
for name, event := range map[string]*pb.ExecSandboxEvent{
"duplicate exit": {Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 1}}},
"late output": {Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("late")}}},
} {
t.Run(name, func(t *testing.T) {
mock := newMockExecServer()
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}}, event,
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
session, err := client.Interactive(ctx, "default", "test-sandbox", []string{"true"}, 0, 0)
require.NoError(t, err)
defer func() { _ = session.Close() }()
code, err := session.ExitCode()
require.Equal(t, 0, code)
require.ErrorContains(t, err, "after exit")
})
}
}
func TestExecInteractive_Write(t *testing.T) {
mock := newMockExecServer()
mock.interactiveWaitInput = true
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("$ ")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "test-sandbox", []string{"/bin/sh"}, 80, 24)
require.NoError(t, err)
defer func() { _ = session.Close() }()
n, err := session.Write([]byte("ls\n"))
require.NoError(t, err)
assert.Equal(t, 3, n)
}
func TestExecInteractive_Resize(t *testing.T) {
mock := newMockExecServer()
mock.interactiveWaitInput = true
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("$ ")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "test-sandbox", []string{"/bin/sh"}, 80, 24)
require.NoError(t, err)
defer func() { _ = session.Close() }()
err = session.Resize(120, 40)
require.NoError(t, err)
}
func TestExecInteractive_ServerError(t *testing.T) {
mock := newMockExecServer()
mock.interactiveErr = status.Error(codes.PermissionDenied, "not allowed")
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "test-sandbox", []string{"/bin/sh"}, 80, 24)
if err != nil {
assert.True(t, IsPermissionDenied(err), "expected permission denied, got: %v", err)
return
}
buf := make([]byte, 1024)
_, err = session.Read(buf)
require.Error(t, err)
}
func TestExecInteractive_ExitCode(t *testing.T) {
mock := newMockExecServer()
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("done\n")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 130}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "test-sandbox", []string{"/bin/sh"}, 80, 24)
require.NoError(t, err)
// Drain output
buf := make([]byte, 1024)
for {
_, readErr := session.Read(buf)
if readErr != nil {
break
}
}
exitCode, err := session.ExitCode()
require.NoError(t, err)
assert.Equal(t, 130, exitCode)
_ = session.Close()
}
func TestExecInteractive_ConcurrentReadAndExitCode(t *testing.T) {
mock := newMockExecServer()
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("line1\n")}}},
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("line2\n")}}},
{Payload: &pb.ExecSandboxEvent_Stdout{Stdout: &pb.ExecSandboxStdout{Data: []byte("line3\n")}}},
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "test-sandbox", []string{"sh"}, 80, 24)
require.NoError(t, err)
var wg sync.WaitGroup
var readData []byte
var readErr error
wg.Add(1)
go func() {
defer wg.Done()
buf := make([]byte, 1024)
for {
n, err := session.Read(buf)
if err != nil {
readErr = err
return
}
readData = append(readData, buf[:n]...)
}
}()
exitCode, exitErr := session.ExitCode()
wg.Wait()
require.NoError(t, exitErr)
assert.Equal(t, 0, exitCode)
assert.Equal(t, io.EOF, readErr)
assert.Contains(t, string(readData), "line1\n")
}
// --- Name-to-ID resolution tests ---
func TestExecRun_UsesName(t *testing.T) {
mock := newMockExecServer()
mock.execEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
_, err := client.Run(context.Background(), "default", "my-sandbox", []string{"echo", "hi"})
require.NoError(t, err)
mock.mu.Lock()
defer mock.mu.Unlock()
// Verify the proto request contains the resolved ID, not the name
assert.Equal(t, "my-sandbox", mock.lastExecRequest.GetSandbox())
}
func TestExecRun_ResolutionError(t *testing.T) {
resolver := &stubSandboxResolver{
getErr: &StatusError{Code: ErrorNotFound, Message: "sandbox not found"},
}
client := newExecClient(stubConn(t), resolver)
_, err := client.Run(context.Background(), "default", "nonexistent", []string{"ls"})
require.Error(t, err)
assert.True(t, IsNotFound(err))
}
func TestExecStream_UsesName(t *testing.T) {
mock := newMockExecServer()
mock.execEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
stream, err := client.Stream(context.Background(), "default", "my-sandbox", []string{"echo"})
require.NoError(t, err)
_, _ = stream.ExitCode()
_ = stream.Close()
mock.mu.Lock()
defer mock.mu.Unlock()
assert.Equal(t, "my-sandbox", mock.lastExecRequest.GetSandbox())
}
func TestExecStream_ResolutionError(t *testing.T) {
resolver := &stubSandboxResolver{
getErr: &StatusError{Code: ErrorNotFound, Message: "sandbox not found"},
}
client := newExecClient(stubConn(t), resolver)
_, err := client.Stream(context.Background(), "default", "nonexistent", []string{"ls"})
require.Error(t, err)
assert.True(t, IsNotFound(err))
}
func TestExecInteractive_UsesName(t *testing.T) {
mock := newMockExecServer()
mock.interactiveEvents = []*pb.ExecSandboxEvent{
{Payload: &pb.ExecSandboxEvent_Exit{Exit: &pb.ExecSandboxExit{ExitCode: 0}}},
}
client, cleanup := setupExecTest(t, mock)
defer cleanup()
session, err := client.Interactive(context.Background(), "default", "my-sandbox", []string{"/bin/sh"}, 80, 24)
require.NoError(t, err)
_, _ = session.ExitCode()
_ = session.Close()
mock.mu.Lock()
defer mock.mu.Unlock()
require.NotEmpty(t, mock.receivedInputs)
startReq := mock.receivedInputs[0].GetStart()
require.NotNil(t, startReq)
assert.Equal(t, "my-sandbox", startReq.GetSandbox())
}
func TestExecInteractive_ResolutionError(t *testing.T) {
resolver := &stubSandboxResolver{
getErr: &StatusError{Code: ErrorNotFound, Message: "sandbox not found"},
}
client := newExecClient(stubConn(t), resolver)
_, err := client.Interactive(context.Background(), "default", "nonexistent", []string{"/bin/sh"}, 80, 24)
require.Error(t, err)
assert.True(t, IsNotFound(err))
}
func TestExecRun_EmptySandboxName(t *testing.T) {
client := newExecClient(stubConn(t), &stubSandboxResolver{})
_, err := client.Run(context.Background(), "default", "", []string{"ls"})
require.Error(t, err)
assert.True(t, IsInvalidArgument(err))
}
func TestExecStream_EmptySandboxName(t *testing.T) {
client := newExecClient(stubConn(t), &stubSandboxResolver{})
_, err := client.Stream(context.Background(), "default", "", []string{"ls"})
require.Error(t, err)
assert.True(t, IsInvalidArgument(err))
}
func TestExecInteractive_EmptySandboxName(t *testing.T) {
client := newExecClient(stubConn(t), &stubSandboxResolver{})
_, err := client.Interactive(context.Background(), "default", "", []string{"/bin/sh"}, 80, 24)
require.Error(t, err)
assert.True(t, IsInvalidArgument(err))
}
// stubConn creates a minimal gRPC connection for resolution-error tests
// where the RPC is never reached.
func stubConn(t *testing.T) *grpc.ClientConn {
t.Helper()
lis := bufconn.Listen(bufSize)
srv := grpc.NewServer()
pb.RegisterOpenShellServer(srv, newMockExecServer())
go func() { _ = srv.Serve(lis) }()
t.Cleanup(func() { srv.Stop() })
conn, err := grpc.NewClient("passthrough:///bufconn",
grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) {
return lis.Dial()
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
t.Cleanup(func() { _ = conn.Close() })
return conn
}
-56
View File
@@ -1,56 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package v1
import (
"errors"
"io"
"testing"
"github.com/stretchr/testify/require"
)
// Deliberately implements only the original interface: downstream mocks must
// continue compiling without adding the optional lifecycle methods.
type legacyInteractiveSession struct {
closed bool
err error
}
var _ InteractiveSession = (*legacyInteractiveSession)(nil)
func (*legacyInteractiveSession) Read([]byte) (int, error) { return 0, io.EOF }
func (*legacyInteractiveSession) Write(p []byte) (int, error) { return len(p), nil }
func (*legacyInteractiveSession) Resize(uint32, uint32) error { return nil }
func (*legacyInteractiveSession) ExitCode() (int, error) { return 0, nil }
func (s *legacyInteractiveSession) Close() error { s.closed = true; return s.err }
type controlledInteractiveSession struct {
legacyInteractiveSession
inputClosed bool
cancelled bool
}
func (s *controlledInteractiveSession) CloseWrite() error { s.inputClosed = true; return s.err }
func (s *controlledInteractiveSession) Cancel() error { s.cancelled = true; return s.err }
func TestInteractiveControlLegacyCompatibility(t *testing.T) {
s := &legacyInteractiveSession{err: errors.New("close error")}
var statusErr *StatusError
require.ErrorAs(t, CloseInteractiveInput(s), &statusErr)
require.Equal(t, ErrorUnimplemented, statusErr.Code)
require.False(t, s.closed, "unsupported input closure must not cancel the session")
require.ErrorIs(t, CancelInteractive(s), s.err)
require.True(t, s.closed)
}
func TestInteractiveControlDispatch(t *testing.T) {
s := &controlledInteractiveSession{legacyInteractiveSession: legacyInteractiveSession{err: errors.New("control error")}}
require.Implements(t, (*InteractiveSessionControl)(nil), s)
require.ErrorIs(t, CloseInteractiveInput(s), s.err)
require.True(t, s.inputClosed)
require.ErrorIs(t, CancelInteractive(s), s.err)
require.True(t, s.cancelled)
require.False(t, s.closed, "explicit cancellation takes precedence over fallback")
}
-155
View File
@@ -1,155 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"sync"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
const watchChannelBuffer = 100
// watchBroadcaster manages a set of watchers and broadcasts events to them.
// Each watcher can optionally filter events by resource name.
type watchBroadcaster[T any] struct {
mu sync.Mutex
watchers []*fakeWatcher[T]
}
// newWatchBroadcaster creates a new watchBroadcaster.
func newWatchBroadcaster[T any]() *watchBroadcaster[T] {
return &watchBroadcaster[T]{}
}
// Watch registers a new watcher. If name is non-empty, the watcher only
// receives events matching that name. If name is empty, all events are
// delivered. The returned WatchInterface must be stopped by the caller.
func (b *watchBroadcaster[T]) Watch(name string) types.WatchInterface[T] {
w := &fakeWatcher[T]{
ch: make(chan types.Event[T], watchChannelBuffer),
name: name,
wake: make(chan struct{}, 1),
stopCh: make(chan struct{}),
done: make(chan struct{}),
}
go w.run()
b.mu.Lock()
b.watchers = append(b.watchers, w)
b.mu.Unlock()
return w
}
// Broadcast sends an event to all registered watchers whose name filter
// matches (or whose filter is empty). Stopped watchers are skipped and
// cleaned up lazily.
func (b *watchBroadcaster[T]) Broadcast(event types.Event[T], name string) {
b.mu.Lock()
defer b.mu.Unlock()
active := b.watchers[:0]
for _, w := range b.watchers {
if w.isStopped() {
continue
}
active = append(active, w)
if w.name != "" && w.name != name {
continue
}
w.send(event)
}
b.watchers = active
}
// StopAll closes all active watchers.
func (b *watchBroadcaster[T]) StopAll() {
b.mu.Lock()
defer b.mu.Unlock()
for _, w := range b.watchers {
w.Stop()
}
b.watchers = nil
}
// fakeWatcher implements types.WatchInterface[T] with a buffered channel
// and optional name filter.
type fakeWatcher[T any] struct {
ch chan types.Event[T]
name string
once sync.Once
stopped bool
mu sync.Mutex
queue []types.Event[T]
wake chan struct{}
stopCh chan struct{}
done chan struct{}
}
// ResultChan returns the channel delivering watch events.
func (w *fakeWatcher[T]) ResultChan() <-chan types.Event[T] {
return w.ch
}
// send delivers an event to the watcher under its lock, preventing a
// race between Broadcast (send) and Stop (close) on w.ch.
func (w *fakeWatcher[T]) send(event types.Event[T]) {
w.mu.Lock()
defer w.mu.Unlock()
if w.stopped {
return
}
w.queue = append(w.queue, event)
select {
case w.wake <- struct{}{}:
default:
}
}
// Stop closes the event channel. It is safe to call multiple times.
func (w *fakeWatcher[T]) Stop() {
w.once.Do(func() {
w.mu.Lock()
w.stopped = true
w.mu.Unlock()
close(w.stopCh)
<-w.done
})
}
// isStopped returns true if Stop has been called.
func (w *fakeWatcher[T]) isStopped() bool {
w.mu.Lock()
defer w.mu.Unlock()
return w.stopped
}
func (w *fakeWatcher[T]) run() {
defer close(w.done)
defer close(w.ch)
for {
w.mu.Lock()
if len(w.queue) > 0 {
event := w.queue[0]
w.queue = w.queue[1:]
w.mu.Unlock()
select {
case w.ch <- event:
case <-w.stopCh:
return
}
continue
}
w.mu.Unlock()
select {
case <-w.wake:
case <-w.stopCh:
return
}
}
}
@@ -1,195 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T005: watchBroadcaster tests ---
func TestWatchBroadcaster_Watch_ReceivesEvents(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
w := b.Watch("")
defer w.Stop()
item := &testItem{Name: "alpha", Value: "v1"}
b.Broadcast(types.Event[*testItem]{Type: types.EventAdded, Object: item}, "alpha")
select {
case ev := <-w.ResultChan():
assert.Equal(t, types.EventAdded, ev.Type)
assert.Equal(t, "alpha", ev.Object.Name)
case <-time.After(time.Second):
t.Fatal("timed out waiting for event")
}
}
func TestWatchBroadcaster_DoesNotDropBurstEvents(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
w := b.Watch("")
defer w.Stop()
const count = watchChannelBuffer + 50
for i := range count {
b.Broadcast(types.Event[*testItem]{Object: &testItem{Name: fmt.Sprint(i)}}, "")
}
for range count {
select {
case <-w.ResultChan():
case <-time.After(time.Second):
t.Fatal("watch event was dropped")
}
}
}
func TestWatchBroadcaster_Watch_NameFiltering(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
// Watcher filtered to "alpha" only
wAlpha := b.Watch("alpha")
defer wAlpha.Stop()
// Watcher filtered to "beta" only
wBeta := b.Watch("beta")
defer wBeta.Stop()
// Broadcast event for "alpha"
b.Broadcast(types.Event[*testItem]{Type: types.EventAdded, Object: &testItem{Name: "alpha"}}, "alpha")
// alpha watcher should receive event
select {
case ev := <-wAlpha.ResultChan():
assert.Equal(t, "alpha", ev.Object.Name)
case <-time.After(time.Second):
t.Fatal("alpha watcher: timed out waiting for event")
}
// beta watcher should NOT receive event
select {
case ev := <-wBeta.ResultChan():
t.Fatalf("beta watcher: unexpected event %v", ev)
case <-time.After(50 * time.Millisecond):
// Expected: no event for beta
}
}
func TestWatchBroadcaster_Watch_EmptyNameReceivesAll(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
// Watcher with empty name receives all events
w := b.Watch("")
defer w.Stop()
b.Broadcast(types.Event[*testItem]{Type: types.EventAdded, Object: &testItem{Name: "alpha"}}, "alpha")
b.Broadcast(types.Event[*testItem]{Type: types.EventAdded, Object: &testItem{Name: "beta"}}, "beta")
received := make([]string, 0, 2)
for i := 0; i < 2; i++ {
select {
case ev := <-w.ResultChan():
received = append(received, ev.Object.Name)
case <-time.After(time.Second):
t.Fatal("timed out waiting for event")
}
}
assert.ElementsMatch(t, []string{"alpha", "beta"}, received)
}
func TestWatchBroadcaster_MultipleWatchers(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
w1 := b.Watch("")
defer w1.Stop()
w2 := b.Watch("")
defer w2.Stop()
b.Broadcast(types.Event[*testItem]{Type: types.EventAdded, Object: &testItem{Name: "alpha"}}, "alpha")
// Both watchers should receive the event
for _, w := range []types.WatchInterface[*testItem]{w1, w2} {
select {
case ev := <-w.ResultChan():
assert.Equal(t, "alpha", ev.Object.Name)
case <-time.After(time.Second):
t.Fatal("timed out waiting for event")
}
}
}
func TestWatchBroadcaster_Stop_ClosesChannel(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
w := b.Watch("")
w.Stop()
// Channel should be closed after Stop
_, ok := <-w.ResultChan()
assert.False(t, ok, "channel should be closed after Stop")
}
func TestWatchBroadcaster_Stop_Idempotent(_ *testing.T) {
b := newWatchBroadcaster[*testItem]()
w := b.Watch("")
// Multiple stops should not panic
w.Stop()
w.Stop()
}
func TestWatchBroadcaster_StopAll(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
w1 := b.Watch("")
w2 := b.Watch("alpha")
b.StopAll()
// Both channels should be closed
_, ok1 := <-w1.ResultChan()
assert.False(t, ok1, "w1 channel should be closed after StopAll")
_, ok2 := <-w2.ResultChan()
assert.False(t, ok2, "w2 channel should be closed after StopAll")
}
func TestWatchBroadcaster_BroadcastAfterStop_NoDelivery(_ *testing.T) {
b := newWatchBroadcaster[*testItem]()
w := b.Watch("")
w.Stop()
// Broadcasting after a watcher stops should not panic
b.Broadcast(types.Event[*testItem]{Type: types.EventAdded, Object: &testItem{Name: "alpha"}}, "alpha")
}
func TestWatchBroadcaster_StoppedWatcher_RemovedFromBroadcast(t *testing.T) {
b := newWatchBroadcaster[*testItem]()
w1 := b.Watch("")
w2 := b.Watch("")
// Stop w1, keep w2
w1.Stop()
b.Broadcast(types.Event[*testItem]{Type: types.EventAdded, Object: &testItem{Name: "alpha"}}, "alpha")
// w2 should still receive events
select {
case ev := <-w2.ResultChan():
assert.Equal(t, "alpha", ev.Object.Name)
case <-time.After(time.Second):
t.Fatal("timed out waiting for event on w2")
}
w2.Stop()
}
-56
View File
@@ -1,56 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// fakeConfigClient implements v1.ConfigInterface. All methods return
// Unimplemented because configuration management requires a real gateway.
type fakeConfigClient struct {
closedFunc func() bool
}
// newFakeConfigClient creates a new fakeConfigClient.
func newFakeConfigClient(closedFunc func() bool) *fakeConfigClient {
return &fakeConfigClient{closedFunc: closedFunc}
}
// GetSandbox returns Unimplemented.
func (c *fakeConfigClient) GetSandbox(_ context.Context, _, sandboxName string) (*types.SandboxConfig, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if sandboxName == "" {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetSandbox is not supported by the fake client"}
}
// GetGateway returns Unimplemented.
func (c *fakeConfigClient) GetGateway(_ context.Context) (*types.GatewayConfig, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetGateway is not supported by the fake client"}
}
// Update returns Unimplemented. A nil update is rejected with InvalidArgument
// to match the real client's behavior.
func (c *fakeConfigClient) Update(_ context.Context, _ string, update *types.ConfigUpdate) (*types.ConfigUpdateResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if update == nil {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "update must not be nil"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Update is not supported by the fake client"}
}
// Compile-time check that fakeConfigClient implements v1.ConfigInterface.
var _ v1.ConfigInterface = (*fakeConfigClient)(nil)
-78
View File
@@ -1,78 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T020: fakeConfigClient stub tests ---
func TestFakeConfig_GetSandbox_ReturnsUnimplemented(t *testing.T) {
c := newFakeConfigClient(func() bool { return false })
_, err := c.GetSandbox(context.Background(), "default", "sandbox-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeConfig_GetGateway_ReturnsUnimplemented(t *testing.T) {
c := newFakeConfigClient(func() bool { return false })
_, err := c.GetGateway(context.Background())
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeConfig_Update_ReturnsUnimplemented(t *testing.T) {
c := newFakeConfigClient(func() bool { return false })
_, err := c.Update(context.Background(), "default", &types.ConfigUpdate{
Name: "sandbox-1",
SettingKey: "key",
})
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeConfig_GetSandbox_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeConfigClient(func() bool { return true })
_, err := c.GetSandbox(context.Background(), "default", "sandbox-1")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeConfig_GetGateway_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeConfigClient(func() bool { return true })
_, err := c.GetGateway(context.Background())
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeConfig_Update_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeConfigClient(func() bool { return true })
_, err := c.Update(context.Background(), "default", &types.ConfigUpdate{
Name: "sandbox-1",
SettingKey: "key",
})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
// --- T033: MergeOperations acceptance test ---
func TestFakeConfig_Update_MergeOperationsAccepted(t *testing.T) {
c := newFakeConfigClient(func() bool { return false })
_, err := c.Update(context.Background(), "default", &types.ConfigUpdate{
Name: "sandbox-1",
MergeOperations: []types.PolicyMergeOperation{{RemoveRule: &types.RemoveNetworkRule{RuleName: "test"}}},
})
require.Error(t, err)
// Should return Unimplemented (not InvalidArgument) — MergeOperations are now accepted
assert.True(t, types.IsUnimplemented(err))
assert.False(t, types.IsInvalidArgument(err))
}
-37
View File
@@ -1,37 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// Package fake provides an in-memory fake implementation of the OpenShell SDK
// client interfaces for use in consumer test suites.
//
// The fake client follows the client-go/kubernetes/fake pattern: it maintains
// in-memory stores for sandboxes and providers, supports watch event broadcasting,
// and returns the same StatusError codes as the real client for equivalent error
// conditions (NotFound, AlreadyExists, Unavailable, Unimplemented).
//
// All operations are safe for concurrent use from multiple goroutines.
//
// # Usage
//
// Create a FakeClient, exercise the sandbox lifecycle, and assert results:
//
// func TestSandboxLifecycle(t *testing.T) {
// client := fake.NewClient()
// defer client.Close()
//
// ctx := context.Background()
//
// // Create a sandbox — starts in Provisioning phase
// sb, err := client.Sandboxes().Create(ctx, "my-sandbox", &v1.SandboxSpec{}, nil)
// require.NoError(t, err)
// assert.Equal(t, types.SandboxProvisioning, sb.Status.Phase)
//
// // Wait until ready — transitions synchronously in the fake
// sb, err = client.Sandboxes().WaitReady(ctx, "my-sandbox")
// require.NoError(t, err)
// assert.Equal(t, types.SandboxReady, sb.Status.Phase)
//
// // Clean up
// require.NoError(t, client.Sandboxes().Delete(ctx, "my-sandbox"))
// }
package fake
-57
View File
@@ -1,57 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
var _ v1.ExecInterface = (*fakeExecClient)(nil)
// fakeExecClient implements v1.ExecInterface. All methods return
// Unimplemented because command execution requires a real sandbox runtime.
type fakeExecClient struct {
closedFunc func() bool
}
// newFakeExecClient creates a new fakeExecClient.
func newFakeExecClient(closedFunc func() bool) *fakeExecClient {
return &fakeExecClient{closedFunc: closedFunc}
}
// Run returns Unimplemented.
func (c *fakeExecClient) Run(_ context.Context, _, sandboxName string, _ []string, _ ...v1.ExecOptions) (*types.ExecResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if sandboxName == "" {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Run is not supported by the fake client"}
}
// Stream returns Unimplemented.
func (c *fakeExecClient) Stream(_ context.Context, _, sandboxName string, _ []string, _ ...v1.ExecOptions) (v1.ExecStream, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if sandboxName == "" {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Stream is not supported by the fake client"}
}
// Interactive returns Unimplemented.
func (c *fakeExecClient) Interactive(_ context.Context, _, sandboxName string, _ []string, _, _ uint32, _ ...v1.ExecOptions) (v1.InteractiveSession, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if sandboxName == "" {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Interactive is not supported by the fake client"}
}
-70
View File
@@ -1,70 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T021: Exec stub tests ---
func TestExec_Run_Unimplemented(t *testing.T) {
ec := newFakeExecClient(func() bool { return false })
ctx := context.Background()
_, err := ec.Run(ctx, "default", "sandbox-1", []string{"echo", "hello"})
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestExec_Stream_Unimplemented(t *testing.T) {
ec := newFakeExecClient(func() bool { return false })
ctx := context.Background()
_, err := ec.Stream(ctx, "default", "sandbox-1", []string{"tail", "-f", "/var/log/app.log"})
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestExec_Interactive_Unimplemented(t *testing.T) {
ec := newFakeExecClient(func() bool { return false })
ctx := context.Background()
_, err := ec.Interactive(ctx, "default", "sandbox-1", []string{"/bin/bash"}, 80, 24)
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestExec_Run_ClosedClient(t *testing.T) {
ec := newFakeExecClient(func() bool { return true })
ctx := context.Background()
_, err := ec.Run(ctx, "default", "sandbox-1", []string{"echo"})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestExec_Stream_ClosedClient(t *testing.T) {
ec := newFakeExecClient(func() bool { return true })
ctx := context.Background()
_, err := ec.Stream(ctx, "default", "sandbox-1", []string{"tail"})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestExec_Interactive_ClosedClient(t *testing.T) {
ec := newFakeExecClient(func() bool { return true })
ctx := context.Background()
_, err := ec.Interactive(ctx, "default", "sandbox-1", []string{"/bin/bash"}, 80, 24)
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
-240
View File
@@ -1,240 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"sync"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// Client implements v1.ClientInterface with in-memory stores. It is
// designed for testing consumers of the OpenShell SDK without requiring a
// real gRPC connection. Create one with NewClient.
type Client struct {
sandboxStore *objectStore[*types.Sandbox]
templateStore *objectStore[*types.SandboxWorkloadTemplate]
providerStore *objectStore[*types.Provider]
workspaceStore *objectStore[*types.Workspace]
memberStore *objectStore[*types.WorkspaceMember]
sandboxBroadcaster *watchBroadcaster[*types.Sandbox]
sandboxes v1.SandboxInterface
templateCreate v1.SandboxTemplateCreateInterface
suspendResume v1.SandboxSuspendResumeInterface
templates v1.SandboxTemplateInterface
providers v1.ProviderInterface
services v1.ServiceInterface
exec v1.ExecInterface
files v1.FileInterface
health v1.HealthInterface
ssh v1.SSHInterface
tcp v1.TCPInterface
cfg v1.ConfigInterface
policy v1.PolicyInterface
workspaces v1.WorkspaceInterface
closeOnce sync.Once
closed bool
mu sync.RWMutex // guards closed flag
}
// ClientOption configures a Client during construction.
type ClientOption func(*Client)
// WithHealthResult returns an option that configures the health sub-client
// to return the given result instead of the default healthy response.
func WithHealthResult(r *types.HealthResult) ClientOption {
return func(fc *Client) {
fc.health.(*fakeHealthClient).result = r
}
}
// WithGatewayInfo returns an option that configures the health sub-client
// to return the given gateway info instead of the default response.
func WithGatewayInfo(info *types.GatewayInfo) ClientOption {
return func(fc *Client) {
fc.health.(*fakeHealthClient).gatewayInfo = copyGatewayInfo(info)
}
}
// WithCurrentUser returns an option that configures the health sub-client
// to return the given current user instead of the default response.
func WithCurrentUser(user *types.CurrentUser) ClientOption {
return func(fc *Client) {
fc.health.(*fakeHealthClient).currentUser = copyCurrentUser(user)
}
}
// NewClient creates a new Client with all sub-clients wired up.
// Options (e.g., WithHealthResult) are applied after the default setup.
func NewClient(opts ...ClientOption) *Client {
fc := &Client{
sandboxStore: newobjectStore(sandboxName, copySandbox),
templateStore: newobjectStore(sandboxWorkloadTemplate, copySandboxWorkloadTemplate),
providerStore: newobjectStore(providerName, copyProvider),
workspaceStore: newobjectStore(workspaceName, copyWorkspace),
memberStore: newobjectStore(memberName, copyMember),
sandboxBroadcaster: newWatchBroadcaster[*types.Sandbox](),
}
sandboxes := newFakeSandboxClient(fc.sandboxStore, fc.templateStore, fc.sandboxBroadcaster, fc.isClosed)
fc.sandboxes = sandboxes
fc.templateCreate = sandboxes
fc.suspendResume = sandboxes
fc.templates = newFakeSandboxTemplateClient(fc.templateStore, fc.isClosed)
fc.providers = newFakeProviderClient(fc.providerStore, fc.isClosed)
fc.services = newFakeServiceClient(fc.isClosed)
fc.exec = newFakeExecClient(fc.isClosed)
fc.files = newFakeFileClient(fc.isClosed)
fc.health = newFakeHealthClient(nil, fc.isClosed)
fc.ssh = newFakeSSHClient(fc.isClosed)
fc.tcp = newFakeTCPClient(fc.isClosed)
fc.cfg = newFakeConfigClient(fc.isClosed)
fc.policy = newFakePolicyClient(fc.isClosed)
fc.workspaces = newFakeWorkspaceClient(fc.workspaceStore, fc.memberStore, fc.isClosed)
options.Apply(fc, opts)
return fc
}
// isClosed returns true if the client has been closed. This is passed to
// all sub-clients as the closedFunc parameter.
func (fc *Client) isClosed() bool {
fc.mu.RLock()
defer fc.mu.RUnlock()
return fc.closed
}
// Sandboxes returns the sandbox sub-client.
func (fc *Client) Sandboxes() v1.SandboxInterface { return fc.sandboxes }
// SandboxTemplates returns the reusable sandbox template sub-client.
func (fc *Client) SandboxTemplates() v1.SandboxTemplateInterface { return fc.templates }
// CreateSandboxFromTemplate creates a sandbox from a named workload template
// without changing the legacy Sandboxes() interface.
func (fc *Client) CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *types.SandboxSpec, opts ...types.CreateOption) (*types.Sandbox, error) {
return fc.templateCreate.CreateFromTemplate(ctx, workspace, name, templateName, spec, opts...)
}
// SandboxSuspendResume returns the sandbox suspend and resume sub-client.
func (fc *Client) SandboxSuspendResume() v1.SandboxSuspendResumeInterface {
return fc.suspendResume
}
// Providers returns the provider sub-client.
func (fc *Client) Providers() v1.ProviderInterface { return fc.providers }
// Services returns the service sub-client.
func (fc *Client) Services() v1.ServiceInterface { return fc.services }
// Exec returns the exec sub-client.
func (fc *Client) Exec() v1.ExecInterface { return fc.exec }
// Files returns the file sub-client.
func (fc *Client) Files() v1.FileInterface { return fc.files }
// Health returns the health sub-client.
func (fc *Client) Health() v1.HealthInterface { return fc.health }
// SSH returns the SSH session sub-client.
func (fc *Client) SSH() v1.SSHInterface { return fc.ssh }
// TCP returns the TCP port forwarding sub-client.
func (fc *Client) TCP() v1.TCPInterface { return fc.tcp }
// Config returns the configuration sub-client.
func (fc *Client) Config() v1.ConfigInterface { return fc.cfg }
// Policy returns the policy management sub-client.
func (fc *Client) Policy() v1.PolicyInterface { return fc.policy }
// Workspaces returns the workspace management sub-client.
func (fc *Client) Workspaces() v1.WorkspaceInterface { return fc.workspaces }
// Close marks the client as closed, stops all active watchers, and causes
// subsequent sub-client calls to return Unavailable. Safe to call multiple
// times.
func (fc *Client) Close() error {
fc.closeOnce.Do(func() {
fc.mu.Lock()
fc.closed = true
fc.mu.Unlock()
fc.sandboxBroadcaster.StopAll()
})
return nil
}
// AddSandbox inserts a sandbox directly into the store without triggering
// watch events. This is intended for pre-seeding test fixtures before the
// test begins. The sandbox is deep-copied on insert.
func (fc *Client) AddSandbox(workspace string, sb *types.Sandbox) {
if sb == nil {
return
}
fc.sandboxStore.Insert(workspace, sb)
}
// AddSandboxTemplate inserts a sandbox workload template directly into the store.
// This is intended for pre-seeding test fixtures before the test begins. The
// template is deep-copied on insert.
func (fc *Client) AddSandboxTemplate(workspace string, template *types.SandboxWorkloadTemplate) {
if template == nil {
return
}
fc.templateStore.Insert(workspace, template)
}
// AddProvider inserts a provider directly into the store without triggering
// any side effects. This is intended for pre-seeding test fixtures before
// the test begins. The provider is deep-copied on insert.
func (fc *Client) AddProvider(workspace string, p *types.Provider) {
if p == nil {
return
}
fc.providerStore.Insert(workspace, p)
}
// AddWorkspace inserts a workspace directly into the store without triggering
// any side effects. This is intended for pre-seeding test fixtures before
// the test begins. The workspace is deep-copied on insert.
func (fc *Client) AddWorkspace(ws *types.Workspace) {
if ws == nil {
return
}
fc.workspaceStore.Insert("", ws)
}
// AddMember inserts a workspace member directly into the store without
// triggering any side effects. This is intended for pre-seeding test fixtures
// before the test begins. The member is deep-copied on insert.
func (fc *Client) AddMember(workspace string, m *types.WorkspaceMember) {
if m == nil {
return
}
fc.memberStore.Insert(workspace, m)
}
// AddGlobalRevision adds a gateway-global policy revision for test seeding.
// Global revisions are returned by Policy().List() and Policy().GetStatus()
// when the global option is enabled.
func (fc *Client) AddGlobalRevision(rev types.SandboxPolicyRevision) {
fc.policy.(*fakePolicyClient).AddGlobalRevision(rev)
}
// AddRevision adds a sandbox-scoped policy revision for test seeding.
// Sandbox revisions are returned by Policy().List() and Policy().GetStatus()
// when the global option is not set.
func (fc *Client) AddRevision(workspace, name string, rev types.SandboxPolicyRevision) {
fc.policy.(*fakePolicyClient).AddRevision(workspace, name, rev)
}
// Compile-time interface check.
var _ v1.ClientInterface = (*Client)(nil)
-298
View File
@@ -1,298 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T025: FakeClient Close tests ---
func TestFakeClient_Close(t *testing.T) {
fc := NewClient()
err := fc.Close()
require.NoError(t, err)
}
func TestFakeClient_Close_Idempotent(t *testing.T) {
fc := NewClient()
err := fc.Close()
require.NoError(t, err)
err = fc.Close()
require.NoError(t, err)
}
func TestFakeClient_Sandboxes_AfterClose(t *testing.T) {
fc := NewClient()
ctx := context.Background()
_ = fc.Close()
_, err := fc.Sandboxes().Create(ctx, "default", "test", &types.SandboxSpec{})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeClient_Providers_AfterClose(t *testing.T) {
fc := NewClient()
ctx := context.Background()
_ = fc.Close()
_, err := fc.Providers().Create(ctx, "default", &types.Provider{Name: "test"})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeClient_Health_AfterClose(t *testing.T) {
fc := NewClient()
ctx := context.Background()
_ = fc.Close()
_, err := fc.Health().Check(ctx)
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeClient_Exec_AfterClose(t *testing.T) {
fc := NewClient()
ctx := context.Background()
_ = fc.Close()
_, err := fc.Exec().Run(ctx, "default", "sandbox", []string{"echo"})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeClient_Files_AfterClose(t *testing.T) {
fc := NewClient()
ctx := context.Background()
_ = fc.Close()
err := fc.Files().Upload(ctx, "default", "sandbox", "/local", "/remote")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeClient_Watch_StoppedOnClose(t *testing.T) {
fc := NewClient()
ctx := context.Background()
w, err := fc.Sandboxes().Watch(ctx, "default", "")
require.NoError(t, err)
_ = fc.Close()
// Channel should be closed after FakeClient.Close
_, ok := <-w.ResultChan()
assert.False(t, ok, "watcher channel should be closed after FakeClient.Close")
}
func TestFakeClient_WithHealthResult(t *testing.T) {
custom := &types.HealthResult{Healthy: false, Version: "broken"}
fc := NewClient(WithHealthResult(custom))
ctx := context.Background()
result, err := fc.Health().Check(ctx)
require.NoError(t, err)
assert.False(t, result.Healthy)
assert.Equal(t, "broken", result.Version)
}
func TestFakeClient_SubClients(t *testing.T) {
fc := NewClient()
assert.NotNil(t, fc.Sandboxes())
assert.NotNil(t, fc.Providers())
assert.NotNil(t, fc.Exec())
assert.NotNil(t, fc.Files())
assert.NotNil(t, fc.Health())
}
// --- T013: Pre-seed tests ---
func TestFakeClient_AddSandbox(t *testing.T) {
fc := NewClient()
ctx := context.Background()
sb := &types.Sandbox{
Name: "pre-seeded",
Spec: types.SandboxSpec{LogLevel: "debug"},
Status: types.SandboxStatus{
Phase: types.SandboxReady,
},
}
fc.AddSandbox("default", sb)
got, err := fc.Sandboxes().Get(ctx, "default", "pre-seeded")
require.NoError(t, err)
assert.Equal(t, "pre-seeded", got.Name)
assert.Equal(t, "debug", got.Spec.LogLevel)
assert.Equal(t, types.SandboxReady, got.Status.Phase)
}
func TestFakeClient_AddSandbox_InList(t *testing.T) {
fc := NewClient()
ctx := context.Background()
fc.AddSandbox("default", &types.Sandbox{Name: "sb-1"})
fc.AddSandbox("default", &types.Sandbox{Name: "sb-2"})
list, err := fc.Sandboxes().ListAll(ctx, "default")
require.NoError(t, err)
assert.Len(t, list, 2)
}
func TestFakeClient_AddSandbox_NoWatchEvents(t *testing.T) {
fc := NewClient()
ctx := context.Background()
w, err := fc.Sandboxes().Watch(ctx, "default", "")
require.NoError(t, err)
defer w.Stop()
fc.AddSandbox("default", &types.Sandbox{Name: "pre-seeded"})
// No event should be received — AddSandbox bypasses the broadcaster
select {
case ev := <-w.ResultChan():
t.Fatalf("unexpected event: %v", ev)
default:
// Good — no event received
}
}
func TestFakeClient_AddSandbox_DeepCopy(t *testing.T) {
fc := NewClient()
ctx := context.Background()
sb := &types.Sandbox{
Name: "pre-seeded",
Labels: map[string]string{"env": "test"},
}
fc.AddSandbox("default", sb)
// Mutate the input
sb.Labels["env"] = "mutated"
got, err := fc.Sandboxes().Get(ctx, "default", "pre-seeded")
require.NoError(t, err)
assert.Equal(t, "test", got.Labels["env"])
}
func TestFakeClient_SandboxEndpointStatuses_DeepCopy(t *testing.T) {
fc := NewClient()
ctx := context.Background()
sb := &types.Sandbox{
Name: "tool-sandbox",
Status: types.SandboxStatus{EndpointStatuses: []types.EndpointStatus{{
EndpointID: "endpoint-one",
Host: "tools.example.test",
Ports: []uint32{443, 8443},
Path: "/mcp",
LastResult: types.EndpointTransportFailed,
LastReportedAt: "2026-09-11T10:00:00Z",
}}},
}
fc.AddSandbox("default", sb)
// Neither the seed object nor returned snapshots may mutate stored endpoints.
sb.Status.EndpointStatuses[0].Host = "seed-changed.example.test"
sb.Status.EndpointStatuses[0].Ports[0] = 80
sb.Status.EndpointStatuses[0].LastResult = types.EndpointHTTPResponseReceived
got, err := fc.Sandboxes().Get(ctx, "default", "tool-sandbox")
require.NoError(t, err)
require.Equal(t, []types.EndpointStatus{{
EndpointID: "endpoint-one", Host: "tools.example.test", Ports: []uint32{443, 8443}, Path: "/mcp",
LastResult: types.EndpointTransportFailed, LastReportedAt: "2026-09-11T10:00:00Z",
}}, got.Status.EndpointStatuses)
got.Status.EndpointStatuses[0].Path = "/changed"
got.Status.EndpointStatuses[0].Ports[1] = 8080
got.Status.EndpointStatuses[0].LastReportedAt = "changed"
listed, err := fc.Sandboxes().ListAll(ctx, "default")
require.NoError(t, err)
require.Len(t, listed, 1)
assert.Equal(t, "/mcp", listed[0].Status.EndpointStatuses[0].Path)
assert.Equal(t, []uint32{443, 8443}, listed[0].Status.EndpointStatuses[0].Ports)
assert.Equal(t, "2026-09-11T10:00:00Z", listed[0].Status.EndpointStatuses[0].LastReportedAt)
}
func TestFakeClient_SandboxGrantFailures_DeepCopy(t *testing.T) {
fc := NewClient()
ctx := context.Background()
upstreamStatus := uint32(401)
failure := &types.EndpointFailure{Code: "provider_authorization_required", UpstreamHTTPStatus: &upstreamStatus}
sb := &types.Sandbox{Name: "grant-sandbox", Status: types.SandboxStatus{
EndpointStatuses: []types.EndpointStatus{{EndpointID: "endpoint-grant", LastFailure: failure}},
LastTokenGrantFailure: &types.TokenGrantFailureObservation{DestinationHost: "api.example.test", Failure: failure},
}}
fc.AddSandbox("default", sb)
// Neither the seed object nor returned snapshots may mutate the stored failure.
failure.Code = "seed_changed"
upstreamStatus = 500
got, err := fc.Sandboxes().Get(ctx, "default", "grant-sandbox")
require.NoError(t, err)
got.Status.EndpointStatuses[0].LastFailure.Code = "changed"
got.Status.LastTokenGrantFailure.DestinationHost = "changed.example.test"
*got.Status.LastTokenGrantFailure.Failure.UpstreamHTTPStatus = 503
stored, err := fc.Sandboxes().Get(ctx, "default", "grant-sandbox")
require.NoError(t, err)
assert.Equal(t, "provider_authorization_required", stored.Status.EndpointStatuses[0].LastFailure.Code)
assert.Equal(t, uint32(401), *stored.Status.EndpointStatuses[0].LastFailure.UpstreamHTTPStatus)
assert.Equal(t, "api.example.test", stored.Status.LastTokenGrantFailure.DestinationHost)
assert.Equal(t, "provider_authorization_required", stored.Status.LastTokenGrantFailure.Failure.Code)
assert.Equal(t, uint32(401), *stored.Status.LastTokenGrantFailure.Failure.UpstreamHTTPStatus)
}
func TestFakeClient_AddProvider(t *testing.T) {
fc := NewClient()
ctx := context.Background()
p := &types.Provider{
Name: "openai",
Type: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-4"}},
}
fc.AddProvider("default", p)
got, err := fc.Providers().Get(ctx, "default", "openai")
require.NoError(t, err)
assert.Equal(t, "openai", got.Name)
assert.Equal(t, "gpt-4", got.Spec.Config["model"])
}
func TestFakeClient_AddProvider_DeepCopy(t *testing.T) {
fc := NewClient()
ctx := context.Background()
p := &types.Provider{
Name: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-4"}},
}
fc.AddProvider("default", p)
// Mutate input
p.Spec.Config["model"] = "mutated"
got, err := fc.Providers().Get(ctx, "default", "openai")
require.NoError(t, err)
assert.Equal(t, "gpt-4", got.Spec.Config["model"])
}
-52
View File
@@ -1,52 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
var _ v1.FileInterface = (*fakeFileClient)(nil)
// fakeFileClient implements v1.FileInterface. All methods return
// Unimplemented because file transfer requires a real sandbox runtime.
type fakeFileClient struct {
closedFunc func() bool
}
// newFakeFileClient creates a new fakeFileClient.
func newFakeFileClient(closedFunc func() bool) *fakeFileClient {
return &fakeFileClient{closedFunc: closedFunc}
}
// Upload returns Unimplemented.
func (c *fakeFileClient) Upload(_ context.Context, _, sandboxName, _, remotePath string) error {
if c.closedFunc() {
return &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if sandboxName == "" {
return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
if remotePath == "" {
return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "remote path must not be empty"}
}
return &types.StatusError{Code: types.ErrorUnimplemented, Message: "Upload is not supported by the fake client"}
}
// Download returns Unimplemented.
func (c *fakeFileClient) Download(_ context.Context, _, sandboxName, remotePath, _ string) error {
if c.closedFunc() {
return &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if sandboxName == "" {
return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
if remotePath == "" {
return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "remote path must not be empty"}
}
return &types.StatusError{Code: types.ErrorUnimplemented, Message: "Download is not supported by the fake client"}
}
-52
View File
@@ -1,52 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T022: File stub tests ---
func TestFile_Upload_Unimplemented(t *testing.T) {
fc := newFakeFileClient(func() bool { return false })
ctx := context.Background()
err := fc.Upload(ctx, "default", "test-sandbox", "/local/file.txt", "/remote/file.txt")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFile_Download_Unimplemented(t *testing.T) {
fc := newFakeFileClient(func() bool { return false })
ctx := context.Background()
err := fc.Download(ctx, "default", "test-sandbox", "/remote/file.txt", "/local/file.txt")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFile_Upload_ClosedClient(t *testing.T) {
fc := newFakeFileClient(func() bool { return true })
ctx := context.Background()
err := fc.Upload(ctx, "default", "test-sandbox", "/local/file.txt", "/remote/file.txt")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFile_Download_ClosedClient(t *testing.T) {
fc := newFakeFileClient(func() bool { return true })
ctx := context.Background()
err := fc.Download(ctx, "default", "test-sandbox", "/remote/file.txt", "/local/file.txt")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
-111
View File
@@ -1,111 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// fakeHealthClient implements v1.HealthInterface with configurable
// responses. When no custom result is provided, Check returns a
// default healthy response.
type fakeHealthClient struct {
result *types.HealthResult
gatewayInfo *types.GatewayInfo
currentUser *types.CurrentUser
closedFunc func() bool
}
// newFakeHealthClient creates a new fakeHealthClient. If result is nil,
// Check will return the default healthy response.
func newFakeHealthClient(result *types.HealthResult, closedFunc func() bool) *fakeHealthClient {
return &fakeHealthClient{
result: result,
closedFunc: closedFunc,
}
}
// Check returns the configured health result. If no custom result was
// provided, it returns {Healthy: true, Version: "fake"}.
func (c *fakeHealthClient) Check(_ context.Context) (*types.HealthResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if c.result != nil {
cp := *c.result
return &cp, nil
}
return &types.HealthResult{
Healthy: true,
Version: "fake",
}, nil
}
// GetGatewayInfo returns the configured gateway info. If no custom info
// was provided, it returns a default healthy response.
func (c *fakeHealthClient) GetGatewayInfo(_ context.Context) (*types.GatewayInfo, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if c.gatewayInfo != nil {
return copyGatewayInfo(c.gatewayInfo), nil
}
return &types.GatewayInfo{
Status: types.ServiceStatusHealthy,
Version: "fake",
}, nil
}
// GetCurrentUser returns the configured current user. If no custom user
// was provided, it returns a default user.
func (c *fakeHealthClient) GetCurrentUser(_ context.Context) (*types.CurrentUser, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if c.currentUser != nil {
return copyCurrentUser(c.currentUser), nil
}
return &types.CurrentUser{
Subject: "fake-user",
DisplayName: "Fake User",
}, nil
}
func copyGatewayInfo(info *types.GatewayInfo) *types.GatewayInfo {
if info == nil {
return nil
}
cp := *info
if info.ComputeDrivers != nil {
cp.ComputeDrivers = make([]types.ComputeDriverInfo, len(info.ComputeDrivers))
copy(cp.ComputeDrivers, info.ComputeDrivers)
}
if info.Extensions != nil {
cp.Extensions = make([]types.ExtensionInfo, len(info.Extensions))
for index, extension := range info.Extensions {
cp.Extensions[index] = extension
cp.Extensions[index].SupportedCapabilities = copyStringSlice(extension.SupportedCapabilities)
cp.Extensions[index].RequiredCapabilities = copyStringSlice(extension.RequiredCapabilities)
}
}
return &cp
}
func copyCurrentUser(user *types.CurrentUser) *types.CurrentUser {
if user == nil {
return nil
}
cp := *user
cp.Roles = copyStringSlice(user.Roles)
cp.Scopes = copyStringSlice(user.Scopes)
return &cp
}
-161
View File
@@ -1,161 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T017: Health check tests ---
func TestHealth_DefaultHealthy(t *testing.T) {
hc := newFakeHealthClient(nil, func() bool { return false })
ctx := context.Background()
result, err := hc.Check(ctx)
require.NoError(t, err)
assert.True(t, result.Healthy)
assert.Equal(t, "fake", result.Version)
}
func TestHealth_ConfigurableResult(t *testing.T) {
custom := &types.HealthResult{
Healthy: false,
Version: "v0.0.0-broken",
}
hc := newFakeHealthClient(custom, func() bool { return false })
ctx := context.Background()
result, err := hc.Check(ctx)
require.NoError(t, err)
assert.False(t, result.Healthy)
assert.Equal(t, "v0.0.0-broken", result.Version)
}
func TestHealth_ClosedClient(t *testing.T) {
hc := newFakeHealthClient(nil, func() bool { return true })
ctx := context.Background()
_, err := hc.Check(ctx)
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestHealth_GetGatewayInfo_Default(t *testing.T) {
fc := NewClient()
info, err := fc.Health().GetGatewayInfo(context.Background())
require.NoError(t, err)
require.NotNil(t, info)
assert.Equal(t, types.ServiceStatusHealthy, info.Status)
assert.Equal(t, "fake", info.Version)
}
func TestHealth_GetGatewayInfo_Custom(t *testing.T) {
fc := NewClient(WithGatewayInfo(&types.GatewayInfo{
Status: types.ServiceStatusDegraded,
Version: "1.2.3",
ComputeDrivers: []types.ComputeDriverInfo{
{Name: "k8s", DriverName: "kubernetes", DriverVersion: "2.0.0"},
},
}))
info, err := fc.Health().GetGatewayInfo(context.Background())
require.NoError(t, err)
require.NotNil(t, info)
assert.Equal(t, types.ServiceStatusDegraded, info.Status)
assert.Equal(t, "1.2.3", info.Version)
require.Len(t, info.ComputeDrivers, 1)
assert.Equal(t, "k8s", info.ComputeDrivers[0].Name)
}
func TestHealth_GetGatewayInfo_DeepCopy(t *testing.T) {
fc := NewClient(WithGatewayInfo(&types.GatewayInfo{
Status: types.ServiceStatusHealthy,
Version: "1.0.0",
ComputeDrivers: []types.ComputeDriverInfo{
{Name: "k8s"},
},
Extensions: []types.ExtensionInfo{{
ConfiguredName: "k8s",
SupportedCapabilities: []string{"openshell.compute.contract"},
}},
}))
info1, _ := fc.Health().GetGatewayInfo(context.Background())
info1.ComputeDrivers[0].Name = "mutated"
info1.Extensions[0].ConfiguredName = "mutated"
info1.Extensions[0].SupportedCapabilities[0] = "mutated"
info2, _ := fc.Health().GetGatewayInfo(context.Background())
assert.Equal(t, "k8s", info2.ComputeDrivers[0].Name)
assert.Equal(t, "k8s", info2.Extensions[0].ConfiguredName)
assert.Equal(t, "openshell.compute.contract", info2.Extensions[0].SupportedCapabilities[0])
}
func TestHealth_GetCurrentUser_Default(t *testing.T) {
fc := NewClient()
user, err := fc.Health().GetCurrentUser(context.Background())
require.NoError(t, err)
require.NotNil(t, user)
assert.Equal(t, "fake-user", user.Subject)
assert.Equal(t, "Fake User", user.DisplayName)
}
func TestHealth_GetCurrentUser_Custom(t *testing.T) {
fc := NewClient(WithCurrentUser(&types.CurrentUser{
Subject: "real-user",
DisplayName: "Real User",
Roles: []string{"admin"},
Scopes: []string{"read", "write"},
IdentityProvider: "oidc",
}))
user, err := fc.Health().GetCurrentUser(context.Background())
require.NoError(t, err)
require.NotNil(t, user)
assert.Equal(t, "real-user", user.Subject)
assert.Equal(t, "Real User", user.DisplayName)
assert.Equal(t, []string{"admin"}, user.Roles)
assert.Equal(t, []string{"read", "write"}, user.Scopes)
assert.Equal(t, "oidc", user.IdentityProvider)
}
func TestHealth_GetCurrentUser_DeepCopy(t *testing.T) {
fc := NewClient(WithCurrentUser(&types.CurrentUser{
Subject: "user",
Roles: []string{"admin"},
}))
user1, _ := fc.Health().GetCurrentUser(context.Background())
user1.Roles[0] = "mutated"
user2, _ := fc.Health().GetCurrentUser(context.Background())
assert.Equal(t, "admin", user2.Roles[0])
}
func TestHealth_GetGatewayInfo_Closed(t *testing.T) {
fc := NewClient()
_ = fc.Close()
_, err := fc.Health().GetGatewayInfo(context.Background())
assert.True(t, types.IsUnavailable(err))
}
func TestHealth_GetCurrentUser_Closed(t *testing.T) {
fc := NewClient()
_ = fc.Close()
_, err := fc.Health().GetCurrentUser(context.Background())
assert.True(t, types.IsUnavailable(err))
}
-19
View File
@@ -1,19 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
func deletionResult(existed bool, sandboxID string, opts []v1.DeleteOptions) (*types.DeletionResult, error) {
if existed {
return &types.DeletionResult{Outcome: types.DeletionCompleted, SandboxID: sandboxID}, nil
}
if len(opts) > 0 && opts[0].AllowMissing {
return &types.DeletionResult{Outcome: types.DeletionAlreadyAbsent}, nil
}
return nil, &types.StatusError{Code: types.ErrorNotFound, Message: "target not found"}
}
@@ -1,30 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
func TestClientOption_NilIgnored(t *testing.T) {
hr := &types.HealthResult{Healthy: false, Version: "1.2.3"}
cu := &types.CurrentUser{Subject: "user-42", DisplayName: "Test User"}
fc := NewClient(
WithHealthResult(hr),
nil,
WithCurrentUser(cu),
)
require.NotNil(t, fc)
healthClient := fc.health.(*fakeHealthClient)
assert.Equal(t, false, healthClient.result.Healthy)
assert.Equal(t, "1.2.3", healthClient.result.Version)
assert.Equal(t, "Test User", healthClient.currentUser.DisplayName)
}
-48
View File
@@ -1,48 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"strconv"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
func newSlicePager[T any](items []T, pageSize int, pageToken string) (*v1.Pager[T], error) {
if pageSize < 0 {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "page size must not be negative"}
}
if pageSize == 0 {
pageSize = 100
}
if _, err := parsePageOffset(pageToken, len(items)); err != nil {
return nil, err
}
return v1.NewPager(pageToken, func(_ context.Context, token string) (*v1.Page[T], error) {
start, err := parsePageOffset(token, len(items))
if err != nil {
return nil, err
}
end := min(start+pageSize, len(items))
next := ""
if end < len(items) {
next = strconv.Itoa(end)
}
pageItems := append(make([]T, 0, end-start), items[start:end]...)
return &v1.Page[T]{Items: pageItems, NextPageToken: next}, nil
}), nil
}
func parsePageOffset(token string, length int) (int, error) {
if token == "" {
return 0, nil
}
offset, err := strconv.Atoi(token)
if err != nil || offset < 0 || offset > length {
return 0, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "invalid page token"}
}
return offset, nil
}
-240
View File
@@ -1,240 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"maps"
"slices"
"sync"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
func copySandboxPolicyRevision(r types.SandboxPolicyRevision) types.SandboxPolicyRevision {
if r.Policy != nil {
cp := *r.Policy
if r.Policy.NetworkPolicies != nil {
cp.NetworkPolicies = make(map[string]types.NetworkPolicyRule, len(r.Policy.NetworkPolicies))
maps.Copy(cp.NetworkPolicies, r.Policy.NetworkPolicies)
}
r.Policy = &cp
}
return r
}
// fakePolicyClient implements v1.PolicyInterface. List and GetStatus support
// in-memory global and sandbox-scoped revisions. Other methods return
// Unimplemented because policy management requires a real gateway.
type fakePolicyClient struct {
mu sync.RWMutex
closedFunc func() bool
// globalRevisions stores gateway-global policy revisions.
globalRevisions []types.SandboxPolicyRevision
// sandboxRevisions stores sandbox-scoped revisions keyed by "workspace/name".
sandboxRevisions map[string][]types.SandboxPolicyRevision
}
// newFakePolicyClient creates a new fakePolicyClient.
func newFakePolicyClient(closedFunc func() bool) *fakePolicyClient {
return &fakePolicyClient{
closedFunc: closedFunc,
sandboxRevisions: make(map[string][]types.SandboxPolicyRevision),
}
}
// AddGlobalRevision adds a global policy revision for test seeding.
func (c *fakePolicyClient) AddGlobalRevision(rev types.SandboxPolicyRevision) {
c.mu.Lock()
defer c.mu.Unlock()
c.globalRevisions = append(c.globalRevisions, copySandboxPolicyRevision(rev))
}
// AddRevision adds a sandbox-scoped policy revision for test seeding.
func (c *fakePolicyClient) AddRevision(workspace, name string, rev types.SandboxPolicyRevision) {
c.mu.Lock()
defer c.mu.Unlock()
key := workspace + "/" + name
c.sandboxRevisions[key] = append(c.sandboxRevisions[key], copySandboxPolicyRevision(rev))
}
// GetDraft returns Unimplemented.
func (c *fakePolicyClient) GetDraft(_ context.Context, _, _ string, _ ...v1.GetDraftOption) (*types.DraftPolicy, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetDraft is not supported by the fake client"}
}
// ApproveDraftChunk returns Unimplemented.
func (c *fakePolicyClient) ApproveDraftChunk(_ context.Context, _, _, _, _ string) (*types.ApproveResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "ApproveDraftChunk is not supported by the fake client"}
}
// RejectDraftChunk returns Unimplemented.
func (c *fakePolicyClient) RejectDraftChunk(_ context.Context, _, _, _, _ string) error {
if c.closedFunc() {
return &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return &types.StatusError{Code: types.ErrorUnimplemented, Message: "RejectDraftChunk is not supported by the fake client"}
}
// ApproveAllDraftChunks returns Unimplemented.
func (c *fakePolicyClient) ApproveAllDraftChunks(_ context.Context, _, _ string, _ ...v1.ApproveAllOption) (*types.ApproveAllResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "ApproveAllDraftChunks is not supported by the fake client"}
}
// ClearDraftChunks returns Unimplemented.
func (c *fakePolicyClient) ClearDraftChunks(_ context.Context, _, _ string) (*types.ClearResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "ClearDraftChunks is not supported by the fake client"}
}
// GetDraftHistory returns Unimplemented.
func (c *fakePolicyClient) GetDraftHistory(_ context.Context, _, _ string) ([]types.DraftHistoryEntry, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetDraftHistory is not supported by the fake client"}
}
// GetStatus returns the status of a policy revision. When the global option is
// set, it queries global revisions; otherwise it queries sandbox-scoped ones.
func (c *fakePolicyClient) GetStatus(_ context.Context, workspace, sandboxName string, opts ...v1.GetStatusOption) (*types.PolicyStatusResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
cfg := types.ApplyGetStatusOptions(opts)
c.mu.RLock()
defer c.mu.RUnlock()
var revisions []types.SandboxPolicyRevision
if cfg.Global() {
revisions = c.globalRevisions
} else {
key := workspace + "/" + sandboxName
revisions = c.sandboxRevisions[key]
}
if len(revisions) == 0 {
return nil, &types.StatusError{Code: types.ErrorNotFound, Message: "no policy revisions found"}
}
// Find the active version (highest version with Loaded status).
var activeVersion uint32
for _, r := range revisions {
if r.Status == types.PolicyLoadStatusLoaded && r.Version > activeVersion {
activeVersion = r.Version
}
}
// If no loaded version, use the highest version.
var maxVersion uint32
var maxIdx int
for i, r := range revisions {
if r.Version > maxVersion {
maxVersion = r.Version
maxIdx = i
}
}
if activeVersion == 0 {
activeVersion = maxVersion
}
// Find the requested revision.
targetVersion := cfg.Version()
if targetVersion == 0 {
// Latest revision (by highest version, not insertion order).
rev := copySandboxPolicyRevision(revisions[maxIdx])
return &types.PolicyStatusResult{Revision: rev, ActiveVersion: activeVersion}, nil
}
for _, r := range revisions {
if r.Version == targetVersion {
rev := copySandboxPolicyRevision(r)
return &types.PolicyStatusResult{Revision: rev, ActiveVersion: activeVersion}, nil
}
}
return nil, &types.StatusError{Code: types.ErrorNotFound, Message: "policy version not found"}
}
// List returns policy revisions. When the global option is set, it returns
// global revisions; otherwise it returns revisions for the specified sandbox.
func (c *fakePolicyClient) List(workspace, sandboxName string, opts ...v1.ListPolicyOption) (*v1.Pager[types.SandboxPolicyRevision], error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
cfg := types.ApplyListPolicyOptions(opts)
if cfg.PageSize() < 0 {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "page size must not be negative"}
}
if !cfg.Global() && sandboxName == "" {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox name must not be empty"}
}
c.mu.RLock()
defer c.mu.RUnlock()
var revisions []types.SandboxPolicyRevision
if cfg.Global() {
revisions = slices.Clone(c.globalRevisions)
} else {
revisions = slices.Clone(c.sandboxRevisions[workspace+"/"+sandboxName])
}
// Sort by version for deterministic ordering (map iteration is random).
slices.SortFunc(revisions, func(a, b types.SandboxPolicyRevision) int {
if a.Version < b.Version {
return -1
}
if a.Version > b.Version {
return 1
}
return 0
})
result := make([]types.SandboxPolicyRevision, len(revisions))
for i, r := range revisions {
result[i] = copySandboxPolicyRevision(r)
}
return newSlicePager(result, int(cfg.PageSize()), cfg.PageToken())
}
func (c *fakePolicyClient) ListAll(ctx context.Context, workspace, sandboxName string, opts ...v1.ListPolicyOption) ([]types.SandboxPolicyRevision, error) {
pager, err := c.List(workspace, sandboxName, opts...)
if err != nil {
return nil, err
}
return pager.All(ctx)
}
// EditDraftChunk returns Unimplemented.
func (c *fakePolicyClient) EditDraftChunk(_ context.Context, _, _, _ string, _ *types.NetworkPolicyRule) error {
if c.closedFunc() {
return &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return &types.StatusError{Code: types.ErrorUnimplemented, Message: "EditDraftChunk is not supported by the fake client"}
}
// UndoDraftChunk returns Unimplemented.
func (c *fakePolicyClient) UndoDraftChunk(_ context.Context, _, _, _ string) (*types.UndoResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "UndoDraftChunk is not supported by the fake client"}
}
// Compile-time check that fakePolicyClient implements v1.PolicyInterface.
var _ v1.PolicyInterface = (*fakePolicyClient)(nil)
-287
View File
@@ -1,287 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T031: fakePolicyClient stub tests ---
func TestFakePolicy_GetDraft_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
_, err := c.GetDraft(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakePolicy_ApproveDraftChunk_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
_, err := c.ApproveDraftChunk(context.Background(), "default", "sb-1", "chunk-1", "token-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakePolicy_RejectDraftChunk_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
err := c.RejectDraftChunk(context.Background(), "default", "sb-1", "chunk-1", "bad rule")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakePolicy_ApproveAllDraftChunks_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
_, err := c.ApproveAllDraftChunks(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakePolicy_ClearDraftChunks_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
_, err := c.ClearDraftChunks(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakePolicy_GetDraftHistory_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
_, err := c.GetDraftHistory(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakePolicy_GetStatus_EmptyReturnsNotFound(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
_, err := c.GetStatus(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.True(t, types.IsNotFound(err))
}
func TestFakePolicy_List_EmptyReturnsNonNil(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
revisions, err := c.ListAll(context.Background(), "default", "sb-1")
require.NoError(t, err)
assert.NotNil(t, revisions)
assert.Empty(t, revisions)
}
func TestFakePolicy_EditDraftChunk_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
err := c.EditDraftChunk(context.Background(), "default", "sb-1", "chunk-1", &types.NetworkPolicyRule{Name: "test"})
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakePolicy_UndoDraftChunk_ReturnsUnimplemented(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
_, err := c.UndoDraftChunk(context.Background(), "default", "sb-1", "chunk-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
// --- T007: Global policy List and GetStatus tests ---
func TestFakePolicy_List_Global(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
// Seed global and sandbox-scoped revisions.
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:global-v1", Status: types.PolicyLoadStatusLoaded})
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 2, PolicyHash: "sha256:global-v2", Status: types.PolicyLoadStatusPending})
c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:sb-v1", Status: types.PolicyLoadStatusLoaded})
// List global revisions.
revisions, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true))
require.NoError(t, err)
require.Len(t, revisions, 2)
assert.Equal(t, uint32(1), revisions[0].Version)
assert.Equal(t, "sha256:global-v1", revisions[0].PolicyHash)
assert.Equal(t, uint32(2), revisions[1].Version)
}
func TestFakePolicy_List_Sandbox(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
// Seed global and sandbox-scoped revisions.
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:global-v1"})
c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:sb-v1", Status: types.PolicyLoadStatusLoaded})
c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 2, PolicyHash: "sha256:sb-v2", Status: types.PolicyLoadStatusPending})
// List sandbox-scoped revisions (no global flag).
revisions, err := c.ListAll(context.Background(), "default", "sb-1")
require.NoError(t, err)
require.Len(t, revisions, 2)
assert.Equal(t, "sha256:sb-v1", revisions[0].PolicyHash)
assert.Equal(t, "sha256:sb-v2", revisions[1].PolicyHash)
}
func TestFakePolicy_List_NoIsolationCrossContamination(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
// Only seed sandbox-scoped revisions.
c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:sb-v1"})
// Global list returns empty (no global revisions seeded).
revisions, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true))
require.NoError(t, err)
assert.NotNil(t, revisions)
assert.Empty(t, revisions)
}
func TestFakePolicy_List_GlobalPageSizeStillReturnsAll(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 1})
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 2})
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 3})
revisions, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true), types.WithPageSize(2))
require.NoError(t, err)
require.Len(t, revisions, 3)
assert.Equal(t, uint32(1), revisions[0].Version)
assert.Equal(t, uint32(2), revisions[1].Version)
assert.Equal(t, uint32(3), revisions[2].Version)
}
func TestFakePolicy_GetStatus_Sandbox(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:sb-v1", Status: types.PolicyLoadStatusLoaded})
c.AddRevision("default", "sb-1", types.SandboxPolicyRevision{Version: 2, PolicyHash: "sha256:sb-v2", Status: types.PolicyLoadStatusPending})
result, err := c.GetStatus(context.Background(), "default", "sb-1")
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, uint32(2), result.Revision.Version)
assert.Equal(t, "sha256:sb-v2", result.Revision.PolicyHash)
assert.Equal(t, uint32(1), result.ActiveVersion)
}
func TestFakePolicy_GetStatus_Global(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:global-v1", Status: types.PolicyLoadStatusSuperseded})
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 2, PolicyHash: "sha256:global-v2", Status: types.PolicyLoadStatusLoaded})
// Get global status (latest).
result, err := c.GetStatus(context.Background(), "", "", types.WithStatusGlobal(true))
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, uint32(2), result.Revision.Version)
assert.Equal(t, "sha256:global-v2", result.Revision.PolicyHash)
assert.Equal(t, uint32(2), result.ActiveVersion)
}
func TestFakePolicy_GetStatus_GlobalWithVersion(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 1, PolicyHash: "sha256:global-v1", Status: types.PolicyLoadStatusSuperseded})
c.AddGlobalRevision(types.SandboxPolicyRevision{Version: 2, PolicyHash: "sha256:global-v2", Status: types.PolicyLoadStatusLoaded})
// Get specific global version.
result, err := c.GetStatus(context.Background(), "", "", types.WithStatusGlobal(true), types.WithVersion(1))
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, uint32(1), result.Revision.Version)
assert.Equal(t, types.PolicyLoadStatusSuperseded, result.Revision.Status)
assert.Equal(t, uint32(2), result.ActiveVersion)
}
func TestFakePolicy_GetStatus_GlobalNotFound(t *testing.T) {
c := newFakePolicyClient(func() bool { return false })
// No global revisions seeded.
_, err := c.GetStatus(context.Background(), "", "", types.WithStatusGlobal(true))
require.Error(t, err)
assert.True(t, types.IsNotFound(err))
}
func TestFakePolicy_DeepCopyWithPolicy(t *testing.T) {
fc := NewClient()
defer fc.Close() //nolint:errcheck
fc.AddGlobalRevision(types.SandboxPolicyRevision{
Version: 1,
PolicyHash: "sha256:with-policy",
Status: types.PolicyLoadStatusLoaded,
Policy: &types.SandboxPolicy{
NetworkPolicies: map[string]types.NetworkPolicyRule{
"rule-1": {Name: "rule-1"},
},
},
})
fc.AddRevision("default", "sb-1", types.SandboxPolicyRevision{
Version: 1,
PolicyHash: "sha256:sb-policy",
Status: types.PolicyLoadStatusLoaded,
Policy: &types.SandboxPolicy{
NetworkPolicies: map[string]types.NetworkPolicyRule{
"rule-2": {Name: "rule-2"},
},
},
})
ctx := context.Background()
// Get global revision and mutate it.
revisions, err := fc.Policy().ListAll(ctx, "", "", types.WithListGlobal(true))
require.NoError(t, err)
require.Len(t, revisions, 1)
require.NotNil(t, revisions[0].Policy)
revisions[0].Policy.NetworkPolicies["rule-1"] = types.NetworkPolicyRule{Name: "mutated"}
// Verify internal state is not corrupted.
revisions2, err := fc.Policy().ListAll(ctx, "", "", types.WithListGlobal(true))
require.NoError(t, err)
assert.Equal(t, "rule-1", revisions2[0].Policy.NetworkPolicies["rule-1"].Name)
// Get sandbox revision via GetStatus and verify deep copy.
status, err := fc.Policy().GetStatus(ctx, "default", "sb-1")
require.NoError(t, err)
require.NotNil(t, status.Revision.Policy)
assert.Equal(t, "rule-2", status.Revision.Policy.NetworkPolicies["rule-2"].Name)
}
func TestFakePolicy_List_ClosedReturnsUnavailable(t *testing.T) {
c := newFakePolicyClient(func() bool { return true })
_, err := c.ListAll(context.Background(), "", "", types.WithListGlobal(true))
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakePolicy_GetStatus_ClosedReturnsUnavailable(t *testing.T) {
c := newFakePolicyClient(func() bool { return true })
_, err := c.GetStatus(context.Background(), "", "", types.WithStatusGlobal(true))
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
// --- Closed client tests ---
func TestFakePolicy_GetDraft_ClosedReturnsUnavailable(t *testing.T) {
c := newFakePolicyClient(func() bool { return true })
_, err := c.GetDraft(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakePolicy_ApproveDraftChunk_ClosedReturnsUnavailable(t *testing.T) {
c := newFakePolicyClient(func() bool { return true })
_, err := c.ApproveDraftChunk(context.Background(), "default", "sb-1", "chunk-1", "token-1")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakePolicy_RejectDraftChunk_ClosedReturnsUnavailable(t *testing.T) {
c := newFakePolicyClient(func() bool { return true })
err := c.RejectDraftChunk(context.Background(), "default", "sb-1", "chunk-1", "reason")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
-81
View File
@@ -1,81 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// fakeProfileClient implements v1.ProfileInterface. All methods return
// Unimplemented because profile management requires a real server.
type fakeProfileClient struct {
closedFunc func() bool
}
// newFakeProfileClient creates a new fakeProfileClient.
func newFakeProfileClient(closedFunc func() bool) *fakeProfileClient {
return &fakeProfileClient{closedFunc: closedFunc}
}
// List returns Unimplemented.
func (c *fakeProfileClient) List(_ string, _ ...v1.ListOptions) (*v1.Pager[*types.ProviderProfile], error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "List is not supported by the fake client"}
}
// ListAll returns Unimplemented.
func (c *fakeProfileClient) ListAll(_ context.Context, _ string, _ ...v1.ListOptions) ([]*types.ProviderProfile, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "ListAll is not supported by the fake client"}
}
// Get returns Unimplemented.
func (c *fakeProfileClient) Get(_ context.Context, _, _ string) (*types.ProviderProfile, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Get is not supported by the fake client"}
}
// Import returns Unimplemented.
func (c *fakeProfileClient) Import(_ context.Context, _ string, _ []types.ProfileImportItem) (*types.ImportResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Import is not supported by the fake client"}
}
// Update returns Unimplemented.
func (c *fakeProfileClient) Update(_ context.Context, _, _ string, _ uint64, _ types.ProfileImportItem) (*types.UpdateResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Update is not supported by the fake client"}
}
// Lint returns Unimplemented.
func (c *fakeProfileClient) Lint(_ context.Context, _ string, _ []types.ProfileImportItem) (*types.LintResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Lint is not supported by the fake client"}
}
// Delete returns Unimplemented.
func (c *fakeProfileClient) Delete(_ context.Context, _, _ string, _ ...v1.DeleteOptions) (*types.DeletionResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Delete is not supported by the fake client"}
}
// Compile-time check that fakeProfileClient implements v1.ProfileInterface.
var _ v1.ProfileInterface = (*fakeProfileClient)(nil)
-100
View File
@@ -1,100 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// --- T027: fakeProfileClient stub tests ---
func TestFakeProfile_List_ReturnsUnimplemented(t *testing.T) {
c := newFakeProfileClient(func() bool { return false })
_, err := c.ListAll(context.Background(), "default")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeProfile_Get_ReturnsUnimplemented(t *testing.T) {
c := newFakeProfileClient(func() bool { return false })
_, err := c.Get(context.Background(), "default", "profile-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeProfile_Import_ReturnsUnimplemented(t *testing.T) {
c := newFakeProfileClient(func() bool { return false })
_, err := c.Import(context.Background(), "default", []types.ProfileImportItem{{Source: "test"}})
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeProfile_Update_ReturnsUnimplemented(t *testing.T) {
c := newFakeProfileClient(func() bool { return false })
_, err := c.Update(context.Background(), "default", "profile-1", 1, types.ProfileImportItem{Source: "test"})
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeProfile_Lint_ReturnsUnimplemented(t *testing.T) {
c := newFakeProfileClient(func() bool { return false })
_, err := c.Lint(context.Background(), "default", []types.ProfileImportItem{{Source: "test"}})
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeProfile_Delete_ReturnsUnimplemented(t *testing.T) {
c := newFakeProfileClient(func() bool { return false })
_, err := c.Delete(context.Background(), "default", "profile-1")
require.Error(t, err)
assert.True(t, types.IsUnimplemented(err))
}
func TestFakeProfile_List_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeProfileClient(func() bool { return true })
_, err := c.ListAll(context.Background(), "default")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeProfile_Get_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeProfileClient(func() bool { return true })
_, err := c.Get(context.Background(), "default", "profile-1")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeProfile_Import_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeProfileClient(func() bool { return true })
_, err := c.Import(context.Background(), "default", []types.ProfileImportItem{{Source: "test"}})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeProfile_Update_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeProfileClient(func() bool { return true })
_, err := c.Update(context.Background(), "default", "profile-1", 1, types.ProfileImportItem{Source: "test"})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeProfile_Lint_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeProfileClient(func() bool { return true })
_, err := c.Lint(context.Background(), "default", []types.ProfileImportItem{{Source: "test"}})
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
func TestFakeProfile_Delete_ClosedReturnsUnavailable(t *testing.T) {
c := newFakeProfileClient(func() bool { return true })
_, err := c.Delete(context.Background(), "default", "profile-1")
require.Error(t, err)
assert.True(t, types.IsUnavailable(err))
}
-190
View File
@@ -1,190 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"time"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// providerName extracts the name from a Provider pointer for use as the
// objectStore key function.
func providerName(p *types.Provider) string {
return p.Name
}
// copyProvider returns a deep copy of a Provider pointer. All maps are
// duplicated to prevent aliasing.
func copyProvider(p *types.Provider) *types.Provider {
if p == nil {
return nil
}
cp := *p
cp.Labels = copyStringMap(p.Labels)
cp.Annotations = copyStringMap(p.Annotations)
if p.DeletionTimestamp != nil {
t := *p.DeletionTimestamp
cp.DeletionTimestamp = &t
}
cp.Spec = copyProviderSpec(p.Spec)
return &cp
}
func copyProviderSpec(s types.ProviderSpec) types.ProviderSpec {
s.Credentials = copyStringMap(s.Credentials)
s.Config = copyStringMap(s.Config)
s.CredentialExpiresAt = copyTimeMap(s.CredentialExpiresAt)
return s
}
// copyTimeMap returns a shallow copy of a string-to-time.Time map.
func copyTimeMap(m map[string]time.Time) map[string]time.Time {
if m == nil {
return nil
}
cp := make(map[string]time.Time, len(m))
for k, v := range m {
cp[k] = v
}
return cp
}
// fakeProviderClient implements v1.ProviderInterface backed by an in-memory
// objectStore.
type fakeProviderClient struct {
store *objectStore[*types.Provider]
closedFunc func() bool
profiles *fakeProfileClient
refresh *fakeRefreshClient
}
// newFakeProviderClient creates a new fakeProviderClient.
func newFakeProviderClient(
store *objectStore[*types.Provider],
closedFunc func() bool,
) *fakeProviderClient {
return &fakeProviderClient{
store: store,
closedFunc: closedFunc,
profiles: newFakeProfileClient(closedFunc),
refresh: newFakeRefreshClient(closedFunc),
}
}
// Profiles returns a sub-client for provider profile operations.
func (c *fakeProviderClient) Profiles() v1.ProfileInterface {
return c.profiles
}
// Refresh returns a sub-client for credential refresh operations.
func (c *fakeProviderClient) Refresh() v1.RefreshInterface {
return c.refresh
}
// Create adds a new provider. CreatedAt and ResourceVersion are set
// automatically.
func (c *fakeProviderClient) Create(_ context.Context, workspace string, provider *types.Provider) (*types.Provider, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if provider == nil {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "provider must not be nil"}
}
p := copyProvider(provider)
p.Workspace = workspace
p.CreatedAt = time.Now()
p.ResourceVersion = 1
return c.store.Create(workspace, p)
}
// Get retrieves a provider by name.
func (c *fakeProviderClient) Get(_ context.Context, workspace, name string) (*types.Provider, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return c.store.Get(workspace, name)
}
// List returns a lazy pager over providers. Filtering is not implemented.
func (c *fakeProviderClient) List(workspace string, opts ...v1.ListOptions) (*v1.Pager[*types.Provider], error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
var options v1.ListOptions
if len(opts) > 0 {
options = opts[0]
}
items := c.store.List(workspace)
if len(opts) > 0 && opts[0].AllWorkspaces {
items = c.store.ListAll()
}
return newSlicePager(items, options.PageSize, options.PageToken)
}
func (c *fakeProviderClient) ListAll(ctx context.Context, workspace string, opts ...v1.ListOptions) ([]*types.Provider, error) {
pager, err := c.List(workspace, opts...)
if err != nil {
return nil, err
}
return pager.All(ctx)
}
// Update replaces an existing provider's data. ResourceVersion is
// incremented automatically.
func (c *fakeProviderClient) Update(_ context.Context, workspace string, provider *types.Provider) (*types.Provider, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
if provider == nil {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "provider must not be nil"}
}
existing, err := c.store.Get(workspace, provider.Name)
if err != nil {
return nil, err
}
p := copyProvider(provider)
p.Workspace = workspace
p.CreatedAt = existing.CreatedAt
p.ResourceVersion = existing.ResourceVersion + 1
return c.store.Update(workspace, p)
}
// Delete removes a provider by name. The operation is idempotent.
func (c *fakeProviderClient) Delete(_ context.Context, workspace, name string, opts ...v1.DeleteOptions) (*types.DeletionResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
_, existed := c.store.DeleteAndGet(workspace, name)
return deletionResult(existed, "", opts)
}
// Ensure creates a provider if it does not exist, or updates it if it does.
func (c *fakeProviderClient) Ensure(ctx context.Context, workspace string, provider *types.Provider) (*types.Provider, error) {
if provider == nil {
return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "provider must not be nil"}
}
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
existing, err := c.store.Get(workspace, provider.Name)
if err != nil {
if types.IsNotFound(err) {
return c.Create(ctx, workspace, provider)
}
return nil, err
}
updated := copyProvider(provider)
updated.ID = existing.ID
updated.ResourceVersion = existing.ResourceVersion
return c.Update(ctx, workspace, updated)
}
-276
View File
@@ -1,276 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// helper to build a minimal fake provider client for testing.
func newTestProviderClient() *fakeProviderClient {
store := newobjectStore(providerName, copyProvider)
return newFakeProviderClient(store, func() bool { return false })
}
// --- T015: Provider CRUD tests ---
func TestProvider_Create(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
p := &types.Provider{
Name: "openai",
Type: "openai",
Spec: types.ProviderSpec{
Credentials: map[string]string{"api_key": "sk-test"},
Config: map[string]string{"model": "gpt-4"},
},
}
result, err := pc.Create(ctx, "default", p)
require.NoError(t, err)
assert.Equal(t, "openai", result.Name)
assert.Equal(t, "openai", result.Type)
assert.Equal(t, "sk-test", result.Spec.Credentials["api_key"])
assert.NotZero(t, result.CreatedAt)
assert.Equal(t, uint64(1), result.ResourceVersion)
}
func TestProvider_Create_AlreadyExists(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
p := &types.Provider{Name: "openai", Type: "openai"}
_, err := pc.Create(ctx, "default", p)
require.NoError(t, err)
_, err = pc.Create(ctx, "default", p)
require.Error(t, err)
assert.True(t, types.IsAlreadyExists(err))
}
func TestProvider_Get(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, _ = pc.Create(ctx, "default", &types.Provider{Name: "openai", Type: "openai"})
got, err := pc.Get(ctx, "default", "openai")
require.NoError(t, err)
assert.Equal(t, "openai", got.Name)
}
func TestProvider_Get_NotFound(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, err := pc.Get(ctx, "default", "nonexistent")
require.Error(t, err)
assert.True(t, types.IsNotFound(err))
}
func TestProvider_List_Empty(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
list, err := pc.ListAll(ctx, "default")
require.NoError(t, err)
assert.Empty(t, list)
}
func TestProvider_List(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, _ = pc.Create(ctx, "default", &types.Provider{Name: "openai", Type: "openai"})
_, _ = pc.Create(ctx, "default", &types.Provider{Name: "anthropic", Type: "anthropic"})
list, err := pc.ListAll(ctx, "default")
require.NoError(t, err)
assert.Len(t, list, 2)
}
func TestProvider_Update(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, _ = pc.Create(ctx, "default", &types.Provider{
Name: "openai",
Type: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-3.5"}},
})
updated, err := pc.Update(ctx, "default", &types.Provider{
Name: "openai",
Type: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-4"}},
})
require.NoError(t, err)
assert.Equal(t, "gpt-4", updated.Spec.Config["model"])
assert.Equal(t, uint64(2), updated.ResourceVersion)
}
func TestProvider_Update_NotFound(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, err := pc.Update(ctx, "default", &types.Provider{Name: "nonexistent"})
require.Error(t, err)
assert.True(t, types.IsNotFound(err))
}
func TestProvider_Delete(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, _ = pc.Create(ctx, "default", &types.Provider{Name: "openai"})
_, err := pc.Delete(ctx, "default", "openai")
require.NoError(t, err)
_, err = pc.Get(ctx, "default", "openai")
require.Error(t, err)
assert.True(t, types.IsNotFound(err))
}
func TestProvider_Delete_Idempotent(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, err := pc.Delete(ctx, "default", "nonexistent", types.DeleteOptions{AllowMissing: true})
require.NoError(t, err)
}
func TestProvider_Ensure_CreatesIfMissing(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
p := &types.Provider{
Name: "openai",
Type: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-4"}},
}
result, err := pc.Ensure(ctx, "default", p)
require.NoError(t, err)
assert.Equal(t, "openai", result.Name)
assert.Equal(t, "gpt-4", result.Spec.Config["model"])
// Verify it was stored
got, err := pc.Get(ctx, "default", "openai")
require.NoError(t, err)
assert.Equal(t, "gpt-4", got.Spec.Config["model"])
}
func TestProvider_Ensure_UpdatesIfExists(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, _ = pc.Create(ctx, "default", &types.Provider{
Name: "openai",
Type: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-3.5"}},
})
result, err := pc.Ensure(ctx, "default", &types.Provider{
Name: "openai",
Type: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-4"}},
})
require.NoError(t, err)
assert.Equal(t, "gpt-4", result.Spec.Config["model"])
}
func TestProvider_DeepCopy_OnCreate(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
spec := types.ProviderSpec{
Credentials: map[string]string{"key": "secret"},
Config: map[string]string{"model": "gpt-4"},
CredentialExpiresAt: map[string]time.Time{"key": time.Now()},
}
p := &types.Provider{
Name: "openai",
Labels: map[string]string{"env": "test"},
Spec: spec,
}
result, err := pc.Create(ctx, "default", p)
require.NoError(t, err)
// Mutate inputs
p.Labels["env"] = "mutated"
p.Spec.Credentials["key"] = "mutated"
p.Spec.Config["model"] = "mutated"
got, err := pc.Get(ctx, "default", "openai")
require.NoError(t, err)
assert.Equal(t, "test", got.Labels["env"])
assert.Equal(t, "secret", got.Spec.Credentials["key"])
assert.Equal(t, "gpt-4", got.Spec.Config["model"])
// Mutate returned object
result.Labels["env"] = "mutated-return"
got2, err := pc.Get(ctx, "default", "openai")
require.NoError(t, err)
assert.Equal(t, "test", got2.Labels["env"])
}
func TestProvider_DeepCopy_OnGet(t *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
_, _ = pc.Create(ctx, "default", &types.Provider{
Name: "openai",
Spec: types.ProviderSpec{Config: map[string]string{"model": "gpt-4"}},
})
got, err := pc.Get(ctx, "default", "openai")
require.NoError(t, err)
got.Spec.Config["model"] = "mutated"
got2, err := pc.Get(ctx, "default", "openai")
require.NoError(t, err)
assert.Equal(t, "gpt-4", got2.Spec.Config["model"])
}
// --- T020: Concurrent provider access tests ---
func TestProvider_ConcurrentCreateGetListDeleteEnsure(_ *testing.T) {
pc := newTestProviderClient()
ctx := context.Background()
const goroutines = 10
const opsPerGoroutine = 20
var wg sync.WaitGroup
for i := 0; i < goroutines; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
for j := 0; j < opsPerGoroutine; j++ {
name := fmt.Sprintf("prov-%d-%d", id, j)
p := &types.Provider{Name: name, Type: "test"}
_, _ = pc.Create(ctx, "default", p)
_, _ = pc.Get(ctx, "default", name)
_, _ = pc.ListAll(ctx, "default")
_, _ = pc.Update(ctx, "default", &types.Provider{Name: name, Type: "updated"})
_, _ = pc.Ensure(ctx, "default", &types.Provider{Name: name, Type: "ensured"})
_, _ = pc.Delete(ctx, "default", name)
}
}(i)
}
wg.Wait()
}
-57
View File
@@ -1,57 +0,0 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package fake
import (
"context"
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
// fakeRefreshClient implements v1.RefreshInterface. All methods return
// Unimplemented because credential refresh requires a real server.
type fakeRefreshClient struct {
closedFunc func() bool
}
// newFakeRefreshClient creates a new fakeRefreshClient.
func newFakeRefreshClient(closedFunc func() bool) *fakeRefreshClient {
return &fakeRefreshClient{closedFunc: closedFunc}
}
// GetStatus returns Unimplemented.
func (c *fakeRefreshClient) GetStatus(_ context.Context, _, _, _ string) ([]*types.RefreshStatus, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetStatus is not supported by the fake client"}
}
// Configure returns Unimplemented.
func (c *fakeRefreshClient) Configure(_ context.Context, _ string, _ *types.RefreshConfig) (*types.RefreshStatus, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Configure is not supported by the fake client"}
}
// Rotate returns Unimplemented.
func (c *fakeRefreshClient) Rotate(_ context.Context, _, _, _ string) (*types.RefreshStatus, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Rotate is not supported by the fake client"}
}
// Delete returns Unimplemented.
func (c *fakeRefreshClient) Delete(_ context.Context, _, _, _ string, _ ...v1.DeleteOptions) (*types.DeletionResult, error) {
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "Delete is not supported by the fake client"}
}
// Compile-time check that fakeRefreshClient implements v1.RefreshInterface.
var _ v1.RefreshInterface = (*fakeRefreshClient)(nil)

Some files were not shown because too many files have changed in this diff Show More