From 745204423c03f57e787fb11fc32bbcabc37c7ac7 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:05:22 +0100 Subject: [PATCH] fix(server): scrub ambient AWS credential variables from child processes The archive store falls back to the AWS SDK default chain when no ARTEX_ARCHIVE_S3_* override is set. Those AWS_* variables stayed in the environment after startup, so agent shells, custom tools and MCP stdio servers inherited them. Add them to secretEnv: they are scrubbed after the store is built and kept out of /proc//environ by the seal. The SDK captures what it needs at config load. Tests cover static keys (both spellings), container credentials and web identity fetched after the scrub, and a real New with WithSecretScrub. --- archivestore/credentials_test.go | 117 ++++++++++++++++++++++++++++ server/env_scrub.go | 10 +++ server/envseal_linux_test.go | 11 +++ server/task_archive_startup_test.go | 96 +++++++++++++++++++++++ 4 files changed, 234 insertions(+) diff --git a/archivestore/credentials_test.go b/archivestore/credentials_test.go index 6c667ed..c549f9d 100644 --- a/archivestore/credentials_test.go +++ b/archivestore/credentials_test.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" "time" ) @@ -130,3 +131,119 @@ func TestArchiveIncompleteCredentialOverride(t *testing.T) { } } } + +// The server removes the AWS credential variables from its environment once the +// store is built, so that child processes do not inherit them. The SDK must have +// captured by then everything it needs to sign: the static keys, and for the +// container and web-identity providers the endpoint, token and file path they +// fetch credentials from later (their first fetch happens after the scrub here). +func TestReview318CredentialsSurviveEnvScrub(t *testing.T) { + scrubbed := []string{ + "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY", "AWS_SESSION_TOKEN", + "AWS_CONTAINER_CREDENTIALS_FULL_URI", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_AUTHORIZATION_TOKEN", + "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", + } + for _, mode := range []string{"environment", "environment-alternate-names", "container", "web-identity"} { + t.Run(mode, func(t *testing.T) { + isolateAWSCredentials(t) + for _, key := range append([]string{ + "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_SESSION_TOKEN", + "ARTEX_ARCHIVE_S3_SSE", "ARTEX_ARCHIVE_S3_KMS_KEY_ID", "ARTEX_ARCHIVE_S3_PREFIX", "AWS_ENDPOINT_URL_STS", + }, scrubbed...) { + t.Setenv(key, "") + } + var envScrubbed atomic.Bool + var fetchedAfterScrub atomic.Int32 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if envScrubbed.Load() { + fetchedAfterScrub.Add(1) + } + expiration := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + if mode == "container" { + if r.Header.Get("Authorization") != "fixture-container-token" { + t.Error("missing container authorization token") + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "AccessKeyId": "fixture-key", "SecretAccessKey": "fixture-secret", + "Token": "fixture-session", "Expiration": expiration, + }) + return + } + if err := r.ParseForm(); err != nil || r.PostForm.Get("Action") != "AssumeRoleWithWebIdentity" || + r.PostForm.Get("WebIdentityToken") != "fixture-web-identity-token" || + r.PostForm.Get("RoleArn") != "arn:aws:iam::123456789012:role/archive" { + t.Errorf("unexpected STS request: %v %v", err, r.PostForm) + } + w.Header().Set("Content-Type", "text/xml") + fmt.Fprintf(w, `fixture-keyfixture-secretfixture-session%s`, expiration) + })) + defer provider.Close() + switch mode { + case "environment": + t.Setenv("AWS_ACCESS_KEY_ID", "fixture-key") + t.Setenv("AWS_SECRET_ACCESS_KEY", "fixture-secret") + t.Setenv("AWS_SESSION_TOKEN", "fixture-session") + case "environment-alternate-names": + t.Setenv("AWS_ACCESS_KEY", "fixture-key") + t.Setenv("AWS_SECRET_KEY", "fixture-secret") + t.Setenv("AWS_SESSION_TOKEN", "fixture-session") + case "container": + t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", provider.URL+"/credentials") + t.Setenv("AWS_CONTAINER_AUTHORIZATION_TOKEN", "fixture-container-token") + case "web-identity": + tokenFile := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(tokenFile, []byte("fixture-web-identity-token"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", tokenFile) + t.Setenv("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/archive") + t.Setenv("AWS_ENDPOINT_URL_STS", provider.URL) + } + var authorization, sessionToken atomic.Value + objects := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodHead { + t.Errorf("unexpected S3 operation: %s", r.Method) + } + authorization.Store(r.Header.Get("Authorization")) + sessionToken.Store(r.Header.Get("X-Amz-Security-Token")) + w.WriteHeader(http.StatusNotFound) + })) + defer objects.Close() + t.Setenv("ARTEX_ARCHIVE_STORAGE", "s3") + t.Setenv("ARTEX_ARCHIVE_S3_ENDPOINT", objects.URL) + t.Setenv("ARTEX_ARCHIVE_S3_REGION", "us-east-1") + t.Setenv("ARTEX_ARCHIVE_S3_BUCKET", "fixture") + t.Setenv("ARTEX_ARCHIVE_S3_PATH_STYLE", "true") + store, err := FromEnv() + if err != nil || store == nil { + t.Fatalf("store from environment: %v", err) + } + for _, key := range scrubbed { + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + envScrubbed.Store(true) + + // HEAD is the first request of a download. The fixture answers 404, so + // the call fails; only the signature of the request matters here. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + checksum := strings.Repeat("a", 64) + err = store.Download(ctx, store.URI(1, 2, checksum), filepath.Join(t.TempDir(), "probe"), checksum, 1) + if err == nil { + t.Fatal("the fixture has no object: the download must fail") + } + got, _ := authorization.Load().(string) + if !strings.Contains(got, "Credential=fixture-key/") || !strings.Contains(got, "Signature=") { + t.Fatalf("request not signed with the captured key after the scrub: Authorization=%q (%v)", got, err) + } + if token, _ := sessionToken.Load().(string); token != "fixture-session" { + t.Fatalf("session token lost after the scrub: %q", token) + } + if lazy := mode == "container" || mode == "web-identity"; lazy && fetchedAfterScrub.Load() == 0 { + t.Fatal("the provider was expected to fetch its credentials after the scrub") + } + }) + } +} diff --git a/server/env_scrub.go b/server/env_scrub.go index 2e4d4f7..188bd2a 100644 --- a/server/env_scrub.go +++ b/server/env_scrub.go @@ -8,10 +8,20 @@ import "os" // can carry credentials in their userinfo (http://user:pass@proxy:3128). The archive // store also captures ARTEX_ARCHIVE_S3_* credentials during New, before the scrub, // so the client can use them without passing them to agent child processes. +// +// Without that override the AWS SDK's default chain reads the AWS_* names below +// while the store is built (LoadDefaultConfig) and keeps what it needs: the static +// keys, or the container endpoint and token and the web-identity role and token +// file path it fetches credentials from later. Credentials that come from a shared +// credentials or config file, or from the instance metadata service, are not in +// the environment: the scrub does not hide them from child processes. var secretEnv = []string{ "ARTEX_PG_DSN", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "ARTEX_LLM_PROXY", "ARTEX_LLM_BASE_URL", "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_SESSION_TOKEN", + "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY", "AWS_SESSION_TOKEN", + "AWS_CONTAINER_CREDENTIALS_FULL_URI", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_AUTHORIZATION_TOKEN", + "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", } // ScrubSecretEnv removes secretEnv from the process environment once startup has diff --git a/server/envseal_linux_test.go b/server/envseal_linux_test.go index deaafa7..65f9faf 100644 --- a/server/envseal_linux_test.go +++ b/server/envseal_linux_test.go @@ -60,6 +60,17 @@ func TestSealedEnvironmentHandoff(t *testing.T) { "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID": "AKIATESTONLY", "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY": "s3-secret-test", "ARTEX_ARCHIVE_S3_SESSION_TOKEN": "", + // Ambient AWS credentials the archive store reads when it has no override. + "AWS_ACCESS_KEY_ID": "AKIAAMBIENTTEST", + "AWS_ACCESS_KEY": "AKIAALTERNATETEST", + "AWS_SECRET_ACCESS_KEY": "ambient-secret-test", + "AWS_SECRET_KEY": "alternate-secret-test", + "AWS_SESSION_TOKEN": "", + "AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1:8080/credentials?id=1", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI": "/v2/credentials/test", + "AWS_CONTAINER_AUTHORIZATION_TOKEN": "container-token-test", + "AWS_WEB_IDENTITY_TOKEN_FILE": "/var/run/secrets/token", + "AWS_ROLE_ARN": "arn:aws:iam::123456789012:role/test", } env := os.Environ() for k, v := range want { diff --git a/server/task_archive_startup_test.go b/server/task_archive_startup_test.go index 96f6c94..faccb2b 100644 --- a/server/task_archive_startup_test.go +++ b/server/task_archive_startup_test.go @@ -5,6 +5,7 @@ import ( "net/http" "net/http/httptest" "os" + "os/exec" "path/filepath" "strings" "sync/atomic" @@ -77,3 +78,98 @@ func TestArchiveStoreLoadsCredentialsBeforeSecretScrub(t *testing.T) { t.Fatal("archive client lost its dedicated credentials during startup scrub") } } + +// The archive store may take its identity from the ambient AWS credential +// variables instead of the ARTEX_ARCHIVE_S3_* override. Those variables are as +// sensitive as the override: after startup no child process may inherit them, +// and the S3 client built before the scrub must keep signing with them. +func TestReview318AmbientAWSCredentialsScrubbedAfterArchiveInit(t *testing.T) { + skipWithoutDSN(t) + sh, err := exec.LookPath("sh") + if err != nil { + t.Skip("no sh in PATH") + } + awsNames := []string{ + "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY", "AWS_SESSION_TOKEN", + "AWS_CONTAINER_CREDENTIALS_FULL_URI", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_AUTHORIZATION_TOKEN", + "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", + } + // New scrubs all startup secrets; t.Setenv restores them for the tests that follow. + for _, key := range secretEnv { + t.Setenv(key, os.Getenv(key)) + } + for _, key := range awsNames { + t.Setenv(key, "probe-"+key) + } + var authorization, sessionToken atomic.Value + endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodHead { + t.Errorf("unexpected S3 operation: %s", r.Method) + } + authorization.Store(r.Header.Get("Authorization")) + sessionToken.Store(r.Header.Get("X-Amz-Security-Token")) + w.WriteHeader(http.StatusNotFound) + })) + defer endpoint.Close() + t.Setenv("ARTEX_ARCHIVE_STORAGE", "s3") + t.Setenv("ARTEX_ARCHIVE_S3_ENDPOINT", endpoint.URL) + t.Setenv("ARTEX_ARCHIVE_S3_REGION", "us-east-1") + t.Setenv("ARTEX_ARCHIVE_S3_BUCKET", "fixture") + t.Setenv("ARTEX_ARCHIVE_S3_PREFIX", "archives") + t.Setenv("ARTEX_ARCHIVE_S3_PATH_STYLE", "true") + // No dedicated override: the SDK's default chain reads the AWS_* variables. + t.Setenv("ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "") + t.Setenv("ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "") + t.Setenv("ARTEX_ARCHIVE_S3_SESSION_TOKEN", "") + t.Setenv("ARTEX_ARCHIVE_S3_SSE", "AES256") + t.Setenv("ARTEX_ARCHIVE_S3_KMS_KEY_ID", "") + t.Setenv("AWS_ACCESS_KEY_ID", "ambient-fixture-key") + t.Setenv("AWS_SECRET_ACCESS_KEY", "ambient-fixture-secret") + t.Setenv("AWS_SESSION_TOKEN", "ambient-fixture-session") + t.Setenv("AWS_PROFILE", "") + t.Setenv("AWS_DEFAULT_PROFILE", "") + t.Setenv("AWS_CA_BUNDLE", "") + t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "no-config")) + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "no-credentials")) + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + defer m.Close() + ctx, cancel := context.WithCancel(context.Background()) + cancel() // Exercise real startup without leaving archive/scheduler workers alive. + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir(), WithSecretScrub()) + s.archiveWG.Wait() + if s.archiveStoreErr != nil || s.archiveStore == nil { + t.Fatalf("S3 initialization failed: %v", s.archiveStoreErr) + } + + out, err := exec.Command(sh, "-c", "env").Output() + if err != nil { + t.Fatal(err) + } + env := "\n" + string(out) + for _, key := range awsNames { + if strings.Contains(env, "\n"+key+"=") { + t.Errorf("%s still reaches child processes after startup", key) + } + } + + // HEAD is the first request of a download. The fixture answers 404, so the + // call fails; only the signature of the request matters here. + requestCtx, stop := context.WithTimeout(context.Background(), 5*time.Second) + defer stop() + checksum := strings.Repeat("a", 64) + err = s.archiveStore.Download(requestCtx, s.archiveStore.URI(1, 2, checksum), filepath.Join(t.TempDir(), "probe"), checksum, 1) + if err == nil { + t.Fatal("the fixture has no object: the download must fail") + } + got, _ := authorization.Load().(string) + if !strings.Contains(got, "Credential=ambient-fixture-key/") || !strings.Contains(got, "Signature=") { + t.Fatalf("archive client did not sign with the ambient key after the scrub: Authorization=%q (%v)", got, err) + } + if token, _ := sessionToken.Load().(string); token != "ambient-fixture-session" { + t.Fatalf("archive client lost the ambient session token after the scrub: %q", token) + } +}