rootaws: bound header waits and body stalls on every AWS client
The SDK's default HTTP client bounds the dial and the TLS handshake and nothing after them. A store that takes a request and never answers, or answers and stops sending the body, holds the call until the caller's context ends, and many host-agent loops run on context.Background(), so one stalled S3 call parks a loop until the agent restarts (audit host.md finding 5, ASTRA item 1). LoadDefaultConfig (root and non-root) and LoadStaticConfig now put two bounds ahead of the caller's options, so every client built from those configs gets them, release.newS3Store's included: - ResponseHeaderTimeout (120 s) on a BuildableClient's transport. It stays buildable so AWS_CA_BUNDLE and defaults modes still apply. - BodyIdleTimeout (120 s): an innermost deserialize middleware that fails a body Read getting no bytes for that long. It is armed only while a Read is in progress, so a caller pausing between reads is never cut, and a large transfer that keeps making progress runs as long as it needs. It covers decoded answers and streamed GetObject bodies alike. No overall http.Client.Timeout and no whole-operation deadline. 120 s is the tree's existing whole-request ceiling for one store request (hostbox.RequestLimit, lease's stagingRequestTimeout and generationRequestLimit), so nothing that fits those today can be cut by these per-phase bounds. Both errors are timeouts, so the SDK retries them as it already retries a reset connection. Tests drive the same option builder with 300 ms bounds against a local server: no headers and a stalled body (streamed and decoded) fail within the bound; a body trickling for many times the bound, and a reader pausing longer than it, succeed. All three stall tests hang without the bounds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+417
−1
internal/rootaws/config.go+3 −1internal/rootaws/stall.go+146 −0internal/rootaws/stall_test.go+268 −0
CI cancelled — superseded by a newer push — run details
diff --git a/internal/rootaws/config.go b/internal/rootaws/config.go| index f24e49766..93d7399c8 100644 |
| --- a/internal/rootaws/config.go |
| +++ b/internal/rootaws/config.go |
| @@ -35,7 +35,9 @@ func offcloudCredentials(path string) (aws.Credentials, error) { |
| // LoadDefaultConfig preserves the SDK chain for non-root callers. Root disables |
| // 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) |
| if os.Geteuid() != 0 { |
| return awsconfig.LoadDefaultConfig(ctx, opts...) |
| } |
| @@ -52,7 +54,7 @@ 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(opts, awsconfig.WithSharedConfigFiles([]string{}), |
| + opts = append(withStallBounds(opts), awsconfig.WithSharedConfigFiles([]string{}), |
| awsconfig.WithSharedCredentialsFiles([]string{}), awsconfig.WithSharedConfigProfile(""), |
| awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, "")), |
| func(o *awsconfig.LoadOptions) error { |
diff --git a/internal/rootaws/stall.go b/internal/rootaws/stall.go| new file mode 100644 |
| index 000000000..a2024c078 |
| --- /dev/null |
| +++ b/internal/rootaws/stall.go |
| @@ -0,0 +1,146 @@ |
| +package rootaws |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "sync/atomic" |
| + "time" |
| + |
| + 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. Neither caps a whole call: |
| +// an upload's own write time is not counted, and a large download that keeps |
| +// receiving bytes is never cut off, however long it takes. |
| +// |
| +// The values are this tree's own ceiling for one store request: 120 s is |
| +// hostbox.RequestLimit, lease's stagingRequestTimeout and |
| +// claimgeneration's generationRequestLimit, each a bound on a WHOLE request. |
| +// A healthy bucket answers in well under a second, so a call that waits this |
| +// long for one header or one chunk of body is stalled, not slow, and no call |
| +// that fits those whole-request bounds today can be cut by these per-phase |
| +// ones. With the SDK's three attempts a stalled call ends in about six |
| +// minutes at worst; convergePassTimeout (5 min) guards the converge pass |
| +// tighter still. |
| +const ( |
| + // ResponseHeaderTimeout bounds the wait for a response's headers once |
| + // the request, body included, has been written. |
| + ResponseHeaderTimeout = 120 * time.Second |
| + // BodyIdleTimeout bounds one wait for response body bytes: a read that |
| + // gets nothing for this long fails. It is armed 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. |
| +func withStallBounds(opts []func(*awsconfig.LoadOptions) error) []func(*awsconfig.LoadOptions) error { |
| + return append(stallBounds(ResponseHeaderTimeout, BodyIdleTimeout), opts...) |
| +} |
| + |
| +// stallBounds is the seam the tests drive with short values. |
| +// |
| +// 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 { |
| + client := awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) { |
| + t.ResponseHeaderTimeout = header |
| + }) |
| + return []func(*awsconfig.LoadOptions) error{ |
| + awsconfig.WithHTTPClient(client), |
| + awsconfig.WithAPIOptions([]func(*middleware.Stack) error{idleBodyOption(idle)}), |
| + } |
| +} |
| + |
| +// 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) { |
| + out, md, err := next.HandleDeserialize(ctx, in) |
| + if err != nil { |
| + return out, md, err |
| + } |
| + if resp, ok := out.RawResponse.(*smithyhttp.Response); ok && resp.Body != nil && resp.Body != http.NoBody { |
| + resp.Body = &idleBody{rc: resp.Body, idle: m.idle} |
| + } |
| + return out, md, nil |
| +} |
| + |
| +// bodyStallError is a body read that got no bytes for the idle bound. It is |
| +// a timeout, as the transport's own header timeout is. |
| +type bodyStallError struct{ idle time.Duration } |
| + |
| +func (e bodyStallError) Error() string { |
| + return fmt.Sprintf("rootaws: response body stalled: no data for %s", e.idle) |
| +} |
| +func (bodyStallError) Timeout() bool { return true } |
| +func (bodyStallError) Temporary() bool { return true } |
| + |
| +// idleBody fails a Read that waits past idle by closing the body under it, |
| +// which is how net/http aborts a pending read. Reads are not concurrent (an |
| +// io.Reader's contract), so one timer serves them all. |
| +type idleBody struct { |
| + rc io.ReadCloser |
| + idle time.Duration |
| + timer *time.Timer |
| + stalled atomic.Bool |
| +} |
| + |
| +func (b *idleBody) Read(p []byte) (int, error) { |
| + if b.stalled.Load() { |
| + return 0, bodyStallError{b.idle} |
| + } |
| + if b.timer == nil { |
| + b.timer = time.AfterFunc(b.idle, b.stall) |
| + } else { |
| + b.timer.Reset(b.idle) |
| + } |
| + n, err := b.rc.Read(p) |
| + b.timer.Stop() |
| + // Checked whatever Stop answered: a timer that fired as the read |
| + // returned may close the body only after this read, and the next one |
| + // must still say why it failed. |
| + if b.stalled.Load() { |
| + return n, bodyStallError{b.idle} |
| + } |
| + return n, err |
| +} |
| + |
| +func (b *idleBody) stall() { |
| + b.stalled.Store(true) |
| + b.rc.Close() // unblocks the pending Read |
| +} |
| + |
| +func (b *idleBody) Close() error { return b.rc.Close() } |
diff --git a/internal/rootaws/stall_test.go b/internal/rootaws/stall_test.go| new file mode 100644 |
| index 000000000..2cc1d58f0 |
| --- /dev/null |
| +++ b/internal/rootaws/stall_test.go |
| @@ -0,0 +1,268 @@ |
| +package rootaws |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/pem" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "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) { |
| + t.Helper() |
| + client, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| + if !ok { |
| + t.Fatalf("HTTP client is %T, want a BuildableClient", cfg.HTTPClient) |
| + } |
| + stack := middleware.NewStack("probe", nil) |
| + for _, fn := range cfg.APIOptions { |
| + 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 config's APIOptions") |
| + } |
| + return client.GetTransport().ResponseHeaderTimeout, m.(idleBodyMiddleware).idle |
| +} |
| + |
| +// Every loader in this package hands out a config carrying both bounds at |
| +// their 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) { |
| + dir := t.TempDir() |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "absent")) |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(dir, "absent")) |
| + return LoadDefaultConfig(context.Background()) |
| + }, |
| + "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. |
| + "loadRootConfig": func(t *testing.T) (aws.Config, error) { |
| + return loadRootConfig(context.Background(), filepath.Join(t.TempDir(), "absent"), withStallBounds(nil)...) |
| + }, |
| + } |
| + for name, load := range loaders { |
| + t.Run(name, func(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + cfg, err := load(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + header, idle := installedBounds(t, cfg) |
| + if header != ResponseHeaderTimeout || idle != BodyIdleTimeout { |
| + t.Fatalf("bounds %s/%s, want %s/%s", header, idle, ResponseHeaderTimeout, BodyIdleTimeout) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The HTTP client stays buildable so a CA bundle still loads, and the |
| +// bundle keeps the header timeout. |
| +func TestStallBoundsKeepCABundle(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + srv := httptest.NewTLSServer(http.NotFoundHandler()) |
| + defer srv.Close() |
| + bundle := filepath.Join(t.TempDir(), "ca.pem") |
| + if err := os.WriteFile(bundle, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("AWS_CA_BUNDLE", bundle) |
| + cfg, err := LoadStaticConfig(context.Background(), "ACCESS", "SECRET") |
| + if err != nil { |
| + t.Fatalf("a CA bundle no longer loads: %v", err) |
| + } |
| + if header, _ := installedBounds(t, cfg); 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") |
| + } |
| +} |
| + |
| +const ( |
| + testHeaderTimeout = 300 * time.Millisecond |
| + testIdleTimeout = 300 * time.Millisecond |
| + // 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 = 10 * time.Second |
| +) |
| + |
| +// stallClient is an S3 client over the bounds with the test values, one |
| +// attempt per call, against url. |
| +func stallClient(t *testing.T, url string) *awss3.Client { |
| + t.Helper() |
| + isolatedAWSEnv(t) |
| + opts := append(stallBounds(testHeaderTimeout, testIdleTimeout), |
| + 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(), opts...) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return awss3.NewFromConfig(cfg, func(o *awss3.Options) { |
| + o.BaseEndpoint = aws.String(url) |
| + o.UsePathStyle = true |
| + }) |
| +} |
| + |
| +// stallServer runs handler; a handler that blocks waits on done, which |
| +// closes before the server does. |
| +func stallServer(t *testing.T, handler func(w http.ResponseWriter, r *http.Request, done <-chan struct{})) string { |
| + t.Helper() |
| + done := make(chan struct{}) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler(w, r, done) })) |
| + t.Cleanup(srv.Close) |
| + t.Cleanup(func() { close(done) }) |
| + return srv.URL |
| +} |
| + |
| +func block(r *http.Request, done <-chan struct{}) { |
| + select { |
| + case <-r.Context().Done(): |
| + case <-done: |
| + } |
| +} |
| + |
| +func wantTimeout(t *testing.T, err error, start time.Time) { |
| + 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) |
| + } |
| +} |
| + |
| +func get(t *testing.T, c *awss3.Client) ([]byte, error) { |
| + t.Helper() |
| + out, err := c.GetObject(context.Background(), &awss3.GetObjectInput{Bucket: aws.String("b"), Key: aws.String("k")}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer out.Body.Close() |
| + return io.ReadAll(out.Body) |
| +} |
| + |
| +// (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)) |
| + wantTimeout(t, err, start) |
| +} |
| + |
| +// (b) Headers, part of the body, then nothing: a streamed GetObject body |
| +// read by the caller. |
| +func TestStallBodyFailsGetObject(t *testing.T) { |
| + url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + w.Header().Set("Content-Length", "1048576") |
| + w.WriteHeader(http.StatusOK) |
| + w.Write(bytes.Repeat([]byte("x"), 1024)) |
| + w.(http.Flusher).Flush() |
| + block(r, done) |
| + }) |
| + start := time.Now() |
| + _, err := get(t, stallClient(t, url)) |
| + wantTimeout(t, err, start) |
| + var stall bodyStallError |
| + if !errors.As(err, &stall) { |
| + t.Fatalf("not the body bound: %v", err) |
| + } |
| +} |
| + |
| +// (b) The same stall inside an answer the SDK decodes itself. |
| +func TestStallBodyFailsDecodedAnswer(t *testing.T) { |
| + url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.WriteHeader(http.StatusOK) |
| + io.WriteString(w, `<?xml version="1.0" encoding="UTF-8"?><ListBucketResult><Name>b</Name>`) |
| + w.(http.Flusher).Flush() |
| + block(r, done) |
| + }) |
| + start := time.Now() |
| + _, err := stallClient(t, url).ListObjectsV2(context.Background(), &awss3.ListObjectsV2Input{Bucket: aws.String("b")}) |
| + wantTimeout(t, err, start) |
| +} |
| + |
| +// (c) A large body that trickles in, never idle as long as the bound but |
| +// taking many times the bound overall, arrives whole. |
| +func TestTrickleBodySucceeds(t *testing.T) { |
| + const chunks, size = 40, 16 << 10 |
| + gap := testIdleTimeout / 6 |
| + url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + w.WriteHeader(http.StatusOK) |
| + for i := 0; i < chunks; i++ { |
| + if _, err := w.Write(bytes.Repeat([]byte{byte('a' + i%26)}, size)); err != nil { |
| + return |
| + } |
| + w.(http.Flusher).Flush() |
| + time.Sleep(gap) |
| + } |
| + }) |
| + start := time.Now() |
| + body, err := get(t, stallClient(t, url)) |
| + if err != nil { |
| + t.Fatalf("a steady transfer was cut off after %s: %v", time.Since(start), err) |
| + } |
| + if len(body) != chunks*size { |
| + t.Fatalf("got %d bytes, want %d", len(body), chunks*size) |
| + } |
| + if d := time.Since(start); d < 3*testIdleTimeout { |
| + t.Fatalf("the transfer took %s, not long enough to prove anything", d) |
| + } |
| +} |
| + |
| +// A caller that pauses between reads longer than the bound is not cut off: |
| +// the bound times the store, not the reader. |
| +func TestPausingReaderSucceeds(t *testing.T) { |
| + want := strings.Repeat("y", 4096) |
| + url := stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + io.WriteString(w, want) |
| + }) |
| + out, err := stallClient(t, url).GetObject(context.Background(), &awss3.GetObjectInput{Bucket: aws.String("b"), Key: aws.String("k")}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer out.Body.Close() |
| + head := make([]byte, 10) |
| + if _, err := io.ReadFull(out.Body, head); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(3 * testIdleTimeout) |
| + rest, err := io.ReadAll(out.Body) |
| + if err != nil { |
| + t.Fatalf("a pausing reader was cut off: %v", err) |
| + } |
| + if string(head)+string(rest) != want { |
| + t.Fatal("the body changed") |
| + } |
| +} |