From c93ead098ea0107405e76092f1c0c2f79235af5e Mon Sep 17 00:00:00 2001 From: kperry Date: Wed, 4 Nov 2026 16:52:25 -0600 Subject: [PATCH 1/2] feat(examples): add a real-runtime OpenShell smoke test Run ans-openshell-middleware and ans-reference-callee against an actual OpenShell gateway, supervisor and sandbox on the Docker driver and assert the identity guarantees the middleware makes. The in-process demo plays the supervisor itself; this shows what only a real runtime can: that OpenShell invokes the service, applies its header mutations before the request leaves, and blocks the request when the service is down. examples/openshell-smoke/smoke.sh downloads the pinned OpenShell release (openshell-release.env: SHA-256 per CLI and gateway asset, manifest-list digests for the supervisor and sandbox runtime images), extracts the verified tarballs into the run directory, mints every piece of trust material a deployment normally receives from elsewhere into a temporary directory (fixtures/: fixture transparency-log root key, one identity with its receipt and status token pinned to files, the gateway's Ed25519 JWT key with matching JWKS, a private CA for the middleware listener), builds a digest-pinned workload image with curl, and starts the stack with TLS and gateway-JWT verification on, the request hook required through binding_policy, and the Docker driver scoped to its own sandbox_label so an OpenShell install sharing the daemon is never touched. It then runs five checks: an authorized sandbox's plain request is verified by the callee; forged identity headers are replaced; an unsigned direct request is rejected and logged, which arms the callee-log sentinel; an unapproved sandbox is denied before the callee; a request is blocked while the middleware is down (fail_closed). Long external steps run under deadlines, supervisor container logs are kept on failure, and minted keys are never retained. All OpenShell state lives under the temporary directory. The proto-drift CI job now also diffs the vendored extension protos against the pinned OpenShell commit, so a release bump without a contract re-pin fails CI. The smoke workflow runs on ubuntu-latest for pushes to main, pull requests touching the exercised code or the vendored contract, and on demand, and uploads the retained logs when it fails. Motivation: the runnable, reproducible evidence proposed in https://github.com/NVIDIA/OpenShell/issues/5011 and the live-gateway verification follow-up deferred by #2. Verified: passing runs against OpenShell v0.1.7 on Docker (Rancher Desktop, Apple silicon), including from an empty asset cache with the digest-pinned runtime images and the CI-style fixed temp directory. Assisted by Claude Code (Claude Fable 5.1) Co-Authored-By: Claude Fable 5.1 Signed-off-by: kperry --- .github/workflows/ci.yml | 10 + .github/workflows/openshell-smoke.yml | 60 ++ .gitignore | 1 + Makefile | 6 +- README.md | 10 + examples/openshell-smoke/README.md | 133 ++++ examples/openshell-smoke/fixtures/main.go | 367 ++++++++++ .../openshell-smoke/fixtures/main_test.go | 338 +++++++++ .../openshell-smoke/openshell-release.env | 17 + examples/openshell-smoke/policy.template.yaml | 33 + examples/openshell-smoke/smoke.sh | 658 ++++++++++++++++++ examples/openshell-smoke/workload/Dockerfile | 11 + 12 files changed, 1643 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/openshell-smoke.yml create mode 100644 examples/openshell-smoke/README.md create mode 100644 examples/openshell-smoke/fixtures/main.go create mode 100644 examples/openshell-smoke/fixtures/main_test.go create mode 100644 examples/openshell-smoke/openshell-release.env create mode 100644 examples/openshell-smoke/policy.template.yaml create mode 100755 examples/openshell-smoke/smoke.sh create mode 100644 examples/openshell-smoke/workload/Dockerfile diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e1d5cf1..4c72678 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -92,3 +92,13 @@ jobs: run: | buf generate git diff --exit-code -- gen/ + # The smoke test pins an OpenShell release; the vendored contract must be + # the one that release ships, or the smoke test proves nothing about it. + - name: Vendored extension protos match the pinned OpenShell release + run: | + source examples/openshell-smoke/openshell-release.env + for f in extension gateway_interceptor supervisor_middleware; do + curl -fsSL "https://raw.githubusercontent.com/NVIDIA/OpenShell/$OPENSHELL_COMMIT/proto/$f.proto" \ + | diff -u "third_party/openshell/proto/$f.proto" - \ + || { echo "third_party/openshell/proto/$f.proto differs from OpenShell $OPENSHELL_VERSION ($OPENSHELL_COMMIT)"; exit 1; } + done diff --git a/.github/workflows/openshell-smoke.yml b/.github/workflows/openshell-smoke.yml new file mode 100644 index 0000000..939fb23 --- /dev/null +++ b/.github/workflows/openshell-smoke.yml @@ -0,0 +1,60 @@ +# Runs the extension against the pinned OpenShell release with a real gateway, +# supervisor and sandbox on the Docker driver. Slower than the unit suite and +# dependent on GitHub's Docker daemon and ghcr.io, so it runs on pushes to main, +# on pull requests that touch what it exercises, and on demand. +name: OpenShell smoke + +on: + push: + branches: [main] + pull_request: + branches: [main] + paths: + - "cmd/ans-openshell-middleware/**" + - "cmd/ans-reference-callee/**" + - "internal/**" + - "gen/**" + - "third_party/openshell/**" + - "examples/openshell-smoke/**" + - "go.mod" + - "go.sum" + - "Makefile" + - ".github/workflows/openshell-smoke.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + smoke: + name: Gateway, supervisor and sandbox on Docker + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e #v7.0.0 + with: + go-version: "1.26.9" + - name: Cache OpenShell release assets + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 #v4.3.0 + with: + path: ~/.cache/ans-openshell-smoke + key: openshell-${{ hashFiles('examples/openshell-smoke/openshell-release.env') }}-${{ runner.os }}-${{ runner.arch }} + - name: Run the smoke test + # A fixed TMPDIR makes the retained log directory addressable by the + # upload step below; the gateway runs at debug so a middleware_failed + # verdict on CI explains itself. + env: + TMPDIR: ${{ runner.temp }}/smoke + ANS_SMOKE_LOG_LEVEL: debug + run: | + mkdir -p "$TMPDIR" + make openshell-smoke + - name: Upload retained logs + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 #v7.0.2 + with: + name: openshell-smoke-logs + path: ${{ runner.temp }}/smoke/ans-openshell-smoke.*/logs/ + if-no-files-found: ignore + retention-days: 7 diff --git a/.gitignore b/.gitignore index 0aeb50e..c18282e 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ /ans-ocsf-hydrator /ans-reference-callee /demo +/fixtures # Test binaries, built with `go test -c` *.test diff --git a/Makefile b/Makefile index b04fb6b..352b0b2 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ LINT_GOTOOLCHAIN ?= local BIN := bin CMDS := ans-openshell-middleware ans-openshell-interceptor ans-ocsf-hydrator ans-reference-callee -.PHONY: all build proto test cover lint vet demo clean +.PHONY: all build proto test cover lint vet demo openshell-smoke clean all: build @@ -44,3 +44,7 @@ demo: clean: rm -rf $(BIN) coverage*.out + +# End-to-end check against a real OpenShell gateway (Docker). See examples/openshell-smoke/README.md. +openshell-smoke: + examples/openshell-smoke/smoke.sh diff --git a/README.md b/README.md index 8353198..19bc111 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,16 @@ Run the tests: make cover ``` +Run the extension against a real OpenShell gateway, supervisor and sandbox on Docker. It +downloads the pinned OpenShell release, mints disposable identity and trust material, and +asserts that an authorized sandbox's plain request arrives signed, forged identity headers are +replaced, an unapproved sandbox is denied, and a request is blocked while the middleware is +down. See [examples/openshell-smoke](examples/openshell-smoke/README.md): + +```bash +make openshell-smoke +``` + ## Running the services Every service takes one YAML file. Flags: `--config` (required), `--listen` to override the diff --git a/examples/openshell-smoke/README.md b/examples/openshell-smoke/README.md new file mode 100644 index 0000000..6c725a0 --- /dev/null +++ b/examples/openshell-smoke/README.md @@ -0,0 +1,133 @@ +# OpenShell smoke test + +Runs `ans-openshell-middleware` and `ans-reference-callee` against a real OpenShell gateway, +supervisor and sandbox, and asserts the identity guarantees the middleware makes. The in-process +demo (`make demo`) plays the supervisor itself; this test shows what only a real runtime can: +that OpenShell invokes the service, applies its header mutations before the request leaves, +and blocks the request when the service is down. + +> OpenShell's supervisor-middleware contract is a research preview upstream and may change. +> The test pins one release; see [Updating the OpenShell pin](#updating-the-openshell-pin). + +## What it does + +```bash +make openshell-smoke +``` + +1. Builds the middleware, the callee and the fixture generator from this checkout, and a + workload image ([workload/Dockerfile](workload/Dockerfile)): OpenShell's default workload + image plus `curl`, the one binary the policy lets reach the callee. +2. Downloads the pinned OpenShell CLI and gateway release assets, verifies their SHA-256 + against [openshell-release.env](openshell-release.env), and caches them under + `~/.cache/ans-openshell-smoke`. +3. Mints everything a deployment normally receives from elsewhere into a temporary directory: + a fixture transparency-log root key; one registered identity with its key, certificate, + receipt and status token; the gateway's Ed25519 JWT signing key with the matching JWKS; + and a private CA with a serving certificate for the middleware's gRPC listener. The + repository holds no key material and the production transparency log is never contacted. +4. Starts the callee, the middleware (TLS, gateway JWTs verified) and an OpenShell gateway on + the Docker driver with the middleware registered under + `binding_policy = "allowlist"` and `bindings = ["http_request_pre_credentials"]`. +5. Creates a sandbox with [policy.template.yaml](policy.template.yaml), reads its + gateway-issued id, approves exactly that id for the identity in the middleware's + `sandbox_identities`, and restarts the middleware. +6. Runs the assertions below and tears everything down. On failure the logs are kept, including + each sandbox's supervisor container log, and the minted keys are not. + +| Check | Expected observation | +|-------|----------------------| +| Authorized sandbox | A plain `POST /v1/tasks` from the workload reaches the callee signed; the callee returns the operator-assigned ANS name and agent id. | +| Forged identity headers | `DPoP`, `X-SCITT-Receipt` and `X-ANS-Status-Token` set by the workload are overwritten; the callee still verifies the assigned identity. | +| Unsigned direct request | A request to the callee that bypasses OpenShell is rejected with `401`, and the callee logs the rejection. This arms the sentinel the next two checks use. | +| Unapproved sandbox | A second sandbox whose id is not in `sandbox_identities` gets `403 middleware_denied` with reason `ans_identity_unauthorized`; the callee's log does not grow, so it never saw the request. | +| Middleware unavailable | With the middleware stopped, the request gets `403 middleware_failed` (`on_error: fail_closed`); the callee's log does not grow. | + +Replay and body tampering are covered by the verifier's own tests and by `make demo`, and are +reported there, not here. + +## Requirements + +- Linux (x86_64 or arm64) or macOS on Apple silicon, with Bash, `curl`, `jq`, `tar`, + `sha256sum` or `shasum`, and Go. +- A Docker daemon reachable over the Unix socket named by the current `docker context`, with + host networking for the supervisor container (the OpenShell Docker driver's default), and + access to `ghcr.io` and `nvcr.io` for the pinned supervisor and sandbox runtime images and + the workload base image. +- A non-loopback IPv4 address on this machine that containers can reach. It is detected + automatically; set `ANS_SMOKE_HOST` to override. For the duration of the run the gateway + (mTLS), the middleware (TLS, gateway JWTs) and the callee (DPoP-verified) listen on all + interfaces so the supervisor, which runs in the daemon's network namespace, can reach them. + +The test never touches an existing OpenShell installation: it points `XDG_CONFIG_HOME`, +`XDG_STATE_HOME` and `OPENSHELL_LOCAL_TLS_DIR` at its temporary directory, so the gateway's +database, TLS bundle and the CLI's gateway registration all live and die with the run. On the +Docker daemon its gateway works under its own `sandbox_label`, `ans-openshell-smoke`, so the +startup reconciliation that removes a gateway's stray supervisor containers cannot reach another +gateway's sandboxes, and leftovers from a crashed run are reclaimed by the next one. + +## Options + +| Flag or variable | Effect | +|------------------|--------| +| `--keep-running` | After the assertions pass, keep the gateway, middleware, callee and sandbox up until Ctrl-C and print the commands to use them. | +| `--print-config` | Print the rendered `gateway.toml` and `middleware.yaml` and exit. | +| `ANS_SMOKE_HOST` | Address the gateway and sandboxes use to reach the middleware and callee. | +| `ANS_SMOKE_CACHE` | Where release assets are cached. | +| `ANS_SMOKE_LOG_LEVEL` | Gateway log level, default `info`. | + +## Fixture trust versus production trust + +The fixture transparency log is one ES256 key minted per run. Its root key is handed to the +middleware (`transparency_log.root_keys_file`) and to the callee (`--root-keys-file`), and the +identity's receipt and status token are pinned with `receipt_file` and `status_token_file`, so +the middleware verifies them against that key at startup and never fetches anything. In +production the middleware is given the real log's base URL and published root keys, fetches +and refreshes the artifacts itself, and the callee pins the same published keys. Nothing else +differs: the proof, the headers, the verifier and the sandbox authorization path are the +production code. + +The gateway's own TLS bundle and the CLI's client certificate come from OpenShell's +`openshell-gateway generate-certs`; only the JWT signing key is replaced with the one the +fixtures minted so the middleware's JWKS matches. + +## What is pinned, and how + +| Artifact | Pin | Verified by | +|----------|-----|-------------| +| OpenShell CLI and gateway tarballs | SHA-256 per asset in [openshell-release.env](openshell-release.env) | `smoke.sh`, every run, before extraction into the run directory | +| Vendored extension protos | `OPENSHELL_COMMIT` in the same file | CI's proto-drift job diffs them against that commit | +| Supervisor and sandbox runtime images | manifest-list digests in the same file, passed to the gateway as `supervisor_image` and `sandbox_runtime_image` | the container engine, by digest | +| Workload base image | manifest-list digest in [workload/Dockerfile](workload/Dockerfile) | the container engine, by digest | + +The `apt-get install curl` layer in the workload image is the one unpinned input; the identity +assertions do not rest on it, because the callee's own log corroborates the two denial checks and +its rejection logging is proven live first. + +## Limitations + +- `sandbox_identities` is read when the middleware starts. Approving a sandbox means editing the + map and restarting the service, and until the supervisor's channel to it reconnects (a few + seconds) matching requests fail closed with `middleware_failed`. The harness does exactly this + and retries the first request through that window; a production operator would see the same + window on every approval. +- The fixture status token lives one hour. A `--keep-running` stack stops signing when it lapses. +- Only Linux and macOS on Apple silicon are supported; the pinned release has no Intel macOS + gateway build. + +## Ownership + +The harness, its OpenShell pin and the `OpenShell smoke` workflow are maintained by this +repository's maintainers under its normal [contribution process](../../CONTRIBUTING.md); a +maintainer roster is proposed in the governance change under review. File problems as issues +on this repository. The link from OpenShell's supervisor-middleware documentation belongs to +the upstream contribution and is not part of this repository. + +## Updating the OpenShell pin + +1. Edit [openshell-release.env](openshell-release.env): the version, the tag's commit, and the + SHA-256 of each asset from the release's `openshell-checksums-sha256.txt` and + `openshell-gateway-checksums-sha256.txt`. +2. Re-pin the vendored contract (`third_party/openshell`, then `make proto`) if the proto-drift + job reports a difference at the new commit. +3. Run `make openshell-smoke`. diff --git a/examples/openshell-smoke/fixtures/main.go b/examples/openshell-smoke/fixtures/main.go new file mode 100644 index 0000000..879b06d --- /dev/null +++ b/examples/openshell-smoke/fixtures/main.go @@ -0,0 +1,367 @@ +// Command fixtures mints the material the OpenShell smoke test needs and that a +// real deployment receives from an ANS registration and an OpenShell gateway: +// a fixture transparency log root key, one registered identity with its +// receipt and status token pinned to files, the gateway's Ed25519 JWT signing +// key with the JWKS the middleware trusts, and a private CA with a serving +// certificate for the middleware's gRPC listener. Everything is written under +// one directory with a manifest the launcher reads. +package main + +import ( + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "flag" + "fmt" + "io" + "math/big" + "net" + "os" + "path/filepath" + "strings" + "time" + + "github.com/agentnameservice/ans-sdk-go/verify/scitt" + + "github.com/agentnameservice/ans-openshell/internal/testfixtures" +) + +const ( + identityName = "example-agent" + ansName = "ans://v1.0.0.example-agent.example.com" + + defaultStatusTokenTTL = time.Hour + statusTokenBackoff = time.Minute + tlsValidity = 24 * time.Hour + tlsBackdate = time.Hour + kidBytes = 6 + uuidBytes = 16 + serialBits = 128 + + // RFC 4122 version 4 and variant bits for the random agent id, and the + // masks that clear the bits they occupy. + uuidVersion4 = 0x40 + uuidVersionMask = 0x0f + uuidVariant = 0x80 + uuidVariantMask = 0x3f + + dirPerm = 0o700 + filePerm = 0o600 + + manifestFile = "manifest.json" +) + +// manifest is what the launcher reads to render the service configurations. +// The file layout under the output directory is fixed and documented in the +// README; the manifest carries only the values that differ per run. +type manifest struct { + Identity string `json:"identity"` + AnsName string `json:"ansName"` + AgentID string `json:"agentId"` + // StatusTokenExpires is when the pinned status token lapses and the + // middleware stops signing; a --keep-running stack dies then. + StatusTokenExpires time.Time `json:"statusTokenExpires"` +} + +// options select what the bundle is minted for. random and now are the +// generator's two sources of nondeterminism, injected so tests can drive both. +type options struct { + middlewareHosts []string + statusTokenTTL time.Duration + now func() time.Time + random io.Reader +} + +// bundle holds every file before it is written, keyed by relative path. +type bundle struct { + manifest manifest + files map[string][]byte +} + +func main() { + if err := run(os.Args[1:], os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, "fixtures:", err) + os.Exit(1) + } +} + +func run(args []string, stdout io.Writer) error { + fs := flag.NewFlagSet("fixtures", flag.ContinueOnError) + fs.SetOutput(stdout) + out := fs.String("out", "", "directory to create (required; must not exist or must be empty)") + hosts := fs.String("middleware-host", "", "comma-separated IP addresses or DNS names the middleware certificate is valid for (required)") + ttl := fs.Duration("status-token-ttl", defaultStatusTokenTTL, "lifetime of the pinned status token") + if err := fs.Parse(args); err != nil { + return err + } + if *out == "" || *hosts == "" { + return errors.New("-out and -middleware-host are required") + } + parsedHosts, err := parseHosts(*hosts) + if err != nil { + return err + } + b, err := generate(options{middlewareHosts: parsedHosts, statusTokenTTL: *ttl, now: time.Now, random: rand.Reader}) + if err != nil { + return err + } + if err := b.write(*out); err != nil { + return err + } + _, err = fmt.Fprintln(stdout, filepath.Join(*out, manifestFile)) + return err +} + +// parseHosts splits a comma-separated list and rejects empty entries. +func parseHosts(csv string) ([]string, error) { + var hosts []string + for h := range strings.SplitSeq(csv, ",") { + h = strings.TrimSpace(h) + if h == "" { + return nil, errors.New("middleware-host: empty entry") + } + hosts = append(hosts, h) + } + if len(hosts) == 0 { + return nil, errors.New("middleware-host: at least one host is required") + } + return hosts, nil +} + +// generate mints the whole bundle in memory. +func generate(opts options) (*bundle, error) { + if opts.statusTokenTTL <= 0 { + return nil, errors.New("status token ttl must be positive") + } + if len(opts.middlewareHosts) == 0 { + return nil, errors.New("at least one middleware host is required") + } + if opts.now == nil || opts.random == nil { + return nil, errors.New("clock and random source are required") + } + now := opts.now() + agentID, err := newUUID(opts.random) + if err != nil { + return nil, err + } + tl, err := testfixtures.NewTL() + if err != nil { + return nil, fmt.Errorf("fixture transparency log: %w", err) + } + ident, err := testfixtures.NewIdentityValid(agentID, ansName, now.Add(-tlsBackdate), now.Add(tlsValidity)) + if err != nil { + return nil, fmt.Errorf("identity: %w", err) + } + exp := now.Add(opts.statusTokenTTL) + token := tl.StatusToken(agentID, ansName, scitt.StatusActive, + now.Add(-statusTokenBackoff).Unix(), exp.Unix(), ident.Fingerprint) + + gw, err := newGatewayKey(opts.random) + if err != nil { + return nil, err + } + tls, err := newServerTLS(opts.random, opts.middlewareHosts, now) + if err != nil { + return nil, err + } + + files := map[string][]byte{ + "tl-root-keys.txt": []byte(tl.RootKeyC2SP() + "\n"), + "identity/key.pem": ident.KeyPEM, + "identity/cert.pem": ident.CertPEM, + "identity/receipt.cose": tl.Receipt(agentID, ansName), + "identity/status-token.cose": token, + "gateway/jwt/signing.pem": gw.signingPEM, + "gateway/jwt/public.pem": gw.publicPEM, + "gateway/jwt/kid": []byte(gw.kid + "\n"), + "gateway/jwks.json": gw.jwks, + "middleware-tls/ca.crt": tls.caPEM, + "middleware-tls/tls.crt": tls.certPEM, + "middleware-tls/tls.key": tls.keyPEM, + } + return &bundle{ + manifest: manifest{ + Identity: identityName, + AnsName: ansName, + AgentID: agentID, + StatusTokenExpires: exp.UTC(), + }, + files: files, + }, nil +} + +// write creates dir (or requires it to be empty) and writes every file with +// owner-only permissions. It never overwrites. +func (b *bundle) write(dir string) error { + if err := os.MkdirAll(dir, dirPerm); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + entries, err := os.ReadDir(dir) + if err != nil { + return err + } + if len(entries) > 0 { + return fmt.Errorf("%s is not empty", dir) + } + for name, data := range b.files { + path := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), dirPerm); err != nil { + return fmt.Errorf("create %s: %w", filepath.Dir(path), err) + } + if err := writeNew(path, data); err != nil { + return err + } + } + m, err := json.MarshalIndent(b.manifest, "", " ") + if err != nil { + return err + } + return writeNew(filepath.Join(dir, manifestFile), append(m, '\n')) +} + +func writeNew(path string, data []byte) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, filePerm) + if err != nil { + return fmt.Errorf("write %s: %w", path, err) + } + if _, err := f.Write(data); err != nil { + _ = f.Close() + return fmt.Errorf("write %s: %w", path, err) + } + return f.Close() +} + +// gatewayKey is the Ed25519 key an OpenShell gateway signs extension JWTs +// with, in the PKCS#8 and SPKI PEM forms its gateway_jwt block loads, plus the +// JWKS document the middleware verifies those tokens against. +type gatewayKey struct { + signingPEM []byte + publicPEM []byte + jwks []byte + kid string +} + +func newGatewayKey(random io.Reader) (*gatewayKey, error) { + pub, priv, err := ed25519.GenerateKey(random) + if err != nil { + return nil, fmt.Errorf("gateway signing key: %w", err) + } + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + return nil, err + } + spki, err := x509.MarshalPKIXPublicKey(pub) + if err != nil { + return nil, err + } + sum := sha256.Sum256(spki) + kid := "ans-smoke-" + hex.EncodeToString(sum[:kidBytes]) + jwks, err := json.Marshal(map[string]any{"keys": []map[string]string{{ + "kty": "OKP", "crv": "Ed25519", "kid": kid, "alg": "EdDSA", "use": "sig", + "x": base64.RawURLEncoding.EncodeToString(pub), + }}}) + if err != nil { + return nil, err + } + return &gatewayKey{ + signingPEM: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}), + publicPEM: pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: spki}), + jwks: append(jwks, '\n'), + kid: kid, + }, nil +} + +// serverTLS is a private CA and a serving certificate for the middleware's +// gRPC listener, valid for the requested IP addresses and DNS names. OpenShell +// is given the CA through tls_ca_cert_path. +type serverTLS struct { + caPEM []byte + certPEM []byte + keyPEM []byte +} + +func newServerTLS(random io.Reader, hosts []string, now time.Time) (*serverTLS, error) { + caKey, err := ecdsa.GenerateKey(elliptic.P256(), random) + if err != nil { + return nil, err + } + caTmpl, err := certTemplate(random, "ans-openshell smoke CA", now) + if err != nil { + return nil, err + } + caTmpl.IsCA = true + caTmpl.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature + caTmpl.BasicConstraintsValid = true + caDER, err := x509.CreateCertificate(random, caTmpl, caTmpl, &caKey.PublicKey, caKey) + if err != nil { + return nil, fmt.Errorf("ca certificate: %w", err) + } + caCert, err := x509.ParseCertificate(caDER) + if err != nil { + return nil, err + } + + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), random) + if err != nil { + return nil, err + } + leafTmpl, err := certTemplate(random, "ans-openshell-middleware", now) + if err != nil { + return nil, err + } + leafTmpl.KeyUsage = x509.KeyUsageDigitalSignature + leafTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + for _, h := range hosts { + if ip := net.ParseIP(h); ip != nil { + leafTmpl.IPAddresses = append(leafTmpl.IPAddresses, ip) + } else { + leafTmpl.DNSNames = append(leafTmpl.DNSNames, h) + } + } + leafDER, err := x509.CreateCertificate(random, leafTmpl, caCert, &leafKey.PublicKey, caKey) + if err != nil { + return nil, fmt.Errorf("middleware certificate: %w", err) + } + leafKeyDER, err := x509.MarshalECPrivateKey(leafKey) + if err != nil { + return nil, err + } + return &serverTLS{ + caPEM: testfixtures.CertificatePEM(caDER), + certPEM: testfixtures.CertificatePEM(leafDER), + keyPEM: pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: leafKeyDER}), + }, nil +} + +func certTemplate(random io.Reader, commonName string, now time.Time) (*x509.Certificate, error) { + serial, err := rand.Int(random, new(big.Int).Lsh(big.NewInt(1), serialBits)) + if err != nil { + return nil, err + } + return &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: commonName}, + NotBefore: now.Add(-tlsBackdate), + NotAfter: now.Add(tlsValidity), + }, nil +} + +// newUUID returns a random RFC 4122 version 4 UUID for the agent id. +func newUUID(random io.Reader) (string, error) { + var b [uuidBytes]byte + if _, err := io.ReadFull(random, b[:]); err != nil { + return "", err + } + b[6] = (b[6] & uuidVersionMask) | uuidVersion4 + b[8] = (b[8] & uuidVariantMask) | uuidVariant + return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil +} diff --git a/examples/openshell-smoke/fixtures/main_test.go b/examples/openshell-smoke/fixtures/main_test.go new file mode 100644 index 0000000..d5b1a57 --- /dev/null +++ b/examples/openshell-smoke/fixtures/main_test.go @@ -0,0 +1,338 @@ +package main + +import ( + "bytes" + "crypto/rand" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/agentnameservice/ans-sdk-go/verify/scitt" + + "github.com/agentnameservice/ans-openshell/internal/callee" + "github.com/agentnameservice/ans-openshell/internal/config" + "github.com/agentnameservice/ans-openshell/internal/extauth" + "github.com/agentnameservice/ans-openshell/internal/identity" +) + +func TestRunWritesABundleTheServicesLoad(t *testing.T) { + t.Parallel() + dir := filepath.Join(t.TempDir(), "fixtures") + var stdout bytes.Buffer + err := run([]string{"-out", dir, "-middleware-host", "192.0.2.10, middleware.test"}, &stdout) + if err != nil { + t.Fatalf("run: %v", err) + } + if got, want := strings.TrimSpace(stdout.String()), filepath.Join(dir, manifestFile); got != want { + t.Fatalf("stdout = %q, want %q", got, want) + } + + m := readManifest(t, dir) + if m.Identity != identityName || m.AnsName != ansName || m.AgentID == "" { + t.Fatalf("manifest = %+v", m) + } + if time.Until(m.StatusTokenExpires) < defaultStatusTokenTTL-time.Minute { + t.Fatalf("status token expires too soon: %s", m.StatusTokenExpires) + } + // The layout is a contract with smoke.sh, which hardcodes these paths. + for _, rel := range []string{ + "tl-root-keys.txt", "identity/key.pem", "identity/cert.pem", "identity/receipt.cose", + "identity/status-token.cose", "gateway/jwt/signing.pem", "gateway/jwt/public.pem", + "gateway/jwt/kid", "gateway/jwks.json", "middleware-tls/ca.crt", "middleware-tls/tls.crt", + "middleware-tls/tls.key", + } { + info, statErr := os.Stat(filepath.Join(dir, rel)) + if statErr != nil { + t.Fatalf("%s: %v", rel, statErr) + } + if perm := info.Mode().Perm(); perm != filePerm { + t.Fatalf("%s: mode %o, want %o", rel, perm, filePerm) + } + } + + // The middleware loads the identity from the pinned files and verifies the + // artifacts against the root key, exactly as the launcher configures it: + // no transparency log is contacted, so none is configured. + logger := slog.New(slog.DiscardHandler) + reg, err := identity.NewRegistry(t.Context(), map[string]identity.Config{ + m.Identity: { + AnsName: m.AnsName, + AgentID: m.AgentID, + KeyFile: filepath.Join(dir, "identity/key.pem"), + CertFile: filepath.Join(dir, "identity/cert.pem"), + ReceiptFile: filepath.Join(dir, "identity/receipt.cose"), + StatusTokenFile: filepath.Join(dir, "identity/status-token.cose"), + }, + }, config.TransparencyLog{RootKeysFile: filepath.Join(dir, "tl-root-keys.txt")}, logger) + if err != nil { + t.Fatalf("NewRegistry: %v", err) + } + defer reg.Close() + if !reg.Healthy() { + t.Fatal("registry not healthy") + } + + // The callee trusts the same root key. + keys, err := callee.ReadRootKeys(filepath.Join(dir, "tl-root-keys.txt")) + if err != nil { + t.Fatalf("ReadRootKeys: %v", err) + } + store, err := scitt.NewKeyStore(keys) + if err != nil { + t.Fatalf("NewKeyStore: %v", err) + } + token, err := os.ReadFile(filepath.Join(dir, "identity/status-token.cose")) + if err != nil { + t.Fatal(err) + } + vt, err := scitt.VerifyStatusTokenAt(token, store, 0, time.Now().Unix()) + if err != nil { + t.Fatalf("status token does not verify under the written root key: %v", err) + } + if vt.Payload.AgentID != m.AgentID { + t.Fatalf("status token agent %q, manifest %q", vt.Payload.AgentID, m.AgentID) + } + + // The middleware verifies gateway JWTs against the written JWKS. + v, err := extauth.NewVerifier(config.Auth{ + GatewayIssuer: "openshell-gateway:smoke", + Audience: "urn:openshell:extension:middleware:ans", + JWKSFile: filepath.Join(dir, "gateway/jwks.json"), + }, logger) + if err != nil { + t.Fatalf("NewVerifier: %v", err) + } + if !v.Ready() { + t.Fatal("verifier did not load a key from jwks.json") + } + kid, err := os.ReadFile(filepath.Join(dir, "gateway/jwt/kid")) + if err != nil { + t.Fatal(err) + } + var jwks struct { + Keys []struct { + Kid string `json:"kid"` + } `json:"keys"` + } + jwksData, err := os.ReadFile(filepath.Join(dir, "gateway/jwks.json")) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(jwksData, &jwks); err != nil || len(jwks.Keys) != 1 || jwks.Keys[0].Kid != strings.TrimSpace(string(kid)) { + t.Fatalf("jwks.json kid does not match the kid file: %s vs %q (%v)", jwksData, kid, err) + } + assertPEMType(t, filepath.Join(dir, "gateway/jwt/signing.pem"), "PRIVATE KEY") + assertPEMType(t, filepath.Join(dir, "gateway/jwt/public.pem"), "PUBLIC KEY") + + // The serving certificate chains to the CA and names every host. + caPool := x509.NewCertPool() + caPEM, err := os.ReadFile(filepath.Join(dir, "middleware-tls/ca.crt")) + if err != nil { + t.Fatal(err) + } + if !caPool.AppendCertsFromPEM(caPEM) { + t.Fatal("ca.crt is not a certificate") + } + leaf := parseCert(t, filepath.Join(dir, "middleware-tls/tls.crt")) + for _, host := range []string{"192.0.2.10", "middleware.test"} { + if _, err := leaf.Verify(x509.VerifyOptions{Roots: caPool, DNSName: host}); err != nil { + t.Fatalf("tls.crt does not verify for %s: %v", host, err) + } + } + if _, err := leaf.Verify(x509.VerifyOptions{Roots: caPool, DNSName: "other.test"}); err == nil { + t.Fatal("tls.crt verified for a host it was not minted for") + } + assertPEMType(t, filepath.Join(dir, "middleware-tls/tls.key"), "EC PRIVATE KEY") +} + +func TestRunRejectsBadArguments(t *testing.T) { + t.Parallel() + base := t.TempDir() + for _, tt := range []struct { + name string + args []string + want string + }{ + {name: "missing flags", args: []string{"-out", filepath.Join(base, "a")}, want: "are required"}, + {name: "empty host entry", args: []string{"-out", filepath.Join(base, "b"), "-middleware-host", "a,,b"}, want: "empty entry"}, + {name: "zero ttl", args: []string{"-out", filepath.Join(base, "c"), "-middleware-host", "h", "-status-token-ttl", "0s"}, want: "must be positive"}, + {name: "unknown flag", args: []string{"-bogus"}, want: "flag provided but not defined"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := run(tt.args, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("run(%v) = %v, want %q", tt.args, err, tt.want) + } + }) + } +} + +func TestWriteRefusesANonEmptyDirectory(t *testing.T) { + t.Parallel() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "existing"), []byte("x"), filePerm); err != nil { + t.Fatal(err) + } + b, err := generate(options{middlewareHosts: []string{"h"}, statusTokenTTL: time.Hour, now: time.Now, random: rand.Reader}) + if err != nil { + t.Fatalf("generate: %v", err) + } + if err := b.write(dir); err == nil || !strings.Contains(err.Error(), "not empty") { + t.Fatalf("write into a non-empty dir = %v, want refusal", err) + } +} + +func TestWriteReportsFilesystemErrors(t *testing.T) { + t.Parallel() + b, err := generate(options{middlewareHosts: []string{"h"}, statusTokenTTL: time.Hour, now: time.Now, random: rand.Reader}) + if err != nil { + t.Fatalf("generate: %v", err) + } + // A regular file where the output directory should be. + file := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(file, []byte("x"), filePerm); err != nil { + t.Fatal(err) + } + if err := b.write(file); err == nil { + t.Fatal("write onto a file succeeded") + } + if err := b.write(filepath.Join(file, "child")); err == nil { + t.Fatal("write under a file succeeded") + } + // writeNew never overwrites. + existing := filepath.Join(t.TempDir(), "kid") + if err := writeNew(existing, []byte("a")); err != nil { + t.Fatalf("writeNew: %v", err) + } + if err := writeNew(existing, []byte("b")); err == nil || !strings.Contains(err.Error(), "exist") { + t.Fatalf("writeNew overwrite = %v", err) + } +} + +func TestGenerateHonoursTheClockAndTTL(t *testing.T) { + t.Parallel() + fixed := time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) + b, err := generate(options{middlewareHosts: []string{"10.0.0.1"}, statusTokenTTL: 15 * time.Minute, now: func() time.Time { return fixed }, random: rand.Reader}) + if err != nil { + t.Fatalf("generate: %v", err) + } + if !b.manifest.StatusTokenExpires.Equal(fixed.Add(15 * time.Minute)) { + t.Fatalf("expires = %s", b.manifest.StatusTokenExpires) + } + // Every certificate follows the injected clock, not the wall clock. + for _, name := range []string{"identity/cert.pem", "middleware-tls/ca.crt", "middleware-tls/tls.crt"} { + block, _ := pem.Decode(b.files[name]) + if block == nil { + t.Fatalf("%s: not PEM", name) + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if !cert.NotBefore.Equal(fixed.Add(-tlsBackdate)) || !cert.NotAfter.Equal(fixed.Add(tlsValidity)) { + t.Fatalf("%s: validity %s to %s, want from the injected clock", name, cert.NotBefore, cert.NotAfter) + } + } + for _, tt := range []struct { + name string + opts options + want string + }{ + {name: "no hosts", opts: options{statusTokenTTL: time.Hour, now: time.Now, random: rand.Reader}, want: "middleware host"}, + {name: "negative ttl", opts: options{middlewareHosts: []string{"h"}, statusTokenTTL: -1, now: time.Now, random: rand.Reader}, want: "positive"}, + {name: "no random source", opts: options{middlewareHosts: []string{"h"}, statusTokenTTL: time.Hour, now: time.Now}, want: "random source"}, + {name: "failing random source", opts: options{middlewareHosts: []string{"h"}, statusTokenTTL: time.Hour, now: time.Now, random: failingReader{}}, want: "unlucky"}, + } { + if _, err := generate(tt.opts); err == nil || !strings.Contains(err.Error(), tt.want) { + t.Errorf("%s: generate = %v, want %q", tt.name, err, tt.want) + } + } +} + +// failingReader fails every read, standing in for an exhausted entropy source. +type failingReader struct{} + +func (failingReader) Read([]byte) (int, error) { return 0, errors.New("unlucky") } + +// TestGeneratorsSurfaceRandomFailures drives each minting helper with a random +// source that fails, so the error returns behind it are exercised. Since Go +// 1.26 ecdsa.GenerateKey ignores the caller's reader, so the P-256 key paths +// cannot be made to fail this way; the Ed25519 key, the certificate serials +// and signatures, and the agent id still read from it. +func TestGeneratorsSurfaceRandomFailures(t *testing.T) { + t.Parallel() + now := time.Now() + if _, err := newGatewayKey(failingReader{}); err == nil { + t.Error("newGatewayKey accepted a failing random source") + } + if _, err := newServerTLS(failingReader{}, []string{"h"}, now); err == nil { + t.Error("newServerTLS accepted a failing random source") + } + if _, err := certTemplate(failingReader{}, "cn", now); err == nil { + t.Error("certTemplate accepted a failing random source") + } + if _, err := newUUID(failingReader{}); err == nil { + t.Error("newUUID accepted a failing random source") + } +} + +func TestParseHosts(t *testing.T) { + t.Parallel() + got, err := parseHosts(" a , b ") + if err != nil || len(got) != 2 || got[0] != "a" || got[1] != "b" { + t.Fatalf("parseHosts = %v, %v", got, err) + } + if _, err := parseHosts(""); err == nil { + t.Fatal("parseHosts(\"\") accepted") + } +} + +func readManifest(t *testing.T, dir string) manifest { + t.Helper() + data, err := os.ReadFile(filepath.Join(dir, manifestFile)) + if err != nil { + t.Fatal(err) + } + var m manifest + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("manifest: %v", err) + } + return m +} + +func assertPEMType(t *testing.T, path, want string) { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + block, _ := pem.Decode(data) + if block == nil || block.Type != want { + t.Fatalf("%s: PEM type %v, want %s", path, block, want) + } +} + +func parseCert(t *testing.T, path string) *x509.Certificate { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + block, _ := pem.Decode(data) + if block == nil { + t.Fatalf("%s: not PEM", path) + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + t.Fatalf("%s: %v", path, err) + } + return cert +} diff --git a/examples/openshell-smoke/openshell-release.env b/examples/openshell-smoke/openshell-release.env new file mode 100644 index 0000000..907d54c --- /dev/null +++ b/examples/openshell-smoke/openshell-release.env @@ -0,0 +1,17 @@ +# OpenShell release the smoke test runs against. smoke.sh downloads these assets +# from https://github.com/NVIDIA/OpenShell/releases/download// and +# refuses any file whose SHA-256 differs. Update every line together. +OPENSHELL_VERSION=v0.1.7 +OPENSHELL_COMMIT=5d25211b25a8fc887e8d5c606d57d6ab22f1d76c +# Runtime images the gateway launches, pinned to the multi-arch manifest-list +# digest of the release tag (docker buildx imagetools inspect :0.1.7). +OPENSHELL_SUPERVISOR_IMAGE=ghcr.io/nvidia/openshell/supervisor@sha256:a07864bd0c546716039c2000a919f50ce8f7f1f67ba37dda350cf64d3a7cfb06 +OPENSHELL_SANDBOX_IMAGE=ghcr.io/nvidia/openshell/sandbox@sha256:89819c03f291d9b909c3fc2962360e24af4516627422d18f3e681829f003f347 +# openshell (CLI) +OPENSHELL_CLI_SHA256_x86_64_unknown_linux_musl=5c1adfcae797eac9b2e8b9280c66c1f75e4e84d9e31ce6938c5b994314ef6098 +OPENSHELL_CLI_SHA256_aarch64_unknown_linux_musl=696b523c263895b69eaa7c7e6afbb19b8af6c65cd79c7ffac7b685b6e3aa23da +OPENSHELL_CLI_SHA256_aarch64_apple_darwin=c5899a2fe6b40c371e7d660bd8983cefb766d04658bd9193b12a80525b12c742 +# openshell-gateway +OPENSHELL_GATEWAY_SHA256_x86_64_unknown_linux_gnu=e1714dcfd85c949e2f53260bcfbf04b203f6f5cbd3a61e61c11c38cbc91cb102 +OPENSHELL_GATEWAY_SHA256_aarch64_unknown_linux_gnu=eb0ba91efebbcc61e4cfae5fb18934c5fe308ece1a09ba16c999d00c452109dc +OPENSHELL_GATEWAY_SHA256_aarch64_apple_darwin=fe47a385c16c10cde8905bf1bf627e4a9fbf4a81bcf44b388dec4d22618fbb48 diff --git a/examples/openshell-smoke/policy.template.yaml b/examples/openshell-smoke/policy.template.yaml new file mode 100644 index 0000000..f2663a4 --- /dev/null +++ b/examples/openshell-smoke/policy.template.yaml @@ -0,0 +1,33 @@ +# Sandbox policy for the smoke test. smoke.sh fills in the placeholders. +# The workload may POST /v1/tasks to the reference callee on the gateway host; +# every such request is signed by the ANS middleware, which runs last in the +# chain and blocks the request when it cannot sign. +version: 1 + +network_middlewares: + ans-identity: + name: ANS identity + middleware: __MIDDLEWARE_NAME__ + order: 100 + on_error: fail_closed + endpoints: + include: + - host.openshell.internal + config: + mode: sign + identity: __IDENTITY__ + +network_policies: + callee: + name: callee + endpoints: + - host: host.openshell.internal + port: __CALLEE_PORT__ + protocol: rest + enforcement: enforce + rules: + - allow: + method: POST + path: /v1/tasks + binaries: + - path: /usr/bin/curl diff --git a/examples/openshell-smoke/smoke.sh b/examples/openshell-smoke/smoke.sh new file mode 100755 index 0000000..7193e32 --- /dev/null +++ b/examples/openshell-smoke/smoke.sh @@ -0,0 +1,658 @@ +#!/usr/bin/env bash +# Runs the ANS identity extension against a real OpenShell gateway, supervisor +# and sandbox and asserts the identity guarantees end to end. Everything the +# run needs is minted into a temporary directory: identity material, the +# gateway's JWT signing key, and a private CA for the middleware listener. +# Nothing in the repository holds a key, and the production ANS transparency +# log is never contacted. +# +# Checks, in order: +# 1. an authorized sandbox's plain POST reaches the callee signed, and the +# callee returns the operator-assigned ANS identity; +# 2. identity headers the workload forges are replaced before the callee +# sees them; +# 3. a request that never passes the middleware is rejected by the callee, +# which logs the rejection (this also arms the sentinel used next); +# 4. a sandbox whose id is not approved for the identity is denied before +# the callee is reached; +# 5. with the middleware stopped, the request is blocked (fail_closed). +# +# The in-process demo (make demo) covers replay and body tampering; this script +# covers what only a real runtime can show: that OpenShell invokes the service, +# applies its header mutations, and blocks traffic when it is down. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +EXAMPLE_DIR="$ROOT/examples/openshell-smoke" +KEEP_RUNNING=0 +PRINT_CONFIG=0 + +usage() { + cat <&2; usage >&2; exit 2 ;; + esac + shift +done + +# shellcheck source=examples/openshell-smoke/openshell-release.env +source "$EXAMPLE_DIR/openshell-release.env" + +require_command() { + command -v "$1" >/dev/null 2>&1 || { echo "FAIL missing required command: $1" >&2; exit 1; } +} +for cmd in curl docker go jq tar; do require_command "$cmd"; done + +sha256_matches() { + # $1: expected hex digest, $2: file + local actual + if command -v sha256sum >/dev/null 2>&1; then + actual="$(sha256sum "$2" | awk '{ print $1 }')" + elif command -v shasum >/dev/null 2>&1; then + actual="$(shasum -a 256 "$2" | awk '{ print $1 }')" + else + echo "FAIL neither sha256sum nor shasum is available" >&2 + exit 1 + fi + [[ "$actual" == "$1" ]] +} + +detect_service_host() { + local address + if [[ -n "${ANS_SMOKE_HOST:-}" ]]; then + printf '%s\n' "$ANS_SMOKE_HOST" + return + fi + if [[ "$(uname -s)" == "Darwin" ]]; then + # Prefer a LAN interface: the default route is often a VPN tunnel that the + # container VM cannot reach. + local candidate + for candidate in $(ifconfig -l 2>/dev/null); do + [[ "$candidate" == en* ]] || continue + address="$(ipconfig getifaddr "$candidate" 2>/dev/null || true)" + if [[ -n "$address" && "$address" != 127.* ]]; then + printf '%s\n' "$address" + return + fi + done + fi + if command -v ip >/dev/null 2>&1; then + address="$(ip route get 1.1.1.1 2>/dev/null | awk '{ for (i = 1; i <= NF; i++) if ($i == "src") { print $(i + 1); exit } }')" + if [[ -n "$address" ]]; then + printf '%s\n' "$address" + return + fi + fi + if command -v hostname >/dev/null 2>&1; then + address="$(hostname -I 2>/dev/null | awk '{ for (i = 1; i <= NF; i++) if ($i !~ /^127\./ && $i !~ /:/) { print $i; exit } }')" + if [[ -n "$address" ]]; then + printf '%s\n' "$address" + return + fi + fi + echo "FAIL could not detect a non-loopback host address; set ANS_SMOKE_HOST" >&2 + exit 1 +} + +SERVICE_HOST="$(detect_service_host)" +if [[ "$SERVICE_HOST" == 127.* || "$SERVICE_HOST" == *:* || "$SERVICE_HOST" == localhost ]]; then + echo "FAIL ANS_SMOKE_HOST must be a non-loopback IPv4 address: $SERVICE_HOST" >&2 + exit 1 +fi + +# The gateway talks to the Docker daemon over its Unix socket. The current +# context names it, which also covers runtimes that do not use the default path. +DOCKER_SOCKET="$(docker context inspect --format '{{.Endpoints.docker.Host}}' 2>/dev/null || true)" +DOCKER_SOCKET="${DOCKER_SOCKET#unix://}" +if [[ -z "$DOCKER_SOCKET" || "$DOCKER_SOCKET" == *://* || ! -S "$DOCKER_SOCKET" ]]; then + echo "FAIL the Docker context does not expose a local Unix socket (got '${DOCKER_SOCKET:-none}')" >&2 + exit 1 +fi + +# --------------------------------------------------------------------------- +# Working directory, ports, cleanup +# --------------------------------------------------------------------------- +WORK="$(mktemp -d "${TMPDIR:-/tmp}/ans-openshell-smoke.XXXXXX")" +LOG_DIR="$WORK/logs" +FIXTURES="$WORK/fixtures" +# Every OpenShell path (config, state, CLI gateway registrations) lives under +# WORK so the run never touches a real installation. +export XDG_CONFIG_HOME="$WORK/xdg/config" +export XDG_STATE_HOME="$WORK/xdg/state" +export XDG_DATA_HOME="$WORK/xdg/data" +export OPENSHELL_LOCAL_TLS_DIR="$WORK/gateway-tls" +unset OPENSHELL_GATEWAY OPENSHELL_GATEWAY_ENDPOINT OPENSHELL_SANDBOX_POLICY OPENSHELL_COMPUTE_DRIVER OPENSHELL_DRIVERS +mkdir -p "$LOG_DIR" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_DATA_HOME" + +RUN_ID="ans-smoke-$$-$RANDOM" +MIDDLEWARE_NAME="ans-identity-smoke" +# Docker namespace for everything the gateway creates; stable across runs on +# purpose, see write_gateway_config. +DOCKER_SANDBOX_LABEL="ans-openshell-smoke" +# The workload image is tagged by its Dockerfile's checksum so repeated runs +# reuse the build and a Dockerfile change forces a new one. +WORKLOAD_IMAGE="ans-openshell-smoke-workload:$(cksum "$EXAMPLE_DIR/workload/Dockerfile" | awk '{ print $1 }')" +SANDBOX_NAME="ans-$$" +UNAPPROVED_SANDBOX_NAME="ans-rogue-$$" +GATEWAY_PID="" +MIDDLEWARE_PID="" +CALLEE_PID="" +declare -a CREATED_SANDBOXES=() +declare -a CLI=() + +# sandbox_containers prints the ids of every container the Docker driver +# created for this run's sandboxes, running or exited. +sandbox_containers() { + local name + for name in ${CREATED_SANDBOXES[@]+"${CREATED_SANDBOXES[@]}"}; do + docker ps -aq --filter "label=openshell.ai/sandbox-namespace=$DOCKER_SANDBOX_LABEL" \ + --filter "label=openshell.ai/sandbox-name=$name" 2>/dev/null + done | tr '\n' ' ' +} + +cleanup() { + local status=$? + trap - EXIT + # fail already captured the container logs on an assertion failure; this + # covers a Ctrl-C or an unexpected exit, before the sandboxes go away. + [[ $status -eq 0 ]] || capture_container_logs + if [[ ${#CLI[@]} -gt 0 ]]; then + for name in ${CREATED_SANDBOXES[@]+"${CREATED_SANDBOXES[@]}"}; do + "${CLI[@]}" sandbox delete "$name" >>"$LOG_DIR/setup.log" 2>&1 || true + done + # The gateway removes a sandbox's containers in a background task after + # the delete RPC returns, and stopping a supervisor can take ten seconds or + # more. Wait for the driver to finish before taking the gateway down, and + # remove anything it did not get to so nothing accumulates on the daemon. + local leftover + for _ in {1..120}; do + leftover="$(sandbox_containers)" + [[ -z "$leftover" ]] && break + sleep 0.5 + done + if [[ -n "$leftover" ]]; then + echo "WARN removing containers the gateway had not finished deleting" >&2 + # shellcheck disable=SC2086 # container ids are whitespace-separated + docker rm -f $leftover >>"$LOG_DIR/setup.log" 2>&1 || true + fi + fi + for pid in "$GATEWAY_PID" "$MIDDLEWARE_PID" "$CALLEE_PID"; do + if [[ -n "$pid" ]]; then + kill "$pid" 2>/dev/null || true + wait "$pid" 2>/dev/null || true + fi + done + if [[ $status -eq 0 ]]; then + rm -rf "$WORK" + else + # Keep the logs for diagnosis, never the minted private keys, the gateway + # database or the CLI client certificate. + rm -rf "$FIXTURES" "$OPENSHELL_LOCAL_TLS_DIR" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_DATA_HOME" "$BIN" "$WORK"/gateway.db* + echo "logs retained in $LOG_DIR" >&2 + fi + exit "$status" +} +trap cleanup EXIT + +port_is_free() { + if command -v lsof >/dev/null 2>&1; then + if lsof -nP -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1; then return 1; fi + return 0 + fi + if (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; then return 1; fi + return 0 +} + +choose_port_block() { + local count="$1" start offset + for _ in {1..200}; do + start=$((20000 + RANDOM % 20000)) + for ((offset = 0; offset < count; offset++)); do + port_is_free "$((start + offset))" || continue 2 + done + printf '%s\n' "$start" + return + done + echo "FAIL no free local port block" >&2 + exit 1 +} + +PORT_BASE="$(choose_port_block 5)" +MIDDLEWARE_PORT="$PORT_BASE" +MIDDLEWARE_HEALTH_PORT="$((PORT_BASE + 1))" +CALLEE_PORT="$((PORT_BASE + 2))" +GATEWAY_PORT="$((PORT_BASE + 3))" +GATEWAY_HEALTH_PORT="$((PORT_BASE + 4))" +GATEWAY_ENDPOINT="https://127.0.0.1:$GATEWAY_PORT" +# The sandbox dials the callee by this authority; the middleware signs for it +# and the callee verifies against it (pop trusted host). +CALLEE_AUTHORITY="host.openshell.internal:$CALLEE_PORT" + +# capture_container_logs saves the stdout and stderr of every container the +# driver created for this run's sandboxes. The supervisor's log is the only +# place a middleware_failed verdict explains itself (TLS handshake, connect +# timeout, JWT audience), and cleanup destroys those containers. +capture_container_logs() { + local id name + for id in $(sandbox_containers); do + name="$(docker inspect --format '{{.Name}}' "$id" 2>/dev/null | sed 's|^/||')" + docker logs "$id" >"$LOG_DIR/container-${name:-$id}.log" 2>&1 || true + done +} + +fail() { + printf 'FAIL %s\n' "$1" >&2 + capture_container_logs + local log + for log in "$LOG_DIR"/*.log; do + printf '\n--- %s ---\n' "$log" >&2 + tail -n 60 "$log" >&2 + done + exit 1 +} + +# run_bounded SECONDS CMD...: runs CMD with a wall-clock deadline so a stalled +# registry pull or a hung RPC becomes a failure with logs instead of a hang. +# Uses coreutils timeout where present (Linux, Homebrew coreutils) and a +# background watchdog otherwise (stock macOS). +run_bounded() { + local seconds="$1" + shift + if command -v timeout >/dev/null 2>&1; then + timeout "$seconds" "$@" + return + fi + "$@" & + local pid=$! + ( sleep "$seconds" && kill "$pid" 2>/dev/null ) & + local watchdog=$! + local status=0 + wait "$pid" || status=$? + kill "$watchdog" 2>/dev/null || true + wait "$watchdog" 2>/dev/null || true + return "$status" +} + +step() { + local label="$1" + shift + printf 'INFO %s\n' "$label" + { printf '\n== %s ==\n+' "$label"; printf ' %q' "$@"; printf '\n'; } >>"$LOG_DIR/setup.log" + "$@" >>"$LOG_DIR/setup.log" 2>&1 || fail "$label" +} + +wait_for_http() { + local label="$1" url="$2" pid="$3" attempts="${4:-60}" + for _ in $(seq 1 "$attempts"); do + if [[ -n "$pid" ]] && ! kill -0 "$pid" 2>/dev/null; then + fail "$label exited early" + fi + if curl -fsS --max-time 2 "$url" >/dev/null 2>&1; then + printf 'INFO %s is ready\n' "$label" + return + fi + sleep 1 + done + fail "$label did not become ready at $url" +} + +# --------------------------------------------------------------------------- +# OpenShell release assets, verified against the pinned checksums +# --------------------------------------------------------------------------- +# The checksum variables are assigned by openshell-release.env. +# shellcheck disable=SC2154 +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) CLI_ASSET=openshell-x86_64-unknown-linux-musl; GW_ASSET=openshell-gateway-x86_64-unknown-linux-gnu + CLI_SHA="$OPENSHELL_CLI_SHA256_x86_64_unknown_linux_musl"; GW_SHA="$OPENSHELL_GATEWAY_SHA256_x86_64_unknown_linux_gnu" ;; + Linux-aarch64 | Linux-arm64) CLI_ASSET=openshell-aarch64-unknown-linux-musl; GW_ASSET=openshell-gateway-aarch64-unknown-linux-gnu + CLI_SHA="$OPENSHELL_CLI_SHA256_aarch64_unknown_linux_musl"; GW_SHA="$OPENSHELL_GATEWAY_SHA256_aarch64_unknown_linux_gnu" ;; + Darwin-arm64) CLI_ASSET=openshell-aarch64-apple-darwin; GW_ASSET=openshell-gateway-aarch64-apple-darwin + CLI_SHA="$OPENSHELL_CLI_SHA256_aarch64_apple_darwin"; GW_SHA="$OPENSHELL_GATEWAY_SHA256_aarch64_apple_darwin" ;; + *) echo "FAIL unsupported platform $(uname -s)-$(uname -m)" >&2; exit 1 ;; +esac + +CACHE="${ANS_SMOKE_CACHE:-${XDG_CACHE_HOME:-${HOME}/.cache}/ans-openshell-smoke}/$OPENSHELL_VERSION" +mkdir -p "$CACHE" + +# fetch_asset NAME SHA BINARY: downloads the release tarball once, verifies it +# against the pinned digest, and extracts BINARY into the cache. Everything it +# prints goes to stderr so the callers below can read nothing but the binary +# path from stdout. +fetch_asset() { + local name="$1" sha="$2" bin="$BIN/$3" + local dest="$CACHE/$name.tar.gz" + if [[ ! -f "$dest" ]]; then + printf 'INFO downloading %s %s\n' "$OPENSHELL_VERSION" "$name" >&2 + curl -fsSL --retry 3 -o "$dest.partial" \ + "https://github.com/NVIDIA/OpenShell/releases/download/$OPENSHELL_VERSION/$name.tar.gz" + mv "$dest.partial" "$dest" + fi + if ! sha256_matches "$sha" "$dest"; then + rm -f "$dest" + fail "checksum mismatch for $name; the download was discarded" + fi + # The binary is extracted from the verified tarball on every run, into the + # run's own directory, so what executes is always what the checksum covered. + tar -xzf "$dest" -C "$BIN" "$3" + chmod 0755 "$bin" + printf '%s\n' "$bin" +} + +BIN="$WORK/bin" +mkdir -p "$BIN" +CLI_BIN="$(fetch_asset "$CLI_ASSET" "$CLI_SHA" openshell)" +GATEWAY_BIN="$(fetch_asset "$GW_ASSET" "$GW_SHA" openshell-gateway)" +[[ -x "$CLI_BIN" && -x "$GATEWAY_BIN" ]] || fail "release binaries are not executable: $CLI_BIN $GATEWAY_BIN" +printf 'INFO openshell %s\n' "$("$CLI_BIN" --version 2>&1 | head -n 1)" + +# --------------------------------------------------------------------------- +# Build the extension and mint the fixtures +# --------------------------------------------------------------------------- +step "building the extension" go build -C "$ROOT" -o "$BIN/" ./cmd/ans-openshell-middleware ./cmd/ans-reference-callee ./examples/openshell-smoke/fixtures +step "minting fixtures" "$BIN/fixtures" -out "$FIXTURES" -middleware-host "$SERVICE_HOST" +if ! docker image inspect "$WORKLOAD_IMAGE" >/dev/null 2>&1; then + step "building the workload image $WORKLOAD_IMAGE" run_bounded 600 docker build -q -t "$WORKLOAD_IMAGE" "$EXAMPLE_DIR/workload" +fi +IDENTITY="$(jq -r .identity "$FIXTURES/manifest.json")" +ANS_NAME="$(jq -r .ansName "$FIXTURES/manifest.json")" +AGENT_ID="$(jq -r .agentId "$FIXTURES/manifest.json")" + +# The gateway's own TLS bundle (listener certificate, CLI client certificate) +# comes from OpenShell's generator; our fixtures supply the JWT signing key so +# the middleware can be given the matching JWKS. +step "generating gateway TLS material" "$GATEWAY_BIN" generate-certs --output-dir "$OPENSHELL_LOCAL_TLS_DIR" \ + --server-san "$SERVICE_HOST" --server-san 127.0.0.1 +rm -rf "$OPENSHELL_LOCAL_TLS_DIR/jwt" +cp -R "$FIXTURES/gateway/jwt" "$OPENSHELL_LOCAL_TLS_DIR/jwt" + +# --------------------------------------------------------------------------- +# Service configuration +# --------------------------------------------------------------------------- +write_middleware_config() { + # $1: sandbox_identities YAML flow map, e.g. "{}" or "{: example-agent}" + cat >"$WORK/middleware.yaml" <"$WORK/gateway.toml" <"$WORK/policy.yaml" +} +render_policy + +# --------------------------------------------------------------------------- +# Start the callee, the middleware, then the gateway +# --------------------------------------------------------------------------- +start_callee() { + "$BIN/ans-reference-callee" --listen "0.0.0.0:$CALLEE_PORT" \ + --root-keys-file "$FIXTURES/tl-root-keys.txt" \ + --trusted-host "$CALLEE_AUTHORITY" \ + --allow-ans-name "$ANS_NAME" >"$LOG_DIR/callee.log" 2>&1 & + CALLEE_PID=$! +} + +start_middleware() { + printf '\n== middleware start %s ==\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >>"$LOG_DIR/middleware.log" + "$BIN/ans-openshell-middleware" --config "$WORK/middleware.yaml" --log-level debug >>"$LOG_DIR/middleware.log" 2>&1 & + MIDDLEWARE_PID=$! + wait_for_http "middleware" "http://127.0.0.1:$MIDDLEWARE_HEALTH_PORT/readyz" "$MIDDLEWARE_PID" +} + +stop_middleware() { + kill "$MIDDLEWARE_PID" 2>/dev/null || true + wait "$MIDDLEWARE_PID" 2>/dev/null || true + MIDDLEWARE_PID="" + for _ in {1..30}; do + port_is_free "$MIDDLEWARE_PORT" && return + sleep 0.2 + done + fail "middleware port did not close" +} + +start_callee +# The callee has no health route; its first signed request is the readiness check. +for _ in {1..30}; do + (exec 3<>"/dev/tcp/127.0.0.1/$CALLEE_PORT") 2>/dev/null && break + kill -0 "$CALLEE_PID" 2>/dev/null || fail "callee exited early" + sleep 0.5 +done +start_middleware + +printf 'INFO starting gateway %s on %s\n' "$OPENSHELL_VERSION" "$GATEWAY_ENDPOINT" +"$GATEWAY_BIN" --config "$WORK/gateway.toml" --compute-driver docker \ + --bind-address 0.0.0.0 --port "$GATEWAY_PORT" --health-port "$GATEWAY_HEALTH_PORT" --metrics-port 0 \ + --log-level "${ANS_SMOKE_LOG_LEVEL:-info}" --db-url "sqlite://$WORK/gateway.db" >"$LOG_DIR/gateway.log" 2>&1 & +GATEWAY_PID=$! +wait_for_http "gateway" "http://127.0.0.1:$GATEWAY_HEALTH_PORT/healthz" "$GATEWAY_PID" 120 + +step "registering the gateway with the CLI" "$CLI_BIN" gateway add "$GATEWAY_ENDPOINT" --local --name smoke +CLI=("$CLI_BIN" --gateway smoke) + +middleware_negotiated() { + "${CLI[@]}" gateway info --output json \ + | jq -e --arg name "$MIDDLEWARE_NAME" '.extensions[] | select(.configured_name == $name)' >/dev/null +} +step "verifying the gateway negotiated the middleware" middleware_negotiated + +# --------------------------------------------------------------------------- +# Sandboxes +# --------------------------------------------------------------------------- +# create_sandbox NAME: creates the sandbox and prints its gateway-issued id. +# Callers add NAME to CREATED_SANDBOXES themselves: this runs inside a command +# substitution, where an append would never reach the parent shell. +create_sandbox() { + local name="$1" + step "creating sandbox $name" run_bounded 600 "${CLI[@]}" sandbox create --name "$name" --from "$WORKLOAD_IMAGE" \ + --policy "$WORK/policy.yaml" --no-tty --detach -- sleep infinity 1>&2 + "${CLI[@]}" sandbox get "$name" --output json | jq -r '.id' +} + +# sandbox_curl NAME [curl args...]: POSTs to the callee from inside the sandbox +# and prints the response body followed by the HTTP status on its own line. +sandbox_curl() { + local name="$1" + shift + run_bounded 90 "${CLI[@]}" sandbox exec --name "$name" --no-tty -- \ + curl -sS --max-time 20 -w '\n%{http_code}' "$@" "http://$CALLEE_AUTHORITY/v1/tasks" \ + -H 'content-type: application/json' --data '{"task":"settle invoice 42"}' +} + +# response_status / response_body split sandbox_curl output. +response_status() { tail -n 1 <<<"$1"; } +response_body() { sed '$d' <<<"$1"; } + +CREATED_SANDBOXES+=("$SANDBOX_NAME") +SANDBOX_ID="$(create_sandbox "$SANDBOX_NAME")" +[[ -n "$SANDBOX_ID" && "$SANDBOX_ID" != null ]] || fail "could not read the sandbox id" +printf 'INFO sandbox %s has id %s\n' "$SANDBOX_NAME" "$SANDBOX_ID" + +# Approve exactly this sandbox for the identity; the operator-owned map is +# the only thing that grants signing. +write_middleware_config "{$SANDBOX_ID: $IDENTITY}" +stop_middleware +start_middleware + +PASS=0 +check() { + printf 'PASS %s\n' "$1" + PASS=$((PASS + 1)) +} + +# 1. Authorized sandbox: the callee returns the assigned identity. The +# middleware was just restarted to approve the sandbox, and the supervisor's +# gRPC channel to it (5 s connect timeout, 10 s keepalive) takes a few seconds +# to notice and reconnect; until then OpenShell reports middleware_failed and +# blocks the request, which is the fail_closed behavior check 4 asserts. +STATUS="" +for attempt in 1 2 3 4 5 6; do + OUT="$(sandbox_curl "$SANDBOX_NAME")" || fail "authorized request did not complete" + STATUS="$(response_status "$OUT")" + BODY="$(response_body "$OUT")" + [[ "$STATUS" == 200 ]] && break + printf 'INFO attempt %d: status %s (%s), retrying\n' "$attempt" "$STATUS" \ + "$(jq -r '[.error, .reason_code] | map(select(. != null)) | join(" ")' <<<"$BODY" 2>/dev/null || printf 'unparsed')" + sleep 3 +done +[[ "$STATUS" == 200 ]] || fail "authorized request: status $STATUS, body: $BODY" +[[ "$(jq -r .caller <<<"$BODY")" == "$ANS_NAME" && "$(jq -r .agentId <<<"$BODY")" == "$AGENT_ID" ]] \ + || fail "callee returned another identity: $BODY" +check "authorized sandbox is verified as $ANS_NAME" + +# 2. Forged identity headers from the workload are replaced, not relayed. +OUT="$(sandbox_curl "$SANDBOX_NAME" -H 'DPoP: forged' -H 'X-SCITT-Receipt: forged' -H 'X-ANS-Status-Token: forged')" \ + || fail "forged-header request did not complete" +STATUS="$(response_status "$OUT")" +BODY="$(response_body "$OUT")" +[[ "$STATUS" == 200 && "$(jq -r .caller <<<"$BODY")" == "$ANS_NAME" ]] \ + || fail "forged headers were not replaced: status $STATUS, body: $BODY" +check "forged identity headers are replaced with the operator-assigned identity" + +# Probe: a request that bypasses OpenShell is rejected by the callee, and the +# callee logs the rejection. Checks 3 and 4 infer "the callee was never +# reached" from its log not growing, so that sentinel is proven live here +# before it is relied on. +CALLEE_LINES_BEFORE="$(wc -l <"$LOG_DIR/callee.log")" +STATUS="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 10 -X POST "http://127.0.0.1:$CALLEE_PORT/v1/tasks" \ + -H "Host: $CALLEE_AUTHORITY" -H 'content-type: application/json' --data '{"task":"settle invoice 42"}')" +[[ "$STATUS" == 401 ]] || fail "unsigned direct request: status $STATUS" +[[ "$(wc -l <"$LOG_DIR/callee.log")" -gt "$CALLEE_LINES_BEFORE" ]] || fail "the callee did not log the rejected direct request; the not-reached checks would be vacuous" +check "unsigned direct request is rejected by the callee (401) and logged" + +# 3. A sandbox that is not approved for the identity is denied before the +# callee: the callee's log, which the probe above showed grows on every +# rejected request, must not grow. +CREATED_SANDBOXES+=("$UNAPPROVED_SANDBOX_NAME") +create_sandbox "$UNAPPROVED_SANDBOX_NAME" >/dev/null +CALLEE_LINES_BEFORE="$(wc -l <"$LOG_DIR/callee.log")" +OUT="$(sandbox_curl "$UNAPPROVED_SANDBOX_NAME")" || true +STATUS="$(response_status "$OUT")" +BODY="$(response_body "$OUT")" +[[ "$STATUS" == 403 ]] || fail "unapproved sandbox: status $STATUS, body: $BODY" +grep -q 'middleware_denied' <<<"$BODY" || fail "unapproved sandbox: not a middleware denial: $BODY" +grep -q 'ans_identity_unauthorized' <<<"$BODY" || fail "unapproved sandbox: unexpected reason: $BODY" +[[ "$(wc -l <"$LOG_DIR/callee.log")" -eq "$CALLEE_LINES_BEFORE" ]] || fail "the callee saw the denied request" +check "unapproved sandbox is denied (ans_identity_unauthorized) and the callee is not reached" + +# 4. Middleware unavailable: fail_closed blocks the request. +stop_middleware +CALLEE_LINES_BEFORE="$(wc -l <"$LOG_DIR/callee.log")" +OUT="$(sandbox_curl "$SANDBOX_NAME")" || true +STATUS="$(response_status "$OUT")" +BODY="$(response_body "$OUT")" +[[ "$STATUS" == 403 ]] || fail "middleware down: status $STATUS, body: $BODY" +grep -q 'middleware_failed' <<<"$BODY" || fail "middleware down: not a middleware failure: $BODY" +[[ "$(wc -l <"$LOG_DIR/callee.log")" -eq "$CALLEE_LINES_BEFORE" ]] || fail "the callee saw the request while the middleware was down" +check "request is blocked while the middleware is unavailable (fail_closed)" +start_middleware + +printf 'ALL PASS %d checks against OpenShell %s (%s)\n' "$PASS" "$OPENSHELL_VERSION" "${OPENSHELL_COMMIT:0:7}" + +if [[ $KEEP_RUNNING -eq 1 ]]; then + cat </dev/null && kill -0 "$MIDDLEWARE_PID" 2>/dev/null; do sleep 1; done + fail "a process exited" +fi diff --git a/examples/openshell-smoke/workload/Dockerfile b/examples/openshell-smoke/workload/Dockerfile new file mode 100644 index 0000000..85627d0 --- /dev/null +++ b/examples/openshell-smoke/workload/Dockerfile @@ -0,0 +1,11 @@ +# Workload image for the smoke test: OpenShell's default workload image plus +# curl, which the sandbox policy admits as the only binary allowed to reach the +# callee. Built by smoke.sh with the local container engine and passed to +# `openshell sandbox create --from`. +# Pinned to the multi-arch manifest digest of nvcr.io/nvidia/base/ubuntu:24.04 +# so the image the sandbox runs is the one that was reviewed; bump the digest +# deliberately (docker buildx imagetools inspect :24.04). +FROM nvcr.io/nvidia/base/ubuntu@sha256:d9461f428eea54e553add3a5158a0f245c6e1ea73efc59fff8e98e3d4a38e378 +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl \ + && apt-get clean From 0846f4602dda9c47048ae21c4f3a7373f7109beb Mon Sep 17 00:00:00 2001 From: kperry Date: Thu, 5 Nov 2026 00:11:57 -0600 Subject: [PATCH 2/2] fix(examples): isolate smoke runs per label and finish cleanup Address the five findings from the review of the smoke harness. The gateway's startup reconciliation force-removes every supervisor container in its sandbox_label, and the label was stable across runs, so a second smoke run against the same daemon destroyed the first run's sandboxes. Each run now works under a label of its own, suffixed with its pid, so two runs on one daemon never reach each other's sandboxes and a run that dies before its own cleanup leaves leftovers the next run can attribute: everything under a harness label whose pid no longer runs is removed before the gateway starts, and a label whose pid is alive is left alone. No lock is needed; a lock keyed on the socket path or the temp directory would not have identified the daemon anyway. cleanup runs under set +e with SIGINT ignored. A Docker query that failed inside the EXIT trap used to abort the trap before the host services were stopped and the minted keys removed; now every step runs whatever fails along the way, each one bounded (the delete RPC under a deadline, TERM then KILL for the host processes), and nothing is retained when there is nothing to retain. The driver creates three volumes per sandbox and removes them after the containers in a background task; when the gateway died before its delete RPC ran, cleanup removed only containers and the volumes stayed on the daemon. The run's whole label, volumes included, is now removed. On stock macOS the run_bounded watchdog subshell inherited the stdout pipe of a "$(run_bounded ...)" capture and held it open until its sleep ended, so a request that completed at once still took the whole deadline to return. The watchdog's output is redirected away and its sleep is killed with it. run_bounded also finds Homebrew's gtimeout. Release downloads fail on a stall (under 1 KiB/s for 30 s) and retry, with the whole retry sequence bounded to ten minutes; the proto-drift fetch in CI carries a deadline and no longer reports a fetch failure as drift. A Docker daemon that is down is reported before any work starts. Verified live on Docker (Rancher Desktop, Apple silicon): two runs at once both reach READY and neither sees the other's sandboxes; a dead run's containers and volumes are reclaimed while a foreign label is untouched; --print-config works while runs are up and changes nothing; SIGKILL of one run's gateway leaves the other run working and removes the dead run's label entirely, retaining only logs; Ctrl-C cleans up fully; a clean run passes all five checks and leaves nothing behind. Assisted by Claude Code (Claude Fable 5.1) Co-Authored-By: Claude Fable 5.1 Signed-off-by: kperry --- .github/workflows/ci.yml | 5 +- examples/openshell-smoke/README.md | 9 +- examples/openshell-smoke/smoke.sh | 200 +++++++++++++++++++---------- 3 files changed, 140 insertions(+), 74 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c72678..3ab3b68 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -98,7 +98,8 @@ jobs: run: | source examples/openshell-smoke/openshell-release.env for f in extension gateway_interceptor supervisor_middleware; do - curl -fsSL "https://raw.githubusercontent.com/NVIDIA/OpenShell/$OPENSHELL_COMMIT/proto/$f.proto" \ - | diff -u "third_party/openshell/proto/$f.proto" - \ + curl -fsSL --connect-timeout 15 --max-time 60 -o "$RUNNER_TEMP/$f.proto" \ + "https://raw.githubusercontent.com/NVIDIA/OpenShell/$OPENSHELL_COMMIT/proto/$f.proto" + diff -u "third_party/openshell/proto/$f.proto" "$RUNNER_TEMP/$f.proto" \ || { echo "third_party/openshell/proto/$f.proto differs from OpenShell $OPENSHELL_VERSION ($OPENSHELL_COMMIT)"; exit 1; } done diff --git a/examples/openshell-smoke/README.md b/examples/openshell-smoke/README.md index 6c725a0..4721ac0 100644 --- a/examples/openshell-smoke/README.md +++ b/examples/openshell-smoke/README.md @@ -62,9 +62,12 @@ reported there, not here. The test never touches an existing OpenShell installation: it points `XDG_CONFIG_HOME`, `XDG_STATE_HOME` and `OPENSHELL_LOCAL_TLS_DIR` at its temporary directory, so the gateway's database, TLS bundle and the CLI's gateway registration all live and die with the run. On the -Docker daemon its gateway works under its own `sandbox_label`, `ans-openshell-smoke`, so the -startup reconciliation that removes a gateway's stray supervisor containers cannot reach another -gateway's sandboxes, and leftovers from a crashed run are reclaimed by the next one. +Docker daemon its gateway works under a `sandbox_label` of its own, `ans-openshell-smoke-`, +so the startup reconciliation that removes a gateway's stray supervisor containers cannot reach +another gateway's sandboxes, whether that gateway belongs to an OpenShell install or to a +concurrent smoke run. When a run ends, including by failure, the harness removes every container +and volume left under its label. A run that dies before its own cleanup leaves its label behind; +the next run removes everything under a label whose pid no longer runs. ## Options diff --git a/examples/openshell-smoke/smoke.sh b/examples/openshell-smoke/smoke.sh index 7193e32..82c91d7 100755 --- a/examples/openshell-smoke/smoke.sh +++ b/examples/openshell-smoke/smoke.sh @@ -133,6 +133,8 @@ if [[ -z "$DOCKER_SOCKET" || "$DOCKER_SOCKET" == *://* || ! -S "$DOCKER_SOCKET" echo "FAIL the Docker context does not expose a local Unix socket (got '${DOCKER_SOCKET:-none}')" >&2 exit 1 fi +docker info --format '{{.ID}}' >/dev/null \ + || { echo "FAIL the Docker daemon at $DOCKER_SOCKET is not reachable" >&2; exit 1; } # --------------------------------------------------------------------------- # Working directory, ports, cleanup @@ -140,6 +142,7 @@ fi WORK="$(mktemp -d "${TMPDIR:-/tmp}/ans-openshell-smoke.XXXXXX")" LOG_DIR="$WORK/logs" FIXTURES="$WORK/fixtures" +BIN="$WORK/bin" # Every OpenShell path (config, state, CLI gateway registrations) lives under # WORK so the run never touches a real installation. export XDG_CONFIG_HOME="$WORK/xdg/config" @@ -147,13 +150,15 @@ export XDG_STATE_HOME="$WORK/xdg/state" export XDG_DATA_HOME="$WORK/xdg/data" export OPENSHELL_LOCAL_TLS_DIR="$WORK/gateway-tls" unset OPENSHELL_GATEWAY OPENSHELL_GATEWAY_ENDPOINT OPENSHELL_SANDBOX_POLICY OPENSHELL_COMPUTE_DRIVER OPENSHELL_DRIVERS -mkdir -p "$LOG_DIR" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_DATA_HOME" +mkdir -p "$LOG_DIR" "$BIN" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_DATA_HOME" RUN_ID="ans-smoke-$$-$RANDOM" MIDDLEWARE_NAME="ans-identity-smoke" -# Docker namespace for everything the gateway creates; stable across runs on -# purpose, see write_gateway_config. -DOCKER_SANDBOX_LABEL="ans-openshell-smoke" +# Docker namespace for everything the gateway creates. One per run, so two runs +# on one daemon never reach each other's sandboxes (see write_gateway_config); +# the pid lets reclaim_dead_runs tell a dead run's leftovers from a live run's. +DOCKER_SANDBOX_LABEL_PREFIX="ans-openshell-smoke-" +DOCKER_SANDBOX_LABEL="$DOCKER_SANDBOX_LABEL_PREFIX$$" # The workload image is tagged by its Dockerfile's checksum so repeated runs # reuse the build and a Dockerfile change forces a new one. WORKLOAD_IMAGE="ans-openshell-smoke-workload:$(cksum "$EXAMPLE_DIR/workload/Dockerfile" | awk '{ print $1 }')" @@ -170,49 +175,141 @@ declare -a CLI=() sandbox_containers() { local name for name in ${CREATED_SANDBOXES[@]+"${CREATED_SANDBOXES[@]}"}; do - docker ps -aq --filter "label=openshell.ai/sandbox-namespace=$DOCKER_SANDBOX_LABEL" \ + run_bounded 30 docker ps -aq --filter "label=openshell.ai/sandbox-namespace=$DOCKER_SANDBOX_LABEL" \ --filter "label=openshell.ai/sandbox-name=$name" 2>/dev/null done | tr '\n' ' ' } +# capture_container_logs saves the stdout and stderr of every container the +# driver created for this run's sandboxes. The supervisor's log is the only +# place a middleware_failed verdict explains itself (TLS handshake, connect +# timeout, JWT audience), and cleanup destroys those containers. +capture_container_logs() { + local id name + for id in $(sandbox_containers); do + name="$(run_bounded 10 docker inspect --format '{{.Name}}' "$id" 2>/dev/null | sed 's|^/||' || true)" + run_bounded 30 docker logs "$id" >"$LOG_DIR/container-${name:-$id}.log" 2>&1 || true + done +} + +# label_resources prints "KIND ID LABEL" for every container and volume the +# Docker driver created under any sandbox namespace, running or exited. Like +# every Docker call on the teardown path it is bounded, so a wedged daemon +# cannot keep cleanup from reaching the key removal. +label_resources() { + run_bounded 30 docker ps -a --filter label=openshell.ai/sandbox-namespace \ + --format 'container {{.ID}} {{.Label "openshell.ai/sandbox-namespace"}}' + run_bounded 30 docker volume ls --filter label=openshell.ai/sandbox-namespace \ + --format 'volume {{.Name}} {{.Label "openshell.ai/sandbox-namespace"}}' +} + +# remove_resources force-removes the "KIND ID LABEL" lines it reads on stdin. +remove_resources() { + local kind id _label + while read -r kind id _label; do + run_bounded 30 docker "$kind" rm -f "$id" >>"$LOG_DIR/setup.log" 2>&1 || true + done +} + +# reclaim_dead_runs removes what earlier runs that died before their own +# cleanup left on the daemon: everything under a harness label whose pid no +# longer runs. A label whose pid is alive is a run in progress and is left +# alone; its gateway never sees this run's label either. +reclaim_dead_runs() { + local kind id label pid stale="" + while read -r kind id label; do + [[ "$label" == "$DOCKER_SANDBOX_LABEL_PREFIX"* ]] || continue + pid="${label#"$DOCKER_SANDBOX_LABEL_PREFIX"}" + [[ "$pid" =~ ^[0-9]+$ && "$pid" != "$$" ]] || continue + ps -p "$pid" -o pid= >/dev/null 2>&1 && continue + stale+="$kind $id $label"$'\n' + done < <(label_resources) + [[ -n "$stale" ]] || return 0 + echo "WARN removing what earlier smoke runs left on the daemon:" >&2 + printf '%s' "$stale" | awk '{ print "WARN " $1 " " $2 " (" $3 ")" }' >&2 + printf '%s' "$stale" | remove_resources +} + +# run_bounded SECONDS CMD...: runs CMD with a wall-clock deadline so a stalled +# registry pull or a hung RPC becomes a failure with logs instead of a hang. +# Uses coreutils timeout where present (Linux; gtimeout from Homebrew coreutils) +# and a background watchdog otherwise (stock macOS). The watchdog's output goes +# nowhere: inside "$(run_bounded ...)" it would otherwise hold the capture pipe +# open until its sleep ends, and a command that finished at once would not +# return to the caller before the whole deadline had passed. +run_bounded() { + local seconds="$1" timeout_cmd + shift + for timeout_cmd in timeout gtimeout; do + if command -v "$timeout_cmd" >/dev/null 2>&1; then + "$timeout_cmd" "$seconds" "$@" + return + fi + done + "$@" & + local pid=$! + ( + trap 'kill "$sleeper" 2>/dev/null; exit 0' TERM + sleep "$seconds" & + sleeper=$! + wait "$sleeper" + kill "$pid" 2>/dev/null + ) >/dev/null 2>&1 & + local watchdog=$! + local status=0 + wait "$pid" || status=$? + kill "$watchdog" 2>/dev/null || true + wait "$watchdog" 2>/dev/null || true + return "$status" +} + +# stop_process PID sends TERM, allows ten seconds, then KILLs what is left. +stop_process() { + kill "$1" 2>/dev/null || true + for _ in {1..100}; do + kill -0 "$1" 2>/dev/null || break + sleep 0.1 + done + kill -9 "$1" 2>/dev/null || true + wait "$1" 2>/dev/null || true +} + cleanup() { local status=$? trap - EXIT + # Everything below runs whatever fails along the way, the Docker daemon + # included, and a second Ctrl-C does not cut it short: every step is + # bounded, and the minted keys are removed last. + set +e + trap '' INT # fail already captured the container logs on an assertion failure; this # covers a Ctrl-C or an unexpected exit, before the sandboxes go away. [[ $status -eq 0 ]] || capture_container_logs if [[ ${#CLI[@]} -gt 0 ]]; then for name in ${CREATED_SANDBOXES[@]+"${CREATED_SANDBOXES[@]}"}; do - "${CLI[@]}" sandbox delete "$name" >>"$LOG_DIR/setup.log" 2>&1 || true + run_bounded 60 "${CLI[@]}" sandbox delete "$name" >>"$LOG_DIR/setup.log" 2>&1 done - # The gateway removes a sandbox's containers in a background task after - # the delete RPC returns, and stopping a supervisor can take ten seconds or - # more. Wait for the driver to finish before taking the gateway down, and - # remove anything it did not get to so nothing accumulates on the daemon. - local leftover - for _ in {1..120}; do - leftover="$(sandbox_containers)" - [[ -z "$leftover" ]] && break + # The gateway removes a sandbox's containers, then its volumes, in a + # background task after the delete RPC returns, and stopping a supervisor + # can take ten seconds or more. Give the driver up to a minute before + # taking the gateway down; whatever it did not get to is removed below. + local deadline=$((SECONDS + 60)) + while ((SECONDS < deadline)); do + kill -0 "$GATEWAY_PID" 2>/dev/null || break + [[ -z "$(sandbox_containers)" ]] && break sleep 0.5 done - if [[ -n "$leftover" ]]; then - echo "WARN removing containers the gateway had not finished deleting" >&2 - # shellcheck disable=SC2086 # container ids are whitespace-separated - docker rm -f $leftover >>"$LOG_DIR/setup.log" 2>&1 || true - fi fi for pid in "$GATEWAY_PID" "$MIDDLEWARE_PID" "$CALLEE_PID"; do - if [[ -n "$pid" ]]; then - kill "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true - fi + [[ -z "$pid" ]] || stop_process "$pid" done - if [[ $status -eq 0 ]]; then + label_resources | awk -v label="$DOCKER_SANDBOX_LABEL" '$3 == label' | remove_resources + if [[ $status -eq 0 || -z "$(ls -A "$LOG_DIR" 2>/dev/null)" ]]; then rm -rf "$WORK" else # Keep the logs for diagnosis, never the minted private keys, the gateway # database or the CLI client certificate. - rm -rf "$FIXTURES" "$OPENSHELL_LOCAL_TLS_DIR" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_DATA_HOME" "$BIN" "$WORK"/gateway.db* + rm -rf "$FIXTURES" "$OPENSHELL_LOCAL_TLS_DIR" "$WORK/xdg" "$BIN" "$WORK"/gateway.db* echo "logs retained in $LOG_DIR" >&2 fi exit "$status" @@ -253,18 +350,6 @@ GATEWAY_ENDPOINT="https://127.0.0.1:$GATEWAY_PORT" # and the callee verifies against it (pop trusted host). CALLEE_AUTHORITY="host.openshell.internal:$CALLEE_PORT" -# capture_container_logs saves the stdout and stderr of every container the -# driver created for this run's sandboxes. The supervisor's log is the only -# place a middleware_failed verdict explains itself (TLS handshake, connect -# timeout, JWT audience), and cleanup destroys those containers. -capture_container_logs() { - local id name - for id in $(sandbox_containers); do - name="$(docker inspect --format '{{.Name}}' "$id" 2>/dev/null | sed 's|^/||')" - docker logs "$id" >"$LOG_DIR/container-${name:-$id}.log" 2>&1 || true - done -} - fail() { printf 'FAIL %s\n' "$1" >&2 capture_container_logs @@ -276,28 +361,6 @@ fail() { exit 1 } -# run_bounded SECONDS CMD...: runs CMD with a wall-clock deadline so a stalled -# registry pull or a hung RPC becomes a failure with logs instead of a hang. -# Uses coreutils timeout where present (Linux, Homebrew coreutils) and a -# background watchdog otherwise (stock macOS). -run_bounded() { - local seconds="$1" - shift - if command -v timeout >/dev/null 2>&1; then - timeout "$seconds" "$@" - return - fi - "$@" & - local pid=$! - ( sleep "$seconds" && kill "$pid" 2>/dev/null ) & - local watchdog=$! - local status=0 - wait "$pid" || status=$? - kill "$watchdog" 2>/dev/null || true - wait "$watchdog" 2>/dev/null || true - return "$status" -} - step() { local label="$1" shift @@ -340,15 +403,16 @@ CACHE="${ANS_SMOKE_CACHE:-${XDG_CACHE_HOME:-${HOME}/.cache}/ans-openshell-smoke} mkdir -p "$CACHE" # fetch_asset NAME SHA BINARY: downloads the release tarball once, verifies it -# against the pinned digest, and extracts BINARY into the cache. Everything it -# prints goes to stderr so the callers below can read nothing but the binary -# path from stdout. +# against the pinned digest, and extracts BINARY into the run directory. +# Everything it prints goes to stderr so the callers below can read nothing +# but the binary path from stdout. fetch_asset() { local name="$1" sha="$2" bin="$BIN/$3" local dest="$CACHE/$name.tar.gz" if [[ ! -f "$dest" ]]; then printf 'INFO downloading %s %s\n' "$OPENSHELL_VERSION" "$name" >&2 - curl -fsSL --retry 3 -o "$dest.partial" \ + curl -fsSL --retry 3 --retry-max-time 600 --connect-timeout 15 \ + --speed-limit 1024 --speed-time 30 --max-time 600 -o "$dest.partial" \ "https://github.com/NVIDIA/OpenShell/releases/download/$OPENSHELL_VERSION/$name.tar.gz" mv "$dest.partial" "$dest" fi @@ -363,8 +427,6 @@ fetch_asset() { printf '%s\n' "$bin" } -BIN="$WORK/bin" -mkdir -p "$BIN" CLI_BIN="$(fetch_asset "$CLI_ASSET" "$CLI_SHA" openshell)" GATEWAY_BIN="$(fetch_asset "$GW_ASSET" "$GW_SHA" openshell-gateway)" [[ -x "$CLI_BIN" && -x "$GATEWAY_BIN" ]] || fail "release binaries are not executable: $CLI_BIN $GATEWAY_BIN" @@ -432,8 +494,8 @@ compute_driver = "docker" # gateway, middleware and callee all listen on; host.openshell.internal in the # sandbox resolves to the same address. The sandbox_label scopes the gateway's # startup reconciliation, which removes every supervisor container in its -# label, to this harness: an OpenShell install sharing the daemon keeps its -# sandboxes, and a crashed smoke run's leftovers are reclaimed by the next one. +# label, to this run: an OpenShell install sharing the daemon keeps its +# sandboxes, and so does a concurrent smoke run, which has a label of its own. [openshell.drivers.docker] socket_path = "$DOCKER_SOCKET" grpc_endpoint = "https://$SERVICE_HOST:$GATEWAY_PORT" @@ -473,6 +535,7 @@ render_policy() { "$EXAMPLE_DIR/policy.template.yaml" >"$WORK/policy.yaml" } render_policy +reclaim_dead_runs # --------------------------------------------------------------------------- # Start the callee, the middleware, then the gateway @@ -493,8 +556,7 @@ start_middleware() { } stop_middleware() { - kill "$MIDDLEWARE_PID" 2>/dev/null || true - wait "$MIDDLEWARE_PID" 2>/dev/null || true + stop_process "$MIDDLEWARE_PID" MIDDLEWARE_PID="" for _ in {1..30}; do port_is_free "$MIDDLEWARE_PORT" && return