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/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/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/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/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/docs/prerequisites.md b/docs/prerequisites.md index 51ab29c39..1696b180f 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,33 @@ 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 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 +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/go.mod b/go.mod index 51e9bbdb9..c5eefc2b0 100644 --- a/go.mod +++ b/go.mod @@ -5,9 +5,11 @@ 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 + 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 @@ -23,7 +25,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 @@ -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/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/aws/config.go b/internal/aws/config.go new file mode 100644 index 000000000..4b702c145 --- /dev/null +++ b/internal/aws/config.go @@ -0,0 +1,142 @@ +/* + * 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" + "fmt" + "io" + "os" + "sync" + + "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" +) + +// 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." + +// 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, 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) { + 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() + } + 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)) { + preferSSOWarnOnce.Do(func() { warnPreferSSO(log, 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 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 + } + 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) || 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(). +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/internal/aws/config_test.go b/internal/aws/config_test.go new file mode 100644 index 000000000..b2a210420 --- /dev/null +++ b/internal/aws/config_test.go @@ -0,0 +1,355 @@ +/* + * 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 +` + +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 +// isolated HOME. +func TestLoadConfigCredentialPrecedence(t *testing.T) { + const ( + 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 + credentials string // ~/.aws/credentials, "" = no file + noAWSDir bool + env map[string]string + explicitCF string // AWS_SHARED_CREDENTIALS_FILE contents, set explicitly + 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, + wantSSO: true, wantSources: ssoSession, warnProfile: "default", + }, + { + name: "P2 only static keys in credentials file stays static", + credentials: "[default]\n" + staticKeys, + wantSources: []aws.CredentialSource{profile}, + }, + { + 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: fakeEnvKeys, + wantSources: []aws.CredentialSource{envVars}, + }, + { + 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", + 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"}, + wantSSO: true, + wantSources: []aws.CredentialSource{profileSSOLegy, ssoLegacy}, + warnProfile: "dev", + }, + { + 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: 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{ //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", + 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 { + 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) + } + + 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) + 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.go b/internal/aws/sso.go new file mode 100644 index 000000000..17e91e815 --- /dev/null +++ b/internal/aws/sso.go @@ -0,0 +1,61 @@ +/* + * 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 ( + "errors" + "fmt" + "os" + "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 +// 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, +// 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 + 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") + 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) +} diff --git a/internal/aws/sso_test.go b/internal/aws/sso_test.go new file mode 100644 index 000000000..0ffed6634 --- /dev/null +++ b/internal/aws/sso_test.go @@ -0,0 +1,281 @@ +/* + * 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" + ssotypes "github.com/aws/aws-sdk-go-v2/service/sso/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + internalaws "github.com/NVIDIA/holodeck/internal/aws" + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +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 := 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")) + 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") + // 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 +} + +// 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. +func fixtureHome(t *testing.T) string { + t.Helper() + return testutil.IsolatedHome(t) +} + +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{})) + // 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"))) + 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: "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, + 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. 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) { + 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/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/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/cleanup/sso_test.go b/pkg/cleanup/sso_test.go new file mode 100644 index 000000000..ed55c18e2 --- /dev/null +++ b/pkg/cleanup/sso_test.go @@ -0,0 +1,110 @@ +/* + * 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, unless the credentials file also assumes +// a role, which the SSO reload would drop. Retrieve is never called. +func TestNewPrefersSSOOverSharedFileKeys(t *testing.T) { + const keys = "aws_access_key_id = AKIAHOLODECKFAKE0001\naws_secret_access_key = holodeck-fake-secret\n" + tests := []struct { + 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, + 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 { + 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 := testutil.IsolatedHome(t) + 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()) + assert.Equal(t, tc.wantSources, creds.ProviderSources()) + }) + } +} 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 } 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/provider/aws/sso_test.go b/pkg/provider/aws/sso_test.go new file mode 100644 index 000000000..5d1aeed9a --- /dev/null +++ b/pkg/provider/aws/sso_test.go @@ -0,0 +1,156 @@ +/* + * 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" + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +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 + credentials string // non-empty: written to the DEFAULT ~/.aws/credentials + }{ + { + 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", + }, + { + // 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) { + // 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 := 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")) + 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)) + 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"}, + 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") + }) + } +} 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/skill/data/skills/using-holodeck/SKILL.md b/pkg/skill/data/skills/using-holodeck/SKILL.md index 25206dc6c..7465f1227 100644 --- a/pkg/skill/data/skills/using-holodeck/SKILL.md +++ b/pkg/skill/data/skills/using-holodeck/SKILL.md @@ -163,6 +163,14 @@ 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. + 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 diff --git a/pkg/testutil/aws_isolation.go b/pkg/testutil/aws_isolation.go new file mode 100644 index 000000000..6a143b2bb --- /dev/null +++ b/pkg/testutil/aws_isolation.go @@ -0,0 +1,276 @@ +/* + * 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" + "net/http" + "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" + +// 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, 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, +// 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. +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, +// 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. +// +// 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() + } + + 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": closedPort, + } + for _, k := range proxyEnv() { + set[k] = closedPort + } + for _, k := range noProxyEnv() { + set[k] = noProxyValue() + } + 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"`) + } + 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)) + } + } + 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( + "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- ")) + } + 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 { + 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..4e3f835ca --- /dev/null +++ b/pkg/testutil/aws_isolation_test.go @@ -0,0 +1,217 @@ +/* + * 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" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "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") + // 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)) + } + 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", "") + t.Setenv("HTTPS_PROXY", "") + t.Setenv("NO_PROXY", "localhost") + + 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"`, + `HTTPS_PROXY is not "http://127.0.0.1:9"`, + `NO_PROXY is not "api.ipify.org,ifconfig.me,icanhazip.com,ident.me"`, + } + 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", "/") + t.Setenv(testutil.IsolatedHomeEnv, "/") + 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"}, + // 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/", ""}, + } + 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()) + }) + } +} + +// TestIPLookupHostsAreNotAWS: the NO_PROXY exemption may never cover an +// AWS host. +func TestIPLookupHostsAreNotAWS(t *testing.T) { + for _, h := range testutil.IPLookupHosts() { + 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) + } + } +} + +// 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") +} diff --git a/pkg/testutil/isolated_home.go b/pkg/testutil/isolated_home.go new file mode 100644 index 000000000..01c8c91e6 --- /dev/null +++ b/pkg/testutil/isolated_home.go @@ -0,0 +1,49 @@ +/* + * 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" + "path/filepath" + "testing" +) + +// IsolatedHomeEnv is set to the isolated HOME in the child process. +const IsolatedHomeEnv = "HOLODECK_TEST_ISOLATED_HOME" + +// 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 +// child. +func IsolatedHome(t *testing.T) string { + t.Helper() + home := os.Getenv(IsolatedHomeEnv) + if home == "" { + t.Fatalf("IsolatedHome called outside a RunAWSIsolated child (add the package TestMain)") + } + 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 new file mode 100644 index 000000000..abb261136 --- /dev/null +++ b/pkg/testutil/isolated_home_test.go @@ -0,0 +1,45 @@ +/* + * 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/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/NVIDIA/holodeck/pkg/testutil" +) + +// 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) } diff --git a/pkg/utils/aws_isolation_test.go b/pkg/utils/aws_isolation_test.go new file mode 100644 index 000000000..0de1f2999 --- /dev/null +++ b/pkg/utils/aws_isolation_test.go @@ -0,0 +1,55 @@ +/* + * 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 ( + "net/url" + "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) } + +// 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) + } + } +}