rootaws: bound every AWS response at one RoundTripper, HTTP/1.1 only
Astra round 2 found three gaps in one fault family (root-worker liveness); stopping rule 2 applied and Paul chose central enforcement. The invariant, stated in stall.go: every response a platform AWS client receives is read through one bounded RoundTripper, with a header bound and body progress measured per response. - The body bound moves from an SDK deserialize middleware into boundedTransport, the http.Client's transport. It wraps resp.Body inside RoundTrip, so net/http's drain of a 307/308 body before a redirect is bounded too. The SDK's redirect policy (Freeze: 307/308 only) is kept as is. - HTTP/1.1 only: ForceAttemptHTTP2 false, TLSNextProto an empty map, Protocols HTTP/1, and "h2" taken out of the TLS config's ALPN list (net/http had already put it there when the SDK's transport was first cloned; left in, an h2-offering server breaks the connection). Connection progress then equals response progress, so PINGs and other streams cannot keep a stalled response alive. - Defaults modes no longer drop the bound. The config still loads over a BuildableClient (the SDK applies AWS_CA_BUNDLE only to one, and IMDS adds its own fail-fast timeouts to one); boundConfig then replaces it with the bounded client, applying the defaults mode's dial and TLS timeouts as a service client would have. That client is not buildable, so no service client can rewrite its dialer. Credential clients the loader builds keep the loading client: header bound and HTTP/1.1, no body bound. - BoundedHTTPClient replaces StallHTTPClient/StallAPIOptions for clients built from bare options (the move probe). A caller's explicit WithHTTPClient still wins; only awsmanaged's tests use that, and the guard keeps it out of root-graph production code. - TestAWSClientsAreBounded scans every non-test file the root binary links (go list -deps, linux amd64 and arm64) and fails on config.LoadDefaultConfig or WithHTTPClient (called or as a value), a non-empty aws.Config literal, or a service Options literal without HTTPClient: rootaws.BoundedHTTPClient(), outside a commented allowlist: grouprollaws/config.go (own 2 s bounds), hostfence/ writer.go (caller's 2 min pass deadline), hostenv/awsssm.go (one-shot non-root path), lease/staging.go (test constructor). Values, the consumer-pause exemption, the move probe's settings and the lease release are unchanged. New regression tests, each failing on the round-1 tip (1325f6ec, run behind the same seams): a 307 whose body stalls (blocked past the 10 s watchdog), a stalled body under AWS_DEFAULTS_MODE standard, in-region, cross-region and auto (each blocked past the watchdog), and a TLS server offering h2 (old: "the request went over HTTP/2"). Stall tests now run under an independent watchdog.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+660
−225
internal/host/movesstore.go+5 −5internal/host/movesstore_stall_test.go+4 −19internal/rootaws/config.go+14 −3internal/rootaws/guard_test.go+250 −0internal/rootaws/stall.go+203 −109internal/rootaws/stall_test.go+184 −89
diff --git a/internal/host/movesstore.go b/internal/host/movesstore.go| index e0f246825..63999245f 100644 |
| --- a/internal/host/movesstore.go |
| +++ b/internal/host/movesstore.go |
| @@ -75,9 +75,10 @@ func probeStore(ctx context.Context, env map[string]string, prefix, id string) e |
| // probeStoreOptions is the T4 client for the store bound at prefix: the |
| // delivered static credentials and region, the delivered endpoint |
| -// path-style, checksums only where required, and rootaws's stall bounds |
| -// (a header timeout and a body inactivity limit), so a store that takes a |
| -// request and goes quiet fails the probe instead of holding the pass. |
| +// path-style, checksums only where required, and rootaws's bounded HTTP |
| +// client (a header timeout and a body inactivity limit), so a store that |
| +// takes a request and goes quiet fails the probe instead of holding the |
| +// pass. |
| func probeStoreOptions(env map[string]string, prefix string) awss3.Options { |
| _, rn, en, ak, sk := objstore.EnvNames(prefix) |
| region := env[rn] |
| @@ -89,8 +90,7 @@ func probeStoreOptions(env map[string]string, prefix string) awss3.Options { |
| Credentials: credentials.NewStaticCredentialsProvider(env[ak], env[sk], ""), |
| RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, |
| ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, |
| - HTTPClient: rootaws.StallHTTPClient(), |
| - APIOptions: rootaws.StallAPIOptions(), |
| + HTTPClient: rootaws.BoundedHTTPClient(), |
| } |
| if ep := env[en]; ep != "" { |
| opts.BaseEndpoint = aws.String(ep) |
diff --git a/internal/host/movesstore_stall_test.go b/internal/host/movesstore_stall_test.go| index 77573d0d8..a15a7994f 100644 |
| --- a/internal/host/movesstore_stall_test.go |
| +++ b/internal/host/movesstore_stall_test.go |
| @@ -5,36 +5,21 @@ import ( |
| "testing" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| - "github.com/aws/smithy-go/middleware" |
| "github.com/carlosframework/platform/internal/objstore" |
| "github.com/carlosframework/platform/internal/rootaws" |
| ) |
| // T4's probe client runs under the moves pass with no deadline of its own, |
| -// so it carries rootaws's stall bounds, and keeps the delivered credentials, |
| -// region, endpoint and checksum settings it always had. |
| +// so it carries rootaws's bounded HTTP client, and keeps the delivered |
| +// credentials, region, endpoint and checksum settings it always had. |
| func TestProbeStoreClientCarriesStallBounds(t *testing.T) { |
| bn, rn, en, ak, sk := objstore.EnvNames("STORE") |
| env := map[string]string{bn: "bkt", rn: "eu-west-2", en: "https://store.example.com", ak: "AK", sk: "SK"} |
| o := probeStoreOptions(env, "STORE") |
| - client, ok := o.HTTPClient.(*awshttp.BuildableClient) |
| - if !ok { |
| - t.Fatalf("HTTP client is %T, want rootaws's BuildableClient", o.HTTPClient) |
| - } |
| - if h := client.GetTransport().ResponseHeaderTimeout; h != rootaws.ResponseHeaderTimeout { |
| - t.Fatalf("header timeout %s, want %s", h, rootaws.ResponseHeaderTimeout) |
| - } |
| - stack := middleware.NewStack("probe", nil) |
| - for _, fn := range o.APIOptions { |
| - if err := fn(stack); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - if _, ok := stack.Deserialize.Get("rootaws.BodyIdleTimeout"); !ok { |
| - t.Fatal("no body inactivity limit on the probe client") |
| + if !rootaws.IsBounded(o.HTTPClient) { |
| + t.Fatalf("HTTP client is %T, want rootaws's bounded client", o.HTTPClient) |
| } |
| creds, err := o.Credentials.Retrieve(context.Background()) |
diff --git a/internal/rootaws/config.go b/internal/rootaws/config.go| index 93d7399c8..07cdecea7 100644 |
| --- a/internal/rootaws/config.go |
| +++ b/internal/rootaws/config.go |
| @@ -38,10 +38,17 @@ func offcloudCredentials(path string) (aws.Credentials, error) { |
| // Both get the stall bounds (stall.go). |
| func LoadDefaultConfig(ctx context.Context, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| opts = withStallBounds(opts) |
| + var cfg aws.Config |
| + var err error |
| if os.Geteuid() != 0 { |
| - return awsconfig.LoadDefaultConfig(ctx, opts...) |
| + cfg, err = awsconfig.LoadDefaultConfig(ctx, opts...) |
| + } else { |
| + cfg, err = loadRootConfig(ctx, credentialsPath, opts...) |
| } |
| - return loadRootConfig(ctx, credentialsPath, opts...) |
| + if err != nil { |
| + return cfg, err |
| + } |
| + return boundConfig(cfg, BodyIdleTimeout) |
| } |
| func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| @@ -63,7 +70,11 @@ func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, |
| o.DefaultsModeOptions.IMDSClient = imds.New(imds.Options{ClientEnableState: imds.ClientDisabled}) |
| return nil |
| }) |
| - return awsconfig.LoadDefaultConfig(ctx, opts...) |
| + cfg, err := awsconfig.LoadDefaultConfig(ctx, opts...) |
| + if err != nil { |
| + return cfg, err |
| + } |
| + return boundConfig(cfg, BodyIdleTimeout) |
| } |
| 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| new file mode 100644 |
| index 000000000..dc30ebb47 |
| --- /dev/null |
| +++ b/internal/rootaws/guard_test.go |
| @@ -0,0 +1,250 @@ |
| +package rootaws |
| + |
| +import ( |
| + "bytes" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// 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{ |
| + // 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", |
| + // 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", |
| + // NewStagingMirrorAt: the test constructor against a local S3 |
| + // (leasetest); production uses NewStagingMirror over rootaws. |
| + "internal/lease/staging.go": "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: |
| +// - 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 service Options composite literal (github.com/aws/aws-sdk-go-v2/ |
| +// service/...) unless it sets HTTPClient 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), |
| +// 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") |
| + } |
| + root := moduleRoot(t) |
| + 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 := unboundedAWSClients(t, filepath.Join(root, rel)) |
| + if _, ok := boundedClientAllowlist[rel]; ok { |
| + seen[rel] = len(hits) > 0 |
| + continue |
| + } |
| + for _, h := range hits { |
| + bad = append(bad, rel+":"+h) |
| + } |
| + } |
| + 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) |
| + } |
| + } |
| +} |
| + |
| +// 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) |
| + cfgpkg.WithHTTPClient(nil) |
| + _ = aws.Config{Region: "r"} |
| + _ = aws.Config{} |
| + load := cfgpkg.LoadDefaultConfig |
| + _ = load |
| + _ = s3.Options{Region: "r"} |
| + _ = s3.Options{HTTPClient: nil} |
| + _ = s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| + _ = &s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| +} |
| +` |
| + path := filepath.Join(t.TempDir(), "x.go") |
| + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := unboundedAWSClients(t, path) |
| + if len(got) != 6 { |
| + t.Fatalf("caught %d, want 6: %v", len(got), got) |
| + } |
| +} |
| + |
| +func moduleRoot(t *testing.T) string { |
| + t.Helper() |
| + dir, err := os.Getwd() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for { |
| + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { |
| + return dir |
| + } |
| + parent := filepath.Dir(dir) |
| + if parent == dir { |
| + t.Fatal("no go.mod above the test") |
| + } |
| + dir = parent |
| + } |
| +} |
| + |
| +// 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 { |
| + t.Helper() |
| + set := map[string]bool{} |
| + for _, arch := range []string{"amd64", "arm64"} { |
| + cmd := exec.Command("go", "list", "-deps", "-f", `{{if not .Standard}}{{.Dir}}|{{join .GoFiles ","}}{{end}}`, ".") |
| + cmd.Dir = root |
| + cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0") |
| + var stderr bytes.Buffer |
| + cmd.Stderr = &stderr |
| + out, err := cmd.Output() |
| + if err != nil { |
| + t.Fatalf("go list (linux/%s): %v: %s", arch, err, stderr.String()) |
| + } |
| + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { |
| + dir, names, _ := strings.Cut(line, "|") |
| + 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 |
| + } |
| + } |
| + } |
| + } |
| + files := make([]string, 0, len(set)) |
| + for f := range set { |
| + files = append(files, f) |
| + } |
| + sort.Strings(files) |
| + return files |
| +} |
| + |
| +// unboundedAWSClients reports, as line:what, each construction in the file |
| +// the rules forbid. |
| +func unboundedAWSClients(t *testing.T, path string) []string { |
| + t.Helper() |
| + fset := token.NewFileSet() |
| + f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatalf("parse %s: %v", path, err) |
| + } |
| + 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 |
| + } |
| + names[name] = p |
| + } |
| + pkgOf := func(e ast.Expr) (pkg, sel string) { |
| + s, ok := e.(*ast.SelectorExpr) |
| + if !ok { |
| + return "", "" |
| + } |
| + id, ok := s.X.(*ast.Ident) |
| + if !ok { |
| + return "", "" |
| + } |
| + return names[id.Name], s.Sel.Name |
| + } |
| + const sdk = "github.com/aws/aws-sdk-go-v2/" |
| + var hits []string |
| + hit := func(n ast.Node, what string) { |
| + hits = append(hits, fmt.Sprintf("%d: %s", fset.Position(n.Pos()).Line, what)) |
| + } |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.SelectorExpr: |
| + // 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) |
| + } |
| + case *ast.CompositeLit: |
| + pkg, sel := pkgOf(n.Type) |
| + 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()") |
| + } |
| + } |
| + return true |
| + }) |
| + 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 |
| + } |
| + s, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok { |
| + return false |
| + } |
| + id, ok := s.X.(*ast.Ident) |
| + return ok && names[id.Name] == "github.com/carlosframework/platform/internal/rootaws" && s.Sel.Name == "BoundedHTTPClient" |
| + } |
| + return false |
| +} |
diff --git a/internal/rootaws/stall.go b/internal/rootaws/stall.go| index e4d65ffc0..394d5123e 100644 |
| --- a/internal/rootaws/stall.go |
| +++ b/internal/rootaws/stall.go |
| @@ -2,33 +2,47 @@ package rootaws |
| import ( |
| "context" |
| + "crypto/tls" |
| "fmt" |
| "io" |
| "net" |
| "net/http" |
| "net/http/httptrace" |
| + "slices" |
| "sync" |
| "sync/atomic" |
| "time" |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "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/smithy-go/middleware" |
| - smithyhttp "github.com/aws/smithy-go/transport/http" |
| ) |
| -// The SDK's default HTTP client bounds the dial (30 s) and the TLS handshake |
| -// (10 s) and nothing after that. A store that accepts the request and never |
| -// answers, or answers and then stops sending the body, holds the call until |
| -// the caller's context ends, and many agent loops run each pass on |
| -// context.Background(): one such call parks the loop until the process |
| -// restarts. The two bounds below end that wait. |
| +// The invariant (stopping rule 2, root-worker liveness): every response a |
| +// platform AWS client receives is read through one bounded RoundTripper |
| +// (boundedTransport). It applies a header timeout and a body inactivity |
| +// 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 |
| +// fails when root-graph code builds an AWS config or client another way, |
| +// apart from its commented allowlist. |
| // |
| -// Both are per-phase INACTIVITY limits, not deadlines. Neither caps a whole |
| -// call: an upload's own write time is not counted, and a download that keeps |
| -// receiving bytes is never cut off, however long it takes. They guarantee |
| -// only that a call cannot wait forever on a store that has gone quiet; a |
| -// caller that needs a whole-request or whole-pass bound still sets its own. |
| +// Why it is needed: the SDK's default HTTP client bounds the dial (30 s) and |
| +// the TLS handshake (10 s) and nothing after that. A store that accepts the |
| +// request and never answers, or answers and then stops sending the body, |
| +// holds the call until the caller's context ends, and many agent loops run |
| +// each pass on context.Background(): one such call parks the loop until the |
| +// process restarts. |
| +// |
| +// Both bounds are per-phase INACTIVITY limits, not deadlines. Neither caps a |
| +// whole call: an upload's own write time is not counted, and a download that |
| +// keeps receiving bytes is never cut off, however long it takes. They |
| +// guarantee only that a call cannot wait forever on a store that has gone |
| +// quiet; a caller that needs a whole-request or whole-pass bound still sets |
| +// its own. |
| // |
| // The values are this tree's own ceiling for one store request: 120 s is |
| // hostbox.RequestLimit, lease's stagingRequestTimeout and |
| @@ -48,71 +62,184 @@ const ( |
| // the request, body included, has been written. |
| ResponseHeaderTimeout = 120 * time.Second |
| // BodyIdleTimeout bounds how long a body read may wait while the |
| - // connection under it receives nothing. It runs only while a read is |
| + // response's connection receives nothing. It runs only while a read is |
| // in progress, so a caller pausing between reads is never cut off. |
| BodyIdleTimeout = 120 * time.Second |
| ) |
| -// withStallBounds puts the bounds ahead of the caller's options, so an |
| -// explicit WithHTTPClient from a caller still wins (none passes one today); |
| -// the body bound is an APIOption and applies whatever the HTTP client. |
| +// 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(stallBounds(ResponseHeaderTimeout, BodyIdleTimeout), opts...) |
| + return append([]func(*awsconfig.LoadOptions) error{awsconfig.WithHTTPClient(loadingClient(ResponseHeaderTimeout))}, opts...) |
| +} |
| + |
| +// 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. |
| +func loadingClient(header time.Duration) *awshttp.BuildableClient { |
| + return awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) { |
| + t.ResponseHeaderTimeout = header |
| + http1Only(t) |
| + }) |
| } |
| -// stallBounds is the seam the tests drive with short values. |
| +// http1Only turns HTTP/2 off. Body progress is measured per connection |
| +// (progressConn), which is per response only when a connection carries one |
| +// response at a time: under HTTP/2 another stream's data or a PING would |
| +// count as progress for a stalled response and keep it alive for good. S3 |
| +// and the S3-compatible stores this platform uses speak HTTP/1.1. |
| // |
| -// The HTTP client stays a BuildableClient: the SDK applies a CA bundle |
| -// (AWS_CA_BUNDLE) and a defaults mode's dial and TLS values only to one, and |
| -// refuses to load a CA bundle over anything else. The body bound is a |
| -// middleware rather than an HTTP client wrapper for the same reason; as an |
| -// APIOption on the config it reaches every client built from it, the |
| -// credential clients the loader builds (STS) included. |
| -func stallBounds(header, idle time.Duration) []func(*awsconfig.LoadOptions) error { |
| - return []func(*awsconfig.LoadOptions) error{ |
| - awsconfig.WithHTTPClient(stallHTTPClient(header)), |
| - awsconfig.WithAPIOptions([]func(*middleware.Stack) error{idleBodyOption(idle)}), |
| +// The SDK's default transport has already offered "h2" in its TLS config's |
| +// ALPN list by the time this runs (net/http sets it when the transport is |
| +// first cloned), so that entry goes too: a server that picked h2 would |
| +// otherwise answer a client that can no longer speak it. |
| +func http1Only(t *http.Transport) { |
| + t.ForceAttemptHTTP2 = false |
| + t.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{} |
| + var p http.Protocols |
| + p.SetHTTP1(true) |
| + t.Protocols = &p |
| + if c := t.TLSClientConfig; c != nil { |
| + c.NextProtos = slices.DeleteFunc(slices.Clone(c.NextProtos), func(s string) bool { return s == "h2" }) |
| } |
| } |
| -// StallHTTPClient and StallAPIOptions are the two bounds for a client built |
| -// from bare service options rather than a loaded config (awss3.New(opts)): |
| -// set the first as the options' HTTPClient and append the second to their |
| -// APIOptions. |
| -func StallHTTPClient() *awshttp.BuildableClient { return stallHTTPClient(ResponseHeaderTimeout) } |
| +// 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) { |
| + bc, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| + if !ok { |
| + return cfg, nil |
| + } |
| + client, err := boundedClient(withDefaultsMode(bc, cfg), idle) |
| + if err != nil { |
| + return aws.Config{}, err |
| + } |
| + cfg.HTTPClient = client |
| + return cfg, nil |
| +} |
| -func StallAPIOptions() []func(*middleware.Stack) error { |
| - return []func(*middleware.Stack) error{idleBodyOption(BodyIdleTimeout)} |
| +// withDefaultsMode applies a non-legacy defaults mode's dial and TLS |
| +// timeouts the way a service client's resolveHTTPClient does for a |
| +// BuildableClient. Legacy, the default, changes nothing. |
| +func withDefaultsMode(bc *awshttp.BuildableClient, cfg aws.Config) *awshttp.BuildableClient { |
| + var mode aws.DefaultsMode |
| + mode.SetFromString(string(cfg.DefaultsMode)) |
| + if mode == aws.DefaultsModeAuto { |
| + mode = defaults.ResolveDefaultsModeAuto(cfg.Region, cfg.RuntimeEnvironment) |
| + } |
| + mc, err := defaults.GetModeConfiguration(mode) |
| + if err != nil { |
| + return bc |
| + } |
| + return bc.WithDialerOptions(func(d *net.Dialer) { |
| + if v, ok := mc.GetConnectTimeout(); ok { |
| + d.Timeout = v |
| + } |
| + }).WithTransportOptions(func(t *http.Transport) { |
| + if v, ok := mc.GetTLSNegotiationTimeout(); ok { |
| + t.TLSHandshakeTimeout = v |
| + } |
| + }) |
| } |
| -// stallHTTPClient is the SDK's default client with the header timeout, and |
| -// every connection it dials counting its reads (progressConn), which is |
| -// what the body bound measures progress by. |
| -// |
| -// A non-legacy defaults mode (AWS_DEFAULTS_MODE) makes a service client |
| -// replace DialContext with a plain dialer's; its connections then go |
| -// uncounted and the body bound stands aside for them (idleBodyMiddleware), |
| -// so the header timeout is all that applies. The default is legacy. |
| -func stallHTTPClient(header time.Duration) *awshttp.BuildableClient { |
| - return awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) { |
| - t.ResponseHeaderTimeout = header |
| +// BoundedHTTPClient is the bounded client for an AWS client built from bare |
| +// service options rather than a loaded config: set it as the options' |
| +// HTTPClient. |
| +func BoundedHTTPClient() aws.HTTPClient { |
| + c, err := boundedClient(loadingClient(ResponseHeaderTimeout), BodyIdleTimeout) |
| + if err != nil { |
| + // Only an SDK whose frozen client is no longer an *http.Client gets |
| + // here, and TestExportedStallBounds fails on it first. |
| + panic(err) |
| + } |
| + return c |
| +} |
| + |
| +// boundedClient is bc's own client (Freeze: the SDK's 307/308-only redirect |
| +// policy and its transport) with boundedTransport between that client and |
| +// the transport, and every connection the transport dials counting its |
| +// reads. The dial wrap goes on last, after any dialer change. |
| +func boundedClient(bc *awshttp.BuildableClient, idle time.Duration) (aws.HTTPClient, error) { |
| + bc = bc.WithTransportOptions(func(t *http.Transport) { |
| + http1Only(t) |
| if dial := t.DialContext; dial != nil { |
| - t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| - c, err := dial(ctx, network, addr) |
| - if err != nil || c == nil { |
| - return c, err |
| - } |
| - return &progressConn{Conn: c}, nil |
| - } |
| + t.DialContext = progressDial(dial) |
| + } else { |
| + t.DialContext = progressDial((&net.Dialer{}).DialContext) |
| } |
| }) |
| + frozen, ok := bc.Freeze().(*http.Client) |
| + if !ok { |
| + return nil, fmt.Errorf("rootaws: the SDK's frozen HTTP client is %T, not *http.Client", bc.Freeze()) |
| + } |
| + c := *frozen |
| + c.Transport = &boundedTransport{next: frozen.Transport, idle: idle, header: bc.GetTransport().ResponseHeaderTimeout} |
| + return &c, nil |
| +} |
| + |
| +// boundedTransport is the one RoundTripper every response passes through. |
| +// It sits under net/http's client, so the body it hands up is already |
| +// bounded when the client drains a redirect's body or the SDK decodes an |
| +// answer or a caller streams a GetObject body. |
| +type boundedTransport struct { |
| + next http.RoundTripper |
| + idle time.Duration |
| + // header is the transport's ResponseHeaderTimeout, kept for tests to |
| + // read; the transport under next enforces it. |
| + header time.Duration |
| +} |
| + |
| +func (t *boundedTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| + var conn atomic.Pointer[progressConn] |
| + trace := &httptrace.ClientTrace{GotConn: func(info httptrace.GotConnInfo) { |
| + if pc := connProgress(info.Conn); pc != nil { |
| + conn.Store(pc) |
| + } |
| + }} |
| + resp, err := t.next.RoundTrip(req.WithContext(httptrace.WithClientTrace(req.Context(), trace))) |
| + if err != nil || resp == nil { |
| + return resp, err |
| + } |
| + if resp.Body != nil && resp.Body != http.NoBody { |
| + // conn is nil only if the connection was not dialed through |
| + // progressDial, which boundedClient always installs; the bound then |
| + // measures each Read on its own, stricter but never absent. |
| + resp.Body = &idleBody{rc: resp.Body, idle: t.idle, conn: conn.Load()} |
| + } |
| + return resp, nil |
| +} |
| + |
| +func progressDial(dial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + return func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + c, err := dial(ctx, network, addr) |
| + if err != nil || c == nil { |
| + return c, err |
| + } |
| + return &progressConn{Conn: c}, nil |
| + } |
| } |
| // progressConn records when the connection last received bytes. Progress is |
| // measured here, below TLS and below HTTP's chunk decoding: one body Read |
| // can span many socket reads (net/http's chunked reader keeps filling the |
| // caller's buffer until the chunk ends), so the time a single Read takes says |
| -// nothing about whether the store is still sending. |
| +// nothing about whether the store is still sending. With HTTP/2 off, a |
| +// connection carries one response at a time. |
| type progressConn struct { |
| net.Conn |
| last atomic.Int64 // UnixNano of the last read that returned bytes; 0 before any |
| @@ -142,52 +269,6 @@ func connProgress(c net.Conn) *progressConn { |
| return nil |
| } |
| -// idleBodyID names the body-bounding middleware. |
| -const idleBodyID = "rootaws.BodyIdleTimeout" |
| - |
| -func idleBodyOption(idle time.Duration) func(*middleware.Stack) error { |
| - return func(stack *middleware.Stack) error { |
| - if _, ok := stack.Deserialize.Get(idleBodyID); ok { |
| - return nil |
| - } |
| - // After: innermost in the deserialize step, so the operation's own |
| - // deserializer (an XML answer, an error document) reads through it |
| - // too, not only a streamed GetObject body. |
| - return stack.Deserialize.Add(idleBodyMiddleware{idle: idle}, middleware.After) |
| - } |
| -} |
| - |
| -type idleBodyMiddleware struct{ idle time.Duration } |
| - |
| -func (idleBodyMiddleware) ID() string { return idleBodyID } |
| - |
| -func (m idleBodyMiddleware) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( |
| - middleware.DeserializeOutput, middleware.Metadata, error) { |
| - // The connection this attempt's request was sent on. The trace composes |
| - // with any the caller or the SDK set; it only observes. |
| - var conn atomic.Pointer[progressConn] |
| - ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GotConn: func(info httptrace.GotConnInfo) { |
| - if pc := connProgress(info.Conn); pc != nil { |
| - conn.Store(pc) |
| - } |
| - }}) |
| - out, md, err := next.HandleDeserialize(ctx, in) |
| - if err != nil { |
| - return out, md, err |
| - } |
| - pc := conn.Load() |
| - if pc == nil { |
| - // Not one of ours (another HTTP client, a non-legacy defaults |
| - // mode): no way to tell a stall from a slow chunk, so no body |
| - // bound rather than one that could cut a healthy transfer. |
| - return out, md, nil |
| - } |
| - if resp, ok := out.RawResponse.(*smithyhttp.Response); ok && resp.Body != nil && resp.Body != http.NoBody { |
| - resp.Body = &idleBody{rc: resp.Body, idle: m.idle, conn: pc} |
| - } |
| - return out, md, nil |
| -} |
| - |
| // bodyStallError is a body read that waited the idle bound with the |
| // connection receiving nothing. It is a timeout, as the transport's own |
| // header timeout is. |
| @@ -199,16 +280,15 @@ func (e bodyStallError) Error() string { |
| func (bodyStallError) Timeout() bool { return true } |
| func (bodyStallError) Temporary() bool { return true } |
| -// idleBody fails a Read during which the connection has received nothing |
| -// for idle, by closing the body under it, which is how net/http aborts a |
| -// pending read. Quiet time counts from the later of the Read's start and the |
| -// connection's last received bytes, so neither a consumer's pause between |
| -// reads nor a long Read that keeps receiving is a stall. With HTTP/2 any |
| -// stream's bytes count as progress, which can only delay a timeout. |
| +// idleBody fails a Read during which the response's connection has received |
| +// nothing for idle, by closing the body under it, which is how net/http |
| +// aborts a pending read. Quiet time counts from the later of the Read's |
| +// start and the connection's last received bytes, so neither a consumer's |
| +// pause between reads nor a long Read that keeps receiving is a stall. |
| type idleBody struct { |
| rc io.ReadCloser |
| idle time.Duration |
| - conn *progressConn |
| + conn *progressConn // nil: each Read measured on its own |
| mu sync.Mutex // guards the fields below; never held across I/O |
| timer *time.Timer |
| @@ -254,7 +334,10 @@ func (b *idleBody) check() { |
| b.mu.Unlock() |
| return |
| } |
| - last := max(b.conn.last.Load(), b.readStart) |
| + last := b.readStart |
| + if b.conn != nil { |
| + last = max(last, b.conn.last.Load()) |
| + } |
| if quiet := time.Duration(time.Now().UnixNano() - last); quiet < b.idle { |
| b.timer.Reset(b.idle - quiet) |
| b.mu.Unlock() |
| @@ -266,3 +349,14 @@ func (b *idleBody) check() { |
| } |
| func (b *idleBody) Close() error { return b.rc.Close() } |
| + |
| +// IsBounded reports whether c is a client from this file: net/http's client |
| +// over boundedTransport. Tests elsewhere use it to check their wiring. |
| +func IsBounded(c aws.HTTPClient) bool { |
| + hc, ok := c.(*http.Client) |
| + if !ok { |
| + return false |
| + } |
| + _, ok = hc.Transport.(*boundedTransport) |
| + return ok |
| +} |
diff --git a/internal/rootaws/stall_test.go b/internal/rootaws/stall_test.go| index edc0f3961..efaacf73a 100644 |
| --- a/internal/rootaws/stall_test.go |
| +++ b/internal/rootaws/stall_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "bufio" |
| "bytes" |
| "context" |
| + "crypto/tls" |
| "encoding/pem" |
| "errors" |
| "fmt" |
| @@ -15,46 +16,28 @@ import ( |
| "path/filepath" |
| "strings" |
| "sync" |
| + "sync/atomic" |
| "testing" |
| "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" |
| - "github.com/aws/smithy-go/middleware" |
| ) |
| -// installedBounds reads back what a loaded config will apply: the header |
| -// timeout on its HTTP client's transport and the idle bound its APIOptions |
| -// register. |
| -func installedBounds(t *testing.T, cfg aws.Config) (header, idle time.Duration) { |
| +// bounds reads back what a client will apply. |
| +func bounds(t *testing.T, c aws.HTTPClient) (header, idle time.Duration) { |
| t.Helper() |
| - client, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| - if !ok { |
| - t.Fatalf("HTTP client is %T, want a BuildableClient", cfg.HTTPClient) |
| + if !IsBounded(c) { |
| + t.Fatalf("HTTP client is %T, not the bounded client", c) |
| } |
| - return client.GetTransport().ResponseHeaderTimeout, registeredIdle(t, cfg.APIOptions) |
| + bt := c.(*http.Client).Transport.(*boundedTransport) |
| + return bt.header, bt.idle |
| } |
| -func registeredIdle(t *testing.T, opts []func(*middleware.Stack) error) time.Duration { |
| - t.Helper() |
| - stack := middleware.NewStack("probe", nil) |
| - for _, fn := range opts { |
| - if err := fn(stack); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - m, ok := stack.Deserialize.Get(idleBodyID) |
| - if !ok { |
| - t.Fatal("no body idle bound among the APIOptions") |
| - } |
| - return m.(idleBodyMiddleware).idle |
| -} |
| - |
| -// Every loader in this package hands out a config carrying both bounds at |
| -// their production values. |
| +// Every loader in this package hands out a config whose HTTP client is the |
| +// bounded one, at the production values. |
| func TestLoadersInstallStallBounds(t *testing.T) { |
| loaders := map[string]func(t *testing.T) (aws.Config, error){ |
| "LoadDefaultConfig": func(t *testing.T) (aws.Config, error) { |
| @@ -66,10 +49,14 @@ func TestLoadersInstallStallBounds(t *testing.T) { |
| "LoadStaticConfig": func(t *testing.T) (aws.Config, error) { |
| return LoadStaticConfig(context.Background(), "ACCESS", "SECRET") |
| }, |
| - // The root branch appends its own options after the caller's; the |
| - // bounds must survive that. |
| + // 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) { |
| - return loadRootConfig(context.Background(), filepath.Join(t.TempDir(), "absent"), withStallBounds(nil)...) |
| + cfg, err := loadRootConfig(context.Background(), filepath.Join(t.TempDir(), "absent"), withStallBounds(nil)...) |
| + if err != nil { |
| + return cfg, err |
| + } |
| + return boundConfig(cfg, BodyIdleTimeout) |
| }, |
| } |
| for name, load := range loaders { |
| @@ -79,7 +66,7 @@ func TestLoadersInstallStallBounds(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - header, idle := installedBounds(t, cfg) |
| + header, idle := bounds(t, cfg.HTTPClient) |
| if header != ResponseHeaderTimeout || idle != BodyIdleTimeout { |
| t.Fatalf("bounds %s/%s, want %s/%s", header, idle, ResponseHeaderTimeout, BodyIdleTimeout) |
| } |
| @@ -87,19 +74,50 @@ func TestLoadersInstallStallBounds(t *testing.T) { |
| } |
| } |
| -// The exported pair for clients built from bare options carries the same |
| -// production values. |
| +// A caller's explicit HTTP client is a deliberate override and stays as |
| +// given (awsmanaged's tests inject fake transports this way). |
| +func TestCallerHTTPClientStays(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + own := &http.Client{} |
| + 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) |
| + } |
| +} |
| + |
| +// The client for bare service options carries the same production values. |
| func TestExportedStallBounds(t *testing.T) { |
| - if h := StallHTTPClient().GetTransport().ResponseHeaderTimeout; h != ResponseHeaderTimeout { |
| - t.Fatalf("header %s", h) |
| + header, idle := bounds(t, BoundedHTTPClient()) |
| + if header != ResponseHeaderTimeout || idle != BodyIdleTimeout { |
| + t.Fatalf("bounds %s/%s", header, idle) |
| + } |
| +} |
| + |
| +// A non-legacy defaults mode's dial and TLS timeouts still apply, as a |
| +// service client applied them to a BuildableClient before. |
| +func TestDefaultsModeTimeoutsStillApply(t *testing.T) { |
| + cfg := aws.Config{DefaultsMode: aws.DefaultsModeStandard, Region: "us-east-1"} |
| + bc := withDefaultsMode(loadingClient(ResponseHeaderTimeout), cfg) |
| + if d := bc.GetDialer().Timeout; d != 3100*time.Millisecond { |
| + t.Fatalf("standard mode dial timeout %s", d) |
| } |
| - if idle := registeredIdle(t, StallAPIOptions()); idle != BodyIdleTimeout { |
| - t.Fatalf("idle %s", idle) |
| + if d := bc.GetTransport().TLSHandshakeTimeout; d != 3100*time.Millisecond { |
| + t.Fatalf("standard mode TLS timeout %s", d) |
| + } |
| + if h := bc.GetTransport().ResponseHeaderTimeout; h != ResponseHeaderTimeout { |
| + t.Fatalf("defaults mode dropped the header timeout: %s", h) |
| + } |
| + legacy := withDefaultsMode(loadingClient(ResponseHeaderTimeout), aws.Config{}) |
| + if d := legacy.GetDialer().Timeout; d != 30*time.Second { |
| + t.Fatalf("legacy mode dial timeout %s", d) |
| } |
| } |
| -// The HTTP client stays buildable so a CA bundle still loads, and the |
| -// bundle keeps the header timeout. |
| +// The CA bundle still loads, through the BuildableClient the SDK loads |
| +// over; TestStallBodyFailsOverTLS shows it reaches the bounded client. |
| func TestStallBoundsKeepCABundle(t *testing.T) { |
| isolatedAWSEnv(t) |
| srv := httptest.NewTLSServer(http.NotFoundHandler()) |
| @@ -109,12 +127,9 @@ func TestStallBoundsKeepCABundle(t *testing.T) { |
| if err != nil { |
| t.Fatalf("a CA bundle no longer loads: %v", err) |
| } |
| - if header, _ := installedBounds(t, cfg); header != ResponseHeaderTimeout { |
| + if header, _ := bounds(t, cfg.HTTPClient); header != ResponseHeaderTimeout { |
| t.Fatalf("the CA bundle dropped the header timeout: %s", header) |
| } |
| - if cfg.HTTPClient.(*awshttp.BuildableClient).GetTransport().TLSClientConfig.RootCAs == nil { |
| - t.Fatal("the CA bundle was not applied") |
| - } |
| } |
| func caBundle(t *testing.T, srv *httptest.Server) string { |
| @@ -135,24 +150,28 @@ const ( |
| // nearly a second to fail them falsely. |
| progressIdle = time.Second |
| progressGap = progressIdle / 20 |
| - // stallDeadline is how long a stalled call may take to fail in these |
| - // tests: the bound plus slack for a loaded machine, far short of a hang. |
| + // stallDeadline is the watchdog on a stalled call: the bound plus slack |
| + // for a loaded machine, far short of a hang. |
| stallDeadline = 10 * time.Second |
| ) |
| -// stallClient is an S3 client over the bounds (testHeaderTimeout and idle), |
| -// one attempt per call, against url. extra adds load options (a CA bundle). |
| -func stallClient(t *testing.T, url string, idle time.Duration, extra ...func(*awsconfig.LoadOptions) error) *awss3.Client { |
| +// 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() |
| - opts := append(stallBounds(testHeaderTimeout, idle), |
| + cfg, err := awsconfig.LoadDefaultConfig(context.Background(), |
| awsconfig.WithRegion("us-east-1"), |
| awsconfig.WithSharedConfigFiles([]string{}), awsconfig.WithSharedCredentialsFiles([]string{}), |
| awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("ACCESS", "SECRET", "")), |
| - awsconfig.WithRetryMaxAttempts(1)) |
| - cfg, err := awsconfig.LoadDefaultConfig(context.Background(), append(opts, extra...)...) |
| + awsconfig.WithRetryMaxAttempts(1), |
| + awsconfig.WithHTTPClient(loadingClient(testHeaderTimeout))) |
| if err != nil { |
| t.Fatal(err) |
| } |
| + if cfg, err = boundConfig(cfg, idle); err != nil { |
| + t.Fatal(err) |
| + } |
| return awss3.NewFromConfig(cfg, func(o *awss3.Options) { |
| o.BaseEndpoint = aws.String(url) |
| o.UsePathStyle = true |
| @@ -178,22 +197,29 @@ func block(r *http.Request, done <-chan struct{}) { |
| } |
| } |
| -func wantTimeout(t *testing.T, err error, start time.Time) { |
| +// stalls runs call under a watchdog and wants it to fail with a timeout |
| +// before stallDeadline. |
| +func stalls(t *testing.T, call func() error) error { |
| t.Helper() |
| - if err == nil { |
| - t.Fatal("a stalled call succeeded") |
| - } |
| - if d := time.Since(start); d > stallDeadline { |
| - t.Fatalf("a stalled call took %s to fail", d) |
| - } |
| - var ne net.Error |
| - if !errors.As(err, &ne) || !ne.Timeout() { |
| - t.Fatalf("not a timeout: %v", err) |
| + got := make(chan error, 1) |
| + go func() { got <- call() }() |
| + select { |
| + case err := <-got: |
| + if err == nil { |
| + t.Fatal("a stalled call succeeded") |
| + } |
| + var ne net.Error |
| + if !errors.As(err, &ne) || !ne.Timeout() { |
| + t.Fatalf("not a timeout: %v", err) |
| + } |
| + return err |
| + case <-time.After(stallDeadline): |
| + t.Fatalf("a stalled call was still blocked after %s", stallDeadline) |
| + return nil |
| } |
| } |
| -func getObject(t *testing.T, c *awss3.Client) (io.ReadCloser, error) { |
| - t.Helper() |
| +func getObject(c *awss3.Client) (io.ReadCloser, error) { |
| out, err := c.GetObject(context.Background(), &awss3.GetObjectInput{Bucket: aws.String("b"), Key: aws.String("k")}) |
| if err != nil { |
| return nil, err |
| @@ -201,9 +227,8 @@ func getObject(t *testing.T, c *awss3.Client) (io.ReadCloser, error) { |
| return out.Body, nil |
| } |
| -func get(t *testing.T, c *awss3.Client) ([]byte, error) { |
| - t.Helper() |
| - body, err := getObject(t, c) |
| +func get(c *awss3.Client) ([]byte, error) { |
| + body, err := getObject(c) |
| if err != nil { |
| return nil, err |
| } |
| @@ -211,12 +236,14 @@ func get(t *testing.T, c *awss3.Client) ([]byte, error) { |
| return io.ReadAll(body) |
| } |
| +func getErr(c *awss3.Client) func() error { |
| + return func() error { _, err := get(c); return err } |
| +} |
| + |
| // (a) A store that takes the request and never sends headers. |
| func TestStallNoHeadersFails(t *testing.T) { |
| url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { block(r, done) }) |
| - start := time.Now() |
| - _, err := get(t, stallClient(t, url, testIdleTimeout)) |
| - wantTimeout(t, err, start) |
| + stalls(t, getErr(stallClient(t, url, testIdleTimeout))) |
| } |
| func stallAfterSome(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| @@ -227,21 +254,69 @@ func stallAfterSome(w http.ResponseWriter, r *http.Request, done <-chan struct{} |
| block(r, done) |
| } |
| +func wantBodyStall(t *testing.T, err error) { |
| + t.Helper() |
| + var stall bodyStallError |
| + if !errors.As(err, &stall) { |
| + t.Fatalf("not the body bound: %v", err) |
| + } |
| +} |
| + |
| // (b) Headers, part of the body, then nothing: a streamed GetObject body |
| // read by the caller. |
| func TestStallBodyFailsGetObject(t *testing.T) { |
| url := stallServer(t, stallAfterSome) |
| - start := time.Now() |
| - _, err := get(t, stallClient(t, url, testIdleTimeout)) |
| - wantTimeout(t, err, start) |
| - var stall bodyStallError |
| - if !errors.As(err, &stall) { |
| - t.Fatalf("not the body bound: %v", err) |
| + wantBodyStall(t, stalls(t, getErr(stallClient(t, url, testIdleTimeout)))) |
| +} |
| + |
| +// (b) under each non-legacy defaults mode, which makes a service client |
| +// rewrite a BuildableClient's dialer (Astra round 2). The bounded client is |
| +// not buildable, so the bound stays. |
| +func TestStallBodyFailsUnderDefaultsModes(t *testing.T) { |
| + for _, mode := range []string{"standard", "in-region", "cross-region", "auto"} { |
| + t.Run(mode, func(t *testing.T) { |
| + url := stallServer(t, stallAfterSome) |
| + t.Setenv("AWS_DEFAULTS_MODE", mode) |
| + wantBodyStall(t, stalls(t, getErr(stallClient(t, url, testIdleTimeout)))) |
| + }) |
| } |
| } |
| -// (b) over TLS: the bound finds its connection under the TLS one, with a |
| -// CA bundle loaded as well. |
| +// (b) A 307 whose body never comes: net/http's client drains a small |
| +// redirect body before following it, under the bounded transport, so the |
| +// drain is bounded too and the call goes on to the redirect's target |
| +// (Astra round 2). Unbounded, the drain blocks for good. |
| +func TestStallRedirectBodyIsBounded(t *testing.T) { |
| + url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + if strings.HasPrefix(r.URL.Path, "/elsewhere/") { |
| + io.WriteString(w, "moved") |
| + return |
| + } |
| + w.Header().Set("Location", "/elsewhere"+r.URL.Path) |
| + w.Header().Set("Content-Length", "100") |
| + w.WriteHeader(http.StatusTemporaryRedirect) |
| + w.(http.Flusher).Flush() |
| + block(r, done) |
| + }) |
| + c := stallClient(t, url, testIdleTimeout) |
| + type result struct { |
| + body []byte |
| + err error |
| + } |
| + got := make(chan result, 1) |
| + go func() { b, err := get(c); got <- result{b, err} }() |
| + select { |
| + case r := <-got: |
| + if r.err != nil || string(r.body) != "moved" { |
| + t.Fatalf("got %q, %v; want the redirect target's answer", r.body, r.err) |
| + } |
| + case <-time.After(stallDeadline): |
| + t.Fatalf("the redirect's body drain was still blocked after %s", stallDeadline) |
| + } |
| +} |
| + |
| +// (b) over TLS: the bound finds its connection under the TLS one, and the |
| +// handshake succeeds only because the CA bundle reached the bounded client. |
| func TestStallBodyFailsOverTLS(t *testing.T) { |
| isolatedAWSEnv(t) |
| done := make(chan struct{}) |
| @@ -249,12 +324,30 @@ func TestStallBodyFailsOverTLS(t *testing.T) { |
| t.Cleanup(srv.Close) |
| t.Cleanup(func() { close(done) }) |
| t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv)) |
| - start := time.Now() |
| - _, err := get(t, stallClient(t, srv.URL, testIdleTimeout)) |
| - wantTimeout(t, err, start) |
| - var stall bodyStallError |
| - if !errors.As(err, &stall) { |
| - t.Fatalf("not the body bound: %v", err) |
| + wantBodyStall(t, stalls(t, getErr(stallClient(t, srv.URL, testIdleTimeout)))) |
| +} |
| + |
| +// The transport never negotiates HTTP/2, even against a TLS server that |
| +// offers it: per-connection progress is per-response progress only over |
| +// HTTP/1.1 (Astra round 2). |
| +func TestNeverNegotiatesHTTP2(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + var proto atomic.Int32 |
| + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + proto.Store(int32(r.ProtoMajor)) |
| + io.WriteString(w, "ok") |
| + })) |
| + srv.EnableHTTP2 = true |
| + srv.TLS = &tls.Config{NextProtos: []string{"h2", "http/1.1"}} // offer both |
| + srv.StartTLS() |
| + t.Cleanup(srv.Close) |
| + t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv)) |
| + body, err := get(stallClient(t, srv.URL, testIdleTimeout)) |
| + if err != nil || string(body) != "ok" { |
| + t.Fatalf("got %q, %v", body, err) |
| + } |
| + if p := proto.Load(); p != 1 { |
| + t.Fatalf("the request went over HTTP/%d", p) |
| } |
| } |
| @@ -267,9 +360,11 @@ func TestStallBodyFailsDecodedAnswer(t *testing.T) { |
| w.(http.Flusher).Flush() |
| block(r, done) |
| }) |
| - start := time.Now() |
| - _, err := stallClient(t, url, testIdleTimeout).ListObjectsV2(context.Background(), &awss3.ListObjectsV2Input{Bucket: aws.String("b")}) |
| - wantTimeout(t, err, start) |
| + c := stallClient(t, url, testIdleTimeout) |
| + stalls(t, func() error { |
| + _, err := c.ListObjectsV2(context.Background(), &awss3.ListObjectsV2Input{Bucket: aws.String("b")}) |
| + return err |
| + }) |
| } |
| // (c) A body that trickles in as many flushed chunks, never quiet for |
| @@ -287,7 +382,7 @@ func TestTrickleBodySucceeds(t *testing.T) { |
| } |
| }) |
| start := time.Now() |
| - body, err := get(t, stallClient(t, url, progressIdle)) |
| + body, err := get(stallClient(t, url, progressIdle)) |
| if err != nil { |
| t.Fatalf("a steady transfer was cut off after %s: %v", time.Since(start), err) |
| } |
| @@ -315,7 +410,7 @@ func TestOneSlowChunkInOneReadSucceeds(t *testing.T) { |
| } |
| io.WriteString(c, "\r\n0\r\n\r\n") |
| }) |
| - body, err := getObject(t, stallClient(t, url, progressIdle)) |
| + body, err := getObject(stallClient(t, url, progressIdle)) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -385,7 +480,7 @@ func TestPausingReaderSucceeds(t *testing.T) { |
| url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| io.WriteString(w, want) |
| }) |
| - body, err := getObject(t, stallClient(t, url, testIdleTimeout)) |
| + body, err := getObject(stallClient(t, url, testIdleTimeout)) |
| if err != nil { |
| t.Fatal(err) |
| } |