From 7ccb82247ba73effff3fd2077a1a4b8a7e0ba512 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 15:05:08 +0100 Subject: [PATCH 01/13] test(aws): cover SSO credential resolution and the expired-session hint Nobody had run holodeck with an AWS SSO profile, so these tests prove the SDK default chain resolves both legacy and sso-session profiles, and pin the exact hint users should see when the SSO session is expired or was never started. The real-SDK cases drive an SSM call through config.LoadDefaultConfig under a fake HOME and token cache; credential resolution fails locally before any request is signed. The provider test guards New against a future change that replaces the default chain, without calling Retrieve, so New stays lazy for holodeck list. SSOHint is a pass-through stub here; the hint cases are expected to fail. go.mod moves aws-sdk-go-v2/credentials to a direct requirement because the tests import ssocreds. Signed-off-by: Carlos Eduardo Arango Gutierrez --- go.mod | 2 +- internal/aws/sso.go | 21 +++ internal/aws/sso_test.go | 256 +++++++++++++++++++++++++++++++++++ pkg/provider/aws/sso_test.go | 125 +++++++++++++++++ 4 files changed, 403 insertions(+), 1 deletion(-) create mode 100644 internal/aws/sso.go create mode 100644 internal/aws/sso_test.go create mode 100644 pkg/provider/aws/sso_test.go diff --git a/go.mod b/go.mod index 51e9bbdb9..1f8430631 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.26.0 require ( github.com/aws/aws-sdk-go-v2 v1.47.5 github.com/aws/aws-sdk-go-v2/config v1.33.13 + github.com/aws/aws-sdk-go-v2/credentials v1.20.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0 github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.57.0 github.com/aws/aws-sdk-go-v2/service/ssm v1.81.2 @@ -23,7 +24,6 @@ require ( require ( github.com/Masterminds/semver/v3 v3.4.0 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.20.13 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect diff --git a/internal/aws/sso.go b/internal/aws/sso.go new file mode 100644 index 000000000..da480a621 --- /dev/null +++ b/internal/aws/sso.go @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws + +// SSOHint adds an "aws sso login" hint to errors caused by an expired or +// missing AWS SSO session. +func SSOHint(err error) error { return err } diff --git a/internal/aws/sso_test.go b/internal/aws/sso_test.go new file mode 100644 index 000000000..1f5b4c4c7 --- /dev/null +++ b/internal/aws/sso_test.go @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws_test + +import ( + "context" + "crypto/sha1" //nolint:gosec // the SDK names SSO token cache files by SHA-1 + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" + "github.com/aws/aws-sdk-go-v2/service/ssm" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + internalaws "github.com/NVIDIA/holodeck/internal/aws" +) + +const ( + testProfile = "holodeck-sso-test" + defaultProfile = "holodeck-sso-default" + testStartURL = "https://holodeck-sso-test.awsapps.com/start" + testSession = "s" +) + +// isolateAWSEnv points every SDK input at a fresh temp HOME so no test can +// read the real machine's AWS config, credentials or SSO token cache. It +// returns the temp HOME. +func isolateAWSEnv(t *testing.T) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("AWS_CONFIG_FILE", filepath.Join(home, ".aws", "config")) + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(home, ".aws", "credentials")) + for _, k := range []string{ + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", + "AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_ROLE_ARN", + "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_REGION", "AWS_DEFAULT_REGION", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", + } { + t.Setenv(k, "") + } + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") + // Belt and braces: if the SDK ever tried to reach a service here, it + // would hit a closed local port instead of AWS. + t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") + require.NoError(t, os.MkdirAll(filepath.Join(home, ".aws", "sso", "cache"), 0o700)) + return home +} + +func writeFile(t *testing.T, path, content string) { + t.Helper() + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) +} + +// cachePath mirrors ssocreds.StandardCachedTokenFilepath: the cache file is +// the lower-case hex SHA-1 of the key, under ~/.aws/sso/cache. +func cachePath(home, key string) string { + sum := sha1.Sum([]byte(key)) //nolint:gosec // matches the SDK naming scheme + return filepath.Join(home, ".aws", "sso", "cache", hex.EncodeToString(sum[:])+".json") +} + +func profileHint(p string) string { + return "AWS SSO session for profile \"" + p + "\" is expired or missing; " + + "run \"aws sso login --profile " + p + "\" and retry: " +} + +const noProfileHint = "AWS SSO session is expired or missing; run \"aws sso login\" and retry: " + +func TestSSOHint(t *testing.T) { + ssoErr := fmt.Errorf("outer: %w", fmt.Errorf("inner: %w", &ssocreds.InvalidTokenError{})) + sessionErr := fmt.Errorf("get identity: %w", fmt.Errorf( + "refresh cached SSO token failed, %w", + errors.New("cached SSO token is expired, or not present, and cannot be refreshed"))) + boom := errors.New("boom") + + tests := []struct { + name string + profile string + defProfile string + in error + wantMsg string + wantSame bool + wantTokenAs bool + }{ + { + name: "plain error is returned unchanged", + profile: testProfile, + in: boom, + wantMsg: "boom", + wantSame: true, + }, + { + name: "typed SSO error with AWS_PROFILE names the profile", + profile: testProfile, + in: ssoErr, + wantMsg: profileHint(testProfile) + "outer: inner: the SSO session has expired or is invalid", + wantTokenAs: true, + }, + { + name: "typed SSO error without a profile gives the generic hint", + in: ssoErr, + wantMsg: noProfileHint + "outer: inner: the SSO session has expired or is invalid", + wantTokenAs: true, + }, + { + name: "typed SSO error falls back to AWS_DEFAULT_PROFILE", + defProfile: defaultProfile, + in: ssoErr, + wantMsg: profileHint(defaultProfile) + "outer: inner: the SSO session has expired or is invalid", + wantTokenAs: true, + }, + { + name: "AWS_PROFILE wins over AWS_DEFAULT_PROFILE", + profile: testProfile, defProfile: defaultProfile, + in: ssoErr, + wantMsg: profileHint(testProfile) + "outer: inner: the SSO session has expired or is invalid", + wantTokenAs: true, + }, + { + name: "untyped sso-session token error names the profile", + profile: testProfile, + in: sessionErr, + wantMsg: profileHint(testProfile) + "get identity: refresh cached SSO token failed, " + + "cached SSO token is expired, or not present, and cannot be refreshed", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + isolateAWSEnv(t) + t.Setenv("AWS_PROFILE", tc.profile) + t.Setenv("AWS_DEFAULT_PROFILE", tc.defProfile) + + got := internalaws.SSOHint(tc.in) + require.Error(t, got) + assert.Equal(t, tc.wantMsg, got.Error()) + assert.ErrorIs(t, got, tc.in, "the original error must stay in the chain") + if tc.wantSame { + assert.Same(t, tc.in, got) + } + var tokenErr *ssocreds.InvalidTokenError + assert.Equal(t, tc.wantTokenAs, errors.As(got, &tokenErr)) + }) + } + + t.Run("nil stays nil", func(t *testing.T) { + isolateAWSEnv(t) + t.Setenv("AWS_PROFILE", testProfile) + assert.NoError(t, internalaws.SSOHint(nil)) + }) +} + +const legacyConfig = `[profile holodeck-sso-test] +sso_start_url = ` + testStartURL + ` +sso_region = us-east-1 +sso_account_id = 123456789012 +sso_role_name = HolodeckTest +region = us-west-2 +` + +const sessionConfig = `[profile holodeck-sso-test] +sso_session = ` + testSession + ` +sso_account_id = 123456789012 +sso_role_name = HolodeckTest +region = us-west-2 + +[sso-session ` + testSession + `] +sso_start_url = ` + testStartURL + ` +sso_region = us-east-1 +sso_registration_scopes = sso:account:access +` + +const expiredLegacyToken = `{"accessToken":"fake-access-token","expiresAt":"2020-01-01T00:00:00Z",` + + `"region":"us-east-1","startUrl":"` + testStartURL + `"}` + +// No refreshToken, clientId or clientSecret, so the SDK cannot refresh it. +const expiredSessionToken = `{"accessToken":"fake-access-token","expiresAt":"2020-01-01T00:00:00Z",` + + `"region":"us-east-1","startUrl":"` + testStartURL + `"}` + +// TestSSOHintRealSDKChain drives a real SSM call through the SDK's default +// credential chain under fake SSO profiles. Credential resolution fails on +// the local token cache before any request is signed, so nothing leaves the +// machine; AWS_ENDPOINT_URL points at a closed local port as a backstop. +func TestSSOHintRealSDKChain(t *testing.T) { + tests := []struct { + name string + config string + cacheKey string + token string + wantTokenAs bool + }{ + { + name: "legacy profile with an expired cached token", + config: legacyConfig, + cacheKey: testStartURL, + token: expiredLegacyToken, + wantTokenAs: true, + }, + { + name: "sso-session profile with an expired token and no refresh token", + config: sessionConfig, + cacheKey: testSession, + token: expiredSessionToken, + }, + { + name: "sso-session profile with no cached token", + config: sessionConfig, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + home := isolateAWSEnv(t) + writeFile(t, filepath.Join(home, ".aws", "config"), tc.config) + if tc.token != "" { + writeFile(t, cachePath(home, tc.cacheKey), tc.token) + } + t.Setenv("AWS_PROFILE", testProfile) + + ctx := context.Background() + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2")) + require.NoError(t, err) + + _, err = ssm.NewFromConfig(cfg).GetParameter(ctx, &ssm.GetParameterInput{ + Name: aws.String("holodeck-sso-test"), + }) + require.Error(t, err) + t.Logf("SDK error: %v", err) + + got := internalaws.SSOHint(err) + assert.Equal(t, profileHint(testProfile)+err.Error(), got.Error()) + assert.ErrorIs(t, got, err) + var tokenErr *ssocreds.InvalidTokenError + assert.Equal(t, tc.wantTokenAs, errors.As(got, &tokenErr)) + }) + } +} diff --git a/pkg/provider/aws/sso_test.go b/pkg/provider/aws/sso_test.go new file mode 100644 index 000000000..1dced816e --- /dev/null +++ b/pkg/provider/aws/sso_test.go @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws + +import ( + "crypto/sha1" //nolint:gosec // the SDK names SSO token cache files by SHA-1 + "encoding/hex" + "os" + "path/filepath" + "testing" + + awssdk "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/NVIDIA/holodeck/api/holodeck/v1alpha1" + "github.com/NVIDIA/holodeck/internal/logger" +) + +const ssoTestStartURL = "https://holodeck-sso-test.awsapps.com/start" + +// A token that expires far in the future, so it is valid if anything reads it. +const validSSOToken = `{"accessToken":"fake-access-token","expiresAt":"2999-01-01T00:00:00Z",` + + `"region":"us-east-1","startUrl":"` + ssoTestStartURL + `"}` + +// TestNewResolvesSSOProfile guards the default credential chain: with +// AWS_PROFILE naming an SSO profile, New must hand the EC2 client the SDK's +// SSO credentials provider. It never calls Retrieve, so it reads no token +// and makes no network call; New must stay lazy (holodeck list depends on it). +func TestNewResolvesSSOProfile(t *testing.T) { + tests := []struct { + name string + config string + cacheKey string + }{ + { + name: "legacy sso_start_url profile", + config: `[profile holodeck-sso-test] +sso_start_url = ` + ssoTestStartURL + ` +sso_region = us-east-1 +sso_account_id = 123456789012 +sso_role_name = HolodeckTest +`, + cacheKey: ssoTestStartURL, + }, + { + name: "sso-session profile", + config: `[profile holodeck-sso-test] +sso_session = s +sso_account_id = 123456789012 +sso_role_name = HolodeckTest + +[sso-session s] +sso_start_url = ` + ssoTestStartURL + ` +sso_region = us-east-1 +sso_registration_scopes = sso:account:access +`, + cacheKey: "s", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("AWS_CONFIG_FILE", filepath.Join(home, ".aws", "config")) + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(home, ".aws", "credentials")) + for _, k := range []string{ + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", + "AWS_DEFAULT_PROFILE", "AWS_ROLE_ARN", "AWS_WEB_IDENTITY_TOKEN_FILE", + "AWS_REGION", "AWS_DEFAULT_REGION", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", + } { + t.Setenv(k, "") + } + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") + t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") + t.Setenv("AWS_PROFILE", "holodeck-sso-test") + + cacheDir := filepath.Join(home, ".aws", "sso", "cache") + require.NoError(t, os.MkdirAll(cacheDir, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".aws", "config"), []byte(tc.config), 0o600)) + sum := sha1.Sum([]byte(tc.cacheKey)) //nolint:gosec // matches the SDK naming scheme + require.NoError(t, os.WriteFile( + filepath.Join(cacheDir, hex.EncodeToString(sum[:])+".json"), []byte(validSSOToken), 0o600)) + + env := v1alpha1.Environment{ + ObjectMeta: metav1.ObjectMeta{Name: "sso-test"}, + Spec: v1alpha1.EnvironmentSpec{ + Provider: v1alpha1.ProviderAWS, + Instance: v1alpha1.Instance{Region: "us-west-2"}, + }, + } + p, err := New(logger.NewLogger(), env, filepath.Join(home, "cache.yaml")) + require.NoError(t, err) + + client, ok := p.ec2.(*ec2.Client) + require.True(t, ok, "New must build a real *ec2.Client, got %T", p.ec2) + creds, ok := client.Options().Credentials.(*awssdk.CredentialsCache) + require.True(t, ok, "credentials must be a *aws.CredentialsCache, got %T", client.Options().Credentials) + + // ProviderSources is not asserted: the SDK reports the legacy SSO + // sources for sso-session profiles too (hasLegacySSOConfiguration + // is true whenever sso_account_id is set). + assert.True(t, creds.IsCredentialsProvider((*ssocreds.Provider)(nil)), + "EC2 credentials must come from the SSO provider") + }) + } +} From b7d33c100cb6a49d6355d559c5f449fc7d8f5da0 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 15:12:04 +0100 Subject: [PATCH 02/13] feat(cli): tell users to run aws sso login when their SSO session is expired With AWS_PROFILE naming an SSO profile, the SDK default chain already resolves credentials, but an expired or never-started session surfaced as a raw SDK error that does not say how to recover. The single CLI error exit now prefixes it with the exact "aws sso login --profile X" command, naming the profile the SDK used (AWS_PROFILE, else AWS_DEFAULT_PROFILE), and keeps the original error in the chain. Legacy profiles fail with the typed ssocreds.InvalidTokenError, but sso-session profiles, the layout "aws configure sso" writes, fail with untyped token-cache errors. Both are matched; the real-SDK tests pin the SDK text so an upgrade that changes it goes red. Credentials stay lazy: nothing is fetched in aws.New, so holodeck list still works with an expired session. Signed-off-by: Carlos Eduardo Arango Gutierrez --- cmd/cli/main.go | 3 ++- internal/aws/sso.go | 38 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/cmd/cli/main.go b/cmd/cli/main.go index 99e5a5ef4..772c8960f 100644 --- a/cmd/cli/main.go +++ b/cmd/cli/main.go @@ -33,6 +33,7 @@ import ( "github.com/NVIDIA/holodeck/cmd/cli/ssh" "github.com/NVIDIA/holodeck/cmd/cli/status" "github.com/NVIDIA/holodeck/cmd/cli/update" + internalaws "github.com/NVIDIA/holodeck/internal/aws" "github.com/NVIDIA/holodeck/internal/logger" cli "github.com/urfave/cli/v3" @@ -220,7 +221,7 @@ For more information about a command, run: err := c.Run(context.Background(), os.Args) if err != nil { - log.Error(err) + log.Error(internalaws.SSOHint(err)) log.Exit(1) } } diff --git a/internal/aws/sso.go b/internal/aws/sso.go index da480a621..d8570b9a6 100644 --- a/internal/aws/sso.go +++ b/internal/aws/sso.go @@ -16,6 +16,40 @@ package aws +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" +) + +// ssoCacheErrMarker appears in every error the SDK's SSO token provider +// and token-cache loader return (ssocreds/sso_token_provider.go and +// sso_cached_token.go). sso-session profiles fail through those paths with +// plain errors, not *ssocreds.InvalidTokenError, so the type alone misses +// them. TestSSOHintRealSDKChain fails if an SDK upgrade changes this text. +const ssoCacheErrMarker = "cached SSO token" + // SSOHint adds an "aws sso login" hint to errors caused by an expired or -// missing AWS SSO session. -func SSOHint(err error) error { return err } +// missing AWS SSO session. The profile named in the hint is the one the SDK +// used: AWS_PROFILE, else AWS_DEFAULT_PROFILE. Any other error, and nil, is +// returned unchanged. The original error stays in the chain. +func SSOHint(err error) error { + if err == nil { + return nil + } + var ssoErr *ssocreds.InvalidTokenError + if !errors.As(err, &ssoErr) && !strings.Contains(err.Error(), ssoCacheErrMarker) { + return err + } + p := os.Getenv("AWS_PROFILE") + if p == "" { + p = os.Getenv("AWS_DEFAULT_PROFILE") + } + if p != "" { + return fmt.Errorf("AWS SSO session for profile %q is expired or missing; run \"aws sso login --profile %s\" and retry: %w", p, p, err) + } + return fmt.Errorf("AWS SSO session is expired or missing; run \"aws sso login\" and retry: %w", err) +} From 7c28fc682b08aeefe88760c122618f31ffb515f9 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 15:24:09 +0100 Subject: [PATCH 03/13] docs: document AWS SSO profile usage SSO users had no documented path: the prerequisites listed only static keys and the shared credentials file. Show the aws sso login, export AWS_PROFILE, holodeck create flow, and warn that holodeck does not record the profile, so delete, status and update must run with the same AWS_PROFILE (the SSM transport inherits it too). Signed-off-by: Carlos Eduardo Arango Gutierrez --- docs/prerequisites.md | 22 +++++++++++++++++++ pkg/skill/data/skills/using-holodeck/SKILL.md | 5 +++++ 2 files changed, 27 insertions(+) diff --git a/docs/prerequisites.md b/docs/prerequisites.md index 51ab29c39..7a2f30eea 100644 --- a/docs/prerequisites.md +++ b/docs/prerequisites.md @@ -23,6 +23,8 @@ To use the AWS provider, you need: - `AWS_ACCESS_KEY_ID` - `AWS_SECRET_ACCESS_KEY` - `AWS_SESSION_TOKEN` (if using temporary credentials) + - An AWS SSO (IAM Identity Center) profile selected with `AWS_PROFILE`, + see [AWS SSO](#aws-sso-iam-identity-center) 1. Appropriate IAM permissions for: - EC2 instance management @@ -37,6 +39,26 @@ To use the AWS provider, you need: warning and lets AWS choose the zone, and rejects a pinned `availabilityZone` +#### AWS SSO (IAM Identity Center) + +Holodeck uses the AWS SDK default credential chain, so a profile created +with `aws configure sso` works. Log in, select the profile, then run +Holodeck: + +```bash +aws sso login --profile my-sso-profile +export AWS_PROFILE=my-sso-profile +holodeck create -f environment.yaml +``` + +Holodeck does not record the profile. Run `holodeck delete`, `status` and +`update` with the same `AWS_PROFILE` you used for `create`. The SSM +transport (`aws ssm start-session`) uses the same `AWS_PROFILE`. + +When the SSO session has expired or was never started, the command fails +at its first AWS call and prints the `aws sso login --profile ` +command to run before you retry. + ### SSH Provider To use the SSH provider, you need: diff --git a/pkg/skill/data/skills/using-holodeck/SKILL.md b/pkg/skill/data/skills/using-holodeck/SKILL.md index 25206dc6c..49a1290f3 100644 --- a/pkg/skill/data/skills/using-holodeck/SKILL.md +++ b/pkg/skill/data/skills/using-holodeck/SKILL.md @@ -163,6 +163,11 @@ Read commands (`list`, `status`, `describe`) accept - **AWS credentials** — the SDK reads `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` from the environment (or any other SDK-supported source: shared credentials file, IAM role, etc.). + For AWS SSO, run `aws sso login --profile X`, then + `export AWS_PROFILE=X`, then `holodeck create ...`. Holodeck does not + record the profile, so `delete`, `status` and `update` must run with + the same `AWS_PROFILE`; the SSM transport uses it too. An expired SSO + session fails with a message naming the `aws sso login` command. These are **separate** from `auth.keyName` / `auth.privateKey` in env.yaml: those are **literal** values — `auth.keyName` is the EC2 SSH key-pair name registered in the target region, and From 12532866b8481c06d7aaff442199162c21c5f84e Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 16:34:08 +0100 Subject: [PATCH 04/13] test(aws): cover credential precedence between SSO and shared-file keys A stale static key in ~/.aws/credentials shadows an SSO login for Go programs: the SDK resolves shared-file static keys before SSO, while the aws CLI does the opposite. These cases pin the intended precedence: prefer SSO only when the profile has both and nothing explicit (env keys, an explicit AWS_SHARED_CREDENTIALS_FILE) says otherwise, and never warn falsely when the keys live in the config file. LoadConfig is a stub with today's behaviour, so the two prefer-SSO cases fail. It already resolves the shared file paths at call time: the SDK's DefaultSharedConfigFiles are computed at package init from the real HOME, which would let a test read the developer's own ~/.aws. Signed-off-by: Carlos Eduardo Arango Gutierrez --- internal/aws/config.go | 42 +++++++ internal/aws/config_test.go | 228 ++++++++++++++++++++++++++++++++++++ 2 files changed, 270 insertions(+) create mode 100644 internal/aws/config.go create mode 100644 internal/aws/config_test.go diff --git a/internal/aws/config.go b/internal/aws/config.go new file mode 100644 index 000000000..55e538928 --- /dev/null +++ b/internal/aws/config.go @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws + +import ( + "context" + "os" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + + "github.com/NVIDIA/holodeck/internal/logger" +) + +// LoadConfig loads the AWS SDK configuration for region. +func LoadConfig(ctx context.Context, _ *logger.FunLogger, region string) (aws.Config, error) { + configFile := os.Getenv("AWS_CONFIG_FILE") + if configFile == "" { + configFile = config.DefaultSharedConfigFilename() + } + credsFile := os.Getenv("AWS_SHARED_CREDENTIALS_FILE") + if credsFile == "" { + credsFile = config.DefaultSharedCredentialsFilename() + } + return config.LoadDefaultConfig(ctx, config.WithRegion(region), + config.WithSharedConfigFiles([]string{configFile}), + config.WithSharedCredentialsFiles([]string{credsFile})) +} diff --git a/internal/aws/config_test.go b/internal/aws/config_test.go new file mode 100644 index 000000000..0fe595c0d --- /dev/null +++ b/internal/aws/config_test.go @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws_test + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + internalaws "github.com/NVIDIA/holodeck/internal/aws" + "github.com/NVIDIA/holodeck/internal/logger" +) + +// captureStdout returns what fn wrote to os.Stdout. FunLogger.Warning +// prints with fmt.Printf, so this is the only way to observe it (same +// pattern as cmd/cli/list/list_test.go). +func captureStdout(t *testing.T, fn func()) string { + t.Helper() + old := os.Stdout + r, w, err := os.Pipe() + require.NoError(t, err) + os.Stdout = w + defer func() { os.Stdout = old }() + + fn() + + require.NoError(t, w.Close()) + var buf bytes.Buffer + _, err = io.Copy(&buf, r) + require.NoError(t, err) + return buf.String() +} + +func preferSSOWarning(profile string) string { + return "AWS profile \"" + profile + "\" has SSO configured and static keys in the " + + "shared credentials file; using SSO, as the aws CLI does. Remove the static keys " + + "from the credentials file to silence this warning." +} + +const staticKeys = "aws_access_key_id = AKIAHOLODECKFAKE0001\n" + + "aws_secret_access_key = holodeck-fake-secret\n" + +const defaultSSOSessionConfig = `[default] +sso_session = s +sso_account_id = 123456789012 +sso_role_name = HolodeckTest + +[sso-session s] +sso_start_url = ` + testStartURL + ` +sso_region = us-east-1 +sso_registration_scopes = sso:account:access +` + +// TestLoadConfigCredentialPrecedence checks which credentials provider +// LoadConfig hands out. It inspects the provider only and never calls +// Retrieve, so no token is read and nothing leaves the machine. +// +// AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE are UNSET (except where a +// case sets one) so LoadConfig takes the default ~/.aws paths, under the +// temp HOME. +func TestLoadConfigCredentialPrecedence(t *testing.T) { + type want int + const ( + wantSSO want = iota + wantSharedStatic + wantEnvStatic + ) + tests := []struct { + name string + config string // ~/.aws/config, "" = no file + credentials string // ~/.aws/credentials, "" = no file + noAWSDir bool + env map[string]string + explicitCF string // AWS_SHARED_CREDENTIALS_FILE contents, set explicitly + want want + wantSource aws.CredentialSource + wantWarning string // "" = stdout must be empty + }{ + { + name: "P1 SSO in config and static keys in credentials file prefers SSO", + config: defaultSSOSessionConfig, + credentials: "[default]\n" + staticKeys, + want: wantSSO, + wantSource: aws.CredentialSourceProfileSSO, + wantWarning: preferSSOWarning("default"), + }, + { + name: "P2 only static keys in credentials file stays static", + credentials: "[default]\n" + staticKeys, + want: wantSharedStatic, + wantSource: aws.CredentialSourceProfile, + }, + { + name: "P3 only SSO in config resolves SSO without a warning", + config: defaultSSOSessionConfig, + want: wantSSO, + wantSource: aws.CredentialSourceProfileSSO, + }, + { + name: "P4 env static keys win over both files", + config: defaultSSOSessionConfig, + credentials: "[default]\n" + staticKeys, + env: map[string]string{ + "AWS_ACCESS_KEY_ID": "AKIAHOLODECKFAKEENV1", + "AWS_SECRET_ACCESS_KEY": "holodeck-fake-env-secret", + }, + want: wantEnvStatic, + wantSource: aws.CredentialSourceEnvVars, + }, + { + name: "P5 explicit AWS_SHARED_CREDENTIALS_FILE is respected", + config: defaultSSOSessionConfig, + explicitCF: "[default]\n" + staticKeys, + want: wantSharedStatic, + wantSource: aws.CredentialSourceProfile, + }, + { + name: "P6 AWS_PROFILE=dev with SSO and static keys prefers SSO for dev", + config: `[profile dev] +sso_start_url = ` + testStartURL + ` +sso_region = us-east-1 +sso_account_id = 123456789012 +sso_role_name = HolodeckTest +`, + credentials: "[default]\n" + staticKeys + "\n[dev]\n" + staticKeys, + env: map[string]string{"AWS_PROFILE": "dev"}, + want: wantSSO, + wantSource: aws.CredentialSourceSSOLegacy, + wantWarning: preferSSOWarning("dev"), + }, + { + name: "P7 no ~/.aws at all with env static keys", + noAWSDir: true, + env: map[string]string{ + "AWS_ACCESS_KEY_ID": "AKIAHOLODECKFAKEENV1", + "AWS_SECRET_ACCESS_KEY": "holodeck-fake-env-secret", + }, + want: wantEnvStatic, + wantSource: aws.CredentialSourceEnvVars, + }, + { + // The keys live in the config file, so dropping the credentials + // file cannot make SSO win; there must be no false warning. + name: "P8 static keys in the config file next to SSO stay static without a warning", + config: strings.Replace(defaultSSOSessionConfig, "[default]\n", "[default]\n"+staticKeys, 1), + want: wantSharedStatic, + wantSource: aws.CredentialSourceProfile, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + home := isolateAWSEnv(t) + // isolateAWSEnv pins both file env vars; unset them so the + // default-path logic is what runs. t.Setenv restores them. + require.NoError(t, os.Unsetenv("AWS_CONFIG_FILE")) + require.NoError(t, os.Unsetenv("AWS_SHARED_CREDENTIALS_FILE")) + if tc.noAWSDir { + require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) + } + if tc.config != "" { + writeFile(t, filepath.Join(home, ".aws", "config"), tc.config) + } + if tc.credentials != "" { + writeFile(t, filepath.Join(home, ".aws", "credentials"), tc.credentials) + } + if tc.explicitCF != "" { + path := filepath.Join(home, "explicit-credentials") + writeFile(t, path, tc.explicitCF) + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", path) + } + for k, v := range tc.env { + t.Setenv(k, v) + } + + var cfg aws.Config + var err error + out := captureStdout(t, func() { + cfg, err = internalaws.LoadConfig(context.Background(), logger.NewLogger(), "us-west-2") + }) + require.NoError(t, err) + assert.Equal(t, "us-west-2", cfg.Region) + + creds, ok := cfg.Credentials.(*aws.CredentialsCache) + require.True(t, ok, "credentials must be a *aws.CredentialsCache, got %T", cfg.Credentials) + sources := creds.ProviderSources() + isSSO := creds.IsCredentialsProvider((*ssocreds.Provider)(nil)) + + switch tc.want { + case wantSSO: + assert.True(t, isSSO, "want the SSO provider, sources=%v", sources) + assert.NotContains(t, sources, aws.CredentialSourceProfile) + case wantSharedStatic, wantEnvStatic: + assert.False(t, isSSO, "want static credentials, sources=%v", sources) + } + assert.Contains(t, sources, tc.wantSource) + + if tc.wantWarning == "" { + assert.Empty(t, out, "no output expected") + } else { + assert.Equal(t, 1, strings.Count(out, tc.wantWarning), "warning exactly once; stdout=%q", out) + assert.Equal(t, 1, strings.Count(out, "\n"), "exactly one line; stdout=%q", out) + } + }) + } +} From c5b295e67e916ad3fffa9bb20c823271fdd1182c Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 16:47:25 +0100 Subject: [PATCH 05/13] test(aws): guard the LoadConfig wiring and isolate HOME for SDK tests The AWS SDK computes DefaultSharedConfigFiles and DefaultSharedCredentialsFiles once, at package init, from HOME. A t.Setenv("HOME") in a test comes too late for them: any code path that falls back to those defaults reads the developer's real ~/.aws. That happened once while building this change, when the call sites were temporarily reverted to raw LoadDefaultConfig for a RED check. testutil.RunWithIsolatedHome re-runs a test in a child process whose HOME is an empty temp dir from process start, and fails if the child fails or does not run the test. Every test that loads SDK config now runs that way, with its fixtures at the isolated HOME, so even a regressed call site reads the fixture and never the real ~/.aws. The new cases in aws.New and cleanup.New fail while those call sites still use LoadDefaultConfig, so they guard the wiring of the prefer-SSO rule, not only the rule itself. Signed-off-by: Carlos Eduardo Arango Gutierrez --- internal/aws/config_test.go | 4 ++ internal/aws/sso_test.go | 23 ++++++- pkg/cleanup/sso_test.go | 104 +++++++++++++++++++++++++++++ pkg/provider/aws/sso_test.go | 45 +++++++++++-- pkg/testutil/isolated_home.go | 63 +++++++++++++++++ pkg/testutil/isolated_home_test.go | 58 ++++++++++++++++ 6 files changed, 292 insertions(+), 5 deletions(-) create mode 100644 pkg/cleanup/sso_test.go create mode 100644 pkg/testutil/isolated_home.go create mode 100644 pkg/testutil/isolated_home_test.go diff --git a/internal/aws/config_test.go b/internal/aws/config_test.go index 0fe595c0d..61b5d39a7 100644 --- a/internal/aws/config_test.go +++ b/internal/aws/config_test.go @@ -32,6 +32,7 @@ import ( internalaws "github.com/NVIDIA/holodeck/internal/aws" "github.com/NVIDIA/holodeck/internal/logger" + "github.com/NVIDIA/holodeck/pkg/testutil" ) // captureStdout returns what fn wrote to os.Stdout. FunLogger.Warning @@ -82,6 +83,9 @@ sso_registration_scopes = sso:account:access // case sets one) so LoadConfig takes the default ~/.aws paths, under the // temp HOME. func TestLoadConfigCredentialPrecedence(t *testing.T) { + if !testutil.RunWithIsolatedHome(t) { + return + } type want int const ( wantSSO want = iota diff --git a/internal/aws/sso_test.go b/internal/aws/sso_test.go index 1f5b4c4c7..2110fc877 100644 --- a/internal/aws/sso_test.go +++ b/internal/aws/sso_test.go @@ -34,6 +34,7 @@ import ( "github.com/stretchr/testify/require" internalaws "github.com/NVIDIA/holodeck/internal/aws" + "github.com/NVIDIA/holodeck/pkg/testutil" ) const ( @@ -48,7 +49,7 @@ const ( // returns the temp HOME. func isolateAWSEnv(t *testing.T) string { t.Helper() - home := t.TempDir() + home := fixtureHome(t) t.Setenv("HOME", home) t.Setenv("AWS_CONFIG_FILE", filepath.Join(home, ".aws", "config")) t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(home, ".aws", "credentials")) @@ -68,6 +69,23 @@ func isolateAWSEnv(t *testing.T) string { return home } +// fixtureHome returns the HOME to build fixtures in. Inside a +// testutil.RunWithIsolatedHome child it is the process HOME, which is also +// where the SDK's package-init default paths point, so even a code path that +// bypasses the call-time paths reads the fixture and never the real ~/.aws. +// Elsewhere it is a fresh temp dir. +func fixtureHome(t *testing.T) string { + t.Helper() + home := os.Getenv(testutil.IsolatedHomeEnv) + if home == "" { + return t.TempDir() + } + awsDir := filepath.Join(home, ".aws") + require.NoError(t, os.RemoveAll(awsDir)) + t.Cleanup(func() { require.NoError(t, os.RemoveAll(awsDir)) }) + return home +} + func writeFile(t *testing.T, path, content string) { t.Helper() require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) @@ -202,6 +220,9 @@ const expiredSessionToken = `{"accessToken":"fake-access-token","expiresAt":"202 // the local token cache before any request is signed, so nothing leaves the // machine; AWS_ENDPOINT_URL points at a closed local port as a backstop. func TestSSOHintRealSDKChain(t *testing.T) { + if !testutil.RunWithIsolatedHome(t) { + return + } tests := []struct { name string config string diff --git a/pkg/cleanup/sso_test.go b/pkg/cleanup/sso_test.go new file mode 100644 index 000000000..93503a7f7 --- /dev/null +++ b/pkg/cleanup/sso_test.go @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cleanup + +import ( + "os" + "path/filepath" + "testing" + + awssdk "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/NVIDIA/holodeck/internal/logger" + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestNewPrefersSSOOverSharedFileKeys guards the cleanup wiring: with an SSO +// profile in the config file and static keys for it in the default shared +// credentials file, New must load through internalaws.LoadConfig and hand +// the EC2 client the SSO provider. Retrieve is never called. +func TestNewPrefersSSOOverSharedFileKeys(t *testing.T) { + if !testutil.RunWithIsolatedHome(t) { + return + } + tests := []struct { + name string + wantSSO bool + creds string + }{ + { + name: "static keys in the default credentials file do not shadow SSO", + wantSSO: true, + creds: "[holodeck-sso-test]\naws_access_key_id = AKIAHOLODECKFAKE0001\n" + + "aws_secret_access_key = holodeck-fake-secret\n", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // The isolated process HOME: the SDK's package-init default + // paths point here too, so a call site that bypassed + // internalaws.LoadConfig would read this fixture, never the + // real ~/.aws. + home := os.Getenv(testutil.IsolatedHomeEnv) + require.NotEmpty(t, home) + require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) + t.Cleanup(func() { require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) }) + t.Setenv("HOME", home) + for _, k := range []string{ + "AWS_CONFIG_FILE", "AWS_SHARED_CREDENTIALS_FILE", + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", + "AWS_DEFAULT_PROFILE", "AWS_ROLE_ARN", "AWS_WEB_IDENTITY_TOKEN_FILE", + "AWS_REGION", "AWS_DEFAULT_REGION", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", + } { + t.Setenv(k, "") + require.NoError(t, os.Unsetenv(k)) + } + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") + t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") + t.Setenv("AWS_PROFILE", "holodeck-sso-test") + + awsDir := filepath.Join(home, ".aws") + require.NoError(t, os.MkdirAll(awsDir, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(awsDir, "config"), []byte(`[profile holodeck-sso-test] +sso_session = s +sso_account_id = 123456789012 +sso_role_name = HolodeckTest + +[sso-session s] +sso_start_url = https://holodeck-sso-test.awsapps.com/start +sso_region = us-east-1 +sso_registration_scopes = sso:account:access +`), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(awsDir, "credentials"), []byte(tc.creds), 0o600)) + + c, err := New(logger.NewLogger(), "us-west-2") + require.NoError(t, err) + + client, ok := c.ec2.(*ec2.Client) + require.True(t, ok, "New must build a real *ec2.Client, got %T", c.ec2) + creds, ok := client.Options().Credentials.(*awssdk.CredentialsCache) + require.True(t, ok, "credentials must be a *aws.CredentialsCache, got %T", client.Options().Credentials) + assert.Equal(t, tc.wantSSO, creds.IsCredentialsProvider((*ssocreds.Provider)(nil)), + "sources=%v", creds.ProviderSources()) + }) + } +} diff --git a/pkg/provider/aws/sso_test.go b/pkg/provider/aws/sso_test.go index 1dced816e..8267e5d6e 100644 --- a/pkg/provider/aws/sso_test.go +++ b/pkg/provider/aws/sso_test.go @@ -32,6 +32,7 @@ import ( "github.com/NVIDIA/holodeck/api/holodeck/v1alpha1" "github.com/NVIDIA/holodeck/internal/logger" + "github.com/NVIDIA/holodeck/pkg/testutil" ) const ssoTestStartURL = "https://holodeck-sso-test.awsapps.com/start" @@ -45,10 +46,14 @@ const validSSOToken = `{"accessToken":"fake-access-token","expiresAt":"2999-01-0 // SSO credentials provider. It never calls Retrieve, so it reads no token // and makes no network call; New must stay lazy (holodeck list depends on it). func TestNewResolvesSSOProfile(t *testing.T) { + if !testutil.RunWithIsolatedHome(t) { + return + } tests := []struct { - name string - config string - cacheKey string + name string + config string + cacheKey string + credentials string // non-empty: written to the DEFAULT ~/.aws/credentials }{ { name: "legacy sso_start_url profile", @@ -74,10 +79,36 @@ sso_registration_scopes = sso:account:access `, cacheKey: "s", }, + { + // Carlos's failure: a stale static key in the default shared + // credentials file shadowed the SSO login. New must go through + // internalaws.LoadConfig, which prefers SSO here. + name: "sso-session profile shadowed by static keys in the default credentials file", + config: `[profile holodeck-sso-test] +sso_session = s +sso_account_id = 123456789012 +sso_role_name = HolodeckTest + +[sso-session s] +sso_start_url = ` + ssoTestStartURL + ` +sso_region = us-east-1 +sso_registration_scopes = sso:account:access +`, + cacheKey: "s", + credentials: "[holodeck-sso-test]\naws_access_key_id = AKIAHOLODECKFAKE0001\n" + + "aws_secret_access_key = holodeck-fake-secret\n", + }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - home := t.TempDir() + // The isolated process HOME: the SDK's package-init default + // paths point here too, so a call site that bypassed + // internalaws.LoadConfig would read this fixture, never the + // real ~/.aws. + home := os.Getenv(testutil.IsolatedHomeEnv) + require.NotEmpty(t, home) + require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) + t.Cleanup(func() { require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) }) t.Setenv("HOME", home) t.Setenv("AWS_CONFIG_FILE", filepath.Join(home, ".aws", "config")) t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(home, ".aws", "credentials")) @@ -99,6 +130,12 @@ sso_registration_scopes = sso:account:access sum := sha1.Sum([]byte(tc.cacheKey)) //nolint:gosec // matches the SDK naming scheme require.NoError(t, os.WriteFile( filepath.Join(cacheDir, hex.EncodeToString(sum[:])+".json"), []byte(validSSOToken), 0o600)) + if tc.credentials != "" { + require.NoError(t, os.WriteFile(filepath.Join(home, ".aws", "credentials"), []byte(tc.credentials), 0o600)) + // Use the default credentials path under the temp HOME, as a + // user without AWS_SHARED_CREDENTIALS_FILE would. + require.NoError(t, os.Unsetenv("AWS_SHARED_CREDENTIALS_FILE")) + } env := v1alpha1.Environment{ ObjectMeta: metav1.ObjectMeta{Name: "sso-test"}, diff --git a/pkg/testutil/isolated_home.go b/pkg/testutil/isolated_home.go new file mode 100644 index 000000000..c22d429a4 --- /dev/null +++ b/pkg/testutil/isolated_home.go @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package testutil + +import ( + "os" + "os/exec" + "regexp" + "strings" + "testing" +) + +// IsolatedHomeEnv is set to the isolated HOME in the child process. +const IsolatedHomeEnv = "HOLODECK_TEST_ISOLATED_HOME" + +// RunWithIsolatedHome re-runs the calling top-level test in a child test +// process whose HOME is a new, empty directory from process start. +// +// The AWS SDK computes config.DefaultSharedConfigFiles and +// DefaultSharedCredentialsFiles once, at package init, from HOME. A +// t.Setenv("HOME", ...) inside a test comes too late for them, so any code +// path that falls back to those defaults would read the developer's real +// ~/.aws. In the child, those defaults point into the empty isolated HOME. +// +// It returns true in the child, where the caller runs the test body, and +// false in the parent, after failing t if the child failed or did not run +// the test. Call it first, from a top-level test (not a subtest). +func RunWithIsolatedHome(t *testing.T) bool { + t.Helper() + if os.Getenv(IsolatedHomeEnv) != "" { + return true + } + + home := t.TempDir() + //nolint:gosec // re-executes this test binary with a fixed, anchored -test.run + cmd := exec.Command(os.Args[0], + "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1", "-test.v") + // exec uses the last value of a duplicated key, so these override HOME. + cmd.Env = append(os.Environ(), "HOME="+home, IsolatedHomeEnv+"="+home) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("isolated-HOME run of %s failed: %v\n%s", t.Name(), err, out) + } + if !strings.Contains(string(out), "--- PASS: "+t.Name()+" ") { + t.Fatalf("isolated-HOME run did not run %s:\n%s", t.Name(), out) + } + t.Logf("isolated-HOME run (HOME=%s):\n%s", home, out) + return false +} diff --git a/pkg/testutil/isolated_home_test.go b/pkg/testutil/isolated_home_test.go new file mode 100644 index 000000000..4dcf3fdb5 --- /dev/null +++ b/pkg/testutil/isolated_home_test.go @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package testutil_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestRunWithIsolatedHome checks the property the helper exists for: in the +// child, the AWS SDK's package-init default paths (computed from HOME before +// any test code runs) point into the isolated HOME, never the real one. It +// only reads the path variables; it opens no file. +func TestRunWithIsolatedHome(t *testing.T) { + if !testutil.RunWithIsolatedHome(t) { + return + } + home := os.Getenv(testutil.IsolatedHomeEnv) + require.NotEmpty(t, home, "child must see %s", testutil.IsolatedHomeEnv) + + tests := []struct { + name string + got string + want string + }{ + {"HOME is the isolated dir", os.Getenv("HOME"), home}, + {"SDK default config file is under the isolated HOME", + config.DefaultSharedConfigFiles[0], filepath.Join(home, ".aws", "config")}, + {"SDK default credentials file is under the isolated HOME", + config.DefaultSharedCredentialsFiles[0], filepath.Join(home, ".aws", "credentials")}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, tc.got) + }) + } +} From 81ba03037fcb1b7e4d1f7ac5403c510e0733ed84 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 16:58:10 +0100 Subject: [PATCH 06/13] test(aws): share the isolated-HOME fixture reset in testutil gosec's taint analysis flags every file path built from the isolated-HOME environment variable. testutil.IsolatedHome now owns that lookup and the per-test reset of ~/.aws, so the path sink lives in one reviewed place and the fixture setup is not repeated in three packages. The fake env credentials in the precedence table get a G101 annotation. Signed-off-by: Carlos Eduardo Arango Gutierrez --- internal/aws/config_test.go | 4 ++-- internal/aws/sso_test.go | 8 ++------ pkg/cleanup/sso_test.go | 5 +---- pkg/provider/aws/sso_test.go | 5 +---- pkg/testutil/isolated_home.go | 24 ++++++++++++++++++++++++ pkg/testutil/isolated_home_test.go | 13 +++++++++++++ 6 files changed, 43 insertions(+), 16 deletions(-) diff --git a/internal/aws/config_test.go b/internal/aws/config_test.go index 61b5d39a7..e3db7c8fd 100644 --- a/internal/aws/config_test.go +++ b/internal/aws/config_test.go @@ -127,7 +127,7 @@ func TestLoadConfigCredentialPrecedence(t *testing.T) { name: "P4 env static keys win over both files", config: defaultSSOSessionConfig, credentials: "[default]\n" + staticKeys, - env: map[string]string{ + env: map[string]string{ //nolint:gosec // G101: fake credentials, never sent anywhere "AWS_ACCESS_KEY_ID": "AKIAHOLODECKFAKEENV1", "AWS_SECRET_ACCESS_KEY": "holodeck-fake-env-secret", }, @@ -158,7 +158,7 @@ sso_role_name = HolodeckTest { name: "P7 no ~/.aws at all with env static keys", noAWSDir: true, - env: map[string]string{ + env: map[string]string{ //nolint:gosec // G101: fake credentials, never sent anywhere "AWS_ACCESS_KEY_ID": "AKIAHOLODECKFAKEENV1", "AWS_SECRET_ACCESS_KEY": "holodeck-fake-env-secret", }, diff --git a/internal/aws/sso_test.go b/internal/aws/sso_test.go index 2110fc877..e075f35d6 100644 --- a/internal/aws/sso_test.go +++ b/internal/aws/sso_test.go @@ -76,14 +76,10 @@ func isolateAWSEnv(t *testing.T) string { // Elsewhere it is a fresh temp dir. func fixtureHome(t *testing.T) string { t.Helper() - home := os.Getenv(testutil.IsolatedHomeEnv) - if home == "" { + if os.Getenv(testutil.IsolatedHomeEnv) == "" { return t.TempDir() } - awsDir := filepath.Join(home, ".aws") - require.NoError(t, os.RemoveAll(awsDir)) - t.Cleanup(func() { require.NoError(t, os.RemoveAll(awsDir)) }) - return home + return testutil.IsolatedHome(t) } func writeFile(t *testing.T, path, content string) { diff --git a/pkg/cleanup/sso_test.go b/pkg/cleanup/sso_test.go index 93503a7f7..06da5632b 100644 --- a/pkg/cleanup/sso_test.go +++ b/pkg/cleanup/sso_test.go @@ -57,10 +57,7 @@ func TestNewPrefersSSOOverSharedFileKeys(t *testing.T) { // paths point here too, so a call site that bypassed // internalaws.LoadConfig would read this fixture, never the // real ~/.aws. - home := os.Getenv(testutil.IsolatedHomeEnv) - require.NotEmpty(t, home) - require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) - t.Cleanup(func() { require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) }) + home := testutil.IsolatedHome(t) t.Setenv("HOME", home) for _, k := range []string{ "AWS_CONFIG_FILE", "AWS_SHARED_CREDENTIALS_FILE", diff --git a/pkg/provider/aws/sso_test.go b/pkg/provider/aws/sso_test.go index 8267e5d6e..f2f30a57f 100644 --- a/pkg/provider/aws/sso_test.go +++ b/pkg/provider/aws/sso_test.go @@ -105,10 +105,7 @@ sso_registration_scopes = sso:account:access // paths point here too, so a call site that bypassed // internalaws.LoadConfig would read this fixture, never the // real ~/.aws. - home := os.Getenv(testutil.IsolatedHomeEnv) - require.NotEmpty(t, home) - require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) - t.Cleanup(func() { require.NoError(t, os.RemoveAll(filepath.Join(home, ".aws"))) }) + home := testutil.IsolatedHome(t) t.Setenv("HOME", home) t.Setenv("AWS_CONFIG_FILE", filepath.Join(home, ".aws", "config")) t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(home, ".aws", "credentials")) diff --git a/pkg/testutil/isolated_home.go b/pkg/testutil/isolated_home.go index c22d429a4..4e3795496 100644 --- a/pkg/testutil/isolated_home.go +++ b/pkg/testutil/isolated_home.go @@ -19,6 +19,7 @@ package testutil import ( "os" "os/exec" + "path/filepath" "regexp" "strings" "testing" @@ -61,3 +62,26 @@ func RunWithIsolatedHome(t *testing.T) bool { t.Logf("isolated-HOME run (HOME=%s):\n%s", home, out) return false } + +// IsolatedHome returns the HOME of a RunWithIsolatedHome child, after +// removing its .aws directory; it removes it again when t ends, so each +// (sub)test starts from an empty HOME. Fixtures written here are what the +// SDK's package-init default paths point at, too. It fails t outside a +// child. +func IsolatedHome(t *testing.T) string { + t.Helper() + home := os.Getenv(IsolatedHomeEnv) + if home == "" { + t.Fatalf("IsolatedHome called outside a RunWithIsolatedHome child") + } + awsDir := filepath.Join(home, ".aws") + reset := func() { + //nolint:gosec // G703: awsDir is under the temp HOME this package created + if err := os.RemoveAll(awsDir); err != nil { + t.Errorf("reset %s: %v", awsDir, err) + } + } + reset() + t.Cleanup(reset) + return home +} diff --git a/pkg/testutil/isolated_home_test.go b/pkg/testutil/isolated_home_test.go index 4dcf3fdb5..5517e779b 100644 --- a/pkg/testutil/isolated_home_test.go +++ b/pkg/testutil/isolated_home_test.go @@ -55,4 +55,17 @@ func TestRunWithIsolatedHome(t *testing.T) { assert.Equal(t, tc.want, tc.got) }) } + + t.Run("IsolatedHome returns the isolated HOME with .aws removed", func(t *testing.T) { + first := testutil.IsolatedHome(t) + stale := filepath.Join(first, ".aws", "config") + require.NoError(t, os.MkdirAll(filepath.Dir(stale), 0o700)) + require.NoError(t, os.WriteFile(stale, []byte("[default]\n"), 0o600)) + + second := testutil.IsolatedHome(t) + assert.Equal(t, home, first) + assert.Equal(t, home, second) + _, err := os.Stat(filepath.Join(second, ".aws")) + assert.True(t, os.IsNotExist(err), "IsolatedHome must remove a leftover .aws, stat err=%v", err) + }) } From 2b2d5394fec3e071ad2789089925db8fead561ad Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 16:58:11 +0100 Subject: [PATCH 07/13] feat(aws): prefer an SSO login over stale shared-file keys, as the aws CLI does The Go SDK resolves static keys from the shared credentials file before an SSO configuration in the same profile; the aws CLI does the opposite. A stale [default] key in ~/.aws/credentials therefore made holodeck fail with a 401 AuthFailure while "aws sts get-caller-identity" succeeded through SSO. internalaws.LoadConfig keeps the SDK default chain, and when the active profile has both an SSO configuration and static keys, with no static keys in the environment and no explicit AWS_SHARED_CREDENTIALS_FILE, it reloads without the shared credentials file and logs one warning. It uses that result only if the SDK really resolved the SSO provider; any error, or any other outcome, falls back to the unchanged default load with no warning. Credentials stay lazy. The shared file paths are resolved at call time instead of from the SDK's package-init defaults; for a real process they are the same paths, and the profile check and the load read the same files. aws.New, cleanup.New and "holodeck os ami" now load through LoadConfig. Signed-off-by: Carlos Eduardo Arango Gutierrez --- cmd/cli/os/os.go | 7 +--- internal/aws/config.go | 86 ++++++++++++++++++++++++++++++++++++++--- pkg/cleanup/cleanup.go | 4 +- pkg/provider/aws/aws.go | 6 +-- 4 files changed, 84 insertions(+), 19 deletions(-) diff --git a/cmd/cli/os/os.go b/cmd/cli/os/os.go index b933e2a99..ece84987f 100644 --- a/cmd/cli/os/os.go +++ b/cmd/cli/os/os.go @@ -25,9 +25,9 @@ import ( "text/tabwriter" "github.com/NVIDIA/holodeck/internal/ami" + internalaws "github.com/NVIDIA/holodeck/internal/aws" "github.com/NVIDIA/holodeck/internal/logger" - "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ssm" cli "github.com/urfave/cli/v3" @@ -203,10 +203,7 @@ func (c *command) runAMI(ctx context.Context, cmd *cli.Command, region, arch str osID := cmd.Args().First() // Load AWS config - cfg, err := config.LoadDefaultConfig( - ctx, - config.WithRegion(region), - ) + cfg, err := internalaws.LoadConfig(ctx, c.log, region) if err != nil { return fmt.Errorf("failed to load AWS config: %w", err) } diff --git a/internal/aws/config.go b/internal/aws/config.go index 55e538928..40ac6cdb3 100644 --- a/internal/aws/config.go +++ b/internal/aws/config.go @@ -18,25 +18,99 @@ package aws import ( "context" - "os" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" "github.com/NVIDIA/holodeck/internal/logger" ) -// LoadConfig loads the AWS SDK configuration for region. -func LoadConfig(ctx context.Context, _ *logger.FunLogger, region string) (aws.Config, error) { - configFile := os.Getenv("AWS_CONFIG_FILE") +const preferSSOWarning = "AWS profile %q has SSO configured and static keys in the shared " + + "credentials file; using SSO, as the aws CLI does. Remove the static keys from the " + + "credentials file to silence this warning." + +// LoadConfig loads the AWS SDK configuration for region through the SDK +// default chain, with one change: when the active profile has SSO configured +// AND static keys in the default shared credentials file, it uses SSO, as the +// aws CLI does, and logs a warning. The Go SDK otherwise lets those (often +// stale) keys shadow the SSO login. +// +// The SSO preference applies only when nothing explicit overrides it: no +// static keys in the environment, and no AWS_SHARED_CREDENTIALS_FILE. If the +// profile cannot be read, or the reload does not actually resolve to SSO, +// the default chain is used unchanged and nothing is logged. +// +// LoadConfig never retrieves credentials; they stay lazy. +func LoadConfig(ctx context.Context, log *logger.FunLogger, region string) (aws.Config, error) { + env, err := config.NewEnvConfig() + if err != nil { + // LoadDefaultConfig parses the same environment and fails the same way. + return config.LoadDefaultConfig(ctx, config.WithRegion(region)) + } + + // Resolve the shared file paths now, not from the SDK's + // DefaultSharedConfigFiles, which are computed once at package init. + // For a real process both give the same paths; resolving here keeps the + // profile check and the load below on the same files. + configFile := env.SharedConfigFile if configFile == "" { configFile = config.DefaultSharedConfigFilename() } - credsFile := os.Getenv("AWS_SHARED_CREDENTIALS_FILE") - if credsFile == "" { + explicitCredsFile := env.SharedCredentialsFile != "" + credsFile := env.SharedCredentialsFile + if !explicitCredsFile { credsFile = config.DefaultSharedCredentialsFilename() } + + if !explicitCredsFile { + if profile, ok := ssoShadowedByStaticKeys(ctx, env, configFile, credsFile); ok { + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region), + config.WithSharedConfigFiles([]string{configFile}), + // An empty, non-nil list reads no credentials file at all. + config.WithSharedCredentialsFiles([]string{})) + if err == nil && aws.IsCredentialsProvider(cfg.Credentials, (*ssocreds.Provider)(nil)) { + if log != nil { + log.Warning(preferSSOWarning, profile) + } + return cfg, nil + } + } + } + return config.LoadDefaultConfig(ctx, config.WithRegion(region), config.WithSharedConfigFiles([]string{configFile}), config.WithSharedCredentialsFiles([]string{credsFile})) } + +// ssoShadowedByStaticKeys reports whether the active profile has both static +// keys and an SSO configuration, with no static keys in the environment. +// It returns the profile name. Any error reading the profile returns false. +func ssoShadowedByStaticKeys(ctx context.Context, env config.EnvConfig, configFile, credsFile string) (string, bool) { + if env.Credentials.HasKeys() { + return "", false + } + profile := env.SharedConfigProfile // AWS_PROFILE, else AWS_DEFAULT_PROFILE + if profile == "" { + profile = "default" + } + sc, err := config.LoadSharedConfigProfile(ctx, profile, func(o *config.LoadSharedConfigOptions) { + o.ConfigFiles = []string{configFile} + o.CredentialsFiles = []string{credsFile} + }) + if err != nil { + return "", false + } + if !sc.Credentials.HasKeys() || !hasSSOConfiguration(sc) { + return "", false + } + return profile, true +} + +// hasSSOConfiguration mirrors the SDK's unexported +// (*config.SharedConfig).hasSSOConfiguration in config v1.33.13: +// hasSSOTokenProviderConfiguration() || hasLegacySSOConfiguration(). +func hasSSOConfiguration(c config.SharedConfig) bool { + return len(c.SSOSessionName) > 0 || + len(c.SSORegion) > 0 || len(c.SSOAccountID) > 0 || len(c.SSOStartURL) > 0 || len(c.SSORoleName) > 0 +} diff --git a/pkg/cleanup/cleanup.go b/pkg/cleanup/cleanup.go index 034f488de..d39ced781 100644 --- a/pkg/cleanup/cleanup.go +++ b/pkg/cleanup/cleanup.go @@ -27,7 +27,6 @@ import ( "time" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2" @@ -104,8 +103,7 @@ func New(log *logger.FunLogger, region string, if c.ec2 == nil || c.elbv2 == nil { // Use Background here because New is a top-level initializer // without caller-provided context. - cfg, err := config.LoadDefaultConfig(context.Background(), - config.WithRegion(region)) + cfg, err := internalaws.LoadConfig(context.Background(), log, region) if err != nil { return nil, fmt.Errorf("failed to load AWS config: %w", err) } diff --git a/pkg/provider/aws/aws.go b/pkg/provider/aws/aws.go index c5bab77cd..c6c5cd6b0 100644 --- a/pkg/provider/aws/aws.go +++ b/pkg/provider/aws/aws.go @@ -28,7 +28,6 @@ import ( "github.com/NVIDIA/holodeck/pkg/jyaml" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2" @@ -211,10 +210,7 @@ func New(log *logger.FunLogger, env v1alpha1.Environment, cacheFile string, // Create AWS clients if not injected (for testing) if p.ec2 == nil || p.ssm == nil { - cfg, err := config.LoadDefaultConfig( - context.TODO(), - config.WithRegion(region), - ) + cfg, err := internalaws.LoadConfig(context.TODO(), log, region) if err != nil { return nil, err } From 229caf1a3ba71558029178f4bd7167131ed9ff57 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Thu, 26 Nov 2026 19:18:39 +0100 Subject: [PATCH 08/13] test(cli): isolate AWS credentials in tests so they never reach a real account Tests in cmd/cli/{create,dryrun,cleanup} built real AWS clients with whatever credentials the machine had and passed only because those credentials failed. Once an SSO login works, a full `go test` run created a real VPC in a shared account. Make every test binary that can reach AWS hermetic by construction. testutil.RunAWSIsolated (called from TestMain) re-executes the test binary with HOME set to a new temp dir, AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE set to empty files in it, every credential or profile variable the SDK reads removed, IMDS disabled and AWS_ENDPOINT_URL set to a closed local port. A re-exec is required: the SDK computes its default config paths from HOME at package init, before TestMain runs. TestAWSIsolation in each package checks all of that, including the SDK's init-time paths, before touching the SDK, then requires that resolving credentials fails without naming a real file. Census (packages whose test binaries can reach a real AWS client): - dynamic, hermetic coverage of internalaws.LoadConfig (every production config load): internal/aws 94.4% (positive control), pkg/cleanup 94.4%, pkg/provider/aws 94.4%, cmd/cli/{cleanup,create,dryrun} 66.7%, internal/instances 66.7%; SSMTransport.DialContext (aws CLI exec) 0% everywhere; api/holodeck/v1alpha1 n/a (negative control). - static, link graph: test binaries linking internal/aws or pkg/provisioner, which also covers paths only an empty HOME hides (for example the default ~/.cache/holodeck instance cache): the seven above plus pkg/provisioner, pkg/utils, cmd/cli, cmd/cli/{common,delete, describe,list,scp,ssh,status,update} and internal/aws/awsfake. All 19 get the TestMain and the guard. No test needed real AWS; the real-AWS e2e suite under tests/ is unchanged. Signed-off-by: Carlos Eduardo Arango Gutierrez --- cmd/cli/aws_isolation_test.go | 32 +++ cmd/cli/cleanup/aws_isolation_test.go | 32 +++ cmd/cli/common/aws_isolation_test.go | 32 +++ cmd/cli/create/aws_isolation_test.go | 32 +++ cmd/cli/delete/aws_isolation_test.go | 32 +++ cmd/cli/describe/aws_isolation_test.go | 32 +++ cmd/cli/dryrun/aws_isolation_test.go | 32 +++ cmd/cli/list/aws_isolation_test.go | 32 +++ cmd/cli/scp/aws_isolation_test.go | 32 +++ cmd/cli/ssh/aws_isolation_test.go | 32 +++ cmd/cli/status/aws_isolation_test.go | 32 +++ cmd/cli/update/aws_isolation_test.go | 32 +++ internal/aws/aws_isolation_test.go | 32 +++ internal/aws/awsfake/aws_isolation_test.go | 32 +++ internal/instances/aws_isolation_test.go | 32 +++ pkg/cleanup/aws_isolation_test.go | 32 +++ pkg/provider/aws/aws_isolation_test.go | 32 +++ pkg/provisioner/aws_isolation_test.go | 32 +++ pkg/testutil/aws_isolation.go | 219 +++++++++++++++++++++ pkg/testutil/aws_isolation_test.go | 122 ++++++++++++ pkg/utils/aws_isolation_test.go | 32 +++ 21 files changed, 949 insertions(+) create mode 100644 cmd/cli/aws_isolation_test.go create mode 100644 cmd/cli/cleanup/aws_isolation_test.go create mode 100644 cmd/cli/common/aws_isolation_test.go create mode 100644 cmd/cli/create/aws_isolation_test.go create mode 100644 cmd/cli/delete/aws_isolation_test.go create mode 100644 cmd/cli/describe/aws_isolation_test.go create mode 100644 cmd/cli/dryrun/aws_isolation_test.go create mode 100644 cmd/cli/list/aws_isolation_test.go create mode 100644 cmd/cli/scp/aws_isolation_test.go create mode 100644 cmd/cli/ssh/aws_isolation_test.go create mode 100644 cmd/cli/status/aws_isolation_test.go create mode 100644 cmd/cli/update/aws_isolation_test.go create mode 100644 internal/aws/aws_isolation_test.go create mode 100644 internal/aws/awsfake/aws_isolation_test.go create mode 100644 internal/instances/aws_isolation_test.go create mode 100644 pkg/cleanup/aws_isolation_test.go create mode 100644 pkg/provider/aws/aws_isolation_test.go create mode 100644 pkg/provisioner/aws_isolation_test.go create mode 100644 pkg/testutil/aws_isolation.go create mode 100644 pkg/testutil/aws_isolation_test.go create mode 100644 pkg/utils/aws_isolation_test.go diff --git a/cmd/cli/aws_isolation_test.go b/cmd/cli/aws_isolation_test.go new file mode 100644 index 000000000..a95557604 --- /dev/null +++ b/cmd/cli/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/cleanup/aws_isolation_test.go b/cmd/cli/cleanup/aws_isolation_test.go new file mode 100644 index 000000000..e921f3cf2 --- /dev/null +++ b/cmd/cli/cleanup/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cleanup_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/common/aws_isolation_test.go b/cmd/cli/common/aws_isolation_test.go new file mode 100644 index 000000000..ff10998a0 --- /dev/null +++ b/cmd/cli/common/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package common + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/create/aws_isolation_test.go b/cmd/cli/create/aws_isolation_test.go new file mode 100644 index 000000000..dc40bb40a --- /dev/null +++ b/cmd/cli/create/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package create_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/delete/aws_isolation_test.go b/cmd/cli/delete/aws_isolation_test.go new file mode 100644 index 000000000..1be362b48 --- /dev/null +++ b/cmd/cli/delete/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package delete_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/describe/aws_isolation_test.go b/cmd/cli/describe/aws_isolation_test.go new file mode 100644 index 000000000..aa60694de --- /dev/null +++ b/cmd/cli/describe/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package describe + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/dryrun/aws_isolation_test.go b/cmd/cli/dryrun/aws_isolation_test.go new file mode 100644 index 000000000..0b52a0450 --- /dev/null +++ b/cmd/cli/dryrun/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dryrun_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/list/aws_isolation_test.go b/cmd/cli/list/aws_isolation_test.go new file mode 100644 index 000000000..bc8dfd9ec --- /dev/null +++ b/cmd/cli/list/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package list_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/scp/aws_isolation_test.go b/cmd/cli/scp/aws_isolation_test.go new file mode 100644 index 000000000..5eae04a12 --- /dev/null +++ b/cmd/cli/scp/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package scp + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/ssh/aws_isolation_test.go b/cmd/cli/ssh/aws_isolation_test.go new file mode 100644 index 000000000..3d53015ce --- /dev/null +++ b/cmd/cli/ssh/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ssh + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/status/aws_isolation_test.go b/cmd/cli/status/aws_isolation_test.go new file mode 100644 index 000000000..20eea6c8c --- /dev/null +++ b/cmd/cli/status/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package status_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/cmd/cli/update/aws_isolation_test.go b/cmd/cli/update/aws_isolation_test.go new file mode 100644 index 000000000..90143a2b4 --- /dev/null +++ b/cmd/cli/update/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package update + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/internal/aws/aws_isolation_test.go b/internal/aws/aws_isolation_test.go new file mode 100644 index 000000000..d15cbb343 --- /dev/null +++ b/internal/aws/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/internal/aws/awsfake/aws_isolation_test.go b/internal/aws/awsfake/aws_isolation_test.go new file mode 100644 index 000000000..62d15b4b8 --- /dev/null +++ b/internal/aws/awsfake/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package awsfake + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/internal/instances/aws_isolation_test.go b/internal/instances/aws_isolation_test.go new file mode 100644 index 000000000..037a1340f --- /dev/null +++ b/internal/instances/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package instances + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/pkg/cleanup/aws_isolation_test.go b/pkg/cleanup/aws_isolation_test.go new file mode 100644 index 000000000..884cadbc5 --- /dev/null +++ b/pkg/cleanup/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cleanup + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/pkg/provider/aws/aws_isolation_test.go b/pkg/provider/aws/aws_isolation_test.go new file mode 100644 index 000000000..a8a1e2f44 --- /dev/null +++ b/pkg/provider/aws/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/pkg/provisioner/aws_isolation_test.go b/pkg/provisioner/aws_isolation_test.go new file mode 100644 index 000000000..b470b399d --- /dev/null +++ b/pkg/provisioner/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package provisioner + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/pkg/testutil/aws_isolation.go b/pkg/testutil/aws_isolation.go new file mode 100644 index 000000000..ef33d845e --- /dev/null +++ b/pkg/testutil/aws_isolation.go @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package testutil + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/config" +) + +// ParentHomeEnv carries the HOME of the process that called RunAWSIsolated, +// so the guard can check that no error names a file under it. +const ParentHomeEnv = "HOLODECK_TEST_PARENT_HOME" + +// isolatedEndpoint is a closed local port: if anything still tried to send an +// AWS request, it would be refused locally instead of reaching AWS. +const isolatedEndpoint = "http://127.0.0.1:9" + +// AWSCredentialEnv lists the environment variables RunAWSIsolated removes: +// every variable the AWS SDK reads to pick a profile or find credentials. +func AWSCredentialEnv() []string { + return []string{ + "AWS_PROFILE", "AWS_DEFAULT_PROFILE", + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", + "AWS_ROLE_ARN", "AWS_WEB_IDENTITY_TOKEN_FILE", + "AWS_ACCESS_KEY", "AWS_SECRET_KEY", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", + "AWS_CONTAINER_AUTHORIZATION_TOKEN", + } +} + +// RunAWSIsolated runs the package's tests in a child test process that cannot +// reach real AWS credentials. Use it from TestMain: +// +// func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } +// +// The child starts with HOME set to a new temp dir, AWS_CONFIG_FILE and +// AWS_SHARED_CREDENTIALS_FILE set to empty files in it, every variable from +// AWSCredentialEnv removed, IMDS disabled, and AWS_ENDPOINT_URL set to a +// closed local port. Because the child is a new process, the AWS SDK's +// package-init default paths (config.DefaultSharedConfigFiles and +// DefaultSharedCredentialsFiles, computed from HOME before TestMain runs) also +// point into the temp HOME. Setting the variables in this process would be +// too late for them. +// +// In the child it just runs the tests. It returns the exit code to pass to +// os.Exit. +func RunAWSIsolated(m *testing.M) int { + if os.Getenv(IsolatedHomeEnv) != "" { + return m.Run() + } + + home, err := os.MkdirTemp("", "holodeck-aws-isolated-*") + if err != nil { + fmt.Fprintf(os.Stderr, "testutil.RunAWSIsolated: %v\n", err) + return 1 + } + defer func() { _ = os.RemoveAll(home) }() //nolint:errcheck // best-effort temp cleanup + + // Outside home/.aws, which IsolatedHome resets between tests. + dir := filepath.Join(home, "isolated-aws") + configFile := filepath.Join(dir, "config") + credsFile := filepath.Join(dir, "credentials") + if err := os.MkdirAll(dir, 0o700); err != nil { + fmt.Fprintf(os.Stderr, "testutil.RunAWSIsolated: %v\n", err) + return 1 + } + for _, f := range []string{configFile, credsFile} { + if err := os.WriteFile(f, nil, 0o600); err != nil { + fmt.Fprintf(os.Stderr, "testutil.RunAWSIsolated: %v\n", err) + return 1 + } + } + + set := map[string]string{ + "HOME": home, + IsolatedHomeEnv: home, + ParentHomeEnv: os.Getenv("HOME"), + "AWS_CONFIG_FILE": configFile, + "AWS_SHARED_CREDENTIALS_FILE": credsFile, + "AWS_EC2_METADATA_DISABLED": "true", + "AWS_ENDPOINT_URL": isolatedEndpoint, + } + drop := map[string]bool{} + for _, k := range AWSCredentialEnv() { + drop[k] = true + } + var env []string + for _, kv := range os.Environ() { + k, _, _ := strings.Cut(kv, "=") + if _, overridden := set[k]; !overridden && !drop[k] { + env = append(env, kv) + } + } + for k, v := range set { + env = append(env, k+"="+v) + } + + //nolint:gosec // re-executes this same test binary with its own arguments + cmd := exec.Command(os.Args[0], os.Args[1:]...) + cmd.Env = env + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + err = cmd.Run() + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return exitErr.ExitCode() + } + if err != nil { + fmt.Fprintf(os.Stderr, "testutil.RunAWSIsolated: %v\n", err) + return 1 + } + return 0 +} + +// AWSIsolationProblems lists every way the current process is not isolated +// the way RunAWSIsolated isolates it. An empty result means isolated. It makes +// no AWS SDK call. +func AWSIsolationProblems() []string { + var problems []string + home := os.Getenv("HOME") + marker := os.Getenv(IsolatedHomeEnv) + if marker == "" { + problems = append(problems, + IsolatedHomeEnv+" is not set: the process was not started by testutil.RunAWSIsolated") + } + if home != marker { + problems = append(problems, fmt.Sprintf("HOME=%q is not the isolated HOME %q", home, marker)) + } + if !within(os.TempDir(), home) { + problems = append(problems, fmt.Sprintf("HOME=%q is not inside os.TempDir() %q", home, os.TempDir())) + } + for _, k := range []string{"AWS_CONFIG_FILE", "AWS_SHARED_CREDENTIALS_FILE"} { + if v := os.Getenv(k); !within(home, v) || !isEmptyFile(v) { + problems = append(problems, fmt.Sprintf("%s=%q is not an empty file inside HOME", k, v)) + } + } + for _, k := range AWSCredentialEnv() { + if _, ok := os.LookupEnv(k); ok { + problems = append(problems, k+" is set") + } + } + if os.Getenv("AWS_EC2_METADATA_DISABLED") != "true" { + problems = append(problems, `AWS_EC2_METADATA_DISABLED is not "true"`) + } + if os.Getenv("AWS_ENDPOINT_URL") != isolatedEndpoint { + problems = append(problems, fmt.Sprintf("AWS_ENDPOINT_URL is not %q", isolatedEndpoint)) + } + if p := config.DefaultSharedConfigFiles[0]; !within(home, p) { + problems = append(problems, fmt.Sprintf( + "SDK default config file %q (computed at package init) is outside the isolated HOME", p)) + } + if p := config.DefaultSharedCredentialsFiles[0]; !within(home, p) { + problems = append(problems, fmt.Sprintf( + "SDK default credentials file %q (computed at package init) is outside the isolated HOME", p)) + } + return problems +} + +// RequireAWSIsolation fails t unless the process is isolated from real AWS +// credentials. It checks the environment and the SDK's package-init paths +// first, without touching the SDK, and stops there if anything is wrong. +// Only then does it load the default SDK config and require that resolving +// credentials fails without naming a file under the parent's HOME. +func RequireAWSIsolation(t *testing.T) { + t.Helper() + if problems := AWSIsolationProblems(); len(problems) > 0 { + t.Fatalf("AWS isolation is not active (add TestMain calling testutil.RunAWSIsolated):\n- %s", + strings.Join(problems, "\n- ")) + } + ctx := context.Background() + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-east-1")) + if err != nil { + t.Fatalf("load default AWS config in the isolated process: %v", err) + } + _, err = cfg.Credentials.Retrieve(ctx) + if err == nil { + t.Fatalf("AWS credentials resolved inside the isolated process") + } + if parent := os.Getenv(ParentHomeEnv); parent != "" && strings.Contains(err.Error(), parent) { + t.Fatalf("credential error names a file under the real HOME %q: %v", parent, err) + } +} + +// within reports whether path is dir or inside it. An empty dir or path is +// never within. +func within(dir, path string) bool { + if dir == "" || path == "" { + return false + } + rel, err := filepath.Rel(filepath.Clean(dir), filepath.Clean(path)) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +// isEmptyFile reports whether path is an existing, empty regular file. +func isEmptyFile(path string) bool { + fi, err := os.Stat(path) //nolint:gosec // G703: read-only stat of a path the guard is checking + return err == nil && fi.Mode().IsRegular() && fi.Size() == 0 +} diff --git a/pkg/testutil/aws_isolation_test.go b/pkg/testutil/aws_isolation_test.go new file mode 100644 index 000000000..40b08bcdf --- /dev/null +++ b/pkg/testutil/aws_isolation_test.go @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package testutil_test + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// fakeIsolation sets up, inside this (NOT re-executed) test process, every +// isolation property that environment variables can provide. What it cannot +// provide is the SDK's package-init default paths, which were computed from +// the real HOME before this test started. +func fakeIsolation(t *testing.T) string { + t.Helper() + home := t.TempDir() + dir := filepath.Join(home, "isolated-aws") + require.NoError(t, os.MkdirAll(dir, 0o700)) + for _, f := range []string{"config", "credentials"} { + require.NoError(t, os.WriteFile(filepath.Join(dir, f), nil, 0o600)) + } + t.Setenv("HOME", home) + t.Setenv(testutil.IsolatedHomeEnv, home) + t.Setenv("AWS_CONFIG_FILE", filepath.Join(dir, "config")) + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "credentials")) + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") + t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") + for _, k := range testutil.AWSCredentialEnv() { + t.Setenv(k, "") + require.NoError(t, os.Unsetenv(k)) + } + return home +} + +func defaultPathProblems() []string { + return []string{ + fmt.Sprintf("SDK default config file %q (computed at package init) is outside the isolated HOME", + config.DefaultSharedConfigFiles[0]), + fmt.Sprintf("SDK default credentials file %q (computed at package init) is outside the isolated HOME", + config.DefaultSharedCredentialsFiles[0]), + } +} + +func TestAWSIsolationProblems(t *testing.T) { + t.Run("credential variables cover the brief list and the SDK alternates", func(t *testing.T) { + assert.Equal(t, []string{ + "AWS_PROFILE", "AWS_DEFAULT_PROFILE", + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", + "AWS_ROLE_ARN", "AWS_WEB_IDENTITY_TOKEN_FILE", + // The SDK also reads these (config/env_config.go:23-33). + "AWS_ACCESS_KEY", "AWS_SECRET_KEY", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", + "AWS_CONTAINER_AUTHORIZATION_TOKEN", + }, testutil.AWSCredentialEnv()) + }) + + t.Run("env-only isolation still reports the package-init SDK paths", func(t *testing.T) { + fakeIsolation(t) + assert.Equal(t, defaultPathProblems(), testutil.AWSIsolationProblems()) + }) + + t.Run("each credential variable is reported when set", func(t *testing.T) { + for _, k := range testutil.AWSCredentialEnv() { + t.Run(k, func(t *testing.T) { + fakeIsolation(t) + t.Setenv(k, "x") + assert.Equal(t, append([]string{k + " is set"}, defaultPathProblems()...), + testutil.AWSIsolationProblems()) + }) + } + }) + + t.Run("missing marker, foreign HOME, non-empty files, IMDS and endpoint are reported", func(t *testing.T) { + home := fakeIsolation(t) + creds := filepath.Join(home, "isolated-aws", "credentials") + require.NoError(t, os.WriteFile(creds, []byte("[default]\n"), 0o600)) + t.Setenv(testutil.IsolatedHomeEnv, "") + t.Setenv("AWS_CONFIG_FILE", "/etc/hosts") + t.Setenv("AWS_EC2_METADATA_DISABLED", "false") + t.Setenv("AWS_ENDPOINT_URL", "") + + want := []string{ + testutil.IsolatedHomeEnv + " is not set: the process was not started by testutil.RunAWSIsolated", + fmt.Sprintf("HOME=%q is not the isolated HOME %q", home, ""), + fmt.Sprintf("AWS_CONFIG_FILE=%q is not an empty file inside HOME", "/etc/hosts"), + fmt.Sprintf("AWS_SHARED_CREDENTIALS_FILE=%q is not an empty file inside HOME", creds), + `AWS_EC2_METADATA_DISABLED is not "true"`, + `AWS_ENDPOINT_URL is not "http://127.0.0.1:9"`, + } + assert.Equal(t, append(want, defaultPathProblems()...), testutil.AWSIsolationProblems()) + }) + + t.Run("HOME outside os.TempDir is reported", func(t *testing.T) { + fakeIsolation(t) + t.Setenv("HOME", "/") + t.Setenv(testutil.IsolatedHomeEnv, "/") + problems := testutil.AWSIsolationProblems() + assert.Contains(t, problems, fmt.Sprintf("HOME=%q is not inside os.TempDir() %q", "/", os.TempDir())) + }) +} diff --git a/pkg/utils/aws_isolation_test.go b/pkg/utils/aws_isolation_test.go new file mode 100644 index 000000000..3dd5de768 --- /dev/null +++ b/pkg/utils/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package utils + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } From 8bd111bda727b961524914e02af5f0318714c445 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Sat, 28 Nov 2026 13:05:47 +0100 Subject: [PATCH 09/13] test(aws): pin the SSO precedence boundary and the review findings The critic gate on 229caf1a found two blocking and five should-fix problems. These tests encode each one before the fix: - holodeck list must stay machine-readable: LoadConfig called three times warns once, on the logger's stderr writer, never on stdout. - The precedence table now pins EXACT SDK credential sources and the warning count for P1-P8 and the critic's cases. Following the aws CLI order, credential_process (A2) and a container URI (A7) flip to SSO; assume-role in either file (A1, A1b, A1c), web identity (A4, A6), credential_source (A5) and a missing profile (A9) do not. A1b fails today: the SSO reload drops a role_arn that lives in the credentials file. - SSOHint names the profile for a revoked session, the SSO service's typed UnauthorizedException. - The isolated child must route AWS hosts, including the SSO portal that AWS_ENDPOINT_URL does not cover, to a closed proxy, while loopback stays direct; and a stale isolation marker must stop a test binary before any test runs. - holodeck os ami has a wiring test like aws.New and cleanup.New. ResetPreferSSOWarning needs the once variable, declared here unused. go.mod moves service/sso to a direct requirement for the typed error. Signed-off-by: Carlos Eduardo Arango Gutierrez --- cmd/cli/os/ami_wiring_test.go | 80 +++++++++ cmd/cli/os/aws_isolation_test.go | 32 ++++ go.mod | 2 +- internal/aws/config.go | 5 + internal/aws/config_test.go | 265 +++++++++++++++++++++-------- internal/aws/export_test.go | 23 +++ internal/aws/sso_test.go | 21 ++- pkg/cleanup/sso_test.go | 24 ++- pkg/testutil/aws_isolation_test.go | 86 +++++++++- pkg/testutil/main_test.go | 31 ++++ 10 files changed, 484 insertions(+), 85 deletions(-) create mode 100644 cmd/cli/os/ami_wiring_test.go create mode 100644 cmd/cli/os/aws_isolation_test.go create mode 100644 internal/aws/export_test.go create mode 100644 pkg/testutil/main_test.go diff --git a/cmd/cli/os/ami_wiring_test.go b/cmd/cli/os/ami_wiring_test.go new file mode 100644 index 000000000..ae323eaca --- /dev/null +++ b/cmd/cli/os/ami_wiring_test.go @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package os_test + +import ( + "bytes" + "context" + "crypto/sha1" //nolint:gosec // the SDK names SSO token cache files by SHA-1 + "encoding/hex" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + cli "github.com/urfave/cli/v3" + + oscmd "github.com/NVIDIA/holodeck/cmd/cli/os" + "github.com/NVIDIA/holodeck/internal/logger" + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +const amiStartURL = "https://holodeck-sso-test.awsapps.com/start" + +// TestAMIUsesLoadConfig guards the "holodeck os ami" wiring. The fixture is +// Carlos's layout: an SSO profile in the config file, stale static keys for +// it in the default credentials file, and an expired cached SSO token. +// Through internalaws.LoadConfig the command prefers SSO and fails on the +// expired token with the typed SSO error. Raw config.LoadDefaultConfig +// would take the static keys and fail on the closed local endpoint instead. +// No request reaches AWS either way (package TestMain). +func TestAMIUsesLoadConfig(t *testing.T) { + home := testutil.IsolatedHome(t) + t.Setenv("HOME", home) + for _, k := range []string{"AWS_CONFIG_FILE", "AWS_SHARED_CREDENTIALS_FILE"} { + t.Setenv(k, "") + require.NoError(t, os.Unsetenv(k)) + } + cacheDir := filepath.Join(home, ".aws", "sso", "cache") + require.NoError(t, os.MkdirAll(cacheDir, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".aws", "config"), []byte(`[default] +sso_start_url = `+amiStartURL+` +sso_region = us-east-1 +sso_account_id = 123456789012 +sso_role_name = HolodeckTest +`), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".aws", "credentials"), []byte( + "[default]\naws_access_key_id = AKIAHOLODECKFAKE0001\naws_secret_access_key = holodeck-fake-secret\n"), 0o600)) + sum := sha1.Sum([]byte(amiStartURL)) //nolint:gosec // matches the SDK naming scheme + require.NoError(t, os.WriteFile(filepath.Join(cacheDir, hex.EncodeToString(sum[:])+".json"), []byte( + `{"accessToken":"fake-access-token","expiresAt":"2020-01-01T00:00:00Z","region":"us-east-1","startUrl":"`+ + amiStartURL+`"}`), 0o600)) + + log := logger.NewLogger() + var stderr bytes.Buffer + log.Out = &stderr + app := &cli.Command{Commands: []*cli.Command{oscmd.NewCommand(log)}} + err := app.Run(context.Background(), []string{"holodeck", "os", "ami", "ubuntu-22.04", "--region", "us-west-2"}) + + require.Error(t, err) + var tokenErr *ssocreds.InvalidTokenError + assert.True(t, errors.As(err, &tokenErr), + "os ami must load through internalaws.LoadConfig, which prefers the SSO login; err=%v", err) +} diff --git a/cmd/cli/os/aws_isolation_test.go b/cmd/cli/os/aws_isolation_test.go new file mode 100644 index 000000000..f655c0a45 --- /dev/null +++ b/cmd/cli/os/aws_isolation_test.go @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package os_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests in a child process that cannot reach +// real AWS credentials: some of these tests construct real AWS clients, and +// they must never reach a real account, whatever credentials the machine has. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } diff --git a/go.mod b/go.mod index 1f8430631..c5eefc2b0 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0 github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.57.0 github.com/aws/aws-sdk-go-v2/service/ssm v1.81.2 + github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 github.com/mattn/go-isatty v0.0.24 github.com/onsi/ginkgo/v2 v2.33.1 github.com/onsi/gomega v1.44.0 @@ -31,7 +32,6 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect github.com/aws/smithy-go v1.28.7 // indirect diff --git a/internal/aws/config.go b/internal/aws/config.go index 40ac6cdb3..fc735bf95 100644 --- a/internal/aws/config.go +++ b/internal/aws/config.go @@ -18,6 +18,7 @@ package aws import ( "context" + "sync" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" @@ -26,6 +27,10 @@ import ( "github.com/NVIDIA/holodeck/internal/logger" ) +// preferSSOWarnOnce limits the prefer-SSO warning to one per process: +// holodeck list loads a config for every cached AWS instance. +var preferSSOWarnOnce sync.Once + const preferSSOWarning = "AWS profile %q has SSO configured and static keys in the shared " + "credentials file; using SSO, as the aws CLI does. Remove the static keys from the " + "credentials file to silence this warning." diff --git a/internal/aws/config_test.go b/internal/aws/config_test.go index e3db7c8fd..f9f8b52f8 100644 --- a/internal/aws/config_test.go +++ b/internal/aws/config_test.go @@ -32,7 +32,6 @@ import ( internalaws "github.com/NVIDIA/holodeck/internal/aws" "github.com/NVIDIA/holodeck/internal/logger" - "github.com/NVIDIA/holodeck/pkg/testutil" ) // captureStdout returns what fn wrote to os.Stdout. FunLogger.Warning @@ -75,23 +74,72 @@ sso_region = us-east-1 sso_registration_scopes = sso:account:access ` -// TestLoadConfigCredentialPrecedence checks which credentials provider -// LoadConfig hands out. It inspects the provider only and never calls +const roleARN = "role_arn = arn:aws:iam::123456789012:role/Target\n" + +// withDefault inserts extra lines at the top of the [default] section of an +// SSO config. +func withDefault(cfg, lines string) string { + return strings.Replace(cfg, "[default]\n", "[default]\n"+lines, 1) +} + +// loadResult is one LoadConfig call: its results, and what it wrote to +// stdout and to the logger's stderr writer. +type loadResult struct { + cfg aws.Config + err error + stdout string + stderr string +} + +// loadConfig runs LoadConfig with a logger whose Out is a buffer, re-arming +// the once-per-process warning first. +func loadConfig(t *testing.T) loadResult { + t.Helper() + internalaws.ResetPreferSSOWarning() + log := logger.NewLogger() + var stderr bytes.Buffer + log.Out = &stderr + var cfg aws.Config + var err error + stdout := captureStdout(t, func() { + cfg, err = internalaws.LoadConfig(context.Background(), log, "us-west-2") + }) + return loadResult{cfg: cfg, err: err, stdout: stdout, stderr: stderr.String()} +} + +// TestLoadConfigCredentialPrecedence pins which credentials provider +// LoadConfig hands out, as EXACT SDK credential sources, and how many +// warnings it prints. It inspects the provider only and never calls // Retrieve, so no token is read and nothing leaves the machine. // +// The rule matches the aws CLI (botocore) order, as chosen for holodeck: +// SSO wins over static keys from the shared credentials file, including +// when the profile also has credential_process (A2) or a container URI is +// set (A7). It must NOT flip when the profile assumes a role (A1, A1b, +// A1c, A4, A5), when web identity comes from the environment (A6), or when +// the profile does not exist (A9). +// // AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE are UNSET (except where a // case sets one) so LoadConfig takes the default ~/.aws paths, under the -// temp HOME. +// isolated HOME. func TestLoadConfigCredentialPrecedence(t *testing.T) { - if !testutil.RunWithIsolatedHome(t) { - return - } - type want int const ( - wantSSO want = iota - wantSharedStatic - wantEnvStatic + envVars = aws.CredentialSourceEnvVars + envWebID = aws.CredentialSourceEnvVarsSTSWebIDToken + assumeRole = aws.CredentialSourceSTSAssumeRole + profile = aws.CredentialSourceProfile + sourceProfile = aws.CredentialSourceProfileSourceProfile + profileSSO = aws.CredentialSourceProfileSSO + profileSSOLegy = aws.CredentialSourceProfileSSOLegacy + ssoLegacy = aws.CredentialSourceSSOLegacy ) + // sso-session profiles also carry the legacy labels, because + // hasLegacySSOConfiguration is true whenever sso_account_id is set. + ssoSession := []aws.CredentialSource{profileSSOLegy, ssoLegacy, profileSSO} + fakeEnvKeys := map[string]string{ //nolint:gosec // G101: fake credentials, never sent anywhere + "AWS_ACCESS_KEY_ID": "AKIAHOLODECKFAKEENV1", + "AWS_SECRET_ACCESS_KEY": "holodeck-fake-env-secret", + } tests := []struct { name string config string // ~/.aws/config, "" = no file @@ -99,47 +147,39 @@ func TestLoadConfigCredentialPrecedence(t *testing.T) { noAWSDir bool env map[string]string explicitCF string // AWS_SHARED_CREDENTIALS_FILE contents, set explicitly - want want - wantSource aws.CredentialSource - wantWarning string // "" = stdout must be empty + wantSSO bool + wantSources []aws.CredentialSource + wantErr string + warnProfile string // "" = no warning }{ { name: "P1 SSO in config and static keys in credentials file prefers SSO", config: defaultSSOSessionConfig, credentials: "[default]\n" + staticKeys, - want: wantSSO, - wantSource: aws.CredentialSourceProfileSSO, - wantWarning: preferSSOWarning("default"), + wantSSO: true, wantSources: ssoSession, warnProfile: "default", }, { name: "P2 only static keys in credentials file stays static", credentials: "[default]\n" + staticKeys, - want: wantSharedStatic, - wantSource: aws.CredentialSourceProfile, + wantSources: []aws.CredentialSource{profile}, }, { - name: "P3 only SSO in config resolves SSO without a warning", - config: defaultSSOSessionConfig, - want: wantSSO, - wantSource: aws.CredentialSourceProfileSSO, + name: "P3 only SSO in config resolves SSO without a warning", + config: defaultSSOSessionConfig, + wantSSO: true, wantSources: ssoSession, }, { name: "P4 env static keys win over both files", config: defaultSSOSessionConfig, credentials: "[default]\n" + staticKeys, - env: map[string]string{ //nolint:gosec // G101: fake credentials, never sent anywhere - "AWS_ACCESS_KEY_ID": "AKIAHOLODECKFAKEENV1", - "AWS_SECRET_ACCESS_KEY": "holodeck-fake-env-secret", - }, - want: wantEnvStatic, - wantSource: aws.CredentialSourceEnvVars, + env: fakeEnvKeys, + wantSources: []aws.CredentialSource{envVars}, }, { - name: "P5 explicit AWS_SHARED_CREDENTIALS_FILE is respected", - config: defaultSSOSessionConfig, - explicitCF: "[default]\n" + staticKeys, - want: wantSharedStatic, - wantSource: aws.CredentialSourceProfile, + name: "P5 explicit AWS_SHARED_CREDENTIALS_FILE is respected", + config: defaultSSOSessionConfig, + explicitCF: "[default]\n" + staticKeys, + wantSources: []aws.CredentialSource{profile}, }, { name: "P6 AWS_PROFILE=dev with SSO and static keys prefers SSO for dev", @@ -151,27 +191,86 @@ sso_role_name = HolodeckTest `, credentials: "[default]\n" + staticKeys + "\n[dev]\n" + staticKeys, env: map[string]string{"AWS_PROFILE": "dev"}, - want: wantSSO, - wantSource: aws.CredentialSourceSSOLegacy, - wantWarning: preferSSOWarning("dev"), + wantSSO: true, + wantSources: []aws.CredentialSource{profileSSOLegy, ssoLegacy}, + warnProfile: "dev", }, { - name: "P7 no ~/.aws at all with env static keys", - noAWSDir: true, - env: map[string]string{ //nolint:gosec // G101: fake credentials, never sent anywhere - "AWS_ACCESS_KEY_ID": "AKIAHOLODECKFAKEENV1", - "AWS_SECRET_ACCESS_KEY": "holodeck-fake-env-secret", - }, - want: wantEnvStatic, - wantSource: aws.CredentialSourceEnvVars, + name: "P7 no ~/.aws at all with env static keys", + noAWSDir: true, + env: fakeEnvKeys, + wantSources: []aws.CredentialSource{envVars}, }, { // The keys live in the config file, so dropping the credentials // file cannot make SSO win; there must be no false warning. - name: "P8 static keys in the config file next to SSO stay static without a warning", - config: strings.Replace(defaultSSOSessionConfig, "[default]\n", "[default]\n"+staticKeys, 1), - want: wantSharedStatic, - wantSource: aws.CredentialSourceProfile, + name: "P8 static keys in the config file next to SSO stay static without a warning", + config: withDefault(defaultSSOSessionConfig, staticKeys), + wantSources: []aws.CredentialSource{profile}, + }, + { + name: "A1 role_arn and source_profile in the credentials file do not flip", + config: defaultSSOSessionConfig, + credentials: "[default]\n" + staticKeys + roleARN + "source_profile = base\n\n[base]\n" + staticKeys, + wantSources: []aws.CredentialSource{sourceProfile, profile, assumeRole}, + }, + { + // Dropping the credentials file would also drop this role_arn: + // holodeck would sign as the bare SSO identity instead. + name: "A1b role_arn without source_profile in the credentials file does not flip", + config: defaultSSOSessionConfig, + credentials: "[default]\n" + staticKeys + roleARN, + wantSources: []aws.CredentialSource{profile, assumeRole}, + }, + { + name: "A1c role_arn in the config file does not flip", + config: withDefault(defaultSSOSessionConfig, roleARN), + credentials: "[default]\n" + staticKeys, + wantSources: []aws.CredentialSource{profile, assumeRole}, + }, + { + name: "A2 credential_process with SSO and credentials-file keys flips, as the aws CLI does", + config: withDefault(defaultSSOSessionConfig, "credential_process = /bin/false\n"), + credentials: "[default]\n" + staticKeys, + wantSSO: true, wantSources: ssoSession, warnProfile: "default", + }, + { + name: "A4 web_identity_token_file with role_arn in the config does not flip", + config: withDefault(defaultSSOSessionConfig, + roleARN+"web_identity_token_file = /nonexistent-token\n"), + credentials: "[default]\n" + staticKeys, + wantSources: []aws.CredentialSource{profile, assumeRole}, + }, + { + name: "A5 credential_source with role_arn does not flip", + config: withDefault(defaultSSOSessionConfig, + roleARN+"credential_source = Ec2InstanceMetadata\n"), + credentials: "[default]\n" + staticKeys, + wantSources: []aws.CredentialSource{profile, assumeRole}, + }, + { + name: "A6 web identity in the environment does not flip", + config: defaultSSOSessionConfig, + credentials: "[default]\n" + staticKeys, + env: map[string]string{ + "AWS_WEB_IDENTITY_TOKEN_FILE": "/nonexistent-token", + "AWS_ROLE_ARN": "arn:aws:iam::123456789012:role/Target", + }, + wantSources: []aws.CredentialSource{envWebID}, + }, + { + name: "A7 a container credentials URI with SSO and credentials-file keys flips, as the aws CLI does", + config: defaultSSOSessionConfig, + credentials: "[default]\n" + staticKeys, + env: map[string]string{"AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:9/creds"}, + wantSSO: true, wantSources: ssoSession, warnProfile: "default", + }, + { + name: "A9 a missing profile fails like the SDK, without a warning", + config: defaultSSOSessionConfig, + credentials: "[default]\n" + staticKeys, + env: map[string]string{"AWS_PROFILE": "nope"}, + wantErr: "failed to get shared config profile, nope", }, } for _, tc := range tests { @@ -199,34 +298,56 @@ sso_role_name = HolodeckTest t.Setenv(k, v) } - var cfg aws.Config - var err error - out := captureStdout(t, func() { - cfg, err = internalaws.LoadConfig(context.Background(), logger.NewLogger(), "us-west-2") - }) + r := loadConfig(t) + cfg, err, stdout, stderr := r.cfg, r.err, r.stdout, r.stderr + assert.Empty(t, stdout, "nothing may go to stdout") + if tc.warnProfile == "" { + assert.NotContains(t, stderr, "has SSO configured", "no warning expected") + } else { + assert.Equal(t, 1, strings.Count(stderr, preferSSOWarning(tc.warnProfile)), + "warning exactly once on stderr; stderr=%q", stderr) + assert.Equal(t, 1, strings.Count(stderr, "\n"), "exactly one line; stderr=%q", stderr) + } + if tc.wantErr != "" { + require.Error(t, err) + assert.Equal(t, tc.wantErr, err.Error()) + return + } require.NoError(t, err) assert.Equal(t, "us-west-2", cfg.Region) creds, ok := cfg.Credentials.(*aws.CredentialsCache) require.True(t, ok, "credentials must be a *aws.CredentialsCache, got %T", cfg.Credentials) - sources := creds.ProviderSources() - isSSO := creds.IsCredentialsProvider((*ssocreds.Provider)(nil)) - - switch tc.want { - case wantSSO: - assert.True(t, isSSO, "want the SSO provider, sources=%v", sources) - assert.NotContains(t, sources, aws.CredentialSourceProfile) - case wantSharedStatic, wantEnvStatic: - assert.False(t, isSSO, "want static credentials, sources=%v", sources) - } - assert.Contains(t, sources, tc.wantSource) - - if tc.wantWarning == "" { - assert.Empty(t, out, "no output expected") - } else { - assert.Equal(t, 1, strings.Count(out, tc.wantWarning), "warning exactly once; stdout=%q", out) - assert.Equal(t, 1, strings.Count(out, "\n"), "exactly one line; stdout=%q", out) - } + assert.Equal(t, tc.wantSSO, creds.IsCredentialsProvider((*ssocreds.Provider)(nil)), + "SSO provider; sources=%v", creds.ProviderSources()) + assert.Equal(t, tc.wantSources, creds.ProviderSources()) }) } } + +// TestLoadConfigWarnsOncePerProcess covers holodeck list, which loads a +// config for every cached AWS instance: the warning must appear once per +// process, on stderr, and never on stdout (list -o json must stay JSON). +func TestLoadConfigWarnsOncePerProcess(t *testing.T) { + home := isolateAWSEnv(t) + require.NoError(t, os.Unsetenv("AWS_CONFIG_FILE")) + require.NoError(t, os.Unsetenv("AWS_SHARED_CREDENTIALS_FILE")) + writeFile(t, filepath.Join(home, ".aws", "config"), defaultSSOSessionConfig) + writeFile(t, filepath.Join(home, ".aws", "credentials"), "[default]\n"+staticKeys) + + internalaws.ResetPreferSSOWarning() + log := logger.NewLogger() + var stderr bytes.Buffer + log.Out = &stderr + stdout := captureStdout(t, func() { + for i := 0; i < 3; i++ { + cfg, err := internalaws.LoadConfig(context.Background(), log, "us-west-2") + require.NoError(t, err) + assert.True(t, aws.IsCredentialsProvider(cfg.Credentials, (*ssocreds.Provider)(nil)), + "call %d must still prefer SSO", i+1) + } + }) + assert.Empty(t, stdout, "nothing may go to stdout") + assert.Equal(t, 1, strings.Count(stderr.String(), preferSSOWarning("default")), "stderr=%q", stderr.String()) + assert.Equal(t, 1, strings.Count(stderr.String(), "\n"), "stderr=%q", stderr.String()) +} diff --git a/internal/aws/export_test.go b/internal/aws/export_test.go new file mode 100644 index 000000000..a8a69f7ad --- /dev/null +++ b/internal/aws/export_test.go @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package aws + +import "sync" + +// ResetPreferSSOWarning re-arms the once-per-process prefer-SSO warning so +// each test case can observe it. +func ResetPreferSSOWarning() { preferSSOWarnOnce = sync.Once{} } diff --git a/internal/aws/sso_test.go b/internal/aws/sso_test.go index e075f35d6..1b0775217 100644 --- a/internal/aws/sso_test.go +++ b/internal/aws/sso_test.go @@ -30,6 +30,7 @@ import ( "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" "github.com/aws/aws-sdk-go-v2/service/ssm" + ssotypes "github.com/aws/aws-sdk-go-v2/service/sso/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -62,8 +63,9 @@ func isolateAWSEnv(t *testing.T) string { t.Setenv(k, "") } t.Setenv("AWS_EC2_METADATA_DISABLED", "true") - // Belt and braces: if the SDK ever tried to reach a service here, it - // would hit a closed local port instead of AWS. + // Points service clients (EC2, SSM, ...) at a closed local port. It does + // NOT cover the SSO and SSO-OIDC clients the credential chain builds; + // the HTTPS_PROXY that testutil.RunAWSIsolated sets is what stops those. t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") require.NoError(t, os.MkdirAll(filepath.Join(home, ".aws", "sso", "cache"), 0o700)) return home @@ -103,6 +105,11 @@ const noProfileHint = "AWS SSO session is expired or missing; run \"aws sso logi func TestSSOHint(t *testing.T) { ssoErr := fmt.Errorf("outer: %w", fmt.Errorf("inner: %w", &ssocreds.InvalidTokenError{})) + // A revoked or server-invalidated session: the token is locally valid, + // and GetRoleCredentials answers 401 UnauthorizedException, which the + // SDK returns raw (ssocreds/sso_credentials_provider.go:120-126). + unauth := &ssotypes.UnauthorizedException{Message: aws.String("Session token not found or invalid")} + unauthErr := fmt.Errorf("outer: %w", fmt.Errorf("inner: %w", unauth)) sessionErr := fmt.Errorf("get identity: %w", fmt.Errorf( "refresh cached SSO token failed, %w", errors.New("cached SSO token is expired, or not present, and cannot be refreshed"))) @@ -151,6 +158,13 @@ func TestSSOHint(t *testing.T) { wantMsg: profileHint(testProfile) + "outer: inner: the SSO session has expired or is invalid", wantTokenAs: true, }, + { + name: "revoked session (sso UnauthorizedException) names the profile", + profile: testProfile, + in: unauthErr, + wantMsg: profileHint(testProfile) + + "outer: inner: UnauthorizedException: Session token not found or invalid", + }, { name: "untyped sso-session token error names the profile", profile: testProfile, @@ -214,7 +228,8 @@ const expiredSessionToken = `{"accessToken":"fake-access-token","expiresAt":"202 // TestSSOHintRealSDKChain drives a real SSM call through the SDK's default // credential chain under fake SSO profiles. Credential resolution fails on // the local token cache before any request is signed, so nothing leaves the -// machine; AWS_ENDPOINT_URL points at a closed local port as a backstop. +// machine. The package TestMain (testutil.RunAWSIsolated) also points +// HTTPS_PROXY at a closed local port, which covers the SSO clients too. func TestSSOHintRealSDKChain(t *testing.T) { if !testutil.RunWithIsolatedHome(t) { return diff --git a/pkg/cleanup/sso_test.go b/pkg/cleanup/sso_test.go index 06da5632b..3dc53af4b 100644 --- a/pkg/cleanup/sso_test.go +++ b/pkg/cleanup/sso_test.go @@ -34,21 +34,32 @@ import ( // TestNewPrefersSSOOverSharedFileKeys guards the cleanup wiring: with an SSO // profile in the config file and static keys for it in the default shared // credentials file, New must load through internalaws.LoadConfig and hand -// the EC2 client the SSO provider. Retrieve is never called. +// the EC2 client the SSO provider, unless the credentials file also assumes +// a role, which the SSO reload would drop. Retrieve is never called. func TestNewPrefersSSOOverSharedFileKeys(t *testing.T) { if !testutil.RunWithIsolatedHome(t) { return } + const keys = "aws_access_key_id = AKIAHOLODECKFAKE0001\naws_secret_access_key = holodeck-fake-secret\n" tests := []struct { - name string - wantSSO bool - creds string + name string + creds string + wantSSO bool + wantSources []awssdk.CredentialSource }{ { name: "static keys in the default credentials file do not shadow SSO", + creds: "[holodeck-sso-test]\n" + keys, wantSSO: true, - creds: "[holodeck-sso-test]\naws_access_key_id = AKIAHOLODECKFAKE0001\n" + - "aws_secret_access_key = holodeck-fake-secret\n", + wantSources: []awssdk.CredentialSource{awssdk.CredentialSourceProfileSSOLegacy, + awssdk.CredentialSourceSSOLegacy, awssdk.CredentialSourceProfileSSO}, + }, + { + name: "a role_arn next to the keys keeps the assumed role", + creds: "[holodeck-sso-test]\n" + keys + + "role_arn = arn:aws:iam::123456789012:role/Target\n", + wantSources: []awssdk.CredentialSource{awssdk.CredentialSourceProfile, + awssdk.CredentialSourceSTSAssumeRole}, }, } for _, tc := range tests { @@ -96,6 +107,7 @@ sso_registration_scopes = sso:account:access require.True(t, ok, "credentials must be a *aws.CredentialsCache, got %T", client.Options().Credentials) assert.Equal(t, tc.wantSSO, creds.IsCredentialsProvider((*ssocreds.Provider)(nil)), "sources=%v", creds.ProviderSources()) + assert.Equal(t, tc.wantSources, creds.ProviderSources()) }) } } diff --git a/pkg/testutil/aws_isolation_test.go b/pkg/testutil/aws_isolation_test.go index 40b08bcdf..8c7d4d24e 100644 --- a/pkg/testutil/aws_isolation_test.go +++ b/pkg/testutil/aws_isolation_test.go @@ -18,7 +18,9 @@ package testutil_test import ( "fmt" + "net/http" "os" + "os/exec" "path/filepath" "testing" @@ -47,7 +49,9 @@ func fakeIsolation(t *testing.T) string { t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "credentials")) t.Setenv("AWS_EC2_METADATA_DISABLED", "true") t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") - for _, k := range testutil.AWSCredentialEnv() { + t.Setenv("HTTPS_PROXY", "http://127.0.0.1:9") + t.Setenv("HTTP_PROXY", "http://127.0.0.1:9") + for _, k := range append(testutil.AWSCredentialEnv(), "NO_PROXY", "no_proxy") { t.Setenv(k, "") require.NoError(t, os.Unsetenv(k)) } @@ -100,6 +104,8 @@ func TestAWSIsolationProblems(t *testing.T) { t.Setenv("AWS_CONFIG_FILE", "/etc/hosts") t.Setenv("AWS_EC2_METADATA_DISABLED", "false") t.Setenv("AWS_ENDPOINT_URL", "") + t.Setenv("HTTPS_PROXY", "") + t.Setenv("NO_PROXY", "localhost") want := []string{ testutil.IsolatedHomeEnv + " is not set: the process was not started by testutil.RunAWSIsolated", @@ -108,6 +114,8 @@ func TestAWSIsolationProblems(t *testing.T) { fmt.Sprintf("AWS_SHARED_CREDENTIALS_FILE=%q is not an empty file inside HOME", creds), `AWS_EC2_METADATA_DISABLED is not "true"`, `AWS_ENDPOINT_URL is not "http://127.0.0.1:9"`, + `HTTPS_PROXY is not "http://127.0.0.1:9"`, + "NO_PROXY is set", } assert.Equal(t, append(want, defaultPathProblems()...), testutil.AWSIsolationProblems()) }) @@ -116,7 +124,79 @@ func TestAWSIsolationProblems(t *testing.T) { fakeIsolation(t) t.Setenv("HOME", "/") t.Setenv(testutil.IsolatedHomeEnv, "/") - problems := testutil.AWSIsolationProblems() - assert.Contains(t, problems, fmt.Sprintf("HOME=%q is not inside os.TempDir() %q", "/", os.TempDir())) + assert.Equal(t, []string{fmt.Sprintf("HOME=%q is not inside os.TempDir() %q", "/", os.TempDir())}, + testutil.AWSIsolationProblems()) }) } + +// TestIsolatedProxy proves the proxy backstop: every AWS host, including +// the SSO portal that AWS_ENDPOINT_URL does not cover, goes to the closed +// local port, while loopback (httptest servers, local fixtures) bypasses +// the proxy, as net/http's ProxyFromEnvironment does for localhost and +// loopback addresses. +func TestIsolatedProxy(t *testing.T) { + tests := []struct { + url string + want string // "" = direct, no proxy + }{ + {"https://portal.sso.us-east-1.amazonaws.com/federation/credentials", "http://127.0.0.1:9"}, + {"https://oidc.us-east-1.amazonaws.com/token", "http://127.0.0.1:9"}, + {"https://ec2.us-west-2.amazonaws.com/", "http://127.0.0.1:9"}, + {"http://169.254.169.254/latest/api/token", "http://127.0.0.1:9"}, + {"http://127.0.0.1:8080/", ""}, + {"http://localhost:8080/", ""}, + {"http://[::1]:8080/", ""}, + } + for _, tc := range tests { + t.Run(tc.url, func(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, tc.url, nil) + require.NoError(t, err) + got, err := http.ProxyFromEnvironment(req) + require.NoError(t, err) + if tc.want == "" { + assert.Nil(t, got) + return + } + require.NotNil(t, got, "AWS traffic must go through the closed proxy") + assert.Equal(t, tc.want, got.String()) + }) + } +} + +// TestRunAWSIsolatedRefusesStaleMarker: a leftover exported +// HOLODECK_TEST_ISOLATED_HOME must not let a test binary run its tests +// un-isolated. The child gets a marker that does not match its HOME; it +// must exit 1 before running any test. +func TestRunAWSIsolatedRefusesStaleMarker(t *testing.T) { + stale := t.TempDir() + //nolint:gosec // re-executes this same test binary with a fixed -test.run + cmd := exec.Command(os.Args[0], "-test.run=^TestAWSIsolation$", "-test.count=1", "-test.v") + cmd.Env = append(os.Environ(), testutil.IsolatedHomeEnv+"="+stale) + out, err := cmd.CombinedOutput() + + var exitErr *exec.ExitError + require.ErrorAs(t, err, &exitErr, "child output:\n%s", out) + assert.Equal(t, 1, exitErr.ExitCode()) + assert.Contains(t, string(out), + "testutil.RunAWSIsolated: refusing to run tests, the process is not isolated:") + assert.Contains(t, string(out), + fmt.Sprintf("HOME=%q is not the isolated HOME %q", os.Getenv("HOME"), stale)) + assert.NotContains(t, string(out), "=== RUN", "no test may run") +} + +// TestIsolatedHome: inside the TestMain child, IsolatedHome returns the +// isolated HOME and clears a leftover .aws directory. +func TestIsolatedHome(t *testing.T) { + home := os.Getenv(testutil.IsolatedHomeEnv) + require.NotEmpty(t, home) + first := testutil.IsolatedHome(t) + stale := filepath.Join(first, ".aws", "config") + require.NoError(t, os.MkdirAll(filepath.Dir(stale), 0o700)) + require.NoError(t, os.WriteFile(stale, []byte("[default]\n"), 0o600)) + + second := testutil.IsolatedHome(t) + assert.Equal(t, home, first) + assert.Equal(t, home, second) + _, err := os.Stat(filepath.Join(second, ".aws")) + assert.True(t, os.IsNotExist(err), "IsolatedHome must remove a leftover .aws, stat err=%v", err) +} diff --git a/pkg/testutil/main_test.go b/pkg/testutil/main_test.go new file mode 100644 index 000000000..1bbc5d5c5 --- /dev/null +++ b/pkg/testutil/main_test.go @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package testutil_test + +import ( + "os" + "testing" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// TestMain runs this package's tests through its own isolation, so the +// helper's tests (stale marker, proxy, IsolatedHome) run where it applies. +func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } + +// TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. +func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } From 8781fe0334b22e114f0b406f1a4c3222024e0af3 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Sat, 28 Nov 2026 13:36:36 +0100 Subject: [PATCH 10/13] fix(aws): warn once on stderr, keep assumed roles, harden test isolation Review fixes on top of the prefer-SSO change: - holodeck list loads one config per cached AWS instance, and the prefer-SSO warning went to stdout each time, breaking list -o json and -q. It is now printed once per process, to the logger's Out writer (os.Stderr by default), regardless of quiet mode. - The SSO reload reads no credentials file, so it dropped a role_arn that lives there and signed as the bare SSO identity. A profile with role_arn no longer flips. - SSOHint also recognises the SSO service's UnauthorizedException, the error for a revoked or server-invalidated session. - The isolated test child now routes HTTP(S) through a closed local proxy. AWS_ENDPOINT_URL alone never covered the SSO and SSO-OIDC clients the credential chain builds. Loopback stays direct, and NO_PROXY is set to exactly the public-IP lookup hosts of utils.DefaultIPServices (none is an AWS host): four existing pkg/provider/aws tests call utils.GetIPAddress, and a strict proxy would have changed their behaviour. A pkg/utils test keeps the two host lists equal. The guard checks the proxy settings and that the SSO portal really resolves to the closed proxy. - A stale HOLODECK_TEST_ISOLATED_HOME no longer runs tests un-isolated: the child refuses to start when the isolation checks fail. - RunWithIsolatedHome is removed; every package that used it has the isolating TestMain, so it had become a no-op. Its IsolatedHome test moves to isolated_home_test.go. Signed-off-by: Carlos Eduardo Arango Gutierrez --- internal/aws/config.go | 39 ++++++++++++---- internal/aws/config_test.go | 6 ++- internal/aws/sso.go | 14 ++++-- internal/aws/sso_test.go | 13 ++---- pkg/cleanup/sso_test.go | 3 -- pkg/provider/aws/sso_test.go | 3 -- pkg/testutil/aws_isolation.go | 72 +++++++++++++++++++++++++----- pkg/testutil/aws_isolation_test.go | 34 +++++++------- pkg/testutil/isolated_home.go | 42 +---------------- pkg/testutil/isolated_home_test.go | 54 ++++++---------------- pkg/utils/aws_isolation_test.go | 23 ++++++++++ 11 files changed, 162 insertions(+), 141 deletions(-) diff --git a/internal/aws/config.go b/internal/aws/config.go index fc735bf95..4b702c145 100644 --- a/internal/aws/config.go +++ b/internal/aws/config.go @@ -18,6 +18,9 @@ package aws import ( "context" + "fmt" + "io" + "os" "sync" "github.com/aws/aws-sdk-go-v2/aws" @@ -42,9 +45,17 @@ const preferSSOWarning = "AWS profile %q has SSO configured and static keys in t // stale) keys shadow the SSO login. // // The SSO preference applies only when nothing explicit overrides it: no -// static keys in the environment, and no AWS_SHARED_CREDENTIALS_FILE. If the -// profile cannot be read, or the reload does not actually resolve to SSO, -// the default chain is used unchanged and nothing is logged. +// static keys in the environment, no AWS_SHARED_CREDENTIALS_FILE, and no +// role_arn on the profile (the reload reads no credentials file, so it would +// drop a role that lives there). If the profile cannot be read, or the +// reload does not actually resolve to SSO, the default chain is used +// unchanged and nothing is logged. This follows the aws CLI order, so a +// profile that also has credential_process, or a container credentials URI +// in the environment, still prefers SSO. +// +// The warning is written once per process to the logger's Out writer +// (os.Stderr by default), never to stdout, which carries machine-readable +// output such as holodeck list -o json. // // LoadConfig never retrieves credentials; they stay lazy. func LoadConfig(ctx context.Context, log *logger.FunLogger, region string) (aws.Config, error) { @@ -75,9 +86,7 @@ func LoadConfig(ctx context.Context, log *logger.FunLogger, region string) (aws. // An empty, non-nil list reads no credentials file at all. config.WithSharedCredentialsFiles([]string{})) if err == nil && aws.IsCredentialsProvider(cfg.Credentials, (*ssocreds.Provider)(nil)) { - if log != nil { - log.Warning(preferSSOWarning, profile) - } + preferSSOWarnOnce.Do(func() { warnPreferSSO(log, profile) }) return cfg, nil } } @@ -89,8 +98,9 @@ func LoadConfig(ctx context.Context, log *logger.FunLogger, region string) (aws. } // ssoShadowedByStaticKeys reports whether the active profile has both static -// keys and an SSO configuration, with no static keys in the environment. -// It returns the profile name. Any error reading the profile returns false. +// keys and an SSO configuration and assumes no role, with no static keys in +// the environment. It returns the profile name. Any error reading the +// profile returns false. func ssoShadowedByStaticKeys(ctx context.Context, env config.EnvConfig, configFile, credsFile string) (string, bool) { if env.Credentials.HasKeys() { return "", false @@ -106,12 +116,23 @@ func ssoShadowedByStaticKeys(ctx context.Context, env config.EnvConfig, configFi if err != nil { return "", false } - if !sc.Credentials.HasKeys() || !hasSSOConfiguration(sc) { + if !sc.Credentials.HasKeys() || !hasSSOConfiguration(sc) || sc.RoleARN != "" { return "", false } return profile, true } +// warnPreferSSO writes the prefer-SSO warning to the logger's Out writer, +// or os.Stderr without a logger. Unlike FunLogger.Info it ignores quiet +// mode: the user's credentials changed. +func warnPreferSSO(log *logger.FunLogger, profile string) { + var w io.Writer = os.Stderr + if log != nil && log.Out != nil { + w = log.Out + } + fmt.Fprintf(w, "warning: "+preferSSOWarning+"\n", profile) //nolint:errcheck // best-effort warning +} + // hasSSOConfiguration mirrors the SDK's unexported // (*config.SharedConfig).hasSSOConfiguration in config v1.33.13: // hasSSOTokenProviderConfiguration() || hasLegacySSOConfiguration(). diff --git a/internal/aws/config_test.go b/internal/aws/config_test.go index f9f8b52f8..b2a210420 100644 --- a/internal/aws/config_test.go +++ b/internal/aws/config_test.go @@ -262,8 +262,10 @@ sso_role_name = HolodeckTest name: "A7 a container credentials URI with SSO and credentials-file keys flips, as the aws CLI does", config: defaultSSOSessionConfig, credentials: "[default]\n" + staticKeys, - env: map[string]string{"AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:9/creds"}, - wantSSO: true, wantSources: ssoSession, warnProfile: "default", + env: map[string]string{ //nolint:gosec // G101: a closed local URL, not a credential + "AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:9/creds", + }, + wantSSO: true, wantSources: ssoSession, warnProfile: "default", }, { name: "A9 a missing profile fails like the SDK, without a warning", diff --git a/internal/aws/sso.go b/internal/aws/sso.go index d8570b9a6..17e91e815 100644 --- a/internal/aws/sso.go +++ b/internal/aws/sso.go @@ -23,6 +23,7 @@ import ( "strings" "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" + ssotypes "github.com/aws/aws-sdk-go-v2/service/sso/types" ) // ssoCacheErrMarker appears in every error the SDK's SSO token provider @@ -32,16 +33,21 @@ import ( // them. TestSSOHintRealSDKChain fails if an SDK upgrade changes this text. const ssoCacheErrMarker = "cached SSO token" -// SSOHint adds an "aws sso login" hint to errors caused by an expired or -// missing AWS SSO session. The profile named in the hint is the one the SDK -// used: AWS_PROFILE, else AWS_DEFAULT_PROFILE. Any other error, and nil, is +// SSOHint adds an "aws sso login" hint to errors caused by an expired, +// missing or revoked AWS SSO session: the typed InvalidTokenError (legacy +// profiles), the SSO service's UnauthorizedException (a token the portal no +// longer accepts), or the untyped token-cache errors of sso-session profiles. +// The profile named in the hint is the one the SDK used: AWS_PROFILE, else +// AWS_DEFAULT_PROFILE. Any other error, and nil, is // returned unchanged. The original error stays in the chain. func SSOHint(err error) error { if err == nil { return nil } var ssoErr *ssocreds.InvalidTokenError - if !errors.As(err, &ssoErr) && !strings.Contains(err.Error(), ssoCacheErrMarker) { + var unauthErr *ssotypes.UnauthorizedException + if !errors.As(err, &ssoErr) && !errors.As(err, &unauthErr) && + !strings.Contains(err.Error(), ssoCacheErrMarker) { return err } p := os.Getenv("AWS_PROFILE") diff --git a/internal/aws/sso_test.go b/internal/aws/sso_test.go index 1b0775217..0ffed6634 100644 --- a/internal/aws/sso_test.go +++ b/internal/aws/sso_test.go @@ -71,16 +71,12 @@ func isolateAWSEnv(t *testing.T) string { return home } -// fixtureHome returns the HOME to build fixtures in. Inside a -// testutil.RunWithIsolatedHome child it is the process HOME, which is also -// where the SDK's package-init default paths point, so even a code path that +// fixtureHome returns the HOME to build fixtures in: the isolated process +// HOME of the package TestMain (testutil.RunAWSIsolated). The SDK's +// package-init default paths point there too, so even a code path that // bypasses the call-time paths reads the fixture and never the real ~/.aws. -// Elsewhere it is a fresh temp dir. func fixtureHome(t *testing.T) string { t.Helper() - if os.Getenv(testutil.IsolatedHomeEnv) == "" { - return t.TempDir() - } return testutil.IsolatedHome(t) } @@ -231,9 +227,6 @@ const expiredSessionToken = `{"accessToken":"fake-access-token","expiresAt":"202 // machine. The package TestMain (testutil.RunAWSIsolated) also points // HTTPS_PROXY at a closed local port, which covers the SSO clients too. func TestSSOHintRealSDKChain(t *testing.T) { - if !testutil.RunWithIsolatedHome(t) { - return - } tests := []struct { name string config string diff --git a/pkg/cleanup/sso_test.go b/pkg/cleanup/sso_test.go index 3dc53af4b..ed55c18e2 100644 --- a/pkg/cleanup/sso_test.go +++ b/pkg/cleanup/sso_test.go @@ -37,9 +37,6 @@ import ( // the EC2 client the SSO provider, unless the credentials file also assumes // a role, which the SSO reload would drop. Retrieve is never called. func TestNewPrefersSSOOverSharedFileKeys(t *testing.T) { - if !testutil.RunWithIsolatedHome(t) { - return - } const keys = "aws_access_key_id = AKIAHOLODECKFAKE0001\naws_secret_access_key = holodeck-fake-secret\n" tests := []struct { name string diff --git a/pkg/provider/aws/sso_test.go b/pkg/provider/aws/sso_test.go index f2f30a57f..5d1aeed9a 100644 --- a/pkg/provider/aws/sso_test.go +++ b/pkg/provider/aws/sso_test.go @@ -46,9 +46,6 @@ const validSSOToken = `{"accessToken":"fake-access-token","expiresAt":"2999-01-0 // SSO credentials provider. It never calls Retrieve, so it reads no token // and makes no network call; New must stay lazy (holodeck list depends on it). func TestNewResolvesSSOProfile(t *testing.T) { - if !testutil.RunWithIsolatedHome(t) { - return - } tests := []struct { name string config string diff --git a/pkg/testutil/aws_isolation.go b/pkg/testutil/aws_isolation.go index ef33d845e..512b434aa 100644 --- a/pkg/testutil/aws_isolation.go +++ b/pkg/testutil/aws_isolation.go @@ -20,6 +20,7 @@ import ( "context" "errors" "fmt" + "net/http" "os" "os/exec" "path/filepath" @@ -33,9 +34,31 @@ import ( // so the guard can check that no error names a file under it. const ParentHomeEnv = "HOLODECK_TEST_PARENT_HOME" -// isolatedEndpoint is a closed local port: if anything still tried to send an -// AWS request, it would be refused locally instead of reaching AWS. -const isolatedEndpoint = "http://127.0.0.1:9" +// closedPort is a closed local port. Two settings point there: +// - AWS_ENDPOINT_URL, which covers the SDK's service clients (EC2, SSM, +// ELBv2, STS). It does NOT cover the SSO and SSO-OIDC clients that the +// credential chain builds, because the SDK resolves credentials before +// it reads AWS_ENDPOINT_URL. +// - HTTPS_PROXY / HTTP_PROXY, which cover every client that uses +// net/http's ProxyFromEnvironment, as the SDK's default HTTP client does, +// including the SSO portal. Loopback hosts bypass the proxy, so local +// test servers keep working. +const closedPort = "http://127.0.0.1:9" + +// proxyEnv lists the proxy variables RunAWSIsolated sets to closedPort. +func proxyEnv() []string { return []string{"HTTPS_PROXY", "HTTP_PROXY"} } + +// IPLookupHosts lists the public-IP lookup hosts of +// pkg/utils.DefaultIPServices. RunAWSIsolated sets NO_PROXY to exactly these, +// so tests that call utils.GetIPAddress keep working; none is an AWS host, +// and NO_PROXY matches by host suffix, so no AWS host can match. A test in +// pkg/utils keeps the two lists equal (testutil cannot import pkg/utils, +// whose own tests import testutil). +func IPLookupHosts() []string { + return []string{"api.ipify.org", "ifconfig.me", "icanhazip.com", "ident.me"} +} + +func noProxyValue() string { return strings.Join(IPLookupHosts(), ",") } // AWSCredentialEnv lists the environment variables RunAWSIsolated removes: // every variable the AWS SDK reads to pick a profile or find credentials. @@ -57,17 +80,25 @@ func AWSCredentialEnv() []string { // // The child starts with HOME set to a new temp dir, AWS_CONFIG_FILE and // AWS_SHARED_CREDENTIALS_FILE set to empty files in it, every variable from -// AWSCredentialEnv removed, IMDS disabled, and AWS_ENDPOINT_URL set to a -// closed local port. Because the child is a new process, the AWS SDK's +// AWSCredentialEnv removed, IMDS disabled, and AWS_ENDPOINT_URL, +// HTTPS_PROXY and HTTP_PROXY set to a closed local port, and NO_PROXY set to +// exactly IPLookupHosts (no_proxy removed); see closedPort. Because the child is a new process, the AWS SDK's // package-init default paths (config.DefaultSharedConfigFiles and // DefaultSharedCredentialsFiles, computed from HOME before TestMain runs) also // point into the temp HOME. Setting the variables in this process would be // too late for them. // -// In the child it just runs the tests. It returns the exit code to pass to -// os.Exit. +// In the child it runs the tests, but only if the isolation checks pass: a +// stale HOLODECK_TEST_ISOLATED_HOME exported in a shell must not run tests +// un-isolated. It returns the exit code to pass to os.Exit. func RunAWSIsolated(m *testing.M) int { if os.Getenv(IsolatedHomeEnv) != "" { + if problems := AWSIsolationProblems(); len(problems) > 0 { + fmt.Fprintf(os.Stderr, + "testutil.RunAWSIsolated: refusing to run tests, the process is not isolated:\n- %s\n", + strings.Join(problems, "\n- ")) + return 1 + } return m.Run() } @@ -100,9 +131,13 @@ func RunAWSIsolated(m *testing.M) int { "AWS_CONFIG_FILE": configFile, "AWS_SHARED_CREDENTIALS_FILE": credsFile, "AWS_EC2_METADATA_DISABLED": "true", - "AWS_ENDPOINT_URL": isolatedEndpoint, + "AWS_ENDPOINT_URL": closedPort, + } + for _, k := range proxyEnv() { + set[k] = closedPort } - drop := map[string]bool{} + set["NO_PROXY"] = noProxyValue() + drop := map[string]bool{"no_proxy": true} for _, k := range AWSCredentialEnv() { drop[k] = true } @@ -163,8 +198,16 @@ func AWSIsolationProblems() []string { if os.Getenv("AWS_EC2_METADATA_DISABLED") != "true" { problems = append(problems, `AWS_EC2_METADATA_DISABLED is not "true"`) } - if os.Getenv("AWS_ENDPOINT_URL") != isolatedEndpoint { - problems = append(problems, fmt.Sprintf("AWS_ENDPOINT_URL is not %q", isolatedEndpoint)) + for _, k := range append([]string{"AWS_ENDPOINT_URL"}, proxyEnv()...) { + if os.Getenv(k) != closedPort { + problems = append(problems, fmt.Sprintf("%s is not %q", k, closedPort)) + } + } + if os.Getenv("NO_PROXY") != noProxyValue() { + problems = append(problems, fmt.Sprintf("NO_PROXY is not %q", noProxyValue())) + } + if _, ok := os.LookupEnv("no_proxy"); ok { + problems = append(problems, "no_proxy is set") } if p := config.DefaultSharedConfigFiles[0]; !within(home, p) { problems = append(problems, fmt.Sprintf( @@ -188,6 +231,13 @@ func RequireAWSIsolation(t *testing.T) { t.Fatalf("AWS isolation is not active (add TestMain calling testutil.RunAWSIsolated):\n- %s", strings.Join(problems, "\n- ")) } + req, err := http.NewRequest(http.MethodGet, "https://portal.sso.us-east-1.amazonaws.com/", nil) + if err != nil { + t.Fatalf("build probe request: %v", err) + } + if u, err := http.ProxyFromEnvironment(req); err != nil || u == nil || u.String() != closedPort { + t.Fatalf("AWS traffic is not routed to the closed proxy %s: proxy=%v err=%v", closedPort, u, err) + } ctx := context.Background() cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-east-1")) if err != nil { diff --git a/pkg/testutil/aws_isolation_test.go b/pkg/testutil/aws_isolation_test.go index 8c7d4d24e..94139f330 100644 --- a/pkg/testutil/aws_isolation_test.go +++ b/pkg/testutil/aws_isolation_test.go @@ -51,7 +51,8 @@ func fakeIsolation(t *testing.T) string { t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") t.Setenv("HTTPS_PROXY", "http://127.0.0.1:9") t.Setenv("HTTP_PROXY", "http://127.0.0.1:9") - for _, k := range append(testutil.AWSCredentialEnv(), "NO_PROXY", "no_proxy") { + t.Setenv("NO_PROXY", "api.ipify.org,ifconfig.me,icanhazip.com,ident.me") + for _, k := range append(testutil.AWSCredentialEnv(), "no_proxy") { t.Setenv(k, "") require.NoError(t, os.Unsetenv(k)) } @@ -115,7 +116,7 @@ func TestAWSIsolationProblems(t *testing.T) { `AWS_EC2_METADATA_DISABLED is not "true"`, `AWS_ENDPOINT_URL is not "http://127.0.0.1:9"`, `HTTPS_PROXY is not "http://127.0.0.1:9"`, - "NO_PROXY is set", + `NO_PROXY is not "api.ipify.org,ifconfig.me,icanhazip.com,ident.me"`, } assert.Equal(t, append(want, defaultPathProblems()...), testutil.AWSIsolationProblems()) }) @@ -143,6 +144,9 @@ func TestIsolatedProxy(t *testing.T) { {"https://oidc.us-east-1.amazonaws.com/token", "http://127.0.0.1:9"}, {"https://ec2.us-west-2.amazonaws.com/", "http://127.0.0.1:9"}, {"http://169.254.169.254/latest/api/token", "http://127.0.0.1:9"}, + // The public-IP lookups some tests make stay direct. + {"https://api.ipify.org?format=text", ""}, + {"https://ident.me", ""}, {"http://127.0.0.1:8080/", ""}, {"http://localhost:8080/", ""}, {"http://[::1]:8080/", ""}, @@ -163,6 +167,15 @@ func TestIsolatedProxy(t *testing.T) { } } +// TestIPLookupHostsAreNotAWS: the NO_PROXY exemption may never cover an +// AWS host. +func TestIPLookupHostsAreNotAWS(t *testing.T) { + for _, h := range testutil.IPLookupHosts() { + assert.NotContains(t, h, "amazonaws", h) + assert.NotContains(t, h, "aws", h) + } +} + // TestRunAWSIsolatedRefusesStaleMarker: a leftover exported // HOLODECK_TEST_ISOLATED_HOME must not let a test binary run its tests // un-isolated. The child gets a marker that does not match its HOME; it @@ -183,20 +196,3 @@ func TestRunAWSIsolatedRefusesStaleMarker(t *testing.T) { fmt.Sprintf("HOME=%q is not the isolated HOME %q", os.Getenv("HOME"), stale)) assert.NotContains(t, string(out), "=== RUN", "no test may run") } - -// TestIsolatedHome: inside the TestMain child, IsolatedHome returns the -// isolated HOME and clears a leftover .aws directory. -func TestIsolatedHome(t *testing.T) { - home := os.Getenv(testutil.IsolatedHomeEnv) - require.NotEmpty(t, home) - first := testutil.IsolatedHome(t) - stale := filepath.Join(first, ".aws", "config") - require.NoError(t, os.MkdirAll(filepath.Dir(stale), 0o700)) - require.NoError(t, os.WriteFile(stale, []byte("[default]\n"), 0o600)) - - second := testutil.IsolatedHome(t) - assert.Equal(t, home, first) - assert.Equal(t, home, second) - _, err := os.Stat(filepath.Join(second, ".aws")) - assert.True(t, os.IsNotExist(err), "IsolatedHome must remove a leftover .aws, stat err=%v", err) -} diff --git a/pkg/testutil/isolated_home.go b/pkg/testutil/isolated_home.go index 4e3795496..01c8c91e6 100644 --- a/pkg/testutil/isolated_home.go +++ b/pkg/testutil/isolated_home.go @@ -18,52 +18,14 @@ package testutil import ( "os" - "os/exec" "path/filepath" - "regexp" - "strings" "testing" ) // IsolatedHomeEnv is set to the isolated HOME in the child process. const IsolatedHomeEnv = "HOLODECK_TEST_ISOLATED_HOME" -// RunWithIsolatedHome re-runs the calling top-level test in a child test -// process whose HOME is a new, empty directory from process start. -// -// The AWS SDK computes config.DefaultSharedConfigFiles and -// DefaultSharedCredentialsFiles once, at package init, from HOME. A -// t.Setenv("HOME", ...) inside a test comes too late for them, so any code -// path that falls back to those defaults would read the developer's real -// ~/.aws. In the child, those defaults point into the empty isolated HOME. -// -// It returns true in the child, where the caller runs the test body, and -// false in the parent, after failing t if the child failed or did not run -// the test. Call it first, from a top-level test (not a subtest). -func RunWithIsolatedHome(t *testing.T) bool { - t.Helper() - if os.Getenv(IsolatedHomeEnv) != "" { - return true - } - - home := t.TempDir() - //nolint:gosec // re-executes this test binary with a fixed, anchored -test.run - cmd := exec.Command(os.Args[0], - "-test.run=^"+regexp.QuoteMeta(t.Name())+"$", "-test.count=1", "-test.v") - // exec uses the last value of a duplicated key, so these override HOME. - cmd.Env = append(os.Environ(), "HOME="+home, IsolatedHomeEnv+"="+home) - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("isolated-HOME run of %s failed: %v\n%s", t.Name(), err, out) - } - if !strings.Contains(string(out), "--- PASS: "+t.Name()+" ") { - t.Fatalf("isolated-HOME run did not run %s:\n%s", t.Name(), out) - } - t.Logf("isolated-HOME run (HOME=%s):\n%s", home, out) - return false -} - -// IsolatedHome returns the HOME of a RunWithIsolatedHome child, after +// IsolatedHome returns the isolated HOME of a RunAWSIsolated child, after // removing its .aws directory; it removes it again when t ends, so each // (sub)test starts from an empty HOME. Fixtures written here are what the // SDK's package-init default paths point at, too. It fails t outside a @@ -72,7 +34,7 @@ func IsolatedHome(t *testing.T) string { t.Helper() home := os.Getenv(IsolatedHomeEnv) if home == "" { - t.Fatalf("IsolatedHome called outside a RunWithIsolatedHome child") + t.Fatalf("IsolatedHome called outside a RunAWSIsolated child (add the package TestMain)") } awsDir := filepath.Join(home, ".aws") reset := func() { diff --git a/pkg/testutil/isolated_home_test.go b/pkg/testutil/isolated_home_test.go index 5517e779b..abb261136 100644 --- a/pkg/testutil/isolated_home_test.go +++ b/pkg/testutil/isolated_home_test.go @@ -21,51 +21,25 @@ import ( "path/filepath" "testing" - "github.com/aws/aws-sdk-go-v2/config" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/NVIDIA/holodeck/pkg/testutil" ) -// TestRunWithIsolatedHome checks the property the helper exists for: in the -// child, the AWS SDK's package-init default paths (computed from HOME before -// any test code runs) point into the isolated HOME, never the real one. It -// only reads the path variables; it opens no file. -func TestRunWithIsolatedHome(t *testing.T) { - if !testutil.RunWithIsolatedHome(t) { - return - } +// TestIsolatedHome: inside the TestMain child, IsolatedHome returns the +// isolated HOME and clears a leftover .aws directory. +func TestIsolatedHome(t *testing.T) { home := os.Getenv(testutil.IsolatedHomeEnv) - require.NotEmpty(t, home, "child must see %s", testutil.IsolatedHomeEnv) - - tests := []struct { - name string - got string - want string - }{ - {"HOME is the isolated dir", os.Getenv("HOME"), home}, - {"SDK default config file is under the isolated HOME", - config.DefaultSharedConfigFiles[0], filepath.Join(home, ".aws", "config")}, - {"SDK default credentials file is under the isolated HOME", - config.DefaultSharedCredentialsFiles[0], filepath.Join(home, ".aws", "credentials")}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, tc.got) - }) - } - - t.Run("IsolatedHome returns the isolated HOME with .aws removed", func(t *testing.T) { - first := testutil.IsolatedHome(t) - stale := filepath.Join(first, ".aws", "config") - require.NoError(t, os.MkdirAll(filepath.Dir(stale), 0o700)) - require.NoError(t, os.WriteFile(stale, []byte("[default]\n"), 0o600)) - - second := testutil.IsolatedHome(t) - assert.Equal(t, home, first) - assert.Equal(t, home, second) - _, err := os.Stat(filepath.Join(second, ".aws")) - assert.True(t, os.IsNotExist(err), "IsolatedHome must remove a leftover .aws, stat err=%v", err) - }) + require.NotEmpty(t, home) + first := testutil.IsolatedHome(t) + stale := filepath.Join(first, ".aws", "config") + require.NoError(t, os.MkdirAll(filepath.Dir(stale), 0o700)) + require.NoError(t, os.WriteFile(stale, []byte("[default]\n"), 0o600)) + + second := testutil.IsolatedHome(t) + assert.Equal(t, home, first) + assert.Equal(t, home, second) + _, err := os.Stat(filepath.Join(second, ".aws")) + assert.True(t, os.IsNotExist(err), "IsolatedHome must remove a leftover .aws, stat err=%v", err) } diff --git a/pkg/utils/aws_isolation_test.go b/pkg/utils/aws_isolation_test.go index 3dd5de768..0de1f2999 100644 --- a/pkg/utils/aws_isolation_test.go +++ b/pkg/utils/aws_isolation_test.go @@ -17,6 +17,7 @@ package utils import ( + "net/url" "os" "testing" @@ -30,3 +31,25 @@ func TestMain(m *testing.M) { os.Exit(testutil.RunAWSIsolated(m)) } // TestAWSIsolation fails unless the AWS isolation from TestMain is in effect. func TestAWSIsolation(t *testing.T) { testutil.RequireAWSIsolation(t) } + +// TestIPLookupHostsMatchDefaultIPServices keeps testutil's NO_PROXY +// exemption equal to the hosts GetIPAddress actually calls. +func TestIPLookupHostsMatchDefaultIPServices(t *testing.T) { + var hosts []string + for _, s := range DefaultIPServices() { + u, err := url.Parse(s.URL) + if err != nil { + t.Fatalf("parse %q: %v", s.URL, err) + } + hosts = append(hosts, u.Hostname()) + } + got, want := testutil.IPLookupHosts(), hosts + if len(got) != len(want) { + t.Fatalf("testutil.IPLookupHosts() = %v, DefaultIPServices hosts = %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("testutil.IPLookupHosts() = %v, DefaultIPServices hosts = %v", got, want) + } + } +} From a93e913b234c8a915ff7fe4a1f5e17f7187db476 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Sat, 28 Nov 2026 13:44:38 +0100 Subject: [PATCH 11/13] docs: describe the SSO-over-shared-keys precedence The prerequisites still said Holodeck simply uses the SDK default chain. Explain the one difference, which matches the aws CLI: SSO wins over static keys in the shared credentials file for the same profile, with a single warning on stderr, while env keys, an explicit AWS_SHARED_CREDENTIALS_FILE and assume-role profiles keep the SDK behaviour. Signed-off-by: Carlos Eduardo Arango Gutierrez --- docs/prerequisites.md | 13 ++++++++++--- pkg/skill/data/skills/using-holodeck/SKILL.md | 3 +++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/prerequisites.md b/docs/prerequisites.md index 7a2f30eea..1696b180f 100644 --- a/docs/prerequisites.md +++ b/docs/prerequisites.md @@ -41,9 +41,16 @@ To use the AWS provider, you need: #### AWS SSO (IAM Identity Center) -Holodeck uses the AWS SDK default credential chain, so a profile created -with `aws configure sso` works. Log in, select the profile, then run -Holodeck: +Holodeck resolves credentials like the AWS SDK default chain, with one +change that matches the aws CLI: when the active profile has an SSO +configuration and also static keys in the shared credentials file, Holodeck +uses SSO, so stale keys cannot shadow your SSO login. It prints one warning +on stderr when that happens; remove the keys to silence it. Static keys in +the environment, an explicit `AWS_SHARED_CREDENTIALS_FILE`, and a profile +that assumes a role (`role_arn`) keep the SDK behavior. + +A profile created with `aws configure sso` works. Log in, select the +profile, then run Holodeck: ```bash aws sso login --profile my-sso-profile diff --git a/pkg/skill/data/skills/using-holodeck/SKILL.md b/pkg/skill/data/skills/using-holodeck/SKILL.md index 49a1290f3..7465f1227 100644 --- a/pkg/skill/data/skills/using-holodeck/SKILL.md +++ b/pkg/skill/data/skills/using-holodeck/SKILL.md @@ -168,6 +168,9 @@ Read commands (`list`, `status`, `describe`) accept record the profile, so `delete`, `status` and `update` must run with the same `AWS_PROFILE`; the SSM transport uses it too. An expired SSO session fails with a message naming the `aws sso login` command. + Like the aws CLI, SSO wins over static keys for the same profile in + the shared credentials file (one warning on stderr), unless the + profile assumes a role or `AWS_SHARED_CREDENTIALS_FILE` is set. These are **separate** from `auth.keyName` / `auth.privateKey` in env.yaml: those are **literal** values — `auth.keyName` is the EC2 SSH key-pair name registered in the target region, and From db1a8ec4c7025bc241b73c6ccc8457002f42b425 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Sat, 28 Nov 2026 14:45:57 +0100 Subject: [PATCH 12/13] test(testutil): cover lowercase proxy variables and AWS host suffixes Go reads HTTPS_PROXY or https_proxy, but Python and the aws CLI read the lowercase spellings, so a subprocess of a test could still use the parent shell's corporate proxy. The isolated baseline now has both spellings at the closed port (no_proxy equal to the IP-lookup allowlist), and a parent's lowercase https_proxy must be reported. This fails until the isolation sets the lowercase variables. The "IP lookup hosts are not AWS" check now matches hostname suffixes (amazonaws.com, aws.amazon.com, amazonaws.com.cn, aws) instead of substrings. Signed-off-by: Carlos Eduardo Arango Gutierrez --- pkg/testutil/aws_isolation_test.go | 31 ++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/pkg/testutil/aws_isolation_test.go b/pkg/testutil/aws_isolation_test.go index 94139f330..4e3f835ca 100644 --- a/pkg/testutil/aws_isolation_test.go +++ b/pkg/testutil/aws_isolation_test.go @@ -22,6 +22,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "testing" "github.com/aws/aws-sdk-go-v2/config" @@ -49,10 +50,15 @@ func fakeIsolation(t *testing.T) string { t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "credentials")) t.Setenv("AWS_EC2_METADATA_DISABLED", "true") t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") - t.Setenv("HTTPS_PROXY", "http://127.0.0.1:9") - t.Setenv("HTTP_PROXY", "http://127.0.0.1:9") - t.Setenv("NO_PROXY", "api.ipify.org,ifconfig.me,icanhazip.com,ident.me") - for _, k := range append(testutil.AWSCredentialEnv(), "no_proxy") { + // Both spellings: Go reads either, but Python and the aws CLI read the + // lowercase ones. + for _, k := range []string{"HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy"} { + t.Setenv(k, "http://127.0.0.1:9") + } + for _, k := range []string{"NO_PROXY", "no_proxy"} { + t.Setenv(k, "api.ipify.org,ifconfig.me,icanhazip.com,ident.me") + } + for _, k := range testutil.AWSCredentialEnv() { t.Setenv(k, "") require.NoError(t, os.Unsetenv(k)) } @@ -121,6 +127,17 @@ func TestAWSIsolationProblems(t *testing.T) { assert.Equal(t, append(want, defaultPathProblems()...), testutil.AWSIsolationProblems()) }) + t.Run("a parent shell's lowercase proxy settings are reported", func(t *testing.T) { + fakeIsolation(t) + t.Setenv("https_proxy", "http://proxy.corp.example:3128") + t.Setenv("no_proxy", "") + require.NoError(t, os.Unsetenv("no_proxy")) + assert.Equal(t, append([]string{ + `https_proxy is not "http://127.0.0.1:9"`, + `no_proxy is not "api.ipify.org,ifconfig.me,icanhazip.com,ident.me"`, + }, defaultPathProblems()...), testutil.AWSIsolationProblems()) + }) + t.Run("HOME outside os.TempDir is reported", func(t *testing.T) { fakeIsolation(t) t.Setenv("HOME", "/") @@ -171,8 +188,10 @@ func TestIsolatedProxy(t *testing.T) { // AWS host. func TestIPLookupHostsAreNotAWS(t *testing.T) { for _, h := range testutil.IPLookupHosts() { - assert.NotContains(t, h, "amazonaws", h) - assert.NotContains(t, h, "aws", h) + for _, suffix := range []string{"amazonaws.com", "aws.amazon.com", "amazonaws.com.cn", "aws"} { + isAWS := h == suffix || strings.HasSuffix(h, "."+suffix) + assert.False(t, isAWS, "%s is an AWS host (suffix %s)", h, suffix) + } } } From f8ba9471249c393789095e620e49bc6108675128 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Arango Gutierrez Date: Sat, 28 Nov 2026 15:23:55 +0100 Subject: [PATCH 13/13] fix(testutil): pin lowercase proxy variables in the isolated test child Python and the aws CLI read https_proxy, http_proxy and no_proxy, not the uppercase spellings Go prefers, so a subprocess of an isolated test could still reach the network through the parent shell's proxy. The child now sets both spellings to the closed local port, and both no-proxy spellings to exactly the IP-lookup allowlist; the guard checks all six. Signed-off-by: Carlos Eduardo Arango Gutierrez --- pkg/testutil/aws_isolation.go | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/pkg/testutil/aws_isolation.go b/pkg/testutil/aws_isolation.go index 512b434aa..6a143b2bb 100644 --- a/pkg/testutil/aws_isolation.go +++ b/pkg/testutil/aws_isolation.go @@ -45,8 +45,14 @@ const ParentHomeEnv = "HOLODECK_TEST_PARENT_HOME" // test servers keep working. const closedPort = "http://127.0.0.1:9" -// proxyEnv lists the proxy variables RunAWSIsolated sets to closedPort. -func proxyEnv() []string { return []string{"HTTPS_PROXY", "HTTP_PROXY"} } +// proxyEnv lists the proxy variables RunAWSIsolated sets to closedPort, in +// both spellings: Go reads either, while Python and the aws CLI read the +// lowercase ones, so a subprocess cannot fall back to a parent shell's proxy. +func proxyEnv() []string { return []string{"HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy"} } + +// noProxyEnv lists the no-proxy variables RunAWSIsolated sets to exactly +// IPLookupHosts, in both spellings. +func noProxyEnv() []string { return []string{"NO_PROXY", "no_proxy"} } // IPLookupHosts lists the public-IP lookup hosts of // pkg/utils.DefaultIPServices. RunAWSIsolated sets NO_PROXY to exactly these, @@ -81,9 +87,9 @@ func AWSCredentialEnv() []string { // The child starts with HOME set to a new temp dir, AWS_CONFIG_FILE and // AWS_SHARED_CREDENTIALS_FILE set to empty files in it, every variable from // AWSCredentialEnv removed, IMDS disabled, and AWS_ENDPOINT_URL, -// HTTPS_PROXY and HTTP_PROXY set to a closed local port, and NO_PROXY set to -// exactly IPLookupHosts (no_proxy removed); see closedPort. Because the child is a new process, the AWS SDK's -// package-init default paths (config.DefaultSharedConfigFiles and +// HTTPS_PROXY and HTTP_PROXY (both spellings) set to a closed local port, and +// NO_PROXY / no_proxy set to exactly IPLookupHosts; see closedPort. Because +// the child is a new process, the AWS SDK's package-init default paths (config.DefaultSharedConfigFiles and // DefaultSharedCredentialsFiles, computed from HOME before TestMain runs) also // point into the temp HOME. Setting the variables in this process would be // too late for them. @@ -136,8 +142,10 @@ func RunAWSIsolated(m *testing.M) int { for _, k := range proxyEnv() { set[k] = closedPort } - set["NO_PROXY"] = noProxyValue() - drop := map[string]bool{"no_proxy": true} + for _, k := range noProxyEnv() { + set[k] = noProxyValue() + } + drop := map[string]bool{} for _, k := range AWSCredentialEnv() { drop[k] = true } @@ -203,11 +211,10 @@ func AWSIsolationProblems() []string { problems = append(problems, fmt.Sprintf("%s is not %q", k, closedPort)) } } - if os.Getenv("NO_PROXY") != noProxyValue() { - problems = append(problems, fmt.Sprintf("NO_PROXY is not %q", noProxyValue())) - } - if _, ok := os.LookupEnv("no_proxy"); ok { - problems = append(problems, "no_proxy is set") + for _, k := range noProxyEnv() { + if os.Getenv(k) != noProxyValue() { + problems = append(problems, fmt.Sprintf("%s is not %q", k, noProxyValue())) + } } if p := config.DefaultSharedConfigFiles[0]; !within(home, p) { problems = append(problems, fmt.Sprintf(