rootaws: bound container creds, refuse login sessions, close two gaps
Astra round 1 P2 fixes on aws-followups-1143 (#1143). 1. Container credentials (AWS_CONTAINER_CREDENTIALS_*) get a bounded client through EndpointCredentialOptions when no client was given; a caller's hook still runs after ours. Login-session credentials (login_session) are refused at load with errLoginSession: the SDK builds their sign-in client during load and offers no hook to bound it. Both under an owned load only; tests stall a local container endpoint and check the refusal comes before any request. 2. hostfence.OpenRootFenceStore's literal config carries rootaws.BoundedHTTPClient(), so the STS exchange the credentials cache runs with the deadline removed ends at the bound. host-env without --group loads through rootaws.LoadDefaultConfig too. Both allowlist entries are gone; the guard accepts an aws.Config literal that sets the bounded client. TestStallCredentialCacheEndsWithoutCallerContext shows a caller that gives up does not leave the request open. 3. Credential tests reach only their fixtures: the test loading client dials loopback only (a dialer Control, kept through the SDK's dialer copies) and uses no proxy, and AWS_IGNORE_CONFIGURED_ENDPOINT_URLS is false. The load stays owned, so the production wrapping runs. withoutWriterTo works around a smithy-go/net/http request-body race the loopback STS fixtures hit about one run in five.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+273
−57
internal/hostenv/awsssm.go+4 −5internal/hostfence/writer.go+6 −1internal/rootaws/guard_test.go+6 −9internal/rootaws/stall.go+42 −4internal/rootaws/stall_credentials_test.go+174 −37internal/rootaws/stall_test.go+41 −1
diff --git a/internal/hostenv/awsssm.go b/internal/hostenv/awsssm.go| index 5c09b5b8e..d0d5375db 100644 |
| --- a/internal/hostenv/awsssm.go |
| +++ b/internal/hostenv/awsssm.go |
| @@ -52,11 +52,10 @@ func openSSMParamsMode(ctx context.Context, awsRegion, kmsKey string, group bool |
| if group { |
| opts = append(opts, config.WithRetryMaxAttempts(1)) |
| } |
| - load := config.LoadDefaultConfig |
| - if group { |
| - load = rootaws.LoadDefaultConfig |
| - } |
| - cfg, err := load(ctx, opts...) |
| + // Both paths load through rootaws, for its stall bounds: write and seed |
| + // run on context.Background(), so nothing else would end a stalled SSM |
| + // call. |
| + cfg, err := rootaws.LoadDefaultConfig(ctx, opts...) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/hostfence/writer.go b/internal/hostfence/writer.go| index 1b2372998..3e9df6c80 100644 |
| --- a/internal/hostfence/writer.go |
| +++ b/internal/hostfence/writer.go |
| @@ -15,6 +15,7 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/service/sts" |
| "github.com/carlosframework/platform/internal/hostfloor" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| ) |
| type fenceCredentials struct { |
| @@ -57,7 +58,11 @@ func OpenRootFenceStore(ctx context.Context, bucket string) (release.Store, erro |
| if err != nil { |
| return nil, err |
| } |
| - cfg := aws.Config{Region: c.Region, Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, ""))} |
| + // The bounded client carries the STS exchange too: the credentials |
| + // cache retrieves with the caller's deadline removed, so only the |
| + // client's own bounds can end a stalled AssumeRole (rootaws stall.go). |
| + cfg := aws.Config{Region: c.Region, HTTPClient: rootaws.BoundedHTTPClient(), |
| + Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, ""))} |
| provider := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), c.Role, func(o *stscreds.AssumeRoleOptions) { o.RoleSessionName = "carlos-root-fence" }) |
| cfg.Credentials = aws.NewCredentialsCache(provider) |
| return &release.S3Store{Client: s3.NewFromConfig(cfg), Bucket: c.Bucket}, nil |
diff --git a/internal/rootaws/guard_test.go b/internal/rootaws/guard_test.go| index 02588d016..8c172a628 100644 |
| --- a/internal/rootaws/guard_test.go |
| +++ b/internal/rootaws/guard_test.go |
| @@ -42,13 +42,6 @@ var boundedClientAllowlist = []allowedConstruction{ |
| // A wrap around the S3 client's own HTTP client, which S3ClientFor |
| // bounded; only the console passes one (console.TimeS3HTTP). |
| {"internal/objstore/aws.go", "NewAWSProvisionerWith", "s3.Options.HTTPClient set", 1, "wraps the bounded client; console-only"}, |
| - // A literal config for the root fence writer's assumed role; its only |
| - // caller (hostfencepass.go) wraps every pass in a 2 min deadline. |
| - {"internal/hostfence/writer.go", "OpenRootFenceStore", "aws.Config literal", 1, "caller's 2 min pass deadline"}, |
| - // carlos system host-env without --group: write (root, the start-up |
| - // script's one-shot step) and seed (an operator's one-shot command) |
| - // load with the SDK directly; the --group path uses rootaws. |
| - {"internal/hostenv/awsssm.go", "openSSMParamsMode", "config.LoadDefaultConfig", 1, "one-shot command; group path is bounded"}, |
| // NewStagingMirrorAt: the test constructor against a local S3 |
| // (leasetest); production uses NewStagingMirror over rootaws. |
| {"internal/lease/staging.go", "NewStagingMirrorAt", "s3.Options literal without rootaws.BoundedHTTPClient()", 1, "test-only constructor NewStagingMirrorAt"}, |
| @@ -60,7 +53,8 @@ var boundedClientAllowlist = []allowedConstruction{ |
| // cannot hide a construction: |
| // - no use of the SDK config package's LoadDefaultConfig or |
| // WithHTTPClient, called or taken as a value; |
| -// - no aws.Config composite literal with fields, and no zero aws.Config |
| +// - no aws.Config composite literal with fields unless it sets |
| +// HTTPClient to rootaws.BoundedHTTPClient(), and no zero aws.Config |
| // to fill in field by field: no empty literal (except as a value |
| // returned, which is a zero value beside an error), no `var c |
| // aws.Config` without a value, no new(aws.Config); |
| @@ -140,6 +134,7 @@ func Literals() (aws.Config, error) { |
| _ = s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| _ = &s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| _ = cfgpkg.LoadOptions{HTTPClient: &http.Client{}} |
| + _ = aws.Config{Region: "r", HTTPClient: rootaws.BoundedHTTPClient()} |
| return aws.Config{}, nil |
| } |
| `, []string{"Literals: aws.Config literal", "Literals: config.LoadOptions literal sets HTTPClient", |
| @@ -459,7 +454,9 @@ func unboundedAWSClients(fset *token.FileSet, info *types.Info, f *ast.File) []a |
| case named == nil: |
| case isAWSConfig(named): |
| if len(n.Elts) > 0 { |
| - hit(n, "aws.Config literal") |
| + if !setsBoundedClient(info, n) { |
| + hit(n, "aws.Config literal") |
| + } |
| } else if _, ok := parent.(*ast.ReturnStmt); !ok { |
| // An empty aws.Config{} returned is a zero value beside |
| // an error; anywhere else it is a config to fill in. |
diff --git a/internal/rootaws/stall.go b/internal/rootaws/stall.go| index fd19ab4cb..fe5b5dac2 100644 |
| --- a/internal/rootaws/stall.go |
| +++ b/internal/rootaws/stall.go |
| @@ -3,6 +3,7 @@ package rootaws |
| import ( |
| "context" |
| "crypto/tls" |
| + "errors" |
| "fmt" |
| "io" |
| "net" |
| @@ -17,6 +18,8 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/aws/defaults" |
| awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" |
| + "github.com/aws/aws-sdk-go-v2/credentials/logincreds" |
| "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" |
| "github.com/aws/aws-sdk-go-v2/credentials/stscreds" |
| "github.com/aws/aws-sdk-go-v2/service/sso" |
| @@ -31,7 +34,8 @@ import ( |
| // response, so a redirect body the client drains is bounded too. The |
| // loaders here (LoadDefaultConfig, LoadStaticConfig) hand out configs whose |
| // HTTPClient is that transport's client, the credential clients the SDK |
| -// builds while loading (STS, SSO) call through it too, and |
| +// builds while loading (STS, SSO, container credentials) call through it |
| +// too, login-session credentials, which cannot, are refused, and |
| // BoundedHTTPClient is the same client for one built from bare service |
| // options. TestAWSClientsAreBounded |
| // fails when root-graph code builds an AWS config or client another way, |
| @@ -89,8 +93,18 @@ type stallLoad struct { |
| idle time.Duration |
| loading *awshttp.BuildableClient |
| owned bool // set while the options run, before the SDK resolves |
| + // login is set when a credential the load resolved is a login session |
| + // (logincreds), directly or as an assumed role's source: its sign-in |
| + // client cannot be bounded, so boundConfig refuses the load. |
| + login bool |
| } |
| +// errLoginSession refuses login-session credentials (a profile's |
| +// login_session): the SDK builds their sign-in client from the config while |
| +// it loads and offers no hook to replace it, so their refresh would have the |
| +// header bound but no body bound. |
| +var errLoginSession = errors.New("rootaws: login-session credentials (login_session) are not supported: their sign-in client cannot be bounded; use another credential source") |
| + |
| func newStallLoad(header, idle time.Duration) *stallLoad { |
| return &stallLoad{idle: idle, loading: loadingClient(header)} |
| } |
| @@ -125,8 +139,10 @@ func (l *stallLoad) options(opts []func(*awsconfig.LoadOptions) error) []func(*a |
| // to one and refuses to load a bundle over anything else, with the header |
| // timeout and HTTP/1.1 only already set (http1Only). The credential clients |
| // the loader builds over it (STS for assume-role and web identity, SSO and |
| -// SSO OIDC) are bounded when their providers are built |
| -// (boundCredentialClients). IMDS keeps this client as the SDK builds it: |
| +// SSO OIDC) are bounded when their providers are built, and container |
| +// credentials, which the SDK would give a default client of their own, get |
| +// a bounded one (boundCredentialClients). Login-session credentials are |
| +// refused (errLoginSession). IMDS keeps this client as the SDK builds it: |
| // IMDS adds its own 250 ms dial and 500 ms header timeouts to a |
| // BuildableClient, which a non-buildable client would lose, and its |
| // provider builds the client after every option has run. Service clients |
| @@ -168,9 +184,27 @@ func http1Only(t *http.Transport) { |
| // SDK applied. Rebuilding the service client instead would rerun its |
| // constructor's finalizers on options that already carry them. |
| func (l *stallLoad) boundCredentialClients(o *awsconfig.LoadOptions) { |
| + endpoint := o.EndpointCredentialOptions |
| + o.EndpointCredentialOptions = func(eo *endpointcreds.Options) { |
| + // Container credentials (AWS_CONTAINER_CREDENTIALS_*): with no |
| + // client the provider would build a default one with no bounds. The |
| + // loading client without its CA bundle, as that default has none. |
| + if eo.HTTPClient == nil { |
| + eo.HTTPClient = mustBoundedClient(l.loading, l.idle) |
| + } |
| + if endpoint != nil { |
| + endpoint(eo) |
| + } |
| + } |
| assumeRole := o.AssumeRoleCredentialOptions |
| o.AssumeRoleCredentialOptions = func(ro *stscreds.AssumeRoleOptions) { |
| if c, ok := ro.Client.(*sts.Client); ok { |
| + // The source credentials the role is assumed with. This SDK |
| + // refuses a login-session source profile itself; the check |
| + // keeps the refusal if a later one accepts it. |
| + if aws.IsCredentialsProvider(c.Options().Credentials, (*logincreds.Provider)(nil)) { |
| + l.login = true |
| + } |
| if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| ro.Client = boundedSTS{c: c, hc: hc} |
| } |
| @@ -271,11 +305,15 @@ func (b boundedSSOOIDC) CreateToken(ctx context.Context, in *ssooidc.CreateToken |
| // would have applied it. The result is not a BuildableClient, so no service |
| // client can rewrite its dialer and drop the progress wrap under a |
| // non-legacy defaults mode. A load whose client the caller overrode |
| -// (stallLoad) is left as given, whatever the client's type. |
| +// (stallLoad) is left as given, whatever the client's type. A load that |
| +// resolved login-session credentials is refused (errLoginSession). |
| func boundConfig(cfg aws.Config, l *stallLoad) (aws.Config, error) { |
| if !l.owned { |
| return cfg, nil |
| } |
| + if l.login || aws.IsCredentialsProvider(cfg.Credentials, (*logincreds.Provider)(nil)) { |
| + return aws.Config{}, errLoginSession |
| + } |
| bc, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| if !ok { |
| return aws.Config{}, fmt.Errorf("rootaws: the SDK loaded over a %T, not the loading client", cfg.HTTPClient) |
diff --git a/internal/rootaws/stall_credentials_test.go b/internal/rootaws/stall_credentials_test.go| index 6b541d182..f6b1c8b1e 100644 |
| --- a/internal/rootaws/stall_credentials_test.go |
| +++ b/internal/rootaws/stall_credentials_test.go |
| @@ -11,19 +11,30 @@ import ( |
| "path/filepath" |
| "sync/atomic" |
| "testing" |
| + "time" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/aws/retry" |
| awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" |
| + "github.com/aws/aws-sdk-go-v2/credentials/stscreds" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| + "github.com/aws/smithy-go/middleware" |
| + smithyhttp "github.com/aws/smithy-go/transport/http" |
| ) |
| // credentialStallServer is a fake credential endpoint for STS (query |
| -// protocol), SSO's GetRoleCredentials and SSO OIDC's CreateToken: it sends |
| -// headers and the start of a well-formed answer, then nothing more until |
| -// the test ends. It counts the requests it gets. |
| -func credentialStallServer(t *testing.T) (string, *atomic.Int32) { |
| +// protocol), SSO's GetRoleCredentials, SSO OIDC's CreateToken and container |
| +// credentials (/container): it sends headers and the start of a well-formed |
| +// answer, then nothing more until the test ends. It counts the requests it |
| +// gets, and sends on ended (buffered) when a request's connection closes |
| +// under it. |
| +func credentialStallServer(t *testing.T) (url string, hits *atomic.Int32, ended <-chan struct{}) { |
| t.Helper() |
| - var hits atomic.Int32 |
| - url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + hits = new(atomic.Int32) |
| + gone := make(chan struct{}, 16) |
| + url = stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| hits.Add(1) |
| var head string |
| switch r.URL.Path { |
| @@ -33,6 +44,9 @@ func credentialStallServer(t *testing.T) (string, *atomic.Int32) { |
| case "/token": |
| w.Header().Set("Content-Type", "application/json") |
| head = `{"accessToken":"A` |
| + case "/container": |
| + w.Header().Set("Content-Type", "application/json") |
| + head = `{"AccessKeyId":"A` |
| default: |
| if err := r.ParseForm(); err != nil { |
| t.Errorf("STS request form: %v", err) |
| @@ -47,24 +61,34 @@ func credentialStallServer(t *testing.T) (string, *atomic.Int32) { |
| io.WriteString(w, head) |
| w.(http.Flusher).Flush() |
| block(r, done) |
| + if r.Context().Err() != nil { |
| + select { |
| + case gone <- struct{}{}: |
| + default: |
| + } |
| + } |
| }) |
| - return url, &hits |
| + return url, hits, gone |
| } |
| -// credentialEnv points every credential service at endpoint, gives the |
| -// loader a home and shared files of its own (absent unless a case writes |
| -// them), and sends anything else to a dead proxy. It returns the home. |
| +// credentialEnv points every credential service at endpoint, makes sure the |
| +// SDK honours that (AWS_IGNORE_CONFIGURED_ENDPOINT_URLS would otherwise send |
| +// it to AWS), and gives the loader a home and shared files of its own |
| +// (absent unless a case writes them). It returns the home. The loads' |
| +// clients dial only loopback (localStallLoad), which is the barrier; the |
| +// endpoints are what make the fixtures the place they dial. |
| func credentialEnv(t *testing.T, endpoint string) string { |
| t.Helper() |
| home := t.TempDir() |
| t.Setenv("HOME", home) |
| t.Setenv("AWS_CONFIG_FILE", filepath.Join(home, "config")) |
| t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(home, "credentials")) |
| + t.Setenv("AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "false") |
| + t.Setenv("AWS_DEFAULTS_MODE", "") |
| + t.Setenv("AWS_CA_BUNDLE", "") |
| for _, svc := range []string{"STS", "SSO", "SSO_OIDC"} { |
| t.Setenv("AWS_ENDPOINT_URL_"+svc, endpoint) |
| } |
| - t.Setenv("HTTP_PROXY", "http://127.0.0.1:9") |
| - t.Setenv("HTTPS_PROXY", "http://127.0.0.1:9") |
| return home |
| } |
| @@ -78,7 +102,7 @@ func writeFile(t *testing.T, path, body string) { |
| } |
| } |
| -func webIdentityEnv(t *testing.T, home string) { |
| +func webIdentityEnv(t *testing.T, home, _ string) { |
| t.Helper() |
| token := filepath.Join(home, "token") |
| writeFile(t, token, "header.payload.signature") |
| @@ -87,6 +111,11 @@ func webIdentityEnv(t *testing.T, home string) { |
| t.Setenv("AWS_ROLE_SESSION_NAME", "s") |
| } |
| +func containerEnv(t *testing.T, _, url string) { |
| + t.Helper() |
| + t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", url+"/container") |
| +} |
| + |
| // ssoCachedToken writes the SSO token cache entry the SDK reads for key (a |
| // start URL, or an sso-session name). |
| func ssoCachedToken(t *testing.T, home, key, body string) { |
| @@ -95,6 +124,42 @@ func ssoCachedToken(t *testing.T, home, key, body string) { |
| writeFile(t, filepath.Join(home, ".aws", "sso", "cache", hex.EncodeToString(sum[:])+".json"), body) |
| } |
| +// withoutWriterTo hides the request stream's WriterTo from net/http. It |
| +// works around a race in the SDK and net/http that a loopback fixture |
| +// answering at once can hit (it is not in the code under test): smithy |
| +// closes a request body as soon as the response headers arrive, a closed |
| +// body's WriteTo returns io.EOF, and net/http, still finishing the request |
| +// write with a WriteTo-based copy, takes that io.EOF for a write error and |
| +// closes the connection under the response. A plain Read returns the same |
| +// io.EOF, which the copy treats as the end of the body. Without this, about |
| +// one STS fixture run in five fails at once with "use of closed network |
| +// connection" instead of at the bound. |
| +func withoutWriterTo(stack *middleware.Stack) error { |
| + return stack.Finalize.Add(middleware.FinalizeMiddlewareFunc("rootawsTestWithoutWriterTo", |
| + func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) { |
| + if req, ok := in.Request.(*smithyhttp.Request); ok { |
| + if rs, ok := req.GetStream().(io.ReadSeeker); ok { |
| + r, err := req.SetStream(struct{ io.ReadSeeker }{rs}) |
| + if err != nil { |
| + return middleware.FinalizeOutput{}, middleware.Metadata{}, err |
| + } |
| + in.Request = r |
| + } |
| + } |
| + return next.HandleFinalize(ctx, in) |
| + }), middleware.After) |
| +} |
| + |
| +// testLoadOptions are the options every fixture load takes: one attempt |
| +// per call, the container provider included, and withoutWriterTo. |
| +var testLoadOptions = []func(*awsconfig.LoadOptions) error{ |
| + awsconfig.WithRetryMaxAttempts(1), |
| + awsconfig.WithAPIOptions([]func(*middleware.Stack) error{withoutWriterTo}), |
| + awsconfig.WithEndpointCredentialOptions(func(o *endpointcreds.Options) { |
| + o.Retryer = retry.AddWithMaxAttempts(retry.NewStandard(), 1) |
| + }), |
| +} |
| + |
| type credentialLoader func(l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) |
| // The non-root branch of LoadDefaultConfig, and its root branch with the |
| @@ -112,53 +177,55 @@ var ( |
| } |
| ) |
| +var profileTarget = []func(*awsconfig.LoadOptions) error{awsconfig.WithSharedConfigProfile("target")} |
| + |
| // A credential response that stalls mid-body fails at the body bound, |
| // through the real loader, for each client the SDK builds while loading |
| -// (#1143): STS for web identity and assume-role, SSO, and SSO OIDC's token |
| -// refresh. Before, these clients had the header bound only and a stalled |
| -// body held the credential refresh for good. |
| +// (#1143): STS for web identity and assume-role, SSO, SSO OIDC's token |
| +// refresh, and container credentials. Before, the first four had the |
| +// header bound only and container credentials no bound at all, so a |
| +// stalled body held the credential refresh for good. |
| func TestStallCredentialBodyFails(t *testing.T) { |
| cases := []struct { |
| name string |
| nonRoot bool // the case reads shared files, which root's branch refuses |
| load credentialLoader |
| - setup func(t *testing.T, home string) |
| + setup func(t *testing.T, home, url string) |
| loadOpts []func(*awsconfig.LoadOptions) error |
| }{ |
| {name: "web identity", load: loadThroughDefault, setup: webIdentityEnv}, |
| {name: "web identity, root branch", load: loadThroughRoot, setup: webIdentityEnv}, |
| - {name: "assume role", nonRoot: true, load: loadThroughDefault, |
| - setup: func(t *testing.T, home string) { |
| + {name: "container", load: loadThroughDefault, setup: containerEnv}, |
| + {name: "container, root branch", load: loadThroughRoot, setup: containerEnv}, |
| + {name: "assume role", nonRoot: true, load: loadThroughDefault, loadOpts: profileTarget, |
| + setup: func(t *testing.T, home, _ string) { |
| writeFile(t, os.Getenv("AWS_CONFIG_FILE"), "[profile target]\nrole_arn = arn:aws:iam::123456789012:role/r\nsource_profile = source\n"+ |
| "[profile source]\naws_access_key_id = ACCESS\naws_secret_access_key = SECRET\n") |
| - }, |
| - loadOpts: []func(*awsconfig.LoadOptions) error{awsconfig.WithSharedConfigProfile("target")}}, |
| - {name: "sso", nonRoot: true, load: loadThroughDefault, |
| - setup: func(t *testing.T, home string) { |
| + }}, |
| + {name: "sso", nonRoot: true, load: loadThroughDefault, loadOpts: profileTarget, |
| + setup: func(t *testing.T, home, _ string) { |
| writeFile(t, os.Getenv("AWS_CONFIG_FILE"), "[profile target]\nsso_start_url = https://start.example.com/start\nsso_region = eu-west-1\n"+ |
| "sso_account_id = 123456789012\nsso_role_name = r\n") |
| ssoCachedToken(t, home, "https://start.example.com/start", `{"accessToken":"T","expiresAt":"2999-01-01T00:00:00Z"}`) |
| - }, |
| - loadOpts: []func(*awsconfig.LoadOptions) error{awsconfig.WithSharedConfigProfile("target")}}, |
| - {name: "sso session token refresh", nonRoot: true, load: loadThroughDefault, |
| - setup: func(t *testing.T, home string) { |
| + }}, |
| + {name: "sso session token refresh", nonRoot: true, load: loadThroughDefault, loadOpts: profileTarget, |
| + setup: func(t *testing.T, home, _ string) { |
| writeFile(t, os.Getenv("AWS_CONFIG_FILE"), "[profile target]\nsso_session = s\nsso_account_id = 123456789012\nsso_role_name = r\n"+ |
| "[sso-session s]\nsso_start_url = https://start.example.com/start\nsso_region = eu-west-1\n") |
| ssoCachedToken(t, home, "s", `{"accessToken":"T","expiresAt":"2000-01-01T00:00:00Z","refreshToken":"R",`+ |
| `"clientId":"C","clientSecret":"S","registrationExpiresAt":"2999-01-01T00:00:00Z"}`) |
| - }, |
| - loadOpts: []func(*awsconfig.LoadOptions) error{awsconfig.WithSharedConfigProfile("target")}}, |
| + }}, |
| } |
| for _, c := range cases { |
| t.Run(c.name, func(t *testing.T) { |
| if c.nonRoot && os.Geteuid() == 0 { |
| t.Skip("reads shared config, which LoadDefaultConfig's root branch refuses") |
| } |
| - url, hits := credentialStallServer(t) |
| + url, hits, _ := credentialStallServer(t) |
| home := credentialEnv(t, url) |
| - c.setup(t, home) |
| - l := newStallLoad(testHeaderTimeout, testIdleTimeout) |
| - cfg, err := c.load(l, append(c.loadOpts, awsconfig.WithRetryMaxAttempts(1))...) |
| + c.setup(t, home, url) |
| + l := localStallLoad(testHeaderTimeout, testIdleTimeout) |
| + cfg, err := c.load(l, append(append([]func(*awsconfig.LoadOptions) error{}, c.loadOpts...), testLoadOptions...)...) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -173,6 +240,76 @@ func TestStallCredentialBodyFails(t *testing.T) { |
| } |
| } |
| +// Login-session credentials, whose sign-in client the SDK gives no way to |
| +// bound, are refused at load, before any request. As an assumed role's |
| +// source this SDK refuses the profile itself; rootaws's check on the |
| +// role's source credentials (boundCredentialClients) is there for an SDK |
| +// that accepts it. |
| +func TestLoginSessionCredentialsRefused(t *testing.T) { |
| + if os.Geteuid() == 0 { |
| + t.Skip("reads shared config, which LoadDefaultConfig's root branch refuses") |
| + } |
| + cases := map[string]struct { |
| + profile string |
| + ours bool // refused by rootaws, not by the SDK |
| + }{ |
| + "login session": {"[profile target]\nlogin_session = arn:aws:iam::123456789012:user/u\n", true}, |
| + "assumed from a login session": {"[profile target]\nrole_arn = arn:aws:iam::123456789012:role/r\nsource_profile = source\n" + |
| + "[profile source]\nlogin_session = arn:aws:iam::123456789012:user/u\n", false}, |
| + } |
| + for name, c := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + url, hits, _ := credentialStallServer(t) |
| + credentialEnv(t, url) |
| + t.Setenv("AWS_ENDPOINT_URL_SIGNIN", url) |
| + writeFile(t, os.Getenv("AWS_CONFIG_FILE"), c.profile) |
| + _, err := loadDefaultConfig(context.Background(), localStallLoad(testHeaderTimeout, testIdleTimeout), |
| + append(append([]func(*awsconfig.LoadOptions) error{}, profileTarget...), testLoadOptions...)...) |
| + if err == nil || (c.ours && !errors.Is(err, errLoginSession)) { |
| + t.Fatalf("loaded login-session credentials: %v", err) |
| + } |
| + if hits.Load() != 0 { |
| + t.Fatal("the refusal came after a request") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The credentials cache retrieves with the caller's deadline removed, so a |
| +// caller that gives up does not end a stalled exchange; the bounded client |
| +// does. This is the fence writer's shape (hostfence.OpenRootFenceStore): a |
| +// literal config over the bounded client, an assume-role provider over STS |
| +// built from it, cached. The caller's short deadline returns at once, and |
| +// the STS request itself still ends at the body bound; a retrieval with no |
| +// deadline at all fails there too. |
| +func TestStallCredentialCacheEndsWithoutCallerContext(t *testing.T) { |
| + url, hits, ended := credentialStallServer(t) |
| + credentialEnv(t, url) |
| + cfg := aws.Config{Region: "eu-west-1", HTTPClient: mustBoundedClient(localStallLoad(testHeaderTimeout, testIdleTimeout).loading, testIdleTimeout), |
| + RetryMaxAttempts: 1, APIOptions: []func(*middleware.Stack) error{withoutWriterTo}, |
| + Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider("ACCESS", "SECRET", ""))} |
| + client := sts.NewFromConfig(cfg, func(o *sts.Options) { o.BaseEndpoint = aws.String(url) }) |
| + cache := aws.NewCredentialsCache(stscreds.NewAssumeRoleProvider(client, "arn:aws:iam::123456789012:role/r")) |
| + |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) |
| + defer cancel() |
| + if _, err := cache.Retrieve(ctx); !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("the caller's deadline did not return it: %v", err) |
| + } |
| + select { |
| + case <-ended: |
| + case <-time.After(stallDeadline): |
| + t.Fatalf("the STS request the caller gave up on was still open after %s", stallDeadline) |
| + } |
| + wantBodyStall(t, stalls(t, func() error { |
| + _, err := cache.Retrieve(context.Background()) |
| + return err |
| + })) |
| + if hits.Load() == 0 { |
| + t.Fatal("the fake STS endpoint was never asked") |
| + } |
| +} |
| + |
| type roundTripFunc func(*http.Request) (*http.Response, error) |
| func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| @@ -180,16 +317,16 @@ func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { retu |
| // A caller's explicit client carries the credential calls too: the loader |
| // bounds only the clients it built over its own. |
| func TestCallerClientCarriesCredentialCalls(t *testing.T) { |
| - url, hits := credentialStallServer(t) |
| + url, hits, _ := credentialStallServer(t) |
| home := credentialEnv(t, url) |
| - webIdentityEnv(t, home) |
| + webIdentityEnv(t, home, url) |
| var seen atomic.Int32 |
| own := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { |
| seen.Add(1) |
| return nil, errors.New("the caller's transport") |
| })} |
| - l := newStallLoad(testHeaderTimeout, testIdleTimeout) |
| - cfg, err := loadDefaultConfig(context.Background(), l, awsconfig.WithHTTPClient(own), awsconfig.WithRetryMaxAttempts(1)) |
| + l := localStallLoad(testHeaderTimeout, testIdleTimeout) |
| + cfg, err := loadDefaultConfig(context.Background(), l, append([]func(*awsconfig.LoadOptions) error{awsconfig.WithHTTPClient(own)}, testLoadOptions...)...) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/rootaws/stall_test.go b/internal/rootaws/stall_test.go| index ff27d3e03..568a0319f 100644 |
| --- a/internal/rootaws/stall_test.go |
| +++ b/internal/rootaws/stall_test.go |
| @@ -17,6 +17,7 @@ import ( |
| "strings" |
| "sync" |
| "sync/atomic" |
| + "syscall" |
| "testing" |
| "time" |
| @@ -202,12 +203,51 @@ const ( |
| stallDeadline = 10 * time.Second |
| ) |
| +// errNotLocal is a test client's refusal to dial anything but loopback. |
| +var errNotLocal = errors.New("rootaws test: refusing to dial a non-loopback address") |
| + |
| +// loopbackOnly is a dialer Control that refuses every address but a |
| +// loopback one. It runs on the address actually dialed, after name |
| +// resolution and before any packet is sent, and survives the dialer copies |
| +// a defaults mode and the bounded client make. |
| +func loopbackOnly(network, address string, _ syscall.RawConn) error { |
| + host, _, err := net.SplitHostPort(address) |
| + if err != nil { |
| + return err |
| + } |
| + if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { |
| + return fmt.Errorf("%w: %s %s", errNotLocal, network, address) |
| + } |
| + return nil |
| +} |
| + |
| +// localStallLoad is newStallLoad for tests: its loading client dials only |
| +// loopback addresses and uses no proxy, whatever the environment says, so a |
| +// test can reach nothing but its own fixtures. The client stays the one the |
| +// load injects, so the loads it runs are owned and take the production |
| +// wrapping path. |
| +func localStallLoad(header, idle time.Duration) *stallLoad { |
| + l := newStallLoad(header, idle) |
| + l.loading = l.loading.WithDialerOptions(func(d *net.Dialer) { d.Control = loopbackOnly }). |
| + WithTransportOptions(func(t *http.Transport) { t.Proxy = nil }) |
| + return l |
| +} |
| + |
| +// The test clients refuse a non-loopback address before dialing it. |
| +func TestLocalStallLoadDialsOnlyLoopback(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + _, err := get(stallClient(t, "http://192.0.2.1", testIdleTimeout)) |
| + if !errors.Is(err, errNotLocal) { |
| + t.Fatalf("a non-loopback dial was not refused: %v", err) |
| + } |
| +} |
| + |
| // stallClient is an S3 client built the way the loaders build one, with |
| // the test bounds (testHeaderTimeout and idle), one attempt per call, |
| // against url. The environment (AWS_CA_BUNDLE, AWS_DEFAULTS_MODE) applies. |
| func stallClient(t *testing.T, url string, idle time.Duration) *awss3.Client { |
| t.Helper() |
| - l := newStallLoad(testHeaderTimeout, idle) |
| + l := localStallLoad(testHeaderTimeout, idle) |
| cfg, err := awsconfig.LoadDefaultConfig(context.Background(), l.options([]func(*awsconfig.LoadOptions) error{ |
| awsconfig.WithRegion("us-east-1"), |
| awsconfig.WithSharedConfigFiles([]string{}), awsconfig.WithSharedCredentialsFiles([]string{}), |