|
| 1 | +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +//go:build e2e |
| 5 | + |
| 6 | +// Package e2e contains end-to-end tests for the Go SDK, run against a real |
| 7 | +// OpenShell gateway with `mise run e2e:go` (Podman) or |
| 8 | +// `mise run e2e:go:docker` (Docker). |
| 9 | +package e2e |
| 10 | + |
| 11 | +import ( |
| 12 | + "context" |
| 13 | + "fmt" |
| 14 | + "os" |
| 15 | + "path/filepath" |
| 16 | + "strings" |
| 17 | + "testing" |
| 18 | + "time" |
| 19 | + |
| 20 | + "github.com/stretchr/testify/require" |
| 21 | + |
| 22 | + v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1" |
| 23 | + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway" |
| 24 | + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" |
| 25 | +) |
| 26 | + |
| 27 | +var ( |
| 28 | + sharedClient *v1.Client |
| 29 | + gatewayName string |
| 30 | +) |
| 31 | + |
| 32 | +func TestMain(m *testing.M) { |
| 33 | + gatewayName = os.Getenv("OPENSHELL_GATEWAY") |
| 34 | + if gatewayName == "" { |
| 35 | + // No gateway configured; requireClient skips every test individually. |
| 36 | + os.Exit(m.Run()) |
| 37 | + } |
| 38 | + |
| 39 | + cfg, err := gateway.LoadConfig(gatewayName) |
| 40 | + if err != nil { |
| 41 | + fmt.Fprintf(os.Stderr, "e2e: failed to load gateway config: %v\n", err) |
| 42 | + os.Exit(1) |
| 43 | + } |
| 44 | + |
| 45 | + var opts []gateway.ClientOption |
| 46 | + if opt := mtlsClientOption(cfg.Dir); opt != nil { |
| 47 | + opts = append(opts, opt) |
| 48 | + } |
| 49 | + |
| 50 | + client, err := gateway.NewClient(gatewayName, opts...) |
| 51 | + if err != nil { |
| 52 | + fmt.Fprintf(os.Stderr, "e2e: failed to build gateway client: %v\n", err) |
| 53 | + os.Exit(1) |
| 54 | + } |
| 55 | + sharedClient = client |
| 56 | + |
| 57 | + if err := waitForPersistenceReady(sharedClient); err != nil { |
| 58 | + fmt.Fprintf(os.Stderr, "e2e: %v\n", err) |
| 59 | + _ = sharedClient.Close() |
| 60 | + os.Exit(1) |
| 61 | + } |
| 62 | + |
| 63 | + code := m.Run() |
| 64 | + _ = sharedClient.Close() |
| 65 | + os.Exit(code) |
| 66 | +} |
| 67 | + |
| 68 | +// mtlsClientOption inspects <dir>/mtls for an on-disk certificate bundle |
| 69 | +// written by e2e_register_mtls_gateway (see e2e/support/gateway-common.sh) |
| 70 | +// and returns a ClientOption applying it. Returns nil when no bundle is |
| 71 | +// present (e.g. plaintext or OIDC e2e lanes), so callers should skip it. |
| 72 | +func mtlsClientOption(dir string) gateway.ClientOption { |
| 73 | + mtlsDir := filepath.Join(dir, "mtls") |
| 74 | + caPath := filepath.Join(mtlsDir, "ca.crt") |
| 75 | + if _, err := os.Stat(caPath); err != nil { |
| 76 | + return nil |
| 77 | + } |
| 78 | + |
| 79 | + cfg := &types.TLSConfig{CAFile: caPath} |
| 80 | + |
| 81 | + certPath := filepath.Join(mtlsDir, "tls.crt") |
| 82 | + keyPath := filepath.Join(mtlsDir, "tls.key") |
| 83 | + if _, err := os.Stat(certPath); err == nil { |
| 84 | + if _, err := os.Stat(keyPath); err == nil { |
| 85 | + cfg.CertFile = certPath |
| 86 | + cfg.KeyFile = keyPath |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + return gateway.WithTLS(cfg) |
| 91 | +} |
| 92 | + |
| 93 | +// requireClient returns the shared gateway client, skipping the calling test |
| 94 | +// when OPENSHELL_GATEWAY was not set at process startup. |
| 95 | +func requireClient(t *testing.T) *v1.Client { |
| 96 | + t.Helper() |
| 97 | + if gatewayName == "" { |
| 98 | + t.Skip("OPENSHELL_GATEWAY not set") |
| 99 | + } |
| 100 | + return sharedClient |
| 101 | +} |
| 102 | + |
| 103 | +// waitForPersistenceReady polls the gateway until its persistence layer is |
| 104 | +// initialized, tolerating the transient errors observed right after the |
| 105 | +// gateway process starts (transport not yet listening, sqlite migrations |
| 106 | +// not yet applied). |
| 107 | +func waitForPersistenceReady(client *v1.Client) error { |
| 108 | + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) |
| 109 | + defer cancel() |
| 110 | + |
| 111 | + var lastErr error |
| 112 | + for range 60 { |
| 113 | + _, err := client.Sandboxes().ListAll(ctx, "default", v1.ListOptions{PageSize: 1}) |
| 114 | + if err == nil { |
| 115 | + return nil |
| 116 | + } |
| 117 | + lastErr = err |
| 118 | + if v1.IsUnavailable(err) { |
| 119 | + time.Sleep(2 * time.Second) |
| 120 | + continue |
| 121 | + } |
| 122 | + if strings.Contains(err.Error(), "no such table: objects") { |
| 123 | + time.Sleep(1 * time.Second) |
| 124 | + continue |
| 125 | + } |
| 126 | + return fmt.Errorf("unexpected error waiting for persistence: %w", err) |
| 127 | + } |
| 128 | + return fmt.Errorf("openshell-server persistence is not initialized after 60 attempts: %w", lastErr) |
| 129 | +} |
| 130 | + |
| 131 | +// uniqueName returns a process-unique resource name so parallel tests never |
| 132 | +// collide on the same sandbox/workspace/provider name. |
| 133 | +func uniqueName(prefix string) string { |
| 134 | + return fmt.Sprintf("%s-%09d", prefix, time.Now().UnixNano()%1_000_000_000) |
| 135 | +} |
| 136 | + |
| 137 | +func requireSandboxResponse(t *testing.T, sandbox *v1.Sandbox, workspace, name string) { |
| 138 | + t.Helper() |
| 139 | + require.NotNil(t, sandbox) |
| 140 | + require.NotEmpty(t, sandbox.ID) |
| 141 | + require.Equal(t, workspace, sandbox.Workspace) |
| 142 | + require.Equal(t, name, sandbox.Name) |
| 143 | + require.False(t, sandbox.CreatedAt.IsZero()) |
| 144 | + require.NotZero(t, sandbox.ResourceVersion) |
| 145 | +} |
| 146 | + |
| 147 | +func requireReadySandbox(t *testing.T, sandbox *v1.Sandbox, id string) { |
| 148 | + t.Helper() |
| 149 | + require.NotNil(t, sandbox) |
| 150 | + require.Equal(t, id, sandbox.ID) |
| 151 | + require.Equal(t, v1.SandboxReady, sandbox.Status.Phase) |
| 152 | +} |
| 153 | + |
| 154 | +func readEnvVar(ctx context.Context, client *v1.Client, workspace, sandboxName, key string) (string, error) { |
| 155 | + command := []string{"sh", "-c", `if value=$(printenv "$1"); then printf "%s" "$value"; else printf NOT_SET; fi`, "--", key} |
| 156 | + result, err := client.Exec().Run(ctx, workspace, sandboxName, command, v1.ExecOptions{}) |
| 157 | + // A supervisor reconnect can make one reverse relay miss its opening window. |
| 158 | + // Retry only that transport timeout; repeated failures still fail the test. |
| 159 | + if err != nil && ctx.Err() == nil && v1.IsDeadlineExceeded(err) && strings.Contains(err.Error(), "relay open timed out") { |
| 160 | + select { |
| 161 | + case <-ctx.Done(): |
| 162 | + return "", ctx.Err() |
| 163 | + case <-time.After(250 * time.Millisecond): |
| 164 | + } |
| 165 | + result, err = client.Exec().Run(ctx, workspace, sandboxName, command, v1.ExecOptions{}) |
| 166 | + } |
| 167 | + if err != nil { |
| 168 | + return "", err |
| 169 | + } |
| 170 | + if result.ExitCode != 0 { |
| 171 | + return "", fmt.Errorf("exec exited %d: %s", result.ExitCode, string(result.Stderr)) |
| 172 | + } |
| 173 | + if len(result.Stderr) != 0 { |
| 174 | + return "", fmt.Errorf("exec wrote unexpected stderr: %s", string(result.Stderr)) |
| 175 | + } |
| 176 | + return string(result.Stdout), nil |
| 177 | +} |
| 178 | + |
| 179 | +func isPlaceholderForEnvKey(value, key string) bool { |
| 180 | + const prefix = "openshell:resolve:env:" |
| 181 | + suffix, ok := strings.CutPrefix(value, prefix) |
| 182 | + if !ok { |
| 183 | + return false |
| 184 | + } |
| 185 | + if suffix == key { |
| 186 | + return true |
| 187 | + } |
| 188 | + |
| 189 | + discriminator, placeholderKey, ok := strings.Cut(suffix, "_") |
| 190 | + if !ok || placeholderKey != key || len(discriminator) < 2 { |
| 191 | + return false |
| 192 | + } |
| 193 | + |
| 194 | + switch discriminator[0] { |
| 195 | + case 'v': |
| 196 | + for _, char := range discriminator[1:] { |
| 197 | + if char < '0' || char > '9' { |
| 198 | + return false |
| 199 | + } |
| 200 | + } |
| 201 | + return true |
| 202 | + case 's': |
| 203 | + if len(discriminator) != 65 { |
| 204 | + return false |
| 205 | + } |
| 206 | + for _, char := range discriminator[1:] { |
| 207 | + if !((char >= '0' && char <= '9') || (char >= 'a' && char <= 'f')) { |
| 208 | + return false |
| 209 | + } |
| 210 | + } |
| 211 | + return true |
| 212 | + default: |
| 213 | + return false |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +func TestIsPlaceholderForEnvKey(t *testing.T) { |
| 218 | + stableHandle := strings.Repeat("a1", 32) |
| 219 | + tests := []struct { |
| 220 | + name string |
| 221 | + value string |
| 222 | + key string |
| 223 | + want bool |
| 224 | + }{ |
| 225 | + {name: "plain", value: "openshell:resolve:env:API_KEY", key: "API_KEY", want: true}, |
| 226 | + {name: "revisioned", value: "openshell:resolve:env:v12_API_KEY", key: "API_KEY", want: true}, |
| 227 | + {name: "stable handle", value: "openshell:resolve:env:s" + stableHandle + "_API_KEY", key: "API_KEY", want: true}, |
| 228 | + {name: "overlapping key suffix", value: "openshell:resolve:env:v12_LONG_API_KEY", key: "API_KEY", want: false}, |
| 229 | + {name: "revision requires digits", value: "openshell:resolve:env:vnext_API_KEY", key: "API_KEY", want: false}, |
| 230 | + {name: "stable handle requires lowercase hex", value: "openshell:resolve:env:s" + strings.ToUpper(stableHandle) + "_API_KEY", key: "API_KEY", want: false}, |
| 231 | + {name: "stable handle requires 64 characters", value: "openshell:resolve:env:sabc_API_KEY", key: "API_KEY", want: false}, |
| 232 | + {name: "wrong key", value: "openshell:resolve:env:v12_OTHER_KEY", key: "API_KEY", want: false}, |
| 233 | + {name: "raw secret", value: "secret", key: "API_KEY", want: false}, |
| 234 | + } |
| 235 | + |
| 236 | + for _, test := range tests { |
| 237 | + t.Run(test.name, func(t *testing.T) { |
| 238 | + require.Equal(t, test.want, isPlaceholderForEnvKey(test.value, test.key)) |
| 239 | + }) |
| 240 | + } |
| 241 | +} |
| 242 | + |
| 243 | +// pollUntil calls fetch until the predicate is satisfied, the local polling |
| 244 | +// timeout expires, or ctx is done, whichever happens first. |
| 245 | +func pollUntil[T any](t *testing.T, ctx context.Context, fetch func() T, predicate func(T) bool) T { |
| 246 | + t.Helper() |
| 247 | + deadline := time.NewTimer(35 * time.Second) |
| 248 | + defer deadline.Stop() |
| 249 | + ticker := time.NewTicker(time.Second) |
| 250 | + defer ticker.Stop() |
| 251 | + |
| 252 | + for { |
| 253 | + value := fetch() |
| 254 | + if predicate(value) { |
| 255 | + return value |
| 256 | + } |
| 257 | + select { |
| 258 | + case <-ctx.Done(): |
| 259 | + t.Fatalf("context done while polling; last observed %v: %v", value, ctx.Err()) |
| 260 | + case <-deadline.C: |
| 261 | + t.Fatalf("timed out waiting for expected value, last observed %v", value) |
| 262 | + case <-ticker.C: |
| 263 | + } |
| 264 | + } |
| 265 | +} |
| 266 | + |
| 267 | +// defaultPolicy returns a baseline sandbox policy sufficient for exec-based tests. |
| 268 | +func defaultPolicy() *v1.SandboxPolicy { |
| 269 | + return &v1.SandboxPolicy{ |
| 270 | + Version: 1, |
| 271 | + Filesystem: &v1.FilesystemPolicy{ |
| 272 | + IncludeWorkdir: true, |
| 273 | + ReadOnly: []string{"/usr", "/lib", "/lib64", "/proc", "/etc", "/app", "/dev/urandom"}, |
| 274 | + ReadWrite: []string{"/sandbox", "/tmp", "/dev/null"}, |
| 275 | + }, |
| 276 | + Landlock: &v1.LandlockPolicy{Compatibility: "best_effort"}, |
| 277 | + Process: &v1.ProcessPolicy{RunAsUser: "10001", RunAsGroup: "10001"}, |
| 278 | + } |
| 279 | +} |
0 commit comments