rootaws: bound credential clients, keep caller clients, widen guard
The three follow-ups from Astra's scoped check of the AWS stall bounds (#1143, after 0374ac2). 1. The STS, SSO and SSO OIDC clients the SDK builds while loading credentials (web identity, assume-role, SSO, SSO token refresh) now call through the bounded client: each provider's options hook wraps the SDK's client so every call passes the bounded client, built from that client's own HTTP client (CA bundle and defaults mode kept), as a per-operation option. A caller's own hook runs after ours. IMDS keeps its own short timeouts. TestStallCredentialBodyFails stalls each through the real loader (both LoadDefaultConfig branches) against a local fake endpoint. 2. Whether the loaded client is ours is decided by identity, in an option after the caller's, before the SDK resolves anything, so an explicit BuildableClient override (and the SDK's CA-bundle copy of it) stays as given, and so do the credential clients over it. 3. TestAWSClientsAreBounded reads the root binary with type information and also catches HTTPClient assigned on any SDK struct (a loaded config, an option callback, LoadOptions), a zero aws.Config or service Options (var, empty literal, new), with overlay fixtures for each form. The allowlist names each construction (file, function, what, count) instead of whole files; the two constructions the new rules found (grouprollaws newAdapter, objstore's console wrap) are listed with why, and the host-env entry no longer says non-root.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+933
−149
internal/rootaws/config.go+11 −4internal/rootaws/guard_test.go+484 −116internal/rootaws/stall.go+179 −20internal/rootaws/stall_credentials_test.go+202 −0internal/rootaws/stall_test.go+57 −9
diff --git a/internal/rootaws/config.go b/internal/rootaws/config.go| index 07cdecea7..1bd489fee 100644 |
| --- a/internal/rootaws/config.go |
| +++ b/internal/rootaws/config.go |
| @@ -37,7 +37,13 @@ func offcloudCredentials(path string) (aws.Credentials, error) { |
| // both shared-file lists, including paths selected through HOME or AWS_* vars. |
| // Both get the stall bounds (stall.go). |
| func LoadDefaultConfig(ctx context.Context, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| - opts = withStallBounds(opts) |
| + return loadDefaultConfig(ctx, newStallLoad(ResponseHeaderTimeout, BodyIdleTimeout), opts...) |
| +} |
| + |
| +// loadDefaultConfig is LoadDefaultConfig under l's bounds (tests use short |
| +// ones). |
| +func loadDefaultConfig(ctx context.Context, l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| + opts = l.options(opts) |
| var cfg aws.Config |
| var err error |
| if os.Geteuid() != 0 { |
| @@ -48,7 +54,7 @@ func LoadDefaultConfig(ctx context.Context, opts ...func(*awsconfig.LoadOptions) |
| if err != nil { |
| return cfg, err |
| } |
| - return boundConfig(cfg, BodyIdleTimeout) |
| + return boundConfig(cfg, l) |
| } |
| func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| @@ -61,7 +67,8 @@ func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, |
| if os.Getenv("AWS_PROFILE") != "" || os.Getenv("AWS_DEFAULT_PROFILE") != "" { |
| return aws.Config{}, errors.New("static AWS clients do not support AWS_PROFILE or AWS_DEFAULT_PROFILE") |
| } |
| - opts = append(withStallBounds(opts), awsconfig.WithSharedConfigFiles([]string{}), |
| + opts, l := withStallBounds(opts) |
| + opts = append(opts, awsconfig.WithSharedConfigFiles([]string{}), |
| awsconfig.WithSharedCredentialsFiles([]string{}), awsconfig.WithSharedConfigProfile(""), |
| awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, "")), |
| func(o *awsconfig.LoadOptions) error { |
| @@ -74,7 +81,7 @@ func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, |
| if err != nil { |
| return cfg, err |
| } |
| - return boundConfig(cfg, BodyIdleTimeout) |
| + return boundConfig(cfg, l) |
| } |
| func loadRootConfig(ctx context.Context, path string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
diff --git a/internal/rootaws/guard_test.go b/internal/rootaws/guard_test.go| index dc30ebb47..02588d016 100644 |
| --- a/internal/rootaws/guard_test.go |
| +++ b/internal/rootaws/guard_test.go |
| @@ -4,117 +4,278 @@ import ( |
| "bytes" |
| "fmt" |
| "go/ast" |
| - "go/parser" |
| "go/token" |
| + "go/types" |
| "os" |
| "os/exec" |
| "path/filepath" |
| "sort" |
| - "strconv" |
| "strings" |
| "testing" |
| + |
| + "golang.org/x/tools/go/packages" |
| ) |
| -// boundedClientAllowlist names the root-graph files that build an AWS config |
| -// or client some other way, and why each may. A file here is exempt from |
| -// every rule below; anything else in the root binary's graph must get its |
| -// config from this package's loaders or set BoundedHTTPClient. |
| -var boundedClientAllowlist = map[string]string{ |
| +// allowedConstruction is one construction in the root binary's graph that |
| +// the rules below catch and that may stay: n hits of what, inside fn |
| +// (a function, "T.Method", or "var name"), in file. |
| +type allowedConstruction struct { |
| + file, fn, what string |
| + n int |
| + reason string |
| +} |
| + |
| +// boundedClientAllowlist names each construction that builds an AWS config |
| +// or client some other way, and why it may. Anything else in the root |
| +// binary's graph must get its config from this package's loaders or set |
| +// BoundedHTTPClient. An entry that matches nothing, or a different number of |
| +// hits, fails the test. |
| +var boundedClientAllowlist = []allowedConstruction{ |
| // Its own 2 s connect, header and body-read bounds that no defaults |
| // mode can replace (timedClient, boundBody), one attempt per call. |
| - "internal/grouprollaws/config.go": "own bounds: 2 s connect, header and body read", |
| + {"internal/grouprollaws/config.go", "New", "config.LoadDefaultConfig", 1, "own bounds: 2 s connect, header and body read"}, |
| + {"internal/grouprollaws/config.go", "New", "config.WithHTTPClient", 1, "own bounds: 2 s connect, header and body read"}, |
| + // The same adapter's config: timedClient when none was given, then |
| + // frozen so no defaults mode rewrites it, with boundBodyOption on |
| + // every client. |
| + {"internal/grouprollaws/group.go", "newAdapter", "aws.Config.HTTPClient set", 2, "own bounds: 2 s connect, header and body read"}, |
| + // 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": "caller's 2 min pass deadline", |
| - // The non-group path loads with the SDK directly for non-root callers |
| - // (carlos host-env), a one-shot command; the group path uses rootaws. |
| - "internal/hostenv/awsssm.go": "one-shot command; group path is bounded", |
| + {"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": "test-only constructor NewStagingMirrorAt", |
| + {"internal/lease/staging.go", "NewStagingMirrorAt", "s3.Options literal without rootaws.BoundedHTTPClient()", 1, "test-only constructor NewStagingMirrorAt"}, |
| } |
| // The rules, over every non-test Go file of every module package the root |
| -// binary links (linux, amd64 and arm64), outside this package: |
| +// binary links (linux, amd64 and arm64), outside this package, read with |
| +// type information so an import alias, a dot import or a method value |
| +// 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 (an empty one is a zero |
| -// value returned beside an error); |
| +// - no aws.Config composite literal with fields, 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); |
| // - no service Options composite literal (github.com/aws/aws-sdk-go-v2/ |
| -// service/...) unless it sets HTTPClient to rootaws.BoundedHTTPClient(). |
| +// service/...) unless it sets HTTPClient to rootaws.BoundedHTTPClient(), |
| +// and no zero service Options the same ways as aws.Config; |
| +// - no assignment to, and no literal setting, the HTTPClient field of any |
| +// SDK struct (aws.Config, a service's Options in an option callback, |
| +// config.LoadOptions, ...) other than to rootaws.BoundedHTTPClient(). |
| // |
| // Clients built FROM a loaded config or from another client's Options() |
| -// carry its HTTP client, so they need no rule. Outside the scan, because |
| -// the root binary does not link them: cmd/moveprobe (a diagnostic tool), |
| +// carry its HTTP client, so they need no rule. A config or Options held as |
| +// a struct field and left zero is not caught. Outside the scan, because the |
| +// root binary does not link them: cmd/moveprobe (a diagnostic tool), |
| // internal/mail/sessend.go (the console's SES sender), the console's own |
| // packages, and test files. |
| func TestAWSClientsAreBounded(t *testing.T) { |
| if testing.Short() { |
| - t.Skip("lists the root binary's packages with go list") |
| + t.Skip("type-checks the root binary's packages") |
| } |
| root := moduleRoot(t) |
| - files := rootBinaryFiles(t, root) |
| + byArch, files := rootBinaryFiles(t, root) |
| if len(files) < 100 { |
| t.Fatalf("listed only %d root-binary files; the scan would prove nothing", len(files)) |
| } |
| - var bad []string |
| - seen := map[string]bool{} |
| - for _, rel := range files { |
| - if strings.HasPrefix(rel, "internal/rootaws/") { |
| - continue |
| + hits := scanRootBinary(t, root, byArch, files) |
| + |
| + type key struct{ file, fn, what string } |
| + got := map[key][]string{} |
| + for rel, hs := range hits { |
| + for _, h := range hs { |
| + k := key{rel, h.fn, h.what} |
| + got[k] = append(got[k], fmt.Sprintf("%s:%d: %s: %s", rel, h.line, h.fn, h.what)) |
| } |
| - hits := unboundedAWSClients(t, filepath.Join(root, rel)) |
| - if _, ok := boundedClientAllowlist[rel]; ok { |
| - seen[rel] = len(hits) > 0 |
| + } |
| + allowed := map[key]allowedConstruction{} |
| + for _, a := range boundedClientAllowlist { |
| + allowed[key{a.file, a.fn, a.what}] = a |
| + } |
| + var bad []string |
| + for k, where := range got { |
| + if a, ok := allowed[k]; ok && a.n == len(where) { |
| continue |
| } |
| - for _, h := range hits { |
| - bad = append(bad, rel+":"+h) |
| - } |
| + bad = append(bad, where...) |
| } |
| sort.Strings(bad) |
| for _, b := range bad { |
| t.Errorf("%s: an AWS client without rootaws's bounded transport (load the config with rootaws, or set HTTPClient: rootaws.BoundedHTTPClient())", b) |
| } |
| - for rel := range boundedClientAllowlist { |
| - if !seen[rel] { |
| - t.Errorf("%s is allowlisted but builds nothing the rules catch (or left the root binary): drop it from the allowlist", rel) |
| + for k, a := range allowed { |
| + if n := len(got[k]); n != a.n { |
| + t.Errorf("allowlisted %s: %s: %s %d time(s), found %d: correct or drop the entry", a.file, a.fn, a.what, a.n, n) |
| } |
| } |
| } |
| -// The scan itself catches each shape, and lets the bounded ones through. |
| -func TestUnboundedAWSClientsScan(t *testing.T) { |
| - src := `package x |
| -import ( |
| - "github.com/aws/aws-sdk-go-v2/aws" |
| - cfgpkg "github.com/aws/aws-sdk-go-v2/config" |
| - s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| - "github.com/carlosframework/platform/internal/rootaws" |
| -) |
| -func f() { |
| - cfgpkg.LoadDefaultConfig(nil) |
| +// Each fixture file holds constructions the scan must catch, each named |
| +// with its function, and ones it must let through. |
| +var awsGuardFixtures = map[string]struct { |
| + src string |
| + want []string |
| +}{ |
| + "sdkloader.go": {` |
| +func Load(ctx context.Context) { |
| + cfgpkg.LoadDefaultConfig(ctx) |
| cfgpkg.WithHTTPClient(nil) |
| - _ = aws.Config{Region: "r"} |
| - _ = aws.Config{} |
| load := cfgpkg.LoadDefaultConfig |
| _ = load |
| +} |
| +`, []string{"Load: config.LoadDefaultConfig", "Load: config.LoadDefaultConfig", "Load: config.WithHTTPClient"}}, |
| + "literals.go": {` |
| +func Literals() (aws.Config, error) { |
| + _ = aws.Config{Region: "r"} |
| _ = s3.Options{Region: "r"} |
| _ = s3.Options{HTTPClient: nil} |
| _ = s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| _ = &s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| + _ = cfgpkg.LoadOptions{HTTPClient: &http.Client{}} |
| + return aws.Config{}, nil |
| } |
| -` |
| - path := filepath.Join(t.TempDir(), "x.go") |
| - if err := os.WriteFile(path, []byte(src), 0o600); err != nil { |
| - t.Fatal(err) |
| +`, []string{"Literals: aws.Config literal", "Literals: config.LoadOptions literal sets HTTPClient", |
| + "Literals: s3.Options literal without rootaws.BoundedHTTPClient()", "Literals: s3.Options literal without rootaws.BoundedHTTPClient()"}}, |
| + // #1143: a loaded config whose client is then replaced. |
| + "assigned.go": {` |
| +func Assigned(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + cfg.Region = "r" |
| + cfg.HTTPClient = &http.Client{} |
| + return s3.NewFromConfig(cfg) |
| +} |
| + |
| +func AssignedBounded(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + cfg.HTTPClient = rootaws.BoundedHTTPClient() |
| + return s3.NewFromConfig(cfg) |
| +} |
| +`, []string{"Assigned: aws.Config.HTTPClient set"}}, |
| + // #1143: a zero config filled in field by field, three ways. |
| + "zero.go": {` |
| +func ZeroVar() *s3.Client { |
| + var cfg aws.Config |
| + cfg.Region = "r" |
| + cfg.Credentials = credentials.NewStaticCredentialsProvider("A", "S", "") |
| + return s3.NewFromConfig(cfg) |
| +} |
| + |
| +func ZeroLiteral() *s3.Client { |
| + cfg := aws.Config{} |
| + cfg.Region = "r" |
| + return s3.NewFromConfig(cfg) |
| +} |
| + |
| +func ZeroNew() *s3.Client { |
| + cfg := new(aws.Config) |
| + cfg.Region = "r" |
| + return s3.NewFromConfig(*cfg) |
| +} |
| + |
| +func ZeroOptions() *s3.Client { |
| + var o s3.Options |
| + o.Region = "r" |
| + return s3.New(o) |
| +} |
| + |
| +func NotZero(ctx context.Context) *s3.Client { |
| + var p *aws.Config |
| + _ = p |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + cfg.Region = "r" |
| + return s3.NewFromConfig(cfg) |
| +} |
| +`, []string{"ZeroLiteral: zero aws.Config", "ZeroNew: zero aws.Config", "ZeroOptions: zero s3.Options", "ZeroVar: zero aws.Config"}}, |
| + // #1143: option callbacks that swap the client. |
| + "callbacks.go": {` |
| +func Callback(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx, func(o *cfgpkg.LoadOptions) error { |
| + o.HTTPClient = &http.Client{} |
| + return nil |
| + }) |
| + return s3.NewFromConfig(cfg, func(o *s3.Options) { |
| + o.HTTPClient = &http.Client{} |
| + }) |
| +} |
| + |
| +func CallbackBounded(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + return s3.NewFromConfig(cfg, func(o *s3.Options) { |
| + o.HTTPClient = rootaws.BoundedHTTPClient() |
| + o.UsePathStyle = true |
| + }) |
| +} |
| +`, []string{"Callback: config.LoadOptions.HTTPClient set", "Callback: s3.Options.HTTPClient set"}}, |
| + "pkgvar.go": {` |
| +var zeroAtPackageLevel aws.Config |
| +`, []string{"var zeroAtPackageLevel: zero aws.Config"}}, |
| +} |
| + |
| +// The scan catches each form and lets the bounded ones through. The |
| +// fixtures are a package that exists only in an overlay. |
| +func TestUnboundedAWSClientsScan(t *testing.T) { |
| + root := moduleRoot(t) |
| + dir := filepath.Join(root, "internal", "rootaws", "zzawsguardfixture") |
| + overlay := map[string][]byte{} |
| + for name, f := range awsGuardFixtures { |
| + overlay[filepath.Join(dir, name)] = []byte(fixtureFile(f.src)) |
| } |
| - got := unboundedAWSClients(t, path) |
| - if len(got) != 6 { |
| - t.Fatalf("caught %d, want 6: %v", len(got), got) |
| + pkgs := loadTyped(t, root, "amd64", overlay, "./internal/rootaws/zzawsguardfixture") |
| + got := map[string][]string{} |
| + for _, pkg := range pkgs { |
| + for _, f := range pkg.Syntax { |
| + name := filepath.Base(pkg.Fset.File(f.Pos()).Name()) |
| + for _, h := range unboundedAWSClients(pkg.Fset, pkg.TypesInfo, f) { |
| + got[name] = append(got[name], h.fn+": "+h.what) |
| + } |
| + } |
| + } |
| + for name, f := range awsGuardFixtures { |
| + want := append([]string(nil), f.want...) |
| + sort.Strings(want) |
| + sort.Strings(got[name]) |
| + if fmt.Sprint(got[name]) != fmt.Sprint(want) { |
| + t.Errorf("%s: caught %q, want %q", name, got[name], want) |
| + } |
| } |
| } |
| +// fixtureFile is a fixture's source in the fixture package, with every |
| +// import it might use kept in use. |
| +func fixtureFile(src string) string { |
| + return `package zzawsguardfixture |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + cfgpkg "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +var ( |
| + _ context.Context |
| + _ http.Client |
| + _ = aws.String |
| + _ = cfgpkg.WithRegion |
| + _ = credentials.NewStaticCredentialsProvider |
| + _ = s3.New |
| + _ = rootaws.BoundedHTTPClient |
| +) |
| +` + src |
| +} |
| + |
| func moduleRoot(t *testing.T) string { |
| t.Helper() |
| dir, err := os.Getwd() |
| @@ -133,13 +294,18 @@ func moduleRoot(t *testing.T) string { |
| } |
| } |
| -// rootBinaryFiles is every non-test Go file, relative to root, of every |
| -// module package the root binary links on linux/amd64 or linux/arm64. |
| -func rootBinaryFiles(t *testing.T, root string) []string { |
| +var rootBinaryArchs = []string{"amd64", "arm64"} |
| + |
| +// rootBinaryFiles lists the module packages the root binary links on |
| +// linux/amd64 and linux/arm64, with their non-test Go files relative to |
| +// root (byArch: arch -> import path -> files), and every such file of |
| +// either architecture (files). |
| +func rootBinaryFiles(t *testing.T, root string) (byArch map[string]map[string][]string, files []string) { |
| t.Helper() |
| + byArch = map[string]map[string][]string{} |
| set := map[string]bool{} |
| - for _, arch := range []string{"amd64", "arm64"} { |
| - cmd := exec.Command("go", "list", "-deps", "-f", `{{if not .Standard}}{{.Dir}}|{{join .GoFiles ","}}{{end}}`, ".") |
| + for _, arch := range rootBinaryArchs { |
| + cmd := exec.Command("go", "list", "-deps", "-f", `{{if not .Standard}}{{.ImportPath}}|{{.Dir}}|{{join .GoFiles ","}}{{end}}`, ".") |
| cmd.Dir = root |
| cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0") |
| var stderr bytes.Buffer |
| @@ -148,77 +314,205 @@ func rootBinaryFiles(t *testing.T, root string) []string { |
| if err != nil { |
| t.Fatalf("go list (linux/%s): %v: %s", arch, err, stderr.String()) |
| } |
| + pkgs := map[string][]string{} |
| for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { |
| - dir, names, _ := strings.Cut(line, "|") |
| + parts := strings.SplitN(line, "|", 3) |
| + if len(parts) != 3 { |
| + continue |
| + } |
| + path, dir, names := parts[0], parts[1], parts[2] |
| rel, err := filepath.Rel(root, dir) |
| if dir == "" || err != nil || strings.HasPrefix(rel, "..") { |
| continue // the standard library and other modules |
| } |
| for _, n := range strings.Split(names, ",") { |
| if n != "" { |
| - set[filepath.ToSlash(filepath.Join(rel, n))] = true |
| + f := filepath.ToSlash(filepath.Join(rel, n)) |
| + pkgs[path] = append(pkgs[path], f) |
| + set[f] = true |
| } |
| } |
| } |
| + byArch[arch] = pkgs |
| } |
| - files := make([]string, 0, len(set)) |
| for f := range set { |
| files = append(files, f) |
| } |
| sort.Strings(files) |
| - return files |
| + return byArch, files |
| } |
| -// unboundedAWSClients reports, as line:what, each construction in the file |
| -// the rules forbid. |
| -func unboundedAWSClients(t *testing.T, path string) []string { |
| +// scanRootBinary type-checks every root-binary file outside this package |
| +// once, under amd64 and then, for any file only arm64 compiles, under |
| +// arm64, and returns the scan's hits by file. |
| +func scanRootBinary(t *testing.T, root string, byArch map[string]map[string][]string, files []string) map[string][]awsHit { |
| t.Helper() |
| - fset := token.NewFileSet() |
| - f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) |
| - if err != nil { |
| - t.Fatalf("parse %s: %v", path, err) |
| + want := map[string]bool{} |
| + for _, f := range files { |
| + if !strings.HasPrefix(f, "internal/rootaws/") { |
| + want[f] = true |
| + } |
| } |
| - names := map[string]string{} // local import name -> path |
| - for _, imp := range f.Imports { |
| - p, _ := strconv.Unquote(imp.Path.Value) |
| - name := p[strings.LastIndex(p, "/")+1:] |
| - if imp.Name != nil { |
| - name = imp.Name.Name |
| + hits := map[string][]awsHit{} |
| + done := map[string]bool{} |
| + for _, arch := range rootBinaryArchs { |
| + var paths []string |
| + for path, fs := range byArch[arch] { |
| + for _, f := range fs { |
| + if want[f] && !done[f] { |
| + paths = append(paths, path) |
| + break |
| + } |
| + } |
| + } |
| + if len(paths) == 0 { |
| + continue |
| + } |
| + sort.Strings(paths) |
| + for _, pkg := range loadTyped(t, root, arch, nil, paths...) { |
| + for _, f := range pkg.Syntax { |
| + rel, err := filepath.Rel(root, pkg.Fset.File(f.Pos()).Name()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rel = filepath.ToSlash(rel) |
| + if !want[rel] || done[rel] { |
| + continue |
| + } |
| + done[rel] = true |
| + if hs := unboundedAWSClients(pkg.Fset, pkg.TypesInfo, f); len(hs) > 0 { |
| + hits[rel] = hs |
| + } |
| + } |
| } |
| - names[name] = p |
| } |
| - pkgOf := func(e ast.Expr) (pkg, sel string) { |
| - s, ok := e.(*ast.SelectorExpr) |
| - if !ok { |
| - return "", "" |
| + for f := range want { |
| + if !done[f] { |
| + t.Errorf("%s: in the root binary but never type-checked", f) |
| } |
| - id, ok := s.X.(*ast.Ident) |
| - if !ok { |
| - return "", "" |
| + } |
| + return hits |
| +} |
| + |
| +// loadTyped loads patterns with syntax and type information for |
| +// linux/arch, and fails the test on any load or type error. |
| +func loadTyped(t *testing.T, root, arch string, overlay map[string][]byte, patterns ...string) []*packages.Package { |
| + t.Helper() |
| + cfg := &packages.Config{Dir: root, Overlay: overlay, |
| + Env: append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0"), |
| + Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports} |
| + pkgs, err := packages.Load(cfg, patterns...) |
| + if err != nil { |
| + t.Fatalf("load (linux/%s): %v", arch, err) |
| + } |
| + var errs []string |
| + for _, p := range pkgs { |
| + for _, e := range p.Errors { |
| + errs = append(errs, e.Error()) |
| } |
| - return names[id.Name], s.Sel.Name |
| } |
| - const sdk = "github.com/aws/aws-sdk-go-v2/" |
| - var hits []string |
| + if len(errs) > 0 || len(pkgs) == 0 { |
| + t.Fatalf("load (linux/%s) of %d package(s): %s", arch, len(pkgs), strings.Join(errs, "; ")) |
| + } |
| + return pkgs |
| +} |
| + |
| +const ( |
| + sdkPath = "github.com/aws/aws-sdk-go-v2/" |
| + rootawsPath = "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +// awsHit is one construction the rules forbid: its line, the function (or |
| +// package-level var) holding it, and what it is. |
| +type awsHit struct { |
| + line int |
| + fn, what string |
| +} |
| + |
| +// unboundedAWSClients reports each construction in f the rules forbid. |
| +func unboundedAWSClients(fset *token.FileSet, info *types.Info, f *ast.File) []awsHit { |
| + var hits []awsHit |
| + var stack []ast.Node |
| hit := func(n ast.Node, what string) { |
| - hits = append(hits, fmt.Sprintf("%d: %s", fset.Position(n.Pos()).Line, what)) |
| + hits = append(hits, awsHit{line: fset.Position(n.Pos()).Line, fn: enclosing(stack), what: what}) |
| } |
| ast.Inspect(f, func(n ast.Node) bool { |
| + if n == nil { |
| + stack = stack[:len(stack)-1] |
| + return true |
| + } |
| + var parent ast.Node |
| + if len(stack) > 0 { |
| + parent = stack[len(stack)-1] |
| + } |
| + stack = append(stack, n) |
| switch n := n.(type) { |
| - case *ast.SelectorExpr: |
| + case *ast.Ident: |
| // A call or a func value (load := config.LoadDefaultConfig). |
| - if pkg, sel := pkgOf(n); pkg == sdk+"config" && (sel == "LoadDefaultConfig" || sel == "WithHTTPClient") { |
| - hit(n, "config."+sel) |
| + if fn, ok := info.Uses[n].(*types.Func); ok && fn.Pkg() != nil && fn.Pkg().Path() == sdkPath+"config" && |
| + (fn.Name() == "LoadDefaultConfig" || fn.Name() == "WithHTTPClient") { |
| + hit(n, "config."+fn.Name()) |
| } |
| case *ast.CompositeLit: |
| - pkg, sel := pkgOf(n.Type) |
| + named := namedStruct(info.TypeOf(n)) |
| switch { |
| - case pkg == sdk+"aws" && sel == "Config" && len(n.Elts) > 0: |
| - // An empty aws.Config{} is a zero value returned beside an |
| - // error; it configures nothing. |
| - hit(n, "aws.Config literal") |
| - case strings.HasPrefix(pkg, sdk+"service/") && sel == "Options" && !setsBoundedClient(n, names): |
| - hit(n, pkg[len(sdk):]+".Options literal without rootaws.BoundedHTTPClient()") |
| + case named == nil: |
| + case isAWSConfig(named): |
| + if len(n.Elts) > 0 { |
| + 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. |
| + hit(n, "zero aws.Config") |
| + } |
| + case isServiceOptions(named): |
| + if !setsBoundedClient(info, n) { |
| + hit(n, typeName(named)+" literal without rootaws.BoundedHTTPClient()") |
| + } |
| + case isSDK(named): |
| + for _, e := range n.Elts { |
| + if kv, ok := e.(*ast.KeyValueExpr); ok && keyName(kv) == "HTTPClient" && !isBoundedCall(info, kv.Value) { |
| + hit(n, typeName(named)+" literal sets HTTPClient") |
| + } |
| + } |
| + } |
| + case *ast.ValueSpec: |
| + if n.Type != nil && len(n.Values) == 0 { |
| + // A nil pointer is not a config; a value is a zero one. |
| + if _, ptr := info.TypeOf(n.Type).(*types.Pointer); ptr { |
| + break |
| + } |
| + if named := namedStruct(info.TypeOf(n.Type)); named != nil && isConfigType(named) { |
| + hit(n, "zero "+typeName(named)) |
| + } |
| + } |
| + case *ast.CallExpr: |
| + if id, ok := n.Fun.(*ast.Ident); ok && len(n.Args) == 1 { |
| + if _, builtin := info.Uses[id].(*types.Builtin); builtin && id.Name == "new" { |
| + if named := namedStruct(info.TypeOf(n.Args[0])); named != nil && isConfigType(named) { |
| + hit(n, "zero "+typeName(named)) |
| + } |
| + } |
| + } |
| + case *ast.AssignStmt: |
| + for i, lhs := range n.Lhs { |
| + sel, ok := lhs.(*ast.SelectorExpr) |
| + if !ok { |
| + continue |
| + } |
| + s := info.Selections[sel] |
| + if s == nil || s.Kind() != types.FieldVal || s.Obj().Name() != "HTTPClient" || s.Obj().Pkg() == nil || |
| + !strings.HasPrefix(s.Obj().Pkg().Path(), sdkPath) { |
| + continue |
| + } |
| + if len(n.Rhs) == len(n.Lhs) && isBoundedCall(info, n.Rhs[i]) { |
| + continue |
| + } |
| + recv := "?" |
| + if named := namedStruct(s.Recv()); named != nil { |
| + recv = typeName(named) |
| + } |
| + hit(sel, recv+".HTTPClient set") |
| } |
| } |
| return true |
| @@ -226,25 +520,99 @@ func unboundedAWSClients(t *testing.T, path string) []string { |
| return hits |
| } |
| -func setsBoundedClient(lit *ast.CompositeLit, names map[string]string) bool { |
| - for _, e := range lit.Elts { |
| - kv, ok := e.(*ast.KeyValueExpr) |
| - if !ok { |
| - continue |
| - } |
| - if k, ok := kv.Key.(*ast.Ident); !ok || k.Name != "HTTPClient" { |
| - continue |
| - } |
| - call, ok := kv.Value.(*ast.CallExpr) |
| - if !ok || len(call.Args) != 0 { |
| - return false |
| +// enclosing names the function declaration (or package-level var) on the |
| +// stack: "F", "T.M", or "var v". |
| +func enclosing(stack []ast.Node) string { |
| + for _, n := range stack { |
| + switch n := n.(type) { |
| + case *ast.FuncDecl: |
| + if n.Recv != nil && len(n.Recv.List) == 1 { |
| + r := n.Recv.List[0].Type |
| + if s, ok := r.(*ast.StarExpr); ok { |
| + r = s.X |
| + } |
| + if ix, ok := r.(*ast.IndexExpr); ok { |
| + r = ix.X |
| + } |
| + if id, ok := r.(*ast.Ident); ok { |
| + return id.Name + "." + n.Name.Name |
| + } |
| + } |
| + return n.Name.Name |
| + case *ast.ValueSpec: |
| + if len(n.Names) > 0 { |
| + return "var " + n.Names[0].Name |
| + } |
| } |
| - s, ok := call.Fun.(*ast.SelectorExpr) |
| - if !ok { |
| - return false |
| + } |
| + return "package" |
| +} |
| + |
| +// namedStruct is t (or what it points to) as a named struct type, or nil. |
| +func namedStruct(t types.Type) *types.Named { |
| + if p, ok := t.(*types.Pointer); ok { |
| + t = p.Elem() |
| + } |
| + n, ok := types.Unalias(t).(*types.Named) |
| + if !ok { |
| + return nil |
| + } |
| + if _, ok := n.Underlying().(*types.Struct); !ok { |
| + return nil |
| + } |
| + return n |
| +} |
| + |
| +func isSDK(n *types.Named) bool { |
| + return n.Obj().Pkg() != nil && strings.HasPrefix(n.Obj().Pkg().Path(), sdkPath) |
| +} |
| + |
| +func isAWSConfig(n *types.Named) bool { |
| + return n.Obj().Pkg() != nil && n.Obj().Pkg().Path() == sdkPath+"aws" && n.Obj().Name() == "Config" |
| +} |
| + |
| +func isServiceOptions(n *types.Named) bool { |
| + return n.Obj().Pkg() != nil && strings.HasPrefix(n.Obj().Pkg().Path(), sdkPath+"service/") && n.Obj().Name() == "Options" |
| +} |
| + |
| +// isConfigType is a struct an AWS client is built from: aws.Config or a |
| +// service's Options. |
| +func isConfigType(n *types.Named) bool { return isAWSConfig(n) || isServiceOptions(n) } |
| + |
| +// typeName is "s3.Options", "aws.Config": the package's name and the type's. |
| +func typeName(n *types.Named) string { return n.Obj().Pkg().Name() + "." + n.Obj().Name() } |
| + |
| +func keyName(kv *ast.KeyValueExpr) string { |
| + if id, ok := kv.Key.(*ast.Ident); ok { |
| + return id.Name |
| + } |
| + return "" |
| +} |
| + |
| +func setsBoundedClient(info *types.Info, lit *ast.CompositeLit) bool { |
| + for _, e := range lit.Elts { |
| + if kv, ok := e.(*ast.KeyValueExpr); ok && keyName(kv) == "HTTPClient" { |
| + return isBoundedCall(info, kv.Value) |
| } |
| - id, ok := s.X.(*ast.Ident) |
| - return ok && names[id.Name] == "github.com/carlosframework/platform/internal/rootaws" && s.Sel.Name == "BoundedHTTPClient" |
| } |
| return false |
| } |
| + |
| +// isBoundedCall is a call of rootaws.BoundedHTTPClient(). |
| +func isBoundedCall(info *types.Info, e ast.Expr) bool { |
| + call, ok := ast.Unparen(e).(*ast.CallExpr) |
| + if !ok || len(call.Args) != 0 { |
| + return false |
| + } |
| + var id *ast.Ident |
| + switch f := ast.Unparen(call.Fun).(type) { |
| + case *ast.SelectorExpr: |
| + id = f.Sel |
| + case *ast.Ident: |
| + id = f |
| + default: |
| + return false |
| + } |
| + fn, ok := info.Uses[id].(*types.Func) |
| + return ok && fn.Pkg() != nil && fn.Pkg().Path() == rootawsPath && fn.Name() == "BoundedHTTPClient" |
| +} |
diff --git a/internal/rootaws/stall.go b/internal/rootaws/stall.go| index 394d5123e..fd19ab4cb 100644 |
| --- a/internal/rootaws/stall.go |
| +++ b/internal/rootaws/stall.go |
| @@ -17,6 +17,11 @@ 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/ssocreds" |
| + "github.com/aws/aws-sdk-go-v2/credentials/stscreds" |
| + "github.com/aws/aws-sdk-go-v2/service/sso" |
| + "github.com/aws/aws-sdk-go-v2/service/ssooidc" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| ) |
| // The invariant (stopping rule 2, root-worker liveness): every response a |
| @@ -25,8 +30,10 @@ import ( |
| // limit measured per response, before net/http's own client sees the |
| // 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, and BoundedHTTPClient is the same |
| -// client for one built from bare service options. TestAWSClientsAreBounded |
| +// HTTPClient is that transport's client, the credential clients the SDK |
| +// builds while loading (STS, SSO) call through it too, 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, |
| // apart from its commented allowlist. |
| // |
| @@ -67,24 +74,63 @@ const ( |
| BodyIdleTimeout = 120 * time.Second |
| ) |
| -// withStallBounds puts the loading client ahead of the caller's options, so |
| -// an explicit WithHTTPClient from a caller still wins: a deliberate |
| -// override, which only tests use (awsmanaged's fake transports) and |
| -// TestAWSClientsAreBounded keeps out of the root binary's production code. |
| -// boundConfig finishes the job once the config loads. |
| -func withStallBounds(opts []func(*awsconfig.LoadOptions) error) []func(*awsconfig.LoadOptions) error { |
| - return append([]func(*awsconfig.LoadOptions) error{awsconfig.WithHTTPClient(loadingClient(ResponseHeaderTimeout))}, opts...) |
| +// stallLoad is one config load under the stall bounds: the body bound, the |
| +// loading client it injects (which carries the header bound), and whether |
| +// that client is still the one the SDK loads over once every option has run |
| +// (owned). A caller's explicit |
| +// client (WithHTTPClient, or an option setting LoadOptions.HTTPClient) is a |
| +// deliberate override, which only tests use (awsmanaged's fake transports) |
| +// and TestAWSClientsAreBounded keeps out of the root binary's production |
| +// code: it is left as given, and so are the credential clients built over |
| +// it. Ownership is decided by identity before the SDK resolves anything, |
| +// so a CA bundle, which the SDK applies to a copy of whichever |
| +// BuildableClient it was given, does not blur ours with a caller's. |
| +type stallLoad struct { |
| + idle time.Duration |
| + loading *awshttp.BuildableClient |
| + owned bool // set while the options run, before the SDK resolves |
| +} |
| + |
| +func newStallLoad(header, idle time.Duration) *stallLoad { |
| + return &stallLoad{idle: idle, loading: loadingClient(header)} |
| +} |
| + |
| +// withStallBounds is the production bounds around the caller's options. |
| +func withStallBounds(opts []func(*awsconfig.LoadOptions) error) ([]func(*awsconfig.LoadOptions) error, *stallLoad) { |
| + l := newStallLoad(ResponseHeaderTimeout, BodyIdleTimeout) |
| + return l.options(opts), l |
| +} |
| + |
| +// options puts the loading client ahead of the caller's options, so a |
| +// caller's own client still wins, and an option after them that records |
| +// whether it did and, if not, bounds the credential clients |
| +// (boundCredentialClients). The loaders' own options that follow set neither |
| +// the HTTP client nor a credential provider's options. boundConfig finishes |
| +// the job once the config loads. |
| +func (l *stallLoad) options(opts []func(*awsconfig.LoadOptions) error) []func(*awsconfig.LoadOptions) error { |
| + out := make([]func(*awsconfig.LoadOptions) error, 0, len(opts)+2) |
| + out = append(out, awsconfig.WithHTTPClient(l.loading)) |
| + out = append(out, opts...) |
| + return append(out, func(o *awsconfig.LoadOptions) error { |
| + l.owned = o.HTTPClient == aws.HTTPClient(l.loading) |
| + if l.owned { |
| + l.boundCredentialClients(o) |
| + } |
| + return nil |
| + }) |
| } |
| // loadingClient is the HTTP client the SDK loads the config over: a |
| // BuildableClient, because the SDK applies a CA bundle (AWS_CA_BUNDLE) only |
| // 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 (STS, SSO, IMDS) keep this client, so they get the |
| -// header timeout but not the body limit; IMDS adds its own 250 ms dial and |
| -// 500 ms header timeouts to a BuildableClient, which a non-buildable client |
| -// would lose. Service clients built from the loaded config get |
| -// boundConfig's client instead. |
| +// 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: |
| +// 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 |
| +// built from the loaded config get boundConfig's client. |
| func loadingClient(header time.Duration) *awshttp.BuildableClient { |
| return awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) { |
| t.ResponseHeaderTimeout = header |
| @@ -113,19 +159,128 @@ func http1Only(t *http.Transport) { |
| } |
| } |
| +// boundCredentialClients bounds the clients the SDK builds for credential |
| +// providers while it loads: each provider's options hook gets ours first, |
| +// then any hook the caller set, so a client the caller's hook supplies stays |
| +// as given. Ours wraps the SDK's client so every call it makes passes the |
| +// bounded client as a per-operation option, built from that client's own |
| +// HTTP client: the loading client with the CA bundle and defaults mode the |
| +// 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) { |
| + assumeRole := o.AssumeRoleCredentialOptions |
| + o.AssumeRoleCredentialOptions = func(ro *stscreds.AssumeRoleOptions) { |
| + if c, ok := ro.Client.(*sts.Client); ok { |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + ro.Client = boundedSTS{c: c, hc: hc} |
| + } |
| + } |
| + if assumeRole != nil { |
| + assumeRole(ro) |
| + } |
| + } |
| + webIdentity := o.WebIdentityRoleCredentialOptions |
| + o.WebIdentityRoleCredentialOptions = func(wo *stscreds.WebIdentityRoleOptions) { |
| + // The SDK runs this hook twice: once with no client, to see whether |
| + // the options name one, then on the provider over its own client. |
| + if c, ok := wo.Client.(*sts.Client); ok { |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + wo.Client = boundedSTS{c: c, hc: hc} |
| + } |
| + } |
| + if webIdentity != nil { |
| + webIdentity(wo) |
| + } |
| + } |
| + ssoProvider := o.SSOProviderOptions |
| + o.SSOProviderOptions = func(so *ssocreds.Options) { |
| + if c, ok := so.Client.(*sso.Client); ok { |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + so.Client = boundedSSO{c: c, hc: hc} |
| + } |
| + } |
| + if ssoProvider != nil { |
| + ssoProvider(so) |
| + } |
| + } |
| + ssoToken := o.SSOTokenProviderOptions |
| + o.SSOTokenProviderOptions = func(to *ssocreds.SSOTokenProviderOptions) { |
| + if c, ok := to.Client.(*ssooidc.Client); ok { |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + to.Client = boundedSSOOIDC{c: c, hc: hc} |
| + } |
| + } |
| + if ssoToken != nil { |
| + ssoToken(to) |
| + } |
| + } |
| +} |
| + |
| +// credentialClient is the bounded client over a credential client's own |
| +// HTTP client, which is the loading client (or the SDK's CA-bundle copy of |
| +// it, with the client's defaults mode applied) while the load is owned. |
| +func (l *stallLoad) credentialClient(hc any) (aws.HTTPClient, bool) { |
| + bc, ok := hc.(*awshttp.BuildableClient) |
| + if !ok { |
| + return nil, false |
| + } |
| + return mustBoundedClient(bc, l.idle), true |
| +} |
| + |
| +// boundedSTS, boundedSSO and boundedSSOOIDC are the SDK's credential |
| +// clients with the bounded HTTP client set ahead of the provider's own |
| +// per-operation options. |
| +type boundedSTS struct { |
| + c *sts.Client |
| + hc aws.HTTPClient |
| +} |
| + |
| +func (b boundedSTS) use(o *sts.Options) { o.HTTPClient = b.hc } |
| + |
| +func (b boundedSTS) AssumeRole(ctx context.Context, in *sts.AssumeRoleInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error) { |
| + return b.c.AssumeRole(ctx, in, append([]func(*sts.Options){b.use}, optFns...)...) |
| +} |
| + |
| +func (b boundedSTS) AssumeRoleWithWebIdentity(ctx context.Context, in *sts.AssumeRoleWithWebIdentityInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleWithWebIdentityOutput, error) { |
| + return b.c.AssumeRoleWithWebIdentity(ctx, in, append([]func(*sts.Options){b.use}, optFns...)...) |
| +} |
| + |
| +type boundedSSO struct { |
| + c *sso.Client |
| + hc aws.HTTPClient |
| +} |
| + |
| +func (b boundedSSO) GetRoleCredentials(ctx context.Context, in *sso.GetRoleCredentialsInput, optFns ...func(*sso.Options)) (*sso.GetRoleCredentialsOutput, error) { |
| + use := func(o *sso.Options) { o.HTTPClient = b.hc } |
| + return b.c.GetRoleCredentials(ctx, in, append([]func(*sso.Options){use}, optFns...)...) |
| +} |
| + |
| +type boundedSSOOIDC struct { |
| + c *ssooidc.Client |
| + hc aws.HTTPClient |
| +} |
| + |
| +func (b boundedSSOOIDC) CreateToken(ctx context.Context, in *ssooidc.CreateTokenInput, optFns ...func(*ssooidc.Options)) (*ssooidc.CreateTokenOutput, error) { |
| + use := func(o *ssooidc.Options) { o.HTTPClient = b.hc } |
| + return b.c.CreateToken(ctx, in, append([]func(*ssooidc.Options){use}, optFns...)...) |
| +} |
| + |
| // boundConfig replaces the loaded config's HTTP client with the bounded |
| // one, built from the client the SDK loaded over (so a CA bundle it applied |
| // stays) with the config's defaults mode applied now, as each service client |
| // 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 client that is not a BuildableClient is a |
| -// caller's own (withStallBounds) and is left as given. |
| -func boundConfig(cfg aws.Config, idle time.Duration) (aws.Config, error) { |
| +// non-legacy defaults mode. A load whose client the caller overrode |
| +// (stallLoad) is left as given, whatever the client's type. |
| +func boundConfig(cfg aws.Config, l *stallLoad) (aws.Config, error) { |
| + if !l.owned { |
| + return cfg, nil |
| + } |
| bc, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| if !ok { |
| - return cfg, nil |
| + return aws.Config{}, fmt.Errorf("rootaws: the SDK loaded over a %T, not the loading client", cfg.HTTPClient) |
| } |
| - client, err := boundedClient(withDefaultsMode(bc, cfg), idle) |
| + client, err := boundedClient(withDefaultsMode(bc, cfg), l.idle) |
| if err != nil { |
| return aws.Config{}, err |
| } |
| @@ -161,7 +316,11 @@ func withDefaultsMode(bc *awshttp.BuildableClient, cfg aws.Config) *awshttp.Buil |
| // service options rather than a loaded config: set it as the options' |
| // HTTPClient. |
| func BoundedHTTPClient() aws.HTTPClient { |
| - c, err := boundedClient(loadingClient(ResponseHeaderTimeout), BodyIdleTimeout) |
| + return mustBoundedClient(loadingClient(ResponseHeaderTimeout), BodyIdleTimeout) |
| +} |
| + |
| +func mustBoundedClient(bc *awshttp.BuildableClient, idle time.Duration) aws.HTTPClient { |
| + c, err := boundedClient(bc, idle) |
| if err != nil { |
| // Only an SDK whose frozen client is no longer an *http.Client gets |
| // here, and TestExportedStallBounds fails on it first. |
diff --git a/internal/rootaws/stall_credentials_test.go b/internal/rootaws/stall_credentials_test.go| new file mode 100644 |
| index 000000000..6b541d182 |
| --- /dev/null |
| +++ b/internal/rootaws/stall_credentials_test.go |
| @@ -0,0 +1,202 @@ |
| +package rootaws |
| + |
| +import ( |
| + "context" |
| + "crypto/sha1" |
| + "encoding/hex" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| +) |
| + |
| +// 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) { |
| + t.Helper() |
| + var hits atomic.Int32 |
| + url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + hits.Add(1) |
| + var head string |
| + switch r.URL.Path { |
| + case "/federation/credentials": |
| + w.Header().Set("Content-Type", "application/json") |
| + head = `{"roleCredentials":{"accessKeyId":"A` |
| + case "/token": |
| + w.Header().Set("Content-Type", "application/json") |
| + head = `{"accessToken":"A` |
| + default: |
| + if err := r.ParseForm(); err != nil { |
| + t.Errorf("STS request form: %v", err) |
| + return |
| + } |
| + action := r.PostForm.Get("Action") |
| + w.Header().Set("Content-Type", "text/xml") |
| + head = `<` + action + `Response xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><` + action + `Result><Credentials><AccessKeyId>A` |
| + } |
| + w.Header().Set("Content-Length", "1048576") |
| + w.WriteHeader(http.StatusOK) |
| + io.WriteString(w, head) |
| + w.(http.Flusher).Flush() |
| + block(r, done) |
| + }) |
| + return url, &hits |
| +} |
| + |
| +// 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. |
| +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")) |
| + 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 |
| +} |
| + |
| +func writeFile(t *testing.T, path, body string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func webIdentityEnv(t *testing.T, home string) { |
| + t.Helper() |
| + token := filepath.Join(home, "token") |
| + writeFile(t, token, "header.payload.signature") |
| + t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", token) |
| + t.Setenv("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/r") |
| + t.Setenv("AWS_ROLE_SESSION_NAME", "s") |
| +} |
| + |
| +// 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) { |
| + t.Helper() |
| + sum := sha1.Sum([]byte(key)) |
| + writeFile(t, filepath.Join(home, ".aws", "sso", "cache", hex.EncodeToString(sum[:])+".json"), body) |
| +} |
| + |
| +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 |
| +// bounds around it as LoadDefaultConfig puts them. |
| +var ( |
| + loadThroughDefault credentialLoader = func(l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| + return loadDefaultConfig(context.Background(), l, opts...) |
| + } |
| + loadThroughRoot credentialLoader = func(l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| + cfg, err := loadRootConfig(context.Background(), filepath.Join(os.Getenv("HOME"), "absent"), l.options(opts)...) |
| + if err != nil { |
| + return cfg, err |
| + } |
| + return boundConfig(cfg, l) |
| + } |
| +) |
| + |
| +// 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. |
| +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) |
| + 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) { |
| + 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) { |
| + 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) { |
| + 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) |
| + home := credentialEnv(t, url) |
| + c.setup(t, home) |
| + l := newStallLoad(testHeaderTimeout, testIdleTimeout) |
| + cfg, err := c.load(l, append(c.loadOpts, awsconfig.WithRetryMaxAttempts(1))...) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + wantBodyStall(t, stalls(t, func() error { |
| + _, err := cfg.Credentials.Retrieve(context.Background()) |
| + return err |
| + })) |
| + if hits.Load() == 0 { |
| + t.Fatal("the fake credential 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) } |
| + |
| +// 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) |
| + home := credentialEnv(t, url) |
| + webIdentityEnv(t, home) |
| + 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)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := cfg.Credentials.Retrieve(context.Background()); err == nil { |
| + t.Fatal("retrieval through a failing transport succeeded") |
| + } |
| + if seen.Load() == 0 || hits.Load() != 0 { |
| + t.Fatalf("the STS call went %d times through the caller's client and %d times past it", seen.Load(), hits.Load()) |
| + } |
| +} |
diff --git a/internal/rootaws/stall_test.go b/internal/rootaws/stall_test.go| index efaacf73a..ff27d3e03 100644 |
| --- a/internal/rootaws/stall_test.go |
| +++ b/internal/rootaws/stall_test.go |
| @@ -21,6 +21,7 @@ import ( |
| "time" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| + 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" |
| awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| @@ -52,11 +53,12 @@ func TestLoadersInstallStallBounds(t *testing.T) { |
| // LoadDefaultConfig's root branch: its own options come after the |
| // caller's, and the config is bounded after it loads. |
| "loadRootConfig": func(t *testing.T) (aws.Config, error) { |
| - cfg, err := loadRootConfig(context.Background(), filepath.Join(t.TempDir(), "absent"), withStallBounds(nil)...) |
| + opts, l := withStallBounds(nil) |
| + cfg, err := loadRootConfig(context.Background(), filepath.Join(t.TempDir(), "absent"), opts...) |
| if err != nil { |
| return cfg, err |
| } |
| - return boundConfig(cfg, BodyIdleTimeout) |
| + return boundConfig(cfg, l) |
| }, |
| } |
| for name, load := range loaders { |
| @@ -75,16 +77,61 @@ func TestLoadersInstallStallBounds(t *testing.T) { |
| } |
| // A caller's explicit HTTP client is a deliberate override and stays as |
| -// given (awsmanaged's tests inject fake transports this way). |
| +// given (awsmanaged's tests inject fake transports this way), whether or not |
| +// it is a BuildableClient like the one the loaders inject (#1143), and |
| +// however the caller sets it. |
| func TestCallerHTTPClientStays(t *testing.T) { |
| + overrides := map[string]func() aws.HTTPClient{ |
| + "http.Client": func() aws.HTTPClient { return &http.Client{} }, |
| + "BuildableClient": func() aws.HTTPClient { return awshttp.NewBuildableClient() }, |
| + } |
| + for name, client := range overrides { |
| + for _, set := range []string{"WithHTTPClient", "option"} { |
| + t.Run(name+"/"+set, func(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + own := client() |
| + opt := awsconfig.WithHTTPClient(own) |
| + if set == "option" { |
| + opt = func(o *awsconfig.LoadOptions) error { o.HTTPClient = own; return nil } |
| + } |
| + cfg, err := LoadStaticConfig(context.Background(), "ACCESS", "SECRET", opt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cfg.HTTPClient != own { |
| + t.Fatalf("the caller's client was replaced by %T", cfg.HTTPClient) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// With a CA bundle the SDK hands back its own copy of a caller's |
| +// BuildableClient, carrying the bundle: still the caller's, so it is not |
| +// bounded, while the loaders' own client under the same bundle is |
| +// (TestStallBoundsKeepCABundle). |
| +func TestCallerBuildableClientStaysUnderCABundle(t *testing.T) { |
| isolatedAWSEnv(t) |
| - own := &http.Client{} |
| + srv := httptest.NewTLSServer(http.NotFoundHandler()) |
| + defer srv.Close() |
| + t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv)) |
| + own := awshttp.NewBuildableClient() |
| cfg, err := LoadStaticConfig(context.Background(), "ACCESS", "SECRET", awsconfig.WithHTTPClient(own)) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if cfg.HTTPClient != own { |
| - t.Fatalf("the caller's client was replaced by %T", cfg.HTTPClient) |
| + if IsBounded(cfg.HTTPClient) { |
| + t.Fatal("the caller's BuildableClient was replaced by the bounded client") |
| + } |
| + bc, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| + if !ok { |
| + t.Fatalf("the caller's client came back as %T", cfg.HTTPClient) |
| + } |
| + if h := bc.GetTransport().ResponseHeaderTimeout; h != 0 { |
| + t.Fatalf("the caller's client picked up a header timeout: %s", h) |
| + } |
| + if bc.GetTransport().TLSClientConfig == nil || bc.GetTransport().TLSClientConfig.RootCAs == nil { |
| + t.Fatal("the CA bundle did not reach the caller's client") |
| } |
| } |
| @@ -160,16 +207,17 @@ const ( |
| // 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() |
| - cfg, err := awsconfig.LoadDefaultConfig(context.Background(), |
| + l := newStallLoad(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{}), |
| awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("ACCESS", "SECRET", "")), |
| awsconfig.WithRetryMaxAttempts(1), |
| - awsconfig.WithHTTPClient(loadingClient(testHeaderTimeout))) |
| + })...) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if cfg, err = boundConfig(cfg, idle); err != nil { |
| + if cfg, err = boundConfig(cfg, l); err != nil { |
| t.Fatal(err) |
| } |
| return awss3.NewFromConfig(cfg, func(o *awss3.Options) { |